Version:  2.0.40 2.2.26 2.4.37 3.9 3.10 3.11 3.12 3.13 3.14 3.15 3.16 3.17 3.18 3.19 4.0 4.1 4.2 4.3 4.4 4.5 4.6

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

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