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