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