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