Version:  2.6.34 2.6.35 2.6.36 2.6.37 2.6.38 2.6.39 3.0 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 3.10 3.11 3.12 3.13 3.14

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

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