Version:  2.0.40 2.2.26 2.4.37 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17

Linux/drivers/staging/fwserial/fwserial.c

  1 /*
  2  * FireWire Serial driver
  3  *
  4  * Copyright (C) 2012 Peter Hurley <peter@hurleysoftware.com>
  5  *
  6  * This program is free software; you can redistribute it and/or modify
  7  * it under the terms of the GNU General Public License as published by
  8  * the Free Software Foundation; either version 2 of the License, or
  9  * (at your option) any later version.
 10  *
 11  * This program is distributed in the hope that it will be useful,
 12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
 13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 14  * GNU General Public License for more details.
 15  */
 16 
 17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 18 
 19 #include <linux/sched.h>
 20 #include <linux/slab.h>
 21 #include <linux/device.h>
 22 #include <linux/mod_devicetable.h>
 23 #include <linux/rculist.h>
 24 #include <linux/workqueue.h>
 25 #include <linux/ratelimit.h>
 26 #include <linux/bug.h>
 27 #include <linux/uaccess.h>
 28 
 29 #include "fwserial.h"
 30 
 31 #define be32_to_u64(hi, lo)  ((u64)be32_to_cpu(hi) << 32 | be32_to_cpu(lo))
 32 
 33 #define LINUX_VENDOR_ID   0xd00d1eU  /* same id used in card root directory   */
 34 #define FWSERIAL_VERSION  0x00e81cU  /* must be unique within LINUX_VENDOR_ID */
 35 
 36 /* configurable options */
 37 static int num_ttys = 4;            /* # of std ttys to create per fw_card    */
 38                                     /* - doubles as loopback port index       */
 39 static bool auto_connect = true;    /* try to VIRT_CABLE to every peer        */
 40 static bool create_loop_dev = true; /* create a loopback device for each card */
 41 
 42 module_param_named(ttys, num_ttys, int, S_IRUGO | S_IWUSR);
 43 module_param_named(auto, auto_connect, bool, S_IRUGO | S_IWUSR);
 44 module_param_named(loop, create_loop_dev, bool, S_IRUGO | S_IWUSR);
 45 
 46 /*
 47  * Threshold below which the tty is woken for writing
 48  * - should be equal to WAKEUP_CHARS in drivers/tty/n_tty.c because
 49  *   even if the writer is woken, n_tty_poll() won't set POLLOUT until
 50  *   our fifo is below this level
 51  */
 52 #define WAKEUP_CHARS             256
 53 
 54 /**
 55  * fwserial_list: list of every fw_serial created for each fw_card
 56  * See discussion in fwserial_probe.
 57  */
 58 static LIST_HEAD(fwserial_list);
 59 static DEFINE_MUTEX(fwserial_list_mutex);
 60 
 61 /**
 62  * port_table: array of tty ports allocated to each fw_card
 63  *
 64  * tty ports are allocated during probe when an fw_serial is first
 65  * created for a given fw_card. Ports are allocated in a contiguous block,
 66  * each block consisting of 'num_ports' ports.
 67  */
 68 static struct fwtty_port *port_table[MAX_TOTAL_PORTS];
 69 static DEFINE_MUTEX(port_table_lock);
 70 static bool port_table_corrupt;
 71 #define FWTTY_INVALID_INDEX  MAX_TOTAL_PORTS
 72 
 73 #define loop_idx(port)  (((port)->index) / num_ports)
 74 #define table_idx(loop) ((loop) * num_ports + num_ttys)
 75 
 76 /* total # of tty ports created per fw_card */
 77 static int num_ports;
 78 
 79 /* slab used as pool for struct fwtty_transactions */
 80 static struct kmem_cache *fwtty_txn_cache;
 81 
 82 struct tty_driver *fwtty_driver;
 83 static struct tty_driver *fwloop_driver;
 84 
 85 static struct dentry *fwserial_debugfs;
 86 
 87 struct fwtty_transaction;
 88 typedef void (*fwtty_transaction_cb)(struct fw_card *card, int rcode,
 89                                      void *data, size_t length,
 90                                      struct fwtty_transaction *txn);
 91 
 92 struct fwtty_transaction {
 93         struct fw_transaction      fw_txn;
 94         fwtty_transaction_cb       callback;
 95         struct fwtty_port          *port;
 96         union {
 97                 struct dma_pending dma_pended;
 98         };
 99 };
100 
101 #define to_device(a, b)                 (a->b)
102 #define fwtty_err(p, fmt, ...)                                          \
103         dev_err(to_device(p, device), fmt, ##__VA_ARGS__)
104 #define fwtty_info(p, fmt, ...)                                         \
105         dev_info(to_device(p, device), fmt, ##__VA_ARGS__)
106 #define fwtty_notice(p, fmt, ...)                                       \
107         dev_notice(to_device(p, device), fmt, ##__VA_ARGS__)
108 #define fwtty_dbg(p, fmt, ...)                                          \
109         dev_dbg(to_device(p, device), "%s: " fmt, __func__, ##__VA_ARGS__)
110 #define fwtty_err_ratelimited(p, fmt, ...)                              \
111         dev_err_ratelimited(to_device(p, device), fmt, ##__VA_ARGS__)
112 
113 #ifdef DEBUG
114 static inline void debug_short_write(struct fwtty_port *port, int c, int n)
115 {
116         int avail;
117 
118         if (n < c) {
119                 spin_lock_bh(&port->lock);
120                 avail = dma_fifo_avail(&port->tx_fifo);
121                 spin_unlock_bh(&port->lock);
122                 fwtty_dbg(port, "short write: avail:%d req:%d wrote:%d\n",
123                           avail, c, n);
124         }
125 }
126 #else
127 #define debug_short_write(port, c, n)
128 #endif
129 
130 static struct fwtty_peer *__fwserial_peer_by_node_id(struct fw_card *card,
131                                                      int generation, int id);
132 
133 #ifdef FWTTY_PROFILING
134 
135 static void fwtty_profile_fifo(struct fwtty_port *port, unsigned *stat)
136 {
137         spin_lock_bh(&port->lock);
138         fwtty_profile_data(stat, dma_fifo_avail(&port->tx_fifo));
139         spin_unlock_bh(&port->lock);
140 }
141 
142 static void fwtty_dump_profile(struct seq_file *m, struct stats *stats)
143 {
144         /* for each stat, print sum of 0 to 2^k, then individually */
145         int k = 4;
146         unsigned sum;
147         int j;
148         char t[10];
149 
150         snprintf(t, 10, "< %d", 1 << k);
151         seq_printf(m, "\n%14s  %6s", " ", t);
152         for (j = k + 1; j < DISTRIBUTION_MAX_INDEX; ++j)
153                 seq_printf(m, "%6d", 1 << j);
154 
155         ++k;
156         for (j = 0, sum = 0; j <= k; ++j)
157                 sum += stats->reads[j];
158         seq_printf(m, "\n%14s: %6d", "reads", sum);
159         for (j = k + 1; j <= DISTRIBUTION_MAX_INDEX; ++j)
160                 seq_printf(m, "%6d", stats->reads[j]);
161 
162         for (j = 0, sum = 0; j <= k; ++j)
163                 sum += stats->writes[j];
164         seq_printf(m, "\n%14s: %6d", "writes", sum);
165         for (j = k + 1; j <= DISTRIBUTION_MAX_INDEX; ++j)
166                 seq_printf(m, "%6d", stats->writes[j]);
167 
168         for (j = 0, sum = 0; j <= k; ++j)
169                 sum += stats->txns[j];
170         seq_printf(m, "\n%14s: %6d", "txns", sum);
171         for (j = k + 1; j <= DISTRIBUTION_MAX_INDEX; ++j)
172                 seq_printf(m, "%6d", stats->txns[j]);
173 
174         for (j = 0, sum = 0; j <= k; ++j)
175                 sum += stats->unthrottle[j];
176         seq_printf(m, "\n%14s: %6d", "avail @ unthr", sum);
177         for (j = k + 1; j <= DISTRIBUTION_MAX_INDEX; ++j)
178                 seq_printf(m, "%6d", stats->unthrottle[j]);
179 }
180 
181 #else
182 #define fwtty_profile_fifo(port, stat)
183 #define fwtty_dump_profile(m, stats)
184 #endif
185 
186 /*
187  * Returns the max receive packet size for the given node
188  * Devices which are OHCI v1.0/ v1.1/ v1.2-draft or RFC 2734 compliant
189  * are required by specification to support max_rec of 8 (512 bytes) or more.
190  */
191 static inline int device_max_receive(struct fw_device *fw_device)
192 {
193         /* see IEEE 1394-2008 table 8-8 */
194         return min(2 << fw_device->max_rec, 4096);
195 }
196 
197 static void fwtty_log_tx_error(struct fwtty_port *port, int rcode)
198 {
199         switch (rcode) {
200         case RCODE_SEND_ERROR:
201                 fwtty_err_ratelimited(port, "card busy\n");
202                 break;
203         case RCODE_ADDRESS_ERROR:
204                 fwtty_err_ratelimited(port, "bad unit addr or write length\n");
205                 break;
206         case RCODE_DATA_ERROR:
207                 fwtty_err_ratelimited(port, "failed rx\n");
208                 break;
209         case RCODE_NO_ACK:
210                 fwtty_err_ratelimited(port, "missing ack\n");
211                 break;
212         case RCODE_BUSY:
213                 fwtty_err_ratelimited(port, "remote busy\n");
214                 break;
215         default:
216                 fwtty_err_ratelimited(port, "failed tx: %d\n", rcode);
217         }
218 }
219 
220 static void fwtty_txn_constructor(void *this)
221 {
222         struct fwtty_transaction *txn = this;
223 
224         init_timer(&txn->fw_txn.split_timeout_timer);
225 }
226 
227 static void fwtty_common_callback(struct fw_card *card, int rcode,
228                                   void *payload, size_t len, void *cb_data)
229 {
230         struct fwtty_transaction *txn = cb_data;
231         struct fwtty_port *port = txn->port;
232 
233         if (port && rcode != RCODE_COMPLETE)
234                 fwtty_log_tx_error(port, rcode);
235         if (txn->callback)
236                 txn->callback(card, rcode, payload, len, txn);
237         kmem_cache_free(fwtty_txn_cache, txn);
238 }
239 
240 static int fwtty_send_data_async(struct fwtty_peer *peer, int tcode,
241                                  unsigned long long addr, void *payload,
242                                  size_t len, fwtty_transaction_cb callback,
243                                  struct fwtty_port *port)
244 {
245         struct fwtty_transaction *txn;
246         int generation;
247 
248         txn = kmem_cache_alloc(fwtty_txn_cache, GFP_ATOMIC);
249         if (!txn)
250                 return -ENOMEM;
251 
252         txn->callback = callback;
253         txn->port = port;
254 
255         generation = peer->generation;
256         smp_rmb();
257         fw_send_request(peer->serial->card, &txn->fw_txn, tcode,
258                         peer->node_id, generation, peer->speed, addr, payload,
259                         len, fwtty_common_callback, txn);
260         return 0;
261 }
262 
263 static void fwtty_send_txn_async(struct fwtty_peer *peer,
264                                  struct fwtty_transaction *txn, int tcode,
265                                  unsigned long long addr, void *payload,
266                                  size_t len, fwtty_transaction_cb callback,
267                                  struct fwtty_port *port)
268 {
269         int generation;
270 
271         txn->callback = callback;
272         txn->port = port;
273 
274         generation = peer->generation;
275         smp_rmb();
276         fw_send_request(peer->serial->card, &txn->fw_txn, tcode,
277                         peer->node_id, generation, peer->speed, addr, payload,
278                         len, fwtty_common_callback, txn);
279 }
280 
281 
282 static void __fwtty_restart_tx(struct fwtty_port *port)
283 {
284         int len, avail;
285 
286         len = dma_fifo_out_level(&port->tx_fifo);
287         if (len)
288                 schedule_delayed_work(&port->drain, 0);
289         avail = dma_fifo_avail(&port->tx_fifo);
290 
291         fwtty_dbg(port, "fifo len: %d avail: %d\n", len, avail);
292 }
293 
294 static void fwtty_restart_tx(struct fwtty_port *port)
295 {
296         spin_lock_bh(&port->lock);
297         __fwtty_restart_tx(port);
298         spin_unlock_bh(&port->lock);
299 }
300 
301 /**
302  * fwtty_update_port_status - decodes & dispatches line status changes
303  *
304  * Note: in loopback, the port->lock is being held. Only use functions that
305  * don't attempt to reclaim the port->lock.
306  */
307 static void fwtty_update_port_status(struct fwtty_port *port, unsigned status)
308 {
309         unsigned delta;
310         struct tty_struct *tty;
311 
312         /* simulated LSR/MSR status from remote */
313         status &= ~MCTRL_MASK;
314         delta = (port->mstatus ^ status) & ~MCTRL_MASK;
315         delta &= ~(status & TIOCM_RNG);
316         port->mstatus = status;
317 
318         if (delta & TIOCM_RNG)
319                 ++port->icount.rng;
320         if (delta & TIOCM_DSR)
321                 ++port->icount.dsr;
322         if (delta & TIOCM_CAR)
323                 ++port->icount.dcd;
324         if (delta & TIOCM_CTS)
325                 ++port->icount.cts;
326 
327         fwtty_dbg(port, "status: %x delta: %x\n", status, delta);
328 
329         if (delta & TIOCM_CAR) {
330                 tty = tty_port_tty_get(&port->port);
331                 if (tty && !C_CLOCAL(tty)) {
332                         if (status & TIOCM_CAR)
333                                 wake_up_interruptible(&port->port.open_wait);
334                         else
335                                 schedule_work(&port->hangup);
336                 }
337                 tty_kref_put(tty);
338         }
339 
340         if (delta & TIOCM_CTS) {
341                 tty = tty_port_tty_get(&port->port);
342                 if (tty && C_CRTSCTS(tty)) {
343                         if (tty->hw_stopped) {
344                                 if (status & TIOCM_CTS) {
345                                         tty->hw_stopped = 0;
346                                         if (port->loopback)
347                                                 __fwtty_restart_tx(port);
348                                         else
349                                                 fwtty_restart_tx(port);
350                                 }
351                         } else {
352                                 if (~status & TIOCM_CTS)
353                                         tty->hw_stopped = 1;
354                         }
355                 }
356                 tty_kref_put(tty);
357 
358         } else if (delta & OOB_TX_THROTTLE) {
359                 tty = tty_port_tty_get(&port->port);
360                 if (tty) {
361                         if (tty->hw_stopped) {
362                                 if (~status & OOB_TX_THROTTLE) {
363                                         tty->hw_stopped = 0;
364                                         if (port->loopback)
365                                                 __fwtty_restart_tx(port);
366                                         else
367                                                 fwtty_restart_tx(port);
368                                 }
369                         } else {
370                                 if (status & OOB_TX_THROTTLE)
371                                         tty->hw_stopped = 1;
372                         }
373                 }
374                 tty_kref_put(tty);
375         }
376 
377         if (delta & (UART_LSR_BI << 24)) {
378                 if (status & (UART_LSR_BI << 24)) {
379                         port->break_last = jiffies;
380                         schedule_delayed_work(&port->emit_breaks, 0);
381                 } else {
382                         /* run emit_breaks one last time (if pending) */
383                         mod_delayed_work(system_wq, &port->emit_breaks, 0);
384                 }
385         }
386 
387         if (delta & (TIOCM_DSR | TIOCM_CAR | TIOCM_CTS | TIOCM_RNG))
388                 wake_up_interruptible(&port->port.delta_msr_wait);
389 }
390 
391 /**
392  * __fwtty_port_line_status - generate 'line status' for indicated port
393  *
394  * This function returns a remote 'MSR' state based on the local 'MCR' state,
395  * as if a null modem cable was attached. The actual status is a mangling
396  * of TIOCM_* bits suitable for sending to a peer's status_addr.
397  *
398  * Note: caller must be holding port lock
399  */
400 static unsigned __fwtty_port_line_status(struct fwtty_port *port)
401 {
402         unsigned status = 0;
403 
404         /* TODO: add module param to tie RNG to DTR as well */
405 
406         if (port->mctrl & TIOCM_DTR)
407                 status |= TIOCM_DSR | TIOCM_CAR;
408         if (port->mctrl & TIOCM_RTS)
409                 status |= TIOCM_CTS;
410         if (port->mctrl & OOB_RX_THROTTLE)
411                 status |= OOB_TX_THROTTLE;
412         /* emulate BRK as add'l line status */
413         if (port->break_ctl)
414                 status |= UART_LSR_BI << 24;
415 
416         return status;
417 }
418 
419 /**
420  * __fwtty_write_port_status - send the port line status to peer
421  *
422  * Note: caller must be holding the port lock.
423  */
424 static int __fwtty_write_port_status(struct fwtty_port *port)
425 {
426         struct fwtty_peer *peer;
427         int err = -ENOENT;
428         unsigned status = __fwtty_port_line_status(port);
429 
430         rcu_read_lock();
431         peer = rcu_dereference(port->peer);
432         if (peer) {
433                 err = fwtty_send_data_async(peer, TCODE_WRITE_QUADLET_REQUEST,
434                                             peer->status_addr, &status,
435                                             sizeof(status), NULL, port);
436         }
437         rcu_read_unlock();
438 
439         return err;
440 }
441 
442 /**
443  * fwtty_write_port_status - same as above but locked by port lock
444  */
445 static int fwtty_write_port_status(struct fwtty_port *port)
446 {
447         int err;
448 
449         spin_lock_bh(&port->lock);
450         err = __fwtty_write_port_status(port);
451         spin_unlock_bh(&port->lock);
452         return err;
453 }
454 
455 static void fwtty_throttle_port(struct fwtty_port *port)
456 {
457         struct tty_struct *tty;
458         unsigned old;
459 
460         tty = tty_port_tty_get(&port->port);
461         if (!tty)
462                 return;
463 
464         spin_lock_bh(&port->lock);
465 
466         old = port->mctrl;
467         port->mctrl |= OOB_RX_THROTTLE;
468         if (C_CRTSCTS(tty))
469                 port->mctrl &= ~TIOCM_RTS;
470         if (~old & OOB_RX_THROTTLE)
471                 __fwtty_write_port_status(port);
472 
473         spin_unlock_bh(&port->lock);
474 
475         tty_kref_put(tty);
476 }
477 
478 /**
479  * fwtty_do_hangup - wait for ldisc to deliver all pending rx; only then hangup
480  *
481  * When the remote has finished tx, and all in-flight rx has been received and
482  * and pushed to the flip buffer, the remote may close its device. This will
483  * drop DTR on the remote which will drop carrier here. Typically, the tty is
484  * hung up when carrier is dropped or lost.
485  *
486  * However, there is a race between the hang up and the line discipline
487  * delivering its data to the reader. A hangup will cause the ldisc to flush
488  * (ie., clear) the read buffer and flip buffer. Because of firewire's
489  * relatively high throughput, the ldisc frequently lags well behind the driver,
490  * resulting in lost data (which has already been received and written to
491  * the flip buffer) when the remote closes its end.
492  *
493  * Unfortunately, since the flip buffer offers no direct method for determining
494  * if it holds data, ensuring the ldisc has delivered all data is problematic.
495  */
496 
497 /* FIXME: drop this workaround when __tty_hangup waits for ldisc completion */
498 static void fwtty_do_hangup(struct work_struct *work)
499 {
500         struct fwtty_port *port = to_port(work, hangup);
501         struct tty_struct *tty;
502 
503         schedule_timeout_uninterruptible(msecs_to_jiffies(50));
504 
505         tty = tty_port_tty_get(&port->port);
506         if (tty)
507                 tty_vhangup(tty);
508         tty_kref_put(tty);
509 }
510 
511 
512 static void fwtty_emit_breaks(struct work_struct *work)
513 {
514         struct fwtty_port *port = to_port(to_delayed_work(work), emit_breaks);
515         static const char buf[16];
516         unsigned long now = jiffies;
517         unsigned long elapsed = now - port->break_last;
518         int n, t, c, brk = 0;
519 
520         /* generate breaks at the line rate (but at least 1) */
521         n = (elapsed * port->cps) / HZ + 1;
522         port->break_last = now;
523 
524         fwtty_dbg(port, "sending %d brks\n", n);
525 
526         while (n) {
527                 t = min(n, 16);
528                 c = tty_insert_flip_string_fixed_flag(&port->port, buf,
529                                                       TTY_BREAK, t);
530                 n -= c;
531                 brk += c;
532                 if (c < t)
533                         break;
534         }
535         tty_flip_buffer_push(&port->port);
536 
537         if (port->mstatus & (UART_LSR_BI << 24))
538                 schedule_delayed_work(&port->emit_breaks, FREQ_BREAKS);
539         port->icount.brk += brk;
540 }
541 
542 static int fwtty_rx(struct fwtty_port *port, unsigned char *data, size_t len)
543 {
544         int c, n = len;
545         unsigned lsr;
546         int err = 0;
547 
548         fwtty_dbg(port, "%d\n", n);
549         fwtty_profile_data(port->stats.reads, n);
550 
551         if (port->write_only) {
552                 n = 0;
553                 goto out;
554         }
555 
556         /* disregard break status; breaks are generated by emit_breaks work */
557         lsr = (port->mstatus >> 24) & ~UART_LSR_BI;
558 
559         if (port->overrun)
560                 lsr |= UART_LSR_OE;
561 
562         if (lsr & UART_LSR_OE)
563                 ++port->icount.overrun;
564 
565         lsr &= port->status_mask;
566         if (lsr & ~port->ignore_mask & UART_LSR_OE) {
567                 if (!tty_insert_flip_char(&port->port, 0, TTY_OVERRUN)) {
568                         err = -EIO;
569                         goto out;
570                 }
571         }
572         port->overrun = false;
573 
574         if (lsr & port->ignore_mask & ~UART_LSR_OE) {
575                 /* TODO: don't drop SAK and Magic SysRq here */
576                 n = 0;
577                 goto out;
578         }
579 
580         c = tty_insert_flip_string_fixed_flag(&port->port, data, TTY_NORMAL, n);
581         if (c > 0)
582                 tty_flip_buffer_push(&port->port);
583         n -= c;
584 
585         if (n) {
586                 port->overrun = true;
587                 err = -EIO;
588                 fwtty_err_ratelimited(port, "flip buffer overrun\n");
589 
590         } else {
591                 /* throttle the sender if remaining flip buffer space has
592                  * reached high watermark to avoid losing data which may be
593                  * in-flight. Since the AR request context is 32k, that much
594                  * data may have _already_ been acked.
595                  */
596                 if (tty_buffer_space_avail(&port->port) < HIGH_WATERMARK)
597                         fwtty_throttle_port(port);
598         }
599 
600 out:
601         port->icount.rx += len;
602         port->stats.lost += n;
603         return err;
604 }
605 
606 /**
607  * fwtty_port_handler - bus address handler for port reads/writes
608  * @parameters: fw_address_callback_t as specified by firewire core interface
609  *
610  * This handler is responsible for handling inbound read/write dma from remotes.
611  */
612 static void fwtty_port_handler(struct fw_card *card,
613                                struct fw_request *request,
614                                int tcode, int destination, int source,
615                                int generation,
616                                unsigned long long addr,
617                                void *data, size_t len,
618                                void *callback_data)
619 {
620         struct fwtty_port *port = callback_data;
621         struct fwtty_peer *peer;
622         int err;
623         int rcode;
624 
625         /* Only accept rx from the peer virtual-cabled to this port */
626         rcu_read_lock();
627         peer = __fwserial_peer_by_node_id(card, generation, source);
628         rcu_read_unlock();
629         if (!peer || peer != rcu_access_pointer(port->peer)) {
630                 rcode = RCODE_ADDRESS_ERROR;
631                 fwtty_err_ratelimited(port, "ignoring unauthenticated data\n");
632                 goto respond;
633         }
634 
635         switch (tcode) {
636         case TCODE_WRITE_QUADLET_REQUEST:
637                 if (addr != port->rx_handler.offset || len != 4) {
638                         rcode = RCODE_ADDRESS_ERROR;
639                 } else {
640                         fwtty_update_port_status(port, *(unsigned *)data);
641                         rcode = RCODE_COMPLETE;
642                 }
643                 break;
644 
645         case TCODE_WRITE_BLOCK_REQUEST:
646                 if (addr != port->rx_handler.offset + 4 ||
647                     len > port->rx_handler.length - 4) {
648                         rcode = RCODE_ADDRESS_ERROR;
649                 } else {
650                         err = fwtty_rx(port, data, len);
651                         switch (err) {
652                         case 0:
653                                 rcode = RCODE_COMPLETE;
654                                 break;
655                         case -EIO:
656                                 rcode = RCODE_DATA_ERROR;
657                                 break;
658                         default:
659                                 rcode = RCODE_CONFLICT_ERROR;
660                                 break;
661                         }
662                 }
663                 break;
664 
665         default:
666                 rcode = RCODE_TYPE_ERROR;
667         }
668 
669 respond:
670         fw_send_response(card, request, rcode);
671 }
672 
673 /**
674  * fwtty_tx_complete - callback for tx dma
675  * @data: ignored, has no meaning for write txns
676  * @length: ignored, has no meaning for write txns
677  *
678  * The writer must be woken here if the fifo has been emptied because it
679  * may have slept if chars_in_buffer was != 0
680  */
681 static void fwtty_tx_complete(struct fw_card *card, int rcode,
682                               void *data, size_t length,
683                               struct fwtty_transaction *txn)
684 {
685         struct fwtty_port *port = txn->port;
686         int len;
687 
688         fwtty_dbg(port, "rcode: %d\n", rcode);
689 
690         switch (rcode) {
691         case RCODE_COMPLETE:
692                 spin_lock_bh(&port->lock);
693                 dma_fifo_out_complete(&port->tx_fifo, &txn->dma_pended);
694                 len = dma_fifo_level(&port->tx_fifo);
695                 spin_unlock_bh(&port->lock);
696 
697                 port->icount.tx += txn->dma_pended.len;
698                 break;
699 
700         default:
701                 /* TODO: implement retries */
702                 spin_lock_bh(&port->lock);
703                 dma_fifo_out_complete(&port->tx_fifo, &txn->dma_pended);
704                 len = dma_fifo_level(&port->tx_fifo);
705                 spin_unlock_bh(&port->lock);
706 
707                 port->stats.dropped += txn->dma_pended.len;
708         }
709 
710         if (len < WAKEUP_CHARS)
711                 tty_port_tty_wakeup(&port->port);
712 }
713 
714 static int fwtty_tx(struct fwtty_port *port, bool drain)
715 {
716         struct fwtty_peer *peer;
717         struct fwtty_transaction *txn;
718         struct tty_struct *tty;
719         int n, len;
720 
721         tty = tty_port_tty_get(&port->port);
722         if (!tty)
723                 return -ENOENT;
724 
725         rcu_read_lock();
726         peer = rcu_dereference(port->peer);
727         if (!peer) {
728                 n = -EIO;
729                 goto out;
730         }
731 
732         if (test_and_set_bit(IN_TX, &port->flags)) {
733                 n = -EALREADY;
734                 goto out;
735         }
736 
737         /* try to write as many dma transactions out as possible */
738         n = -EAGAIN;
739         while (!tty->stopped && !tty->hw_stopped &&
740                !test_bit(STOP_TX, &port->flags)) {
741                 txn = kmem_cache_alloc(fwtty_txn_cache, GFP_ATOMIC);
742                 if (!txn) {
743                         n = -ENOMEM;
744                         break;
745                 }
746 
747                 spin_lock_bh(&port->lock);
748                 n = dma_fifo_out_pend(&port->tx_fifo, &txn->dma_pended);
749                 spin_unlock_bh(&port->lock);
750 
751                 fwtty_dbg(port, "out: %u rem: %d\n", txn->dma_pended.len, n);
752 
753                 if (n < 0) {
754                         kmem_cache_free(fwtty_txn_cache, txn);
755                         if (n == -EAGAIN) {
756                                 ++port->stats.tx_stall;
757                         } else if (n == -ENODATA) {
758                                 fwtty_profile_data(port->stats.txns, 0);
759                         } else {
760                                 ++port->stats.fifo_errs;
761                                 fwtty_err_ratelimited(port, "fifo err: %d\n",
762                                                       n);
763                         }
764                         break;
765                 }
766 
767                 fwtty_profile_data(port->stats.txns, txn->dma_pended.len);
768 
769                 fwtty_send_txn_async(peer, txn, TCODE_WRITE_BLOCK_REQUEST,
770                                      peer->fifo_addr, txn->dma_pended.data,
771                                      txn->dma_pended.len, fwtty_tx_complete,
772                                      port);
773                 ++port->stats.sent;
774 
775                 /*
776                  * Stop tx if the 'last view' of the fifo is empty or if
777                  * this is the writer and there's not enough data to bother
778                  */
779                 if (n == 0 || (!drain && n < WRITER_MINIMUM))
780                         break;
781         }
782 
783         if (n >= 0 || n == -EAGAIN || n == -ENOMEM || n == -ENODATA) {
784                 spin_lock_bh(&port->lock);
785                 len = dma_fifo_out_level(&port->tx_fifo);
786                 if (len) {
787                         unsigned long delay = (n == -ENOMEM) ? HZ : 1;
788 
789                         schedule_delayed_work(&port->drain, delay);
790                 }
791                 len = dma_fifo_level(&port->tx_fifo);
792                 spin_unlock_bh(&port->lock);
793 
794                 /* wakeup the writer */
795                 if (drain && len < WAKEUP_CHARS)
796                         tty_wakeup(tty);
797         }
798 
799         clear_bit(IN_TX, &port->flags);
800         wake_up_interruptible(&port->wait_tx);
801 
802 out:
803         rcu_read_unlock();
804         tty_kref_put(tty);
805         return n;
806 }
807 
808 static void fwtty_drain_tx(struct work_struct *work)
809 {
810         struct fwtty_port *port = to_port(to_delayed_work(work), drain);
811 
812         fwtty_tx(port, true);
813 }
814 
815 static void fwtty_write_xchar(struct fwtty_port *port, char ch)
816 {
817         struct fwtty_peer *peer;
818 
819         ++port->stats.xchars;
820 
821         fwtty_dbg(port, "%02x\n", ch);
822 
823         rcu_read_lock();
824         peer = rcu_dereference(port->peer);
825         if (peer) {
826                 fwtty_send_data_async(peer, TCODE_WRITE_BLOCK_REQUEST,
827                                       peer->fifo_addr, &ch, sizeof(ch),
828                                       NULL, port);
829         }
830         rcu_read_unlock();
831 }
832 
833 struct fwtty_port *fwtty_port_get(unsigned index)
834 {
835         struct fwtty_port *port;
836 
837         if (index >= MAX_TOTAL_PORTS)
838                 return NULL;
839 
840         mutex_lock(&port_table_lock);
841         port = port_table[index];
842         if (port)
843                 kref_get(&port->serial->kref);
844         mutex_unlock(&port_table_lock);
845         return port;
846 }
847 EXPORT_SYMBOL(fwtty_port_get);
848 
849 static int fwtty_ports_add(struct fw_serial *serial)
850 {
851         int err = -EBUSY;
852         int i, j;
853 
854         if (port_table_corrupt)
855                 return err;
856 
857         mutex_lock(&port_table_lock);
858         for (i = 0; i + num_ports <= MAX_TOTAL_PORTS; i += num_ports) {
859                 if (!port_table[i]) {
860                         for (j = 0; j < num_ports; ++i, ++j) {
861                                 serial->ports[j]->index = i;
862                                 port_table[i] = serial->ports[j];
863                         }
864                         err = 0;
865                         break;
866                 }
867         }
868         mutex_unlock(&port_table_lock);
869         return err;
870 }
871 
872 static void fwserial_destroy(struct kref *kref)
873 {
874         struct fw_serial *serial = to_serial(kref, kref);
875         struct fwtty_port **ports = serial->ports;
876         int j, i = ports[0]->index;
877 
878         synchronize_rcu();
879 
880         mutex_lock(&port_table_lock);
881         for (j = 0; j < num_ports; ++i, ++j) {
882                 port_table_corrupt |= port_table[i] != ports[j];
883                 WARN_ONCE(port_table_corrupt, "port_table[%d]: %p != ports[%d]: %p",
884                           i, port_table[i], j, ports[j]);
885 
886                 port_table[i] = NULL;
887         }
888         mutex_unlock(&port_table_lock);
889 
890         for (j = 0; j < num_ports; ++j) {
891                 fw_core_remove_address_handler(&ports[j]->rx_handler);
892                 tty_port_destroy(&ports[j]->port);
893                 kfree(ports[j]);
894         }
895         kfree(serial);
896 }
897 
898 void fwtty_port_put(struct fwtty_port *port)
899 {
900         kref_put(&port->serial->kref, fwserial_destroy);
901 }
902 EXPORT_SYMBOL(fwtty_port_put);
903 
904 static void fwtty_port_dtr_rts(struct tty_port *tty_port, int on)
905 {
906         struct fwtty_port *port = to_port(tty_port, port);
907 
908         fwtty_dbg(port, "on/off: %d\n", on);
909 
910         spin_lock_bh(&port->lock);
911         /* Don't change carrier state if this is a console */
912         if (!port->port.console) {
913                 if (on)
914                         port->mctrl |= TIOCM_DTR | TIOCM_RTS;
915                 else
916                         port->mctrl &= ~(TIOCM_DTR | TIOCM_RTS);
917         }
918 
919         __fwtty_write_port_status(port);
920         spin_unlock_bh(&port->lock);
921 }
922 
923 /**
924  * fwtty_port_carrier_raised: required tty_port operation
925  *
926  * This port operation is polled after a tty has been opened and is waiting for
927  * carrier detect -- see drivers/tty/tty_port:tty_port_block_til_ready().
928  */
929 static int fwtty_port_carrier_raised(struct tty_port *tty_port)
930 {
931         struct fwtty_port *port = to_port(tty_port, port);
932         int rc;
933 
934         rc = (port->mstatus & TIOCM_CAR);
935 
936         fwtty_dbg(port, "%d\n", rc);
937 
938         return rc;
939 }
940 
941 static unsigned set_termios(struct fwtty_port *port, struct tty_struct *tty)
942 {
943         unsigned baud, frame;
944 
945         baud = tty_termios_baud_rate(&tty->termios);
946         tty_termios_encode_baud_rate(&tty->termios, baud, baud);
947 
948         /* compute bit count of 2 frames */
949         frame = 12 + ((C_CSTOPB(tty)) ? 4 : 2) + ((C_PARENB(tty)) ? 2 : 0);
950 
951         switch (C_CSIZE(tty)) {
952         case CS5:
953                 frame -= (C_CSTOPB(tty)) ? 1 : 0;
954                 break;
955         case CS6:
956                 frame += 2;
957                 break;
958         case CS7:
959                 frame += 4;
960                 break;
961         case CS8:
962                 frame += 6;
963                 break;
964         }
965 
966         port->cps = (baud << 1) / frame;
967 
968         port->status_mask = UART_LSR_OE;
969         if (_I_FLAG(tty, BRKINT | PARMRK))
970                 port->status_mask |= UART_LSR_BI;
971 
972         port->ignore_mask = 0;
973         if (I_IGNBRK(tty)) {
974                 port->ignore_mask |= UART_LSR_BI;
975                 if (I_IGNPAR(tty))
976                         port->ignore_mask |= UART_LSR_OE;
977         }
978 
979         port->write_only = !C_CREAD(tty);
980 
981         /* turn off echo and newline xlat if loopback */
982         if (port->loopback) {
983                 tty->termios.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHOKE |
984                                           ECHONL | ECHOPRT | ECHOCTL);
985                 tty->termios.c_oflag &= ~ONLCR;
986         }
987 
988         return baud;
989 }
990 
991 static int fwtty_port_activate(struct tty_port *tty_port,
992                                struct tty_struct *tty)
993 {
994         struct fwtty_port *port = to_port(tty_port, port);
995         unsigned baud;
996         int err;
997 
998         set_bit(TTY_IO_ERROR, &tty->flags);
999 
1000         err = dma_fifo_alloc(&port->tx_fifo, FWTTY_PORT_TXFIFO_LEN,
1001                              cache_line_size(),
1002                              port->max_payload,
1003                              FWTTY_PORT_MAX_PEND_DMA,
1004                              GFP_KERNEL);
1005         if (err)
1006                 return err;
1007 
1008         spin_lock_bh(&port->lock);
1009 
1010         baud = set_termios(port, tty);
1011 
1012         /* if console, don't change carrier state */
1013         if (!port->port.console) {
1014                 port->mctrl = 0;
1015                 if (baud != 0)
1016                         port->mctrl = TIOCM_DTR | TIOCM_RTS;
1017         }
1018 
1019         if (C_CRTSCTS(tty) && ~port->mstatus & TIOCM_CTS)
1020                 tty->hw_stopped = 1;
1021 
1022         __fwtty_write_port_status(port);
1023         spin_unlock_bh(&port->lock);
1024 
1025         clear_bit(TTY_IO_ERROR, &tty->flags);
1026 
1027         return 0;
1028 }
1029 
1030 /**
1031  * fwtty_port_shutdown
1032  *
1033  * Note: the tty port core ensures this is not the console and
1034  * manages TTY_IO_ERROR properly
1035  */
1036 static void fwtty_port_shutdown(struct tty_port *tty_port)
1037 {
1038         struct fwtty_port *port = to_port(tty_port, port);
1039 
1040         /* TODO: cancel outstanding transactions */
1041 
1042         cancel_delayed_work_sync(&port->emit_breaks);
1043         cancel_delayed_work_sync(&port->drain);
1044 
1045         spin_lock_bh(&port->lock);
1046         port->flags = 0;
1047         port->break_ctl = 0;
1048         port->overrun = 0;
1049         __fwtty_write_port_status(port);
1050         dma_fifo_free(&port->tx_fifo);
1051         spin_unlock_bh(&port->lock);
1052 }
1053 
1054 static int fwtty_open(struct tty_struct *tty, struct file *fp)
1055 {
1056         struct fwtty_port *port = tty->driver_data;
1057 
1058         return tty_port_open(&port->port, tty, fp);
1059 }
1060 
1061 static void fwtty_close(struct tty_struct *tty, struct file *fp)
1062 {
1063         struct fwtty_port *port = tty->driver_data;
1064 
1065         tty_port_close(&port->port, tty, fp);
1066 }
1067 
1068 static void fwtty_hangup(struct tty_struct *tty)
1069 {
1070         struct fwtty_port *port = tty->driver_data;
1071 
1072         tty_port_hangup(&port->port);
1073 }
1074 
1075 static void fwtty_cleanup(struct tty_struct *tty)
1076 {
1077         struct fwtty_port *port = tty->driver_data;
1078 
1079         tty->driver_data = NULL;
1080         fwtty_port_put(port);
1081 }
1082 
1083 static int fwtty_install(struct tty_driver *driver, struct tty_struct *tty)
1084 {
1085         struct fwtty_port *port = fwtty_port_get(tty->index);
1086         int err;
1087 
1088         err = tty_standard_install(driver, tty);
1089         if (!err)
1090                 tty->driver_data = port;
1091         else
1092                 fwtty_port_put(port);
1093         return err;
1094 }
1095 
1096 static int fwloop_install(struct tty_driver *driver, struct tty_struct *tty)
1097 {
1098         struct fwtty_port *port = fwtty_port_get(table_idx(tty->index));
1099         int err;
1100 
1101         err = tty_standard_install(driver, tty);
1102         if (!err)
1103                 tty->driver_data = port;
1104         else
1105                 fwtty_port_put(port);
1106         return err;
1107 }
1108 
1109 static int fwtty_write(struct tty_struct *tty, const unsigned char *buf, int c)
1110 {
1111         struct fwtty_port *port = tty->driver_data;
1112         int n, len;
1113 
1114         fwtty_dbg(port, "%d\n", c);
1115         fwtty_profile_data(port->stats.writes, c);
1116 
1117         spin_lock_bh(&port->lock);
1118         n = dma_fifo_in(&port->tx_fifo, buf, c);
1119         len = dma_fifo_out_level(&port->tx_fifo);
1120         if (len < DRAIN_THRESHOLD)
1121                 schedule_delayed_work(&port->drain, 1);
1122         spin_unlock_bh(&port->lock);
1123 
1124         if (len >= DRAIN_THRESHOLD)
1125                 fwtty_tx(port, false);
1126 
1127         debug_short_write(port, c, n);
1128 
1129         return (n < 0) ? 0 : n;
1130 }
1131 
1132 static int fwtty_write_room(struct tty_struct *tty)
1133 {
1134         struct fwtty_port *port = tty->driver_data;
1135         int n;
1136 
1137         spin_lock_bh(&port->lock);
1138         n = dma_fifo_avail(&port->tx_fifo);
1139         spin_unlock_bh(&port->lock);
1140 
1141         fwtty_dbg(port, "%d\n", n);
1142 
1143         return n;
1144 }
1145 
1146 static int fwtty_chars_in_buffer(struct tty_struct *tty)
1147 {
1148         struct fwtty_port *port = tty->driver_data;
1149         int n;
1150 
1151         spin_lock_bh(&port->lock);
1152         n = dma_fifo_level(&port->tx_fifo);
1153         spin_unlock_bh(&port->lock);
1154 
1155         fwtty_dbg(port, "%d\n", n);
1156 
1157         return n;
1158 }
1159 
1160 static void fwtty_send_xchar(struct tty_struct *tty, char ch)
1161 {
1162         struct fwtty_port *port = tty->driver_data;
1163 
1164         fwtty_dbg(port, "%02x\n", ch);
1165 
1166         fwtty_write_xchar(port, ch);
1167 }
1168 
1169 static void fwtty_throttle(struct tty_struct *tty)
1170 {
1171         struct fwtty_port *port = tty->driver_data;
1172 
1173         /*
1174          * Ignore throttling (but not unthrottling).
1175          * It only makes sense to throttle when data will no longer be
1176          * accepted by the tty flip buffer. For example, it is
1177          * possible for received data to overflow the tty buffer long
1178          * before the line discipline ever has a chance to throttle the driver.
1179          * Additionally, the driver may have already completed the I/O
1180          * but the tty buffer is still emptying, so the line discipline is
1181          * throttling and unthrottling nothing.
1182          */
1183 
1184         ++port->stats.throttled;
1185 }
1186 
1187 static void fwtty_unthrottle(struct tty_struct *tty)
1188 {
1189         struct fwtty_port *port = tty->driver_data;
1190 
1191         fwtty_dbg(port, "CRTSCTS: %d\n", (C_CRTSCTS(tty) != 0));
1192 
1193         fwtty_profile_fifo(port, port->stats.unthrottle);
1194 
1195         spin_lock_bh(&port->lock);
1196         port->mctrl &= ~OOB_RX_THROTTLE;
1197         if (C_CRTSCTS(tty))
1198                 port->mctrl |= TIOCM_RTS;
1199         __fwtty_write_port_status(port);
1200         spin_unlock_bh(&port->lock);
1201 }
1202 
1203 static int check_msr_delta(struct fwtty_port *port, unsigned long mask,
1204                            struct async_icount *prev)
1205 {
1206         struct async_icount now;
1207         int delta;
1208 
1209         now = port->icount;
1210 
1211         delta = ((mask & TIOCM_RNG && prev->rng != now.rng) ||
1212                  (mask & TIOCM_DSR && prev->dsr != now.dsr) ||
1213                  (mask & TIOCM_CAR && prev->dcd != now.dcd) ||
1214                  (mask & TIOCM_CTS && prev->cts != now.cts));
1215 
1216         *prev = now;
1217 
1218         return delta;
1219 }
1220 
1221 static int wait_msr_change(struct fwtty_port *port, unsigned long mask)
1222 {
1223         struct async_icount prev;
1224 
1225         prev = port->icount;
1226 
1227         return wait_event_interruptible(port->port.delta_msr_wait,
1228                                         check_msr_delta(port, mask, &prev));
1229 }
1230 
1231 static int get_serial_info(struct fwtty_port *port,
1232                            struct serial_struct __user *info)
1233 {
1234         struct serial_struct tmp;
1235 
1236         memset(&tmp, 0, sizeof(tmp));
1237 
1238         tmp.type =  PORT_UNKNOWN;
1239         tmp.line =  port->port.tty->index;
1240         tmp.flags = port->port.flags;
1241         tmp.xmit_fifo_size = FWTTY_PORT_TXFIFO_LEN;
1242         tmp.baud_base = 400000000;
1243         tmp.close_delay = port->port.close_delay;
1244 
1245         return (copy_to_user(info, &tmp, sizeof(*info))) ? -EFAULT : 0;
1246 }
1247 
1248 static int set_serial_info(struct fwtty_port *port,
1249                            struct serial_struct __user *info)
1250 {
1251         struct serial_struct tmp;
1252 
1253         if (copy_from_user(&tmp, info, sizeof(tmp)))
1254                 return -EFAULT;
1255 
1256         if (tmp.irq != 0 || tmp.port != 0 || tmp.custom_divisor != 0 ||
1257             tmp.baud_base != 400000000)
1258                 return -EPERM;
1259 
1260         if (!capable(CAP_SYS_ADMIN)) {
1261                 if (((tmp.flags & ~ASYNC_USR_MASK) !=
1262                      (port->port.flags & ~ASYNC_USR_MASK)))
1263                         return -EPERM;
1264         } else {
1265                 port->port.close_delay = tmp.close_delay * HZ / 100;
1266         }
1267 
1268         return 0;
1269 }
1270 
1271 static int fwtty_ioctl(struct tty_struct *tty, unsigned cmd,
1272                        unsigned long arg)
1273 {
1274         struct fwtty_port *port = tty->driver_data;
1275         int err;
1276 
1277         switch (cmd) {
1278         case TIOCGSERIAL:
1279                 mutex_lock(&port->port.mutex);
1280                 err = get_serial_info(port, (void __user *)arg);
1281                 mutex_unlock(&port->port.mutex);
1282                 break;
1283 
1284         case TIOCSSERIAL:
1285                 mutex_lock(&port->port.mutex);
1286                 err = set_serial_info(port, (void __user *)arg);
1287                 mutex_unlock(&port->port.mutex);
1288                 break;
1289 
1290         case TIOCMIWAIT:
1291                 err = wait_msr_change(port, arg);
1292                 break;
1293 
1294         default:
1295                 err = -ENOIOCTLCMD;
1296         }
1297 
1298         return err;
1299 }
1300 
1301 static void fwtty_set_termios(struct tty_struct *tty, struct ktermios *old)
1302 {
1303         struct fwtty_port *port = tty->driver_data;
1304         unsigned baud;
1305 
1306         spin_lock_bh(&port->lock);
1307         baud = set_termios(port, tty);
1308 
1309         if ((baud == 0) && (old->c_cflag & CBAUD)) {
1310                 port->mctrl &= ~(TIOCM_DTR | TIOCM_RTS);
1311         } else if ((baud != 0) && !(old->c_cflag & CBAUD)) {
1312                 if (C_CRTSCTS(tty) || !test_bit(TTY_THROTTLED, &tty->flags))
1313                         port->mctrl |= TIOCM_DTR | TIOCM_RTS;
1314                 else
1315                         port->mctrl |= TIOCM_DTR;
1316         }
1317         __fwtty_write_port_status(port);
1318         spin_unlock_bh(&port->lock);
1319 
1320         if (old->c_cflag & CRTSCTS) {
1321                 if (!C_CRTSCTS(tty)) {
1322                         tty->hw_stopped = 0;
1323                         fwtty_restart_tx(port);
1324                 }
1325         } else if (C_CRTSCTS(tty) && ~port->mstatus & TIOCM_CTS) {
1326                 tty->hw_stopped = 1;
1327         }
1328 }
1329 
1330 /**
1331  * fwtty_break_ctl - start/stop sending breaks
1332  *
1333  * Signals the remote to start or stop generating simulated breaks.
1334  * First, stop dequeueing from the fifo and wait for writer/drain to leave tx
1335  * before signalling the break line status. This guarantees any pending rx will
1336  * be queued to the line discipline before break is simulated on the remote.
1337  * Conversely, turning off break_ctl requires signalling the line status change,
1338  * then enabling tx.
1339  */
1340 static int fwtty_break_ctl(struct tty_struct *tty, int state)
1341 {
1342         struct fwtty_port *port = tty->driver_data;
1343         long ret;
1344 
1345         fwtty_dbg(port, "%d\n", state);
1346 
1347         if (state == -1) {
1348                 set_bit(STOP_TX, &port->flags);
1349                 ret = wait_event_interruptible_timeout(port->wait_tx,
1350                                                !test_bit(IN_TX, &port->flags),
1351                                                10);
1352                 if (ret == 0 || ret == -ERESTARTSYS) {
1353                         clear_bit(STOP_TX, &port->flags);
1354                         fwtty_restart_tx(port);
1355                         return -EINTR;
1356                 }
1357         }
1358 
1359         spin_lock_bh(&port->lock);
1360         port->break_ctl = (state == -1);
1361         __fwtty_write_port_status(port);
1362         spin_unlock_bh(&port->lock);
1363 
1364         if (state == 0) {
1365                 spin_lock_bh(&port->lock);
1366                 dma_fifo_reset(&port->tx_fifo);
1367                 clear_bit(STOP_TX, &port->flags);
1368                 spin_unlock_bh(&port->lock);
1369         }
1370         return 0;
1371 }
1372 
1373 static int fwtty_tiocmget(struct tty_struct *tty)
1374 {
1375         struct fwtty_port *port = tty->driver_data;
1376         unsigned tiocm;
1377 
1378         spin_lock_bh(&port->lock);
1379         tiocm = (port->mctrl & MCTRL_MASK) | (port->mstatus & ~MCTRL_MASK);
1380         spin_unlock_bh(&port->lock);
1381 
1382         fwtty_dbg(port, "%x\n", tiocm);
1383 
1384         return tiocm;
1385 }
1386 
1387 static int fwtty_tiocmset(struct tty_struct *tty, unsigned set, unsigned clear)
1388 {
1389         struct fwtty_port *port = tty->driver_data;
1390 
1391         fwtty_dbg(port, "set: %x clear: %x\n", set, clear);
1392 
1393         /* TODO: simulate loopback if TIOCM_LOOP set */
1394 
1395         spin_lock_bh(&port->lock);
1396         port->mctrl &= ~(clear & MCTRL_MASK & 0xffff);
1397         port->mctrl |= set & MCTRL_MASK & 0xffff;
1398         __fwtty_write_port_status(port);
1399         spin_unlock_bh(&port->lock);
1400         return 0;
1401 }
1402 
1403 static int fwtty_get_icount(struct tty_struct *tty,
1404                             struct serial_icounter_struct *icount)
1405 {
1406         struct fwtty_port *port = tty->driver_data;
1407         struct stats stats;
1408 
1409         memcpy(&stats, &port->stats, sizeof(stats));
1410         if (port->port.console)
1411                 (*port->fwcon_ops->stats)(&stats, port->con_data);
1412 
1413         icount->cts = port->icount.cts;
1414         icount->dsr = port->icount.dsr;
1415         icount->rng = port->icount.rng;
1416         icount->dcd = port->icount.dcd;
1417         icount->rx  = port->icount.rx;
1418         icount->tx  = port->icount.tx + stats.xchars;
1419         icount->frame   = port->icount.frame;
1420         icount->overrun = port->icount.overrun;
1421         icount->parity  = port->icount.parity;
1422         icount->brk     = port->icount.brk;
1423         icount->buf_overrun = port->icount.overrun;
1424         return 0;
1425 }
1426 
1427 static void fwtty_proc_show_port(struct seq_file *m, struct fwtty_port *port)
1428 {
1429         struct stats stats;
1430 
1431         memcpy(&stats, &port->stats, sizeof(stats));
1432         if (port->port.console)
1433                 (*port->fwcon_ops->stats)(&stats, port->con_data);
1434 
1435         seq_printf(m, " addr:%012llx tx:%d rx:%d", port->rx_handler.offset,
1436                    port->icount.tx + stats.xchars, port->icount.rx);
1437         seq_printf(m, " cts:%d dsr:%d rng:%d dcd:%d", port->icount.cts,
1438                    port->icount.dsr, port->icount.rng, port->icount.dcd);
1439         seq_printf(m, " fe:%d oe:%d pe:%d brk:%d", port->icount.frame,
1440                    port->icount.overrun, port->icount.parity, port->icount.brk);
1441 }
1442 
1443 static void fwtty_debugfs_show_port(struct seq_file *m, struct fwtty_port *port)
1444 {
1445         struct stats stats;
1446 
1447         memcpy(&stats, &port->stats, sizeof(stats));
1448         if (port->port.console)
1449                 (*port->fwcon_ops->stats)(&stats, port->con_data);
1450 
1451         seq_printf(m, " dr:%d st:%d err:%d lost:%d", stats.dropped,
1452                    stats.tx_stall, stats.fifo_errs, stats.lost);
1453         seq_printf(m, " pkts:%d thr:%d", stats.sent, stats.throttled);
1454 
1455         if (port->port.console) {
1456                 seq_puts(m, "\n    ");
1457                 (*port->fwcon_ops->proc_show)(m, port->con_data);
1458         }
1459 
1460         fwtty_dump_profile(m, &port->stats);
1461 }
1462 
1463 static void fwtty_debugfs_show_peer(struct seq_file *m, struct fwtty_peer *peer)
1464 {
1465         int generation = peer->generation;
1466 
1467         smp_rmb();
1468         seq_printf(m, " %s:", dev_name(&peer->unit->device));
1469         seq_printf(m, " node:%04x gen:%d", peer->node_id, generation);
1470         seq_printf(m, " sp:%d max:%d guid:%016llx", peer->speed,
1471                    peer->max_payload, (unsigned long long) peer->guid);
1472         seq_printf(m, " mgmt:%012llx", (unsigned long long) peer->mgmt_addr);
1473         seq_printf(m, " addr:%012llx", (unsigned long long) peer->status_addr);
1474         seq_putc(m, '\n');
1475 }
1476 
1477 static int fwtty_proc_show(struct seq_file *m, void *v)
1478 {
1479         struct fwtty_port *port;
1480         int i;
1481 
1482         seq_puts(m, "fwserinfo: 1.0 driver: 1.0\n");
1483         for (i = 0; i < MAX_TOTAL_PORTS && (port = fwtty_port_get(i)); ++i) {
1484                 seq_printf(m, "%2d:", i);
1485                 if (capable(CAP_SYS_ADMIN))
1486                         fwtty_proc_show_port(m, port);
1487                 fwtty_port_put(port);
1488                 seq_puts(m, "\n");
1489         }
1490         return 0;
1491 }
1492 
1493 static int fwtty_debugfs_stats_show(struct seq_file *m, void *v)
1494 {
1495         struct fw_serial *serial = m->private;
1496         struct fwtty_port *port;
1497         int i;
1498 
1499         for (i = 0; i < num_ports; ++i) {
1500                 port = fwtty_port_get(serial->ports[i]->index);
1501                 if (port) {
1502                         seq_printf(m, "%2d:", port->index);
1503                         fwtty_proc_show_port(m, port);
1504                         fwtty_debugfs_show_port(m, port);
1505                         fwtty_port_put(port);
1506                         seq_puts(m, "\n");
1507                 }
1508         }
1509         return 0;
1510 }
1511 
1512 static int fwtty_debugfs_peers_show(struct seq_file *m, void *v)
1513 {
1514         struct fw_serial *serial = m->private;
1515         struct fwtty_peer *peer;
1516 
1517         rcu_read_lock();
1518         seq_printf(m, "card: %s  guid: %016llx\n",
1519                    dev_name(serial->card->device),
1520                    (unsigned long long) serial->card->guid);
1521         list_for_each_entry_rcu(peer, &serial->peer_list, list)
1522                 fwtty_debugfs_show_peer(m, peer);
1523         rcu_read_unlock();
1524         return 0;
1525 }
1526 
1527 static int fwtty_proc_open(struct inode *inode, struct file *fp)
1528 {
1529         return single_open(fp, fwtty_proc_show, NULL);
1530 }
1531 
1532 static int fwtty_stats_open(struct inode *inode, struct file *fp)
1533 {
1534         return single_open(fp, fwtty_debugfs_stats_show, inode->i_private);
1535 }
1536 
1537 static int fwtty_peers_open(struct inode *inode, struct file *fp)
1538 {
1539         return single_open(fp, fwtty_debugfs_peers_show, inode->i_private);
1540 }
1541 
1542 static const struct file_operations fwtty_stats_fops = {
1543         .owner =        THIS_MODULE,
1544         .open =         fwtty_stats_open,
1545         .read =         seq_read,
1546         .llseek =       seq_lseek,
1547         .release =      single_release,
1548 };
1549 
1550 static const struct file_operations fwtty_peers_fops = {
1551         .owner =        THIS_MODULE,
1552         .open =         fwtty_peers_open,
1553         .read =         seq_read,
1554         .llseek =       seq_lseek,
1555         .release =      single_release,
1556 };
1557 
1558 static const struct file_operations fwtty_proc_fops = {
1559         .owner =        THIS_MODULE,
1560         .open =         fwtty_proc_open,
1561         .read =         seq_read,
1562         .llseek =       seq_lseek,
1563         .release =      single_release,
1564 };
1565 
1566 static const struct tty_port_operations fwtty_port_ops = {
1567         .dtr_rts =              fwtty_port_dtr_rts,
1568         .carrier_raised =       fwtty_port_carrier_raised,
1569         .shutdown =             fwtty_port_shutdown,
1570         .activate =             fwtty_port_activate,
1571 };
1572 
1573 static const struct tty_operations fwtty_ops = {
1574         .open =                 fwtty_open,
1575         .close =                fwtty_close,
1576         .hangup =               fwtty_hangup,
1577         .cleanup =              fwtty_cleanup,
1578         .install =              fwtty_install,
1579         .write =                fwtty_write,
1580         .write_room =           fwtty_write_room,
1581         .chars_in_buffer =      fwtty_chars_in_buffer,
1582         .send_xchar =           fwtty_send_xchar,
1583         .throttle =             fwtty_throttle,
1584         .unthrottle =           fwtty_unthrottle,
1585         .ioctl =                fwtty_ioctl,
1586         .set_termios =          fwtty_set_termios,
1587         .break_ctl =            fwtty_break_ctl,
1588         .tiocmget =             fwtty_tiocmget,
1589         .tiocmset =             fwtty_tiocmset,
1590         .get_icount =           fwtty_get_icount,
1591         .proc_fops =            &fwtty_proc_fops,
1592 };
1593 
1594 static const struct tty_operations fwloop_ops = {
1595         .open =                 fwtty_open,
1596         .close =                fwtty_close,
1597         .hangup =               fwtty_hangup,
1598         .cleanup =              fwtty_cleanup,
1599         .install =              fwloop_install,
1600         .write =                fwtty_write,
1601         .write_room =           fwtty_write_room,
1602         .chars_in_buffer =      fwtty_chars_in_buffer,
1603         .send_xchar =           fwtty_send_xchar,
1604         .throttle =             fwtty_throttle,
1605         .unthrottle =           fwtty_unthrottle,
1606         .ioctl =                fwtty_ioctl,
1607         .set_termios =          fwtty_set_termios,
1608         .break_ctl =            fwtty_break_ctl,
1609         .tiocmget =             fwtty_tiocmget,
1610         .tiocmset =             fwtty_tiocmset,
1611         .get_icount =           fwtty_get_icount,
1612 };
1613 
1614 static inline int mgmt_pkt_expected_len(__be16 code)
1615 {
1616         static const struct fwserial_mgmt_pkt pkt;
1617 
1618         switch (be16_to_cpu(code)) {
1619         case FWSC_VIRT_CABLE_PLUG:
1620                 return sizeof(pkt.hdr) + sizeof(pkt.plug_req);
1621 
1622         case FWSC_VIRT_CABLE_PLUG_RSP:  /* | FWSC_RSP_OK */
1623                 return sizeof(pkt.hdr) + sizeof(pkt.plug_rsp);
1624 
1625 
1626         case FWSC_VIRT_CABLE_UNPLUG:
1627         case FWSC_VIRT_CABLE_UNPLUG_RSP:
1628         case FWSC_VIRT_CABLE_PLUG_RSP | FWSC_RSP_NACK:
1629         case FWSC_VIRT_CABLE_UNPLUG_RSP | FWSC_RSP_NACK:
1630                 return sizeof(pkt.hdr);
1631 
1632         default:
1633                 return -1;
1634         }
1635 }
1636 
1637 static inline void fill_plug_params(struct virt_plug_params *params,
1638                                     struct fwtty_port *port)
1639 {
1640         u64 status_addr = port->rx_handler.offset;
1641         u64 fifo_addr = port->rx_handler.offset + 4;
1642         size_t fifo_len = port->rx_handler.length - 4;
1643 
1644         params->status_hi = cpu_to_be32(status_addr >> 32);
1645         params->status_lo = cpu_to_be32(status_addr);
1646         params->fifo_hi = cpu_to_be32(fifo_addr >> 32);
1647         params->fifo_lo = cpu_to_be32(fifo_addr);
1648         params->fifo_len = cpu_to_be32(fifo_len);
1649 }
1650 
1651 static inline void fill_plug_req(struct fwserial_mgmt_pkt *pkt,
1652                                  struct fwtty_port *port)
1653 {
1654         pkt->hdr.code = cpu_to_be16(FWSC_VIRT_CABLE_PLUG);
1655         pkt->hdr.len = cpu_to_be16(mgmt_pkt_expected_len(pkt->hdr.code));
1656         fill_plug_params(&pkt->plug_req, port);
1657 }
1658 
1659 static inline void fill_plug_rsp_ok(struct fwserial_mgmt_pkt *pkt,
1660                                     struct fwtty_port *port)
1661 {
1662         pkt->hdr.code = cpu_to_be16(FWSC_VIRT_CABLE_PLUG_RSP);
1663         pkt->hdr.len = cpu_to_be16(mgmt_pkt_expected_len(pkt->hdr.code));
1664         fill_plug_params(&pkt->plug_rsp, port);
1665 }
1666 
1667 static inline void fill_plug_rsp_nack(struct fwserial_mgmt_pkt *pkt)
1668 {
1669         pkt->hdr.code = cpu_to_be16(FWSC_VIRT_CABLE_PLUG_RSP | FWSC_RSP_NACK);
1670         pkt->hdr.len = cpu_to_be16(mgmt_pkt_expected_len(pkt->hdr.code));
1671 }
1672 
1673 static inline void fill_unplug_req(struct fwserial_mgmt_pkt *pkt)
1674 {
1675         pkt->hdr.code = cpu_to_be16(FWSC_VIRT_CABLE_UNPLUG);
1676         pkt->hdr.len = cpu_to_be16(mgmt_pkt_expected_len(pkt->hdr.code));
1677 }
1678 
1679 static inline void fill_unplug_rsp_nack(struct fwserial_mgmt_pkt *pkt)
1680 {
1681         pkt->hdr.code = cpu_to_be16(FWSC_VIRT_CABLE_UNPLUG_RSP | FWSC_RSP_NACK);
1682         pkt->hdr.len = cpu_to_be16(mgmt_pkt_expected_len(pkt->hdr.code));
1683 }
1684 
1685 static inline void fill_unplug_rsp_ok(struct fwserial_mgmt_pkt *pkt)
1686 {
1687         pkt->hdr.code = cpu_to_be16(FWSC_VIRT_CABLE_UNPLUG_RSP);
1688         pkt->hdr.len = cpu_to_be16(mgmt_pkt_expected_len(pkt->hdr.code));
1689 }
1690 
1691 static void fwserial_virt_plug_complete(struct fwtty_peer *peer,
1692                                         struct virt_plug_params *params)
1693 {
1694         struct fwtty_port *port = peer->port;
1695 
1696         peer->status_addr = be32_to_u64(params->status_hi, params->status_lo);
1697         peer->fifo_addr = be32_to_u64(params->fifo_hi, params->fifo_lo);
1698         peer->fifo_len = be32_to_cpu(params->fifo_len);
1699         peer_set_state(peer, FWPS_ATTACHED);
1700 
1701         /* reconfigure tx_fifo optimally for this peer */
1702         spin_lock_bh(&port->lock);
1703         port->max_payload = min(peer->max_payload, peer->fifo_len);
1704         dma_fifo_change_tx_limit(&port->tx_fifo, port->max_payload);
1705         spin_unlock_bh(&peer->port->lock);
1706 
1707         if (port->port.console && port->fwcon_ops->notify != NULL)
1708                 (*port->fwcon_ops->notify)(FWCON_NOTIFY_ATTACH, port->con_data);
1709 
1710         fwtty_info(&peer->unit, "peer (guid:%016llx) connected on %s\n",
1711                    (unsigned long long)peer->guid, dev_name(port->device));
1712 }
1713 
1714 static inline int fwserial_send_mgmt_sync(struct fwtty_peer *peer,
1715                                           struct fwserial_mgmt_pkt *pkt)
1716 {
1717         int generation;
1718         int rcode, tries = 5;
1719 
1720         do {
1721                 generation = peer->generation;
1722                 smp_rmb();
1723 
1724                 rcode = fw_run_transaction(peer->serial->card,
1725                                            TCODE_WRITE_BLOCK_REQUEST,
1726                                            peer->node_id,
1727                                            generation, peer->speed,
1728                                            peer->mgmt_addr,
1729                                            pkt, be16_to_cpu(pkt->hdr.len));
1730                 if (rcode == RCODE_BUSY || rcode == RCODE_SEND_ERROR ||
1731                     rcode == RCODE_GENERATION) {
1732                         fwtty_dbg(&peer->unit, "mgmt write error: %d\n", rcode);
1733                         continue;
1734                 } else {
1735                         break;
1736                 }
1737         } while (--tries > 0);
1738         return rcode;
1739 }
1740 
1741 /**
1742  * fwserial_claim_port - attempt to claim port @ index for peer
1743  *
1744  * Returns ptr to claimed port or error code (as ERR_PTR())
1745  * Can sleep - must be called from process context
1746  */
1747 static struct fwtty_port *fwserial_claim_port(struct fwtty_peer *peer,
1748                                               int index)
1749 {
1750         struct fwtty_port *port;
1751 
1752         if (index < 0 || index >= num_ports)
1753                 return ERR_PTR(-EINVAL);
1754 
1755         /* must guarantee that previous port releases have completed */
1756         synchronize_rcu();
1757 
1758         port = peer->serial->ports[index];
1759         spin_lock_bh(&port->lock);
1760         if (!rcu_access_pointer(port->peer))
1761                 rcu_assign_pointer(port->peer, peer);
1762         else
1763                 port = ERR_PTR(-EBUSY);
1764         spin_unlock_bh(&port->lock);
1765 
1766         return port;
1767 }
1768 
1769 /**
1770  * fwserial_find_port - find avail port and claim for peer
1771  *
1772  * Returns ptr to claimed port or NULL if none avail
1773  * Can sleep - must be called from process context
1774  */
1775 static struct fwtty_port *fwserial_find_port(struct fwtty_peer *peer)
1776 {
1777         struct fwtty_port **ports = peer->serial->ports;
1778         int i;
1779 
1780         /* must guarantee that previous port releases have completed */
1781         synchronize_rcu();
1782 
1783         /* TODO: implement optional GUID-to-specific port # matching */
1784 
1785         /* find an unattached port (but not the loopback port, if present) */
1786         for (i = 0; i < num_ttys; ++i) {
1787                 spin_lock_bh(&ports[i]->lock);
1788                 if (!ports[i]->peer) {
1789                         /* claim port */
1790                         rcu_assign_pointer(ports[i]->peer, peer);
1791                         spin_unlock_bh(&ports[i]->lock);
1792                         return ports[i];
1793                 }
1794                 spin_unlock_bh(&ports[i]->lock);
1795         }
1796         return NULL;
1797 }
1798 
1799 static void fwserial_release_port(struct fwtty_port *port, bool reset)
1800 {
1801         /* drop carrier (and all other line status) */
1802         if (reset)
1803                 fwtty_update_port_status(port, 0);
1804 
1805         spin_lock_bh(&port->lock);
1806 
1807         /* reset dma fifo max transmission size back to S100 */
1808         port->max_payload = link_speed_to_max_payload(SCODE_100);
1809         dma_fifo_change_tx_limit(&port->tx_fifo, port->max_payload);
1810 
1811         RCU_INIT_POINTER(port->peer, NULL);
1812         spin_unlock_bh(&port->lock);
1813 
1814         if (port->port.console && port->fwcon_ops->notify != NULL)
1815                 (*port->fwcon_ops->notify)(FWCON_NOTIFY_DETACH, port->con_data);
1816 }
1817 
1818 static void fwserial_plug_timeout(unsigned long data)
1819 {
1820         struct fwtty_peer *peer = (struct fwtty_peer *)data;
1821         struct fwtty_port *port;
1822 
1823         spin_lock_bh(&peer->lock);
1824         if (peer->state != FWPS_PLUG_PENDING) {
1825                 spin_unlock_bh(&peer->lock);
1826                 return;
1827         }
1828 
1829         port = peer_revert_state(peer);
1830         spin_unlock_bh(&peer->lock);
1831 
1832         if (port)
1833                 fwserial_release_port(port, false);
1834 }
1835 
1836 /**
1837  * fwserial_connect_peer - initiate virtual cable with peer
1838  *
1839  * Returns 0 if VIRT_CABLE_PLUG request was successfully sent,
1840  * otherwise error code.  Must be called from process context.
1841  */
1842 static int fwserial_connect_peer(struct fwtty_peer *peer)
1843 {
1844         struct fwtty_port *port;
1845         struct fwserial_mgmt_pkt *pkt;
1846         int err, rcode;
1847 
1848         pkt = kmalloc(sizeof(*pkt), GFP_KERNEL);
1849         if (!pkt)
1850                 return -ENOMEM;
1851 
1852         port = fwserial_find_port(peer);
1853         if (!port) {
1854                 fwtty_err(&peer->unit, "avail ports in use\n");
1855                 err = -EBUSY;
1856                 goto free_pkt;
1857         }
1858 
1859         spin_lock_bh(&peer->lock);
1860 
1861         /* only initiate VIRT_CABLE_PLUG if peer is currently not attached */
1862         if (peer->state != FWPS_NOT_ATTACHED) {
1863                 err = -EBUSY;
1864                 goto release_port;
1865         }
1866 
1867         peer->port = port;
1868         peer_set_state(peer, FWPS_PLUG_PENDING);
1869 
1870         fill_plug_req(pkt, peer->port);
1871 
1872         setup_timer(&peer->timer, fwserial_plug_timeout, (unsigned long)peer);
1873         mod_timer(&peer->timer, jiffies + VIRT_CABLE_PLUG_TIMEOUT);
1874         spin_unlock_bh(&peer->lock);
1875 
1876         rcode = fwserial_send_mgmt_sync(peer, pkt);
1877 
1878         spin_lock_bh(&peer->lock);
1879         if (peer->state == FWPS_PLUG_PENDING && rcode != RCODE_COMPLETE) {
1880                 if (rcode == RCODE_CONFLICT_ERROR)
1881                         err = -EAGAIN;
1882                 else
1883                         err = -EIO;
1884                 goto cancel_timer;
1885         }
1886         spin_unlock_bh(&peer->lock);
1887 
1888         kfree(pkt);
1889         return 0;
1890 
1891 cancel_timer:
1892         del_timer(&peer->timer);
1893         peer_revert_state(peer);
1894 release_port:
1895         spin_unlock_bh(&peer->lock);
1896         fwserial_release_port(port, false);
1897 free_pkt:
1898         kfree(pkt);
1899         return err;
1900 }
1901 
1902 /**
1903  * fwserial_close_port -
1904  * HUP the tty (if the tty exists) and unregister the tty device.
1905  * Only used by the unit driver upon unit removal to disconnect and
1906  * cleanup all attached ports
1907  *
1908  * The port reference is put by fwtty_cleanup (if a reference was
1909  * ever taken).
1910  */
1911 static void fwserial_close_port(struct tty_driver *driver,
1912                                 struct fwtty_port *port)
1913 {
1914         struct tty_struct *tty;
1915 
1916         mutex_lock(&port->port.mutex);
1917         tty = tty_port_tty_get(&port->port);
1918         if (tty) {
1919                 tty_vhangup(tty);
1920                 tty_kref_put(tty);
1921         }
1922         mutex_unlock(&port->port.mutex);
1923 
1924         if (driver == fwloop_driver)
1925                 tty_unregister_device(driver, loop_idx(port));
1926         else
1927                 tty_unregister_device(driver, port->index);
1928 }
1929 
1930 /**
1931  * fwserial_lookup - finds first fw_serial associated with card
1932  * @card: fw_card to match
1933  *
1934  * NB: caller must be holding fwserial_list_mutex
1935  */
1936 static struct fw_serial *fwserial_lookup(struct fw_card *card)
1937 {
1938         struct fw_serial *serial;
1939 
1940         list_for_each_entry(serial, &fwserial_list, list) {
1941                 if (card == serial->card)
1942                         return serial;
1943         }
1944 
1945         return NULL;
1946 }
1947 
1948 /**
1949  * __fwserial_lookup_rcu - finds first fw_serial associated with card
1950  * @card: fw_card to match
1951  *
1952  * NB: caller must be inside rcu_read_lock() section
1953  */
1954 static struct fw_serial *__fwserial_lookup_rcu(struct fw_card *card)
1955 {
1956         struct fw_serial *serial;
1957 
1958         list_for_each_entry_rcu(serial, &fwserial_list, list) {
1959                 if (card == serial->card)
1960                         return serial;
1961         }
1962 
1963         return NULL;
1964 }
1965 
1966 /**
1967  * __fwserial_peer_by_node_id - finds a peer matching the given generation + id
1968  *
1969  * If a matching peer could not be found for the specified generation/node id,
1970  * this could be because:
1971  * a) the generation has changed and one of the nodes hasn't updated yet
1972  * b) the remote node has created its remote unit device before this
1973  *    local node has created its corresponding remote unit device
1974  * In either case, the remote node should retry
1975  *
1976  * Note: caller must be in rcu_read_lock() section
1977  */
1978 static struct fwtty_peer *__fwserial_peer_by_node_id(struct fw_card *card,
1979                                                      int generation, int id)
1980 {
1981         struct fw_serial *serial;
1982         struct fwtty_peer *peer;
1983 
1984         serial = __fwserial_lookup_rcu(card);
1985         if (!serial) {
1986                 /*
1987                  * Something is very wrong - there should be a matching
1988                  * fw_serial structure for every fw_card. Maybe the remote node
1989                  * has created its remote unit device before this driver has
1990                  * been probed for any unit devices...
1991                  */
1992                 fwtty_err(card, "unknown card (guid %016llx)\n",
1993                           (unsigned long long) card->guid);
1994                 return NULL;
1995         }
1996 
1997         list_for_each_entry_rcu(peer, &serial->peer_list, list) {
1998                 int g = peer->generation;
1999 
2000                 smp_rmb();
2001                 if (generation == g && id == peer->node_id)
2002                         return peer;
2003         }
2004 
2005         return NULL;
2006 }
2007 
2008 #ifdef DEBUG
2009 static void __dump_peer_list(struct fw_card *card)
2010 {
2011         struct fw_serial *serial;
2012         struct fwtty_peer *peer;
2013 
2014         serial = __fwserial_lookup_rcu(card);
2015         if (!serial)
2016                 return;
2017 
2018         list_for_each_entry_rcu(peer, &serial->peer_list, list) {
2019                 int g = peer->generation;
2020 
2021                 smp_rmb();
2022                 fwtty_dbg(card, "peer(%d:%x) guid: %016llx\n",
2023                           g, peer->node_id, (unsigned long long) peer->guid);
2024         }
2025 }
2026 #else
2027 #define __dump_peer_list(s)
2028 #endif
2029 
2030 static void fwserial_auto_connect(struct work_struct *work)
2031 {
2032         struct fwtty_peer *peer = to_peer(to_delayed_work(work), connect);
2033         int err;
2034 
2035         err = fwserial_connect_peer(peer);
2036         if (err == -EAGAIN && ++peer->connect_retries < MAX_CONNECT_RETRIES)
2037                 schedule_delayed_work(&peer->connect, CONNECT_RETRY_DELAY);
2038 }
2039 
2040 static void fwserial_peer_workfn(struct work_struct *work)
2041 {
2042         struct fwtty_peer *peer = to_peer(work, work);
2043 
2044         peer->workfn(work);
2045 }
2046 
2047 /**
2048  * fwserial_add_peer - add a newly probed 'serial' unit device as a 'peer'
2049  * @serial: aggregate representing the specific fw_card to add the peer to
2050  * @unit: 'peer' to create and add to peer_list of serial
2051  *
2052  * Adds a 'peer' (ie, a local or remote 'serial' unit device) to the list of
2053  * peers for a specific fw_card. Optionally, auto-attach this peer to an
2054  * available tty port. This function is called either directly or indirectly
2055  * as a result of a 'serial' unit device being created & probed.
2056  *
2057  * Note: this function is serialized with fwserial_remove_peer() by the
2058  * fwserial_list_mutex held in fwserial_probe().
2059  *
2060  * A 1:1 correspondence between an fw_unit and an fwtty_peer is maintained
2061  * via the dev_set_drvdata() for the device of the fw_unit.
2062  */
2063 static int fwserial_add_peer(struct fw_serial *serial, struct fw_unit *unit)
2064 {
2065         struct device *dev = &unit->device;
2066         struct fw_device  *parent = fw_parent_device(unit);
2067         struct fwtty_peer *peer;
2068         struct fw_csr_iterator ci;
2069         int key, val;
2070         int generation;
2071 
2072         peer = kzalloc(sizeof(*peer), GFP_KERNEL);
2073         if (!peer)
2074                 return -ENOMEM;
2075 
2076         peer_set_state(peer, FWPS_NOT_ATTACHED);
2077 
2078         dev_set_drvdata(dev, peer);
2079         peer->unit = unit;
2080         peer->guid = (u64)parent->config_rom[3] << 32 | parent->config_rom[4];
2081         peer->speed = parent->max_speed;
2082         peer->max_payload = min(device_max_receive(parent),
2083                                 link_speed_to_max_payload(peer->speed));
2084 
2085         generation = parent->generation;
2086         smp_rmb();
2087         peer->node_id = parent->node_id;
2088         smp_wmb();
2089         peer->generation = generation;
2090 
2091         /* retrieve the mgmt bus addr from the unit directory */
2092         fw_csr_iterator_init(&ci, unit->directory);
2093         while (fw_csr_iterator_next(&ci, &key, &val)) {
2094                 if (key == (CSR_OFFSET | CSR_DEPENDENT_INFO)) {
2095                         peer->mgmt_addr = CSR_REGISTER_BASE + 4 * val;
2096                         break;
2097                 }
2098         }
2099         if (peer->mgmt_addr == 0ULL) {
2100                 /*
2101                  * No mgmt address effectively disables VIRT_CABLE_PLUG -
2102                  * this peer will not be able to attach to a remote
2103                  */
2104                 peer_set_state(peer, FWPS_NO_MGMT_ADDR);
2105         }
2106 
2107         spin_lock_init(&peer->lock);
2108         peer->port = NULL;
2109 
2110         init_timer(&peer->timer);
2111         INIT_WORK(&peer->work, fwserial_peer_workfn);
2112         INIT_DELAYED_WORK(&peer->connect, fwserial_auto_connect);
2113 
2114         /* associate peer with specific fw_card */
2115         peer->serial = serial;
2116         list_add_rcu(&peer->list, &serial->peer_list);
2117 
2118         fwtty_info(&peer->unit, "peer added (guid:%016llx)\n",
2119                    (unsigned long long)peer->guid);
2120 
2121         /* identify the local unit & virt cable to loopback port */
2122         if (parent->is_local) {
2123                 serial->self = peer;
2124                 if (create_loop_dev) {
2125                         struct fwtty_port *port;
2126 
2127                         port = fwserial_claim_port(peer, num_ttys);
2128                         if (!IS_ERR(port)) {
2129                                 struct virt_plug_params params;
2130 
2131                                 spin_lock_bh(&peer->lock);
2132                                 peer->port = port;
2133                                 fill_plug_params(&params, port);
2134                                 fwserial_virt_plug_complete(peer, &params);
2135                                 spin_unlock_bh(&peer->lock);
2136 
2137                                 fwtty_write_port_status(port);
2138                         }
2139                 }
2140 
2141         } else if (auto_connect) {
2142                 /* auto-attach to remote units only (if policy allows) */
2143                 schedule_delayed_work(&peer->connect, 1);
2144         }
2145 
2146         return 0;
2147 }
2148 
2149 /**
2150  * fwserial_remove_peer - remove a 'serial' unit device as a 'peer'
2151  *
2152  * Remove a 'peer' from its list of peers. This function is only
2153  * called by fwserial_remove() on bus removal of the unit device.
2154  *
2155  * Note: this function is serialized with fwserial_add_peer() by the
2156  * fwserial_list_mutex held in fwserial_remove().
2157  */
2158 static void fwserial_remove_peer(struct fwtty_peer *peer)
2159 {
2160         struct fwtty_port *port;
2161 
2162         spin_lock_bh(&peer->lock);
2163         peer_set_state(peer, FWPS_GONE);
2164         spin_unlock_bh(&peer->lock);
2165 
2166         cancel_delayed_work_sync(&peer->connect);
2167         cancel_work_sync(&peer->work);
2168 
2169         spin_lock_bh(&peer->lock);
2170         /* if this unit is the local unit, clear link */
2171         if (peer == peer->serial->self)
2172                 peer->serial->self = NULL;
2173 
2174         /* cancel the request timeout timer (if running) */
2175         del_timer(&peer->timer);
2176 
2177         port = peer->port;
2178         peer->port = NULL;
2179 
2180         list_del_rcu(&peer->list);
2181 
2182         fwtty_info(&peer->unit, "peer removed (guid:%016llx)\n",
2183                    (unsigned long long)peer->guid);
2184 
2185         spin_unlock_bh(&peer->lock);
2186 
2187         if (port)
2188                 fwserial_release_port(port, true);
2189 
2190         synchronize_rcu();
2191         kfree(peer);
2192 }
2193 
2194 /**
2195  * fwserial_create - init everything to create TTYs for a specific fw_card
2196  * @unit: fw_unit for first 'serial' unit device probed for this fw_card
2197  *
2198  * This function inits the aggregate structure (an fw_serial instance)
2199  * used to manage the TTY ports registered by a specific fw_card. Also, the
2200  * unit device is added as the first 'peer'.
2201  *
2202  * This unit device may represent a local unit device (as specified by the
2203  * config ROM unit directory) or it may represent a remote unit device
2204  * (as specified by the reading of the remote node's config ROM).
2205  *
2206  * Returns 0 to indicate "ownership" of the unit device, or a negative errno
2207  * value to indicate which error.
2208  */
2209 static int fwserial_create(struct fw_unit *unit)
2210 {
2211         struct fw_device *parent = fw_parent_device(unit);
2212         struct fw_card *card = parent->card;
2213         struct fw_serial *serial;
2214         struct fwtty_port *port;
2215         struct device *tty_dev;
2216         int i, j;
2217         int err;
2218 
2219         serial = kzalloc(sizeof(*serial), GFP_KERNEL);
2220         if (!serial)
2221                 return -ENOMEM;
2222 
2223         kref_init(&serial->kref);
2224         serial->card = card;
2225         INIT_LIST_HEAD(&serial->peer_list);
2226 
2227         for (i = 0; i < num_ports; ++i) {
2228                 port = kzalloc(sizeof(*port), GFP_KERNEL);
2229                 if (!port) {
2230                         err = -ENOMEM;
2231                         goto free_ports;
2232                 }
2233                 tty_port_init(&port->port);
2234                 port->index = FWTTY_INVALID_INDEX;
2235                 port->port.ops = &fwtty_port_ops;
2236                 port->serial = serial;
2237                 tty_buffer_set_limit(&port->port, 128 * 1024);
2238 
2239                 spin_lock_init(&port->lock);
2240                 INIT_DELAYED_WORK(&port->drain, fwtty_drain_tx);
2241                 INIT_DELAYED_WORK(&port->emit_breaks, fwtty_emit_breaks);
2242                 INIT_WORK(&port->hangup, fwtty_do_hangup);
2243                 init_waitqueue_head(&port->wait_tx);
2244                 port->max_payload = link_speed_to_max_payload(SCODE_100);
2245                 dma_fifo_init(&port->tx_fifo);
2246 
2247                 RCU_INIT_POINTER(port->peer, NULL);
2248                 serial->ports[i] = port;
2249 
2250                 /* get unique bus addr region for port's status & recv fifo */
2251                 port->rx_handler.length = FWTTY_PORT_RXFIFO_LEN + 4;
2252                 port->rx_handler.address_callback = fwtty_port_handler;
2253                 port->rx_handler.callback_data = port;
2254                 /*
2255                  * XXX: use custom memory region above cpu physical memory addrs
2256                  * this will ease porting to 64-bit firewire adapters
2257                  */
2258                 err = fw_core_add_address_handler(&port->rx_handler,
2259                                                   &fw_high_memory_region);
2260                 if (err) {
2261                         kfree(port);
2262                         goto free_ports;
2263                 }
2264         }
2265         /* preserve i for error cleanup */
2266 
2267         err = fwtty_ports_add(serial);
2268         if (err) {
2269                 fwtty_err(&unit, "no space in port table\n");
2270                 goto free_ports;
2271         }
2272 
2273         for (j = 0; j < num_ttys; ++j) {
2274                 tty_dev = tty_port_register_device(&serial->ports[j]->port,
2275                                                    fwtty_driver,
2276                                                    serial->ports[j]->index,
2277                                                    card->device);
2278                 if (IS_ERR(tty_dev)) {
2279                         err = PTR_ERR(tty_dev);
2280                         fwtty_err(&unit, "register tty device error (%d)\n",
2281                                   err);
2282                         goto unregister_ttys;
2283                 }
2284 
2285                 serial->ports[j]->device = tty_dev;
2286         }
2287         /* preserve j for error cleanup */
2288 
2289         if (create_loop_dev) {
2290                 struct device *loop_dev;
2291 
2292                 loop_dev = tty_port_register_device(&serial->ports[j]->port,
2293                                                     fwloop_driver,
2294                                                     loop_idx(serial->ports[j]),
2295                                                     card->device);
2296                 if (IS_ERR(loop_dev)) {
2297                         err = PTR_ERR(loop_dev);
2298                         fwtty_err(&unit, "create loop device failed (%d)\n",
2299                                   err);
2300                         goto unregister_ttys;
2301                 }
2302                 serial->ports[j]->device = loop_dev;
2303                 serial->ports[j]->loopback = true;
2304         }
2305 
2306         if (!IS_ERR_OR_NULL(fwserial_debugfs)) {
2307                 serial->debugfs = debugfs_create_dir(dev_name(&unit->device),
2308                                                      fwserial_debugfs);
2309                 if (!IS_ERR_OR_NULL(serial->debugfs)) {
2310                         debugfs_create_file("peers", 0444, serial->debugfs,
2311                                             serial, &fwtty_peers_fops);
2312                         debugfs_create_file("stats", 0444, serial->debugfs,
2313                                             serial, &fwtty_stats_fops);
2314                 }
2315         }
2316 
2317         list_add_rcu(&serial->list, &fwserial_list);
2318 
2319         fwtty_notice(&unit, "TTY over FireWire on device %s (guid %016llx)\n",
2320                      dev_name(card->device), (unsigned long long) card->guid);
2321 
2322         err = fwserial_add_peer(serial, unit);
2323         if (!err)
2324                 return 0;
2325 
2326         fwtty_err(&unit, "unable to add peer unit device (%d)\n", err);
2327 
2328         /* fall-through to error processing */
2329         debugfs_remove_recursive(serial->debugfs);
2330 
2331         list_del_rcu(&serial->list);
2332         if (create_loop_dev)
2333                 tty_unregister_device(fwloop_driver,
2334                                       loop_idx(serial->ports[j]));
2335 unregister_ttys:
2336         for (--j; j >= 0; --j)
2337                 tty_unregister_device(fwtty_driver, serial->ports[j]->index);
2338         kref_put(&serial->kref, fwserial_destroy);
2339         return err;
2340 
2341 free_ports:
2342         for (--i; i >= 0; --i) {
2343                 tty_port_destroy(&serial->ports[i]->port);
2344                 kfree(serial->ports[i]);
2345         }
2346         kfree(serial);
2347         return err;
2348 }
2349 
2350 /**
2351  * fwserial_probe: bus probe function for firewire 'serial' unit devices
2352  *
2353  * A 'serial' unit device is created and probed as a result of:
2354  * - declaring a ieee1394 bus id table for 'devices' matching a fabricated
2355  *   'serial' unit specifier id
2356  * - adding a unit directory to the config ROM(s) for a 'serial' unit
2357  *
2358  * The firewire core registers unit devices by enumerating unit directories
2359  * of a node's config ROM after reading the config ROM when a new node is
2360  * added to the bus topology after a bus reset.
2361  *
2362  * The practical implications of this are:
2363  * - this probe is called for both local and remote nodes that have a 'serial'
2364  *   unit directory in their config ROM (that matches the specifiers in
2365  *   fwserial_id_table).
2366  * - no specific order is enforced for local vs. remote unit devices
2367  *
2368  * This unit driver copes with the lack of specific order in the same way the
2369  * firewire net driver does -- each probe, for either a local or remote unit
2370  * device, is treated as a 'peer' (has a struct fwtty_peer instance) and the
2371  * first peer created for a given fw_card (tracked by the global fwserial_list)
2372  * creates the underlying TTYs (aggregated in a fw_serial instance).
2373  *
2374  * NB: an early attempt to differentiate local & remote unit devices by creating
2375  *     peers only for remote units and fw_serial instances (with their
2376  *     associated TTY devices) only for local units was discarded. Managing
2377  *     the peer lifetimes on device removal proved too complicated.
2378  *
2379  * fwserial_probe/fwserial_remove are effectively serialized by the
2380  * fwserial_list_mutex. This is necessary because the addition of the first peer
2381  * for a given fw_card will trigger the creation of the fw_serial for that
2382  * fw_card, which must not simultaneously contend with the removal of the
2383  * last peer for a given fw_card triggering the destruction of the same
2384  * fw_serial for the same fw_card.
2385  */
2386 static int fwserial_probe(struct fw_unit *unit,
2387                           const struct ieee1394_device_id *id)
2388 {
2389         struct fw_serial *serial;
2390         int err;
2391 
2392         mutex_lock(&fwserial_list_mutex);
2393         serial = fwserial_lookup(fw_parent_device(unit)->card);
2394         if (!serial)
2395                 err = fwserial_create(unit);
2396         else
2397                 err = fwserial_add_peer(serial, unit);
2398         mutex_unlock(&fwserial_list_mutex);
2399         return err;
2400 }
2401 
2402 /**
2403  * fwserial_remove: bus removal function for firewire 'serial' unit devices
2404  *
2405  * The corresponding 'peer' for this unit device is removed from the list of
2406  * peers for the associated fw_serial (which has a 1:1 correspondence with a
2407  * specific fw_card). If this is the last peer being removed, then trigger
2408  * the destruction of the underlying TTYs.
2409  */
2410 static void fwserial_remove(struct fw_unit *unit)
2411 {
2412         struct fwtty_peer *peer = dev_get_drvdata(&unit->device);
2413         struct fw_serial *serial = peer->serial;
2414         int i;
2415 
2416         mutex_lock(&fwserial_list_mutex);
2417         fwserial_remove_peer(peer);
2418 
2419         if (list_empty(&serial->peer_list)) {
2420                 /* unlink from the fwserial_list here */
2421                 list_del_rcu(&serial->list);
2422 
2423                 debugfs_remove_recursive(serial->debugfs);
2424 
2425                 for (i = 0; i < num_ttys; ++i)
2426                         fwserial_close_port(fwtty_driver, serial->ports[i]);
2427                 if (create_loop_dev)
2428                         fwserial_close_port(fwloop_driver, serial->ports[i]);
2429                 kref_put(&serial->kref, fwserial_destroy);
2430         }
2431         mutex_unlock(&fwserial_list_mutex);
2432 }
2433 
2434 /**
2435  * fwserial_update: bus update function for 'firewire' serial unit devices
2436  *
2437  * Updates the new node_id and bus generation for this peer. Note that locking
2438  * is unnecessary; but careful memory barrier usage is important to enforce the
2439  * load and store order of generation & node_id.
2440  *
2441  * The fw-core orders the write of node_id before generation in the parent
2442  * fw_device to ensure that a stale node_id cannot be used with a current
2443  * bus generation. So the generation value must be read before the node_id.
2444  *
2445  * In turn, this orders the write of node_id before generation in the peer to
2446  * also ensure a stale node_id cannot be used with a current bus generation.
2447  */
2448 static void fwserial_update(struct fw_unit *unit)
2449 {
2450         struct fw_device *parent = fw_parent_device(unit);
2451         struct fwtty_peer *peer = dev_get_drvdata(&unit->device);
2452         int generation;
2453 
2454         generation = parent->generation;
2455         smp_rmb();
2456         peer->node_id = parent->node_id;
2457         smp_wmb();
2458         peer->generation = generation;
2459 }
2460 
2461 static const struct ieee1394_device_id fwserial_id_table[] = {
2462         {
2463                 .match_flags  = IEEE1394_MATCH_SPECIFIER_ID |
2464                                 IEEE1394_MATCH_VERSION,
2465                 .specifier_id = LINUX_VENDOR_ID,
2466                 .version      = FWSERIAL_VERSION,
2467         },
2468         { }
2469 };
2470 
2471 static struct fw_driver fwserial_driver = {
2472         .driver = {
2473                 .owner  = THIS_MODULE,
2474                 .name   = KBUILD_MODNAME,
2475                 .bus    = &fw_bus_type,
2476         },
2477         .probe    = fwserial_probe,
2478         .update   = fwserial_update,
2479         .remove   = fwserial_remove,
2480         .id_table = fwserial_id_table,
2481 };
2482 
2483 #define FW_UNIT_SPECIFIER(id)   ((CSR_SPECIFIER_ID << 24) | (id))
2484 #define FW_UNIT_VERSION(ver)    ((CSR_VERSION << 24) | (ver))
2485 #define FW_UNIT_ADDRESS(ofs)    (((CSR_OFFSET | CSR_DEPENDENT_INFO) << 24)  \
2486                                  | (((ofs) - CSR_REGISTER_BASE) >> 2))
2487 /* XXX: config ROM definitons could be improved with semi-automated offset
2488  * and length calculation
2489  */
2490 #define FW_ROM_LEN(quads)       ((quads) << 16)
2491 #define FW_ROM_DESCRIPTOR(ofs)  (((CSR_LEAF | CSR_DESCRIPTOR) << 24) | (ofs))
2492 
2493 struct fwserial_unit_directory_data {
2494         u32     len_crc;
2495         u32     unit_specifier;
2496         u32     unit_sw_version;
2497         u32     unit_addr_offset;
2498         u32     desc1_ofs;
2499         u32     desc1_len_crc;
2500         u32     desc1_data[5];
2501 } __packed;
2502 
2503 static struct fwserial_unit_directory_data fwserial_unit_directory_data = {
2504         .len_crc = FW_ROM_LEN(4),
2505         .unit_specifier = FW_UNIT_SPECIFIER(LINUX_VENDOR_ID),
2506         .unit_sw_version = FW_UNIT_VERSION(FWSERIAL_VERSION),
2507         .desc1_ofs = FW_ROM_DESCRIPTOR(1),
2508         .desc1_len_crc = FW_ROM_LEN(5),
2509         .desc1_data = {
2510                 0x00000000,                     /*   type = text            */
2511                 0x00000000,                     /*   enc = ASCII, lang EN   */
2512                 0x4c696e75,                     /* 'Linux TTY'              */
2513                 0x78205454,
2514                 0x59000000,
2515         },
2516 };
2517 
2518 static struct fw_descriptor fwserial_unit_directory = {
2519         .length = sizeof(fwserial_unit_directory_data) / sizeof(u32),
2520         .key    = (CSR_DIRECTORY | CSR_UNIT) << 24,
2521         .data   = (u32 *)&fwserial_unit_directory_data,
2522 };
2523 
2524 /*
2525  * The management address is in the unit space region but above other known
2526  * address users (to keep wild writes from causing havoc)
2527  */
2528 static const struct fw_address_region fwserial_mgmt_addr_region = {
2529         .start = CSR_REGISTER_BASE + 0x1e0000ULL,
2530         .end = 0x1000000000000ULL,
2531 };
2532 
2533 static struct fw_address_handler fwserial_mgmt_addr_handler;
2534 
2535 /**
2536  * fwserial_handle_plug_req - handle VIRT_CABLE_PLUG request work
2537  * @work: ptr to peer->work
2538  *
2539  * Attempts to complete the VIRT_CABLE_PLUG handshake sequence for this peer.
2540  *
2541  * This checks for a collided request-- ie, that a VIRT_CABLE_PLUG request was
2542  * already sent to this peer. If so, the collision is resolved by comparing
2543  * guid values; the loser sends the plug response.
2544  *
2545  * Note: if an error prevents a response, don't do anything -- the
2546  * remote will timeout its request.
2547  */
2548 static void fwserial_handle_plug_req(struct work_struct *work)
2549 {
2550         struct fwtty_peer *peer = to_peer(work, work);
2551         struct virt_plug_params *plug_req = &peer->work_params.plug_req;
2552         struct fwtty_port *port;
2553         struct fwserial_mgmt_pkt *pkt;
2554         int rcode;
2555 
2556         pkt = kmalloc(sizeof(*pkt), GFP_KERNEL);
2557         if (!pkt)
2558                 return;
2559 
2560         port = fwserial_find_port(peer);
2561 
2562         spin_lock_bh(&peer->lock);
2563 
2564         switch (peer->state) {
2565         case FWPS_NOT_ATTACHED:
2566                 if (!port) {
2567                         fwtty_err(&peer->unit, "no more ports avail\n");
2568                         fill_plug_rsp_nack(pkt);
2569                 } else {
2570                         peer->port = port;
2571                         fill_plug_rsp_ok(pkt, peer->port);
2572                         peer_set_state(peer, FWPS_PLUG_RESPONDING);
2573                         /* don't release claimed port */
2574                         port = NULL;
2575                 }
2576                 break;
2577 
2578         case FWPS_PLUG_PENDING:
2579                 if (peer->serial->card->guid > peer->guid)
2580                         goto cleanup;
2581 
2582                 /* We lost - hijack the already-claimed port and send ok */
2583                 del_timer(&peer->timer);
2584                 fill_plug_rsp_ok(pkt, peer->port);
2585                 peer_set_state(peer, FWPS_PLUG_RESPONDING);
2586                 break;
2587 
2588         default:
2589                 fill_plug_rsp_nack(pkt);
2590         }
2591 
2592         spin_unlock_bh(&peer->lock);
2593         if (port)
2594                 fwserial_release_port(port, false);
2595 
2596         rcode = fwserial_send_mgmt_sync(peer, pkt);
2597 
2598         spin_lock_bh(&peer->lock);
2599         if (peer->state == FWPS_PLUG_RESPONDING) {
2600                 if (rcode == RCODE_COMPLETE) {
2601                         struct fwtty_port *tmp = peer->port;
2602 
2603                         fwserial_virt_plug_complete(peer, plug_req);
2604                         spin_unlock_bh(&peer->lock);
2605 
2606                         fwtty_write_port_status(tmp);
2607                         spin_lock_bh(&peer->lock);
2608                 } else {
2609                         fwtty_err(&peer->unit, "PLUG_RSP error (%d)\n", rcode);
2610                         port = peer_revert_state(peer);
2611                 }
2612         }
2613 cleanup:
2614         spin_unlock_bh(&peer->lock);
2615         if (port)
2616                 fwserial_release_port(port, false);
2617         kfree(pkt);
2618 }
2619 
2620 static void fwserial_handle_unplug_req(struct work_struct *work)
2621 {
2622         struct fwtty_peer *peer = to_peer(work, work);
2623         struct fwtty_port *port = NULL;
2624         struct fwserial_mgmt_pkt *pkt;
2625         int rcode;
2626 
2627         pkt = kmalloc(sizeof(*pkt), GFP_KERNEL);
2628         if (!pkt)
2629                 return;
2630 
2631         spin_lock_bh(&peer->lock);
2632 
2633         switch (peer->state) {
2634         case FWPS_ATTACHED:
2635                 fill_unplug_rsp_ok(pkt);
2636                 peer_set_state(peer, FWPS_UNPLUG_RESPONDING);
2637                 break;
2638 
2639         case FWPS_UNPLUG_PENDING:
2640                 if (peer->serial->card->guid > peer->guid)
2641                         goto cleanup;
2642 
2643                 /* We lost - send unplug rsp */
2644                 del_timer(&peer->timer);
2645                 fill_unplug_rsp_ok(pkt);
2646                 peer_set_state(peer, FWPS_UNPLUG_RESPONDING);
2647                 break;
2648 
2649         default:
2650                 fill_unplug_rsp_nack(pkt);
2651         }
2652 
2653         spin_unlock_bh(&peer->lock);
2654 
2655         rcode = fwserial_send_mgmt_sync(peer, pkt);
2656 
2657         spin_lock_bh(&peer->lock);
2658         if (peer->state == FWPS_UNPLUG_RESPONDING) {
2659                 if (rcode != RCODE_COMPLETE)
2660                         fwtty_err(&peer->unit, "UNPLUG_RSP error (%d)\n",
2661                                   rcode);
2662                 port = peer_revert_state(peer);
2663         }
2664 cleanup:
2665         spin_unlock_bh(&peer->lock);
2666         if (port)
2667                 fwserial_release_port(port, true);
2668         kfree(pkt);
2669 }
2670 
2671 static int fwserial_parse_mgmt_write(struct fwtty_peer *peer,
2672                                      struct fwserial_mgmt_pkt *pkt,
2673                                      unsigned long long addr,
2674                                      size_t len)
2675 {
2676         struct fwtty_port *port = NULL;
2677         bool reset = false;
2678         int rcode;
2679 
2680         if (addr != fwserial_mgmt_addr_handler.offset || len < sizeof(pkt->hdr))
2681                 return RCODE_ADDRESS_ERROR;
2682 
2683         if (len != be16_to_cpu(pkt->hdr.len) ||
2684             len != mgmt_pkt_expected_len(pkt->hdr.code))
2685                 return RCODE_DATA_ERROR;
2686 
2687         spin_lock_bh(&peer->lock);
2688         if (peer->state == FWPS_GONE) {
2689                 /*
2690                  * This should never happen - it would mean that the
2691                  * remote unit that just wrote this transaction was
2692                  * already removed from the bus -- and the removal was
2693                  * processed before we rec'd this transaction
2694                  */
2695                 fwtty_err(&peer->unit, "peer already removed\n");
2696                 spin_unlock_bh(&peer->lock);
2697                 return RCODE_ADDRESS_ERROR;
2698         }
2699 
2700         rcode = RCODE_COMPLETE;
2701 
2702         fwtty_dbg(&peer->unit, "mgmt: hdr.code: %04hx\n", pkt->hdr.code);
2703 
2704         switch (be16_to_cpu(pkt->hdr.code) & FWSC_CODE_MASK) {
2705         case FWSC_VIRT_CABLE_PLUG:
2706                 if (work_pending(&peer->work)) {
2707                         fwtty_err(&peer->unit, "plug req: busy\n");
2708                         rcode = RCODE_CONFLICT_ERROR;
2709 
2710                 } else {
2711                         peer->work_params.plug_req = pkt->plug_req;
2712                         peer->workfn = fwserial_handle_plug_req;
2713                         queue_work(system_unbound_wq, &peer->work);
2714                 }
2715                 break;
2716 
2717         case FWSC_VIRT_CABLE_PLUG_RSP:
2718                 if (peer->state != FWPS_PLUG_PENDING) {
2719                         rcode = RCODE_CONFLICT_ERROR;
2720 
2721                 } else if (be16_to_cpu(pkt->hdr.code) & FWSC_RSP_NACK) {
2722                         fwtty_notice(&peer->unit, "NACK plug rsp\n");
2723                         port = peer_revert_state(peer);
2724 
2725                 } else {
2726                         struct fwtty_port *tmp = peer->port;
2727 
2728                         fwserial_virt_plug_complete(peer, &pkt->plug_rsp);
2729                         spin_unlock_bh(&peer->lock);
2730 
2731                         fwtty_write_port_status(tmp);
2732                         spin_lock_bh(&peer->lock);
2733                 }
2734                 break;
2735 
2736         case FWSC_VIRT_CABLE_UNPLUG:
2737                 if (work_pending(&peer->work)) {
2738                         fwtty_err(&peer->unit, "unplug req: busy\n");
2739                         rcode = RCODE_CONFLICT_ERROR;
2740                 } else {
2741                         peer->workfn = fwserial_handle_unplug_req;
2742                         queue_work(system_unbound_wq, &peer->work);
2743                 }
2744                 break;
2745 
2746         case FWSC_VIRT_CABLE_UNPLUG_RSP:
2747                 if (peer->state != FWPS_UNPLUG_PENDING) {
2748                         rcode = RCODE_CONFLICT_ERROR;
2749                 } else {
2750                         if (be16_to_cpu(pkt->hdr.code) & FWSC_RSP_NACK)
2751                                 fwtty_notice(&peer->unit, "NACK unplug?\n");
2752                         port = peer_revert_state(peer);
2753                         reset = true;
2754                 }
2755                 break;
2756 
2757         default:
2758                 fwtty_err(&peer->unit, "unknown mgmt code %d\n",
2759                           be16_to_cpu(pkt->hdr.code));
2760                 rcode = RCODE_DATA_ERROR;
2761         }
2762         spin_unlock_bh(&peer->lock);
2763 
2764         if (port)
2765                 fwserial_release_port(port, reset);
2766 
2767         return rcode;
2768 }
2769 
2770 /**
2771  * fwserial_mgmt_handler: bus address handler for mgmt requests
2772  * @parameters: fw_address_callback_t as specified by firewire core interface
2773  *
2774  * This handler is responsible for handling virtual cable requests from remotes
2775  * for all cards.
2776  */
2777 static void fwserial_mgmt_handler(struct fw_card *card,
2778                                   struct fw_request *request,
2779                                   int tcode, int destination, int source,
2780                                   int generation,
2781                                   unsigned long long addr,
2782                                   void *data, size_t len,
2783                                   void *callback_data)
2784 {
2785         struct fwserial_mgmt_pkt *pkt = data;
2786         struct fwtty_peer *peer;
2787         int rcode;
2788 
2789         rcu_read_lock();
2790         peer = __fwserial_peer_by_node_id(card, generation, source);
2791         if (!peer) {
2792                 fwtty_dbg(card, "peer(%d:%x) not found\n", generation, source);
2793                 __dump_peer_list(card);
2794                 rcode = RCODE_CONFLICT_ERROR;
2795 
2796         } else {
2797                 switch (tcode) {
2798                 case TCODE_WRITE_BLOCK_REQUEST:
2799                         rcode = fwserial_parse_mgmt_write(peer, pkt, addr, len);
2800                         break;
2801 
2802                 default:
2803                         rcode = RCODE_TYPE_ERROR;
2804                 }
2805         }
2806 
2807         rcu_read_unlock();
2808         fw_send_response(card, request, rcode);
2809 }
2810 
2811 static int __init fwserial_init(void)
2812 {
2813         int err, num_loops = !!(create_loop_dev);
2814 
2815         /* XXX: placeholder for a "firewire" debugfs node */
2816         fwserial_debugfs = debugfs_create_dir(KBUILD_MODNAME, NULL);
2817 
2818         /* num_ttys/num_ports must not be set above the static alloc avail */
2819         if (num_ttys + num_loops > MAX_CARD_PORTS)
2820                 num_ttys = MAX_CARD_PORTS - num_loops;
2821         num_ports = num_ttys + num_loops;
2822 
2823         fwtty_driver = tty_alloc_driver(MAX_TOTAL_PORTS, TTY_DRIVER_REAL_RAW
2824                                         | TTY_DRIVER_DYNAMIC_DEV);
2825         if (IS_ERR(fwtty_driver)) {
2826                 err = PTR_ERR(fwtty_driver);
2827                 return err;
2828         }
2829 
2830         fwtty_driver->driver_name       = KBUILD_MODNAME;
2831         fwtty_driver->name              = tty_dev_name;
2832         fwtty_driver->major             = 0;
2833         fwtty_driver->minor_start       = 0;
2834         fwtty_driver->type              = TTY_DRIVER_TYPE_SERIAL;
2835         fwtty_driver->subtype           = SERIAL_TYPE_NORMAL;
2836         fwtty_driver->init_termios          = tty_std_termios;
2837         fwtty_driver->init_termios.c_cflag  |= CLOCAL;
2838         tty_set_operations(fwtty_driver, &fwtty_ops);
2839 
2840         err = tty_register_driver(fwtty_driver);
2841         if (err) {
2842                 pr_err("register tty driver failed (%d)\n", err);
2843                 goto put_tty;
2844         }
2845 
2846         if (create_loop_dev) {
2847                 fwloop_driver = tty_alloc_driver(MAX_TOTAL_PORTS / num_ports,
2848                                                  TTY_DRIVER_REAL_RAW
2849                                                  | TTY_DRIVER_DYNAMIC_DEV);
2850                 if (IS_ERR(fwloop_driver)) {
2851                         err = PTR_ERR(fwloop_driver);
2852                         goto unregister_driver;
2853                 }
2854 
2855                 fwloop_driver->driver_name      = KBUILD_MODNAME "_loop";
2856                 fwloop_driver->name             = loop_dev_name;
2857                 fwloop_driver->major            = 0;
2858                 fwloop_driver->minor_start      = 0;
2859                 fwloop_driver->type             = TTY_DRIVER_TYPE_SERIAL;
2860                 fwloop_driver->subtype          = SERIAL_TYPE_NORMAL;
2861                 fwloop_driver->init_termios         = tty_std_termios;
2862                 fwloop_driver->init_termios.c_cflag  |= CLOCAL;
2863                 tty_set_operations(fwloop_driver, &fwloop_ops);
2864 
2865                 err = tty_register_driver(fwloop_driver);
2866                 if (err) {
2867                         pr_err("register loop driver failed (%d)\n", err);
2868                         goto put_loop;
2869                 }
2870         }
2871 
2872         fwtty_txn_cache = kmem_cache_create("fwtty_txn_cache",
2873                                             sizeof(struct fwtty_transaction),
2874                                             0, 0, fwtty_txn_constructor);
2875         if (!fwtty_txn_cache) {
2876                 err = -ENOMEM;
2877                 goto unregister_loop;
2878         }
2879 
2880         /*
2881          * Ideally, this address handler would be registered per local node
2882          * (rather than the same handler for all local nodes). However,
2883          * since the firewire core requires the config rom descriptor *before*
2884          * the local unit device(s) are created, a single management handler
2885          * must suffice for all local serial units.
2886          */
2887         fwserial_mgmt_addr_handler.length = sizeof(struct fwserial_mgmt_pkt);
2888         fwserial_mgmt_addr_handler.address_callback = fwserial_mgmt_handler;
2889 
2890         err = fw_core_add_address_handler(&fwserial_mgmt_addr_handler,
2891                                           &fwserial_mgmt_addr_region);
2892         if (err) {
2893                 pr_err("add management handler failed (%d)\n", err);
2894                 goto destroy_cache;
2895         }
2896 
2897         fwserial_unit_directory_data.unit_addr_offset =
2898                 FW_UNIT_ADDRESS(fwserial_mgmt_addr_handler.offset);
2899         err = fw_core_add_descriptor(&fwserial_unit_directory);
2900         if (err) {
2901                 pr_err("add unit descriptor failed (%d)\n", err);
2902                 goto remove_handler;
2903         }
2904 
2905         err = driver_register(&fwserial_driver.driver);
2906         if (err) {
2907                 pr_err("register fwserial driver failed (%d)\n", err);
2908                 goto remove_descriptor;
2909         }
2910 
2911         return 0;
2912 
2913 remove_descriptor:
2914         fw_core_remove_descriptor(&fwserial_unit_directory);
2915 remove_handler:
2916         fw_core_remove_address_handler(&fwserial_mgmt_addr_handler);
2917 destroy_cache:
2918         kmem_cache_destroy(fwtty_txn_cache);
2919 unregister_loop:
2920         if (create_loop_dev)
2921                 tty_unregister_driver(fwloop_driver);
2922 put_loop:
2923         if (create_loop_dev)
2924                 put_tty_driver(fwloop_driver);
2925 unregister_driver:
2926         tty_unregister_driver(fwtty_driver);
2927 put_tty:
2928         put_tty_driver(fwtty_driver);
2929         debugfs_remove_recursive(fwserial_debugfs);
2930         return err;
2931 }
2932 
2933 static void __exit fwserial_exit(void)
2934 {
2935         driver_unregister(&fwserial_driver.driver);
2936         fw_core_remove_descriptor(&fwserial_unit_directory);
2937         fw_core_remove_address_handler(&fwserial_mgmt_addr_handler);
2938         kmem_cache_destroy(fwtty_txn_cache);
2939         if (create_loop_dev) {
2940                 tty_unregister_driver(fwloop_driver);
2941                 put_tty_driver(fwloop_driver);
2942         }
2943         tty_unregister_driver(fwtty_driver);
2944         put_tty_driver(fwtty_driver);
2945         debugfs_remove_recursive(fwserial_debugfs);
2946 }
2947 
2948 module_init(fwserial_init);
2949 module_exit(fwserial_exit);
2950 
2951 MODULE_AUTHOR("Peter Hurley (peter@hurleysoftware.com)");
2952 MODULE_DESCRIPTION("FireWire Serial TTY Driver");
2953 MODULE_LICENSE("GPL");
2954 MODULE_DEVICE_TABLE(ieee1394, fwserial_id_table);
2955 MODULE_PARM_DESC(ttys, "Number of ttys to create for each local firewire node");
2956 MODULE_PARM_DESC(auto, "Auto-connect a tty to each firewire node discovered");
2957 MODULE_PARM_DESC(loop, "Create a loopback device, fwloop<n>, with ttys");
2958 

This page was automatically generated by LXR 0.3.1 (source).  •  Linux is a registered trademark of Linus Torvalds  •  Contact us