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