linux/drivers/usb/host/fotg210-hcd.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0+
   2/* Faraday FOTG210 EHCI-like driver
   3 *
   4 * Copyright (c) 2013 Faraday Technology Corporation
   5 *
   6 * Author: Yuan-Hsin Chen <yhchen@faraday-tech.com>
   7 *         Feng-Hsin Chiang <john453@faraday-tech.com>
   8 *         Po-Yu Chuang <ratbert.chuang@gmail.com>
   9 *
  10 * Most of code borrowed from the Linux-3.7 EHCI driver
  11 */
  12#include <linux/module.h>
  13#include <linux/device.h>
  14#include <linux/dmapool.h>
  15#include <linux/kernel.h>
  16#include <linux/delay.h>
  17#include <linux/ioport.h>
  18#include <linux/sched.h>
  19#include <linux/vmalloc.h>
  20#include <linux/errno.h>
  21#include <linux/init.h>
  22#include <linux/hrtimer.h>
  23#include <linux/list.h>
  24#include <linux/interrupt.h>
  25#include <linux/usb.h>
  26#include <linux/usb/hcd.h>
  27#include <linux/moduleparam.h>
  28#include <linux/dma-mapping.h>
  29#include <linux/debugfs.h>
  30#include <linux/slab.h>
  31#include <linux/uaccess.h>
  32#include <linux/platform_device.h>
  33#include <linux/io.h>
  34#include <linux/clk.h>
  35
  36#include <asm/byteorder.h>
  37#include <asm/irq.h>
  38#include <asm/unaligned.h>
  39
  40#define DRIVER_AUTHOR "Yuan-Hsin Chen"
  41#define DRIVER_DESC "FOTG210 Host Controller (EHCI) Driver"
  42static const char hcd_name[] = "fotg210_hcd";
  43
  44#undef FOTG210_URB_TRACE
  45#define FOTG210_STATS
  46
  47/* magic numbers that can affect system performance */
  48#define FOTG210_TUNE_CERR       3 /* 0-3 qtd retries; 0 == don't stop */
  49#define FOTG210_TUNE_RL_HS      4 /* nak throttle; see 4.9 */
  50#define FOTG210_TUNE_RL_TT      0
  51#define FOTG210_TUNE_MULT_HS    1 /* 1-3 transactions/uframe; 4.10.3 */
  52#define FOTG210_TUNE_MULT_TT    1
  53
  54/* Some drivers think it's safe to schedule isochronous transfers more than 256
  55 * ms into the future (partly as a result of an old bug in the scheduling
  56 * code).  In an attempt to avoid trouble, we will use a minimum scheduling
  57 * length of 512 frames instead of 256.
  58 */
  59#define FOTG210_TUNE_FLS 1 /* (medium) 512-frame schedule */
  60
  61/* Initial IRQ latency:  faster than hw default */
  62static int log2_irq_thresh; /* 0 to 6 */
  63module_param(log2_irq_thresh, int, S_IRUGO);
  64MODULE_PARM_DESC(log2_irq_thresh, "log2 IRQ latency, 1-64 microframes");
  65
  66/* initial park setting:  slower than hw default */
  67static unsigned park;
  68module_param(park, uint, S_IRUGO);
  69MODULE_PARM_DESC(park, "park setting; 1-3 back-to-back async packets");
  70
  71/* for link power management(LPM) feature */
  72static unsigned int hird;
  73module_param(hird, int, S_IRUGO);
  74MODULE_PARM_DESC(hird, "host initiated resume duration, +1 for each 75us");
  75
  76#define INTR_MASK (STS_IAA | STS_FATAL | STS_PCD | STS_ERR | STS_INT)
  77
  78#include "fotg210.h"
  79
  80#define fotg210_dbg(fotg210, fmt, args...) \
  81        dev_dbg(fotg210_to_hcd(fotg210)->self.controller, fmt, ## args)
  82#define fotg210_err(fotg210, fmt, args...) \
  83        dev_err(fotg210_to_hcd(fotg210)->self.controller, fmt, ## args)
  84#define fotg210_info(fotg210, fmt, args...) \
  85        dev_info(fotg210_to_hcd(fotg210)->self.controller, fmt, ## args)
  86#define fotg210_warn(fotg210, fmt, args...) \
  87        dev_warn(fotg210_to_hcd(fotg210)->self.controller, fmt, ## args)
  88
  89/* check the values in the HCSPARAMS register (host controller _Structural_
  90 * parameters) see EHCI spec, Table 2-4 for each value
  91 */
  92static void dbg_hcs_params(struct fotg210_hcd *fotg210, char *label)
  93{
  94        u32 params = fotg210_readl(fotg210, &fotg210->caps->hcs_params);
  95
  96        fotg210_dbg(fotg210, "%s hcs_params 0x%x ports=%d\n", label, params,
  97                        HCS_N_PORTS(params));
  98}
  99
 100/* check the values in the HCCPARAMS register (host controller _Capability_
 101 * parameters) see EHCI Spec, Table 2-5 for each value
 102 */
 103static void dbg_hcc_params(struct fotg210_hcd *fotg210, char *label)
 104{
 105        u32 params = fotg210_readl(fotg210, &fotg210->caps->hcc_params);
 106
 107        fotg210_dbg(fotg210, "%s hcc_params %04x uframes %s%s\n", label,
 108                        params,
 109                        HCC_PGM_FRAMELISTLEN(params) ? "256/512/1024" : "1024",
 110                        HCC_CANPARK(params) ? " park" : "");
 111}
 112
 113static void __maybe_unused
 114dbg_qtd(const char *label, struct fotg210_hcd *fotg210, struct fotg210_qtd *qtd)
 115{
 116        fotg210_dbg(fotg210, "%s td %p n%08x %08x t%08x p0=%08x\n", label, qtd,
 117                        hc32_to_cpup(fotg210, &qtd->hw_next),
 118                        hc32_to_cpup(fotg210, &qtd->hw_alt_next),
 119                        hc32_to_cpup(fotg210, &qtd->hw_token),
 120                        hc32_to_cpup(fotg210, &qtd->hw_buf[0]));
 121        if (qtd->hw_buf[1])
 122                fotg210_dbg(fotg210, "  p1=%08x p2=%08x p3=%08x p4=%08x\n",
 123                                hc32_to_cpup(fotg210, &qtd->hw_buf[1]),
 124                                hc32_to_cpup(fotg210, &qtd->hw_buf[2]),
 125                                hc32_to_cpup(fotg210, &qtd->hw_buf[3]),
 126                                hc32_to_cpup(fotg210, &qtd->hw_buf[4]));
 127}
 128
 129static void __maybe_unused
 130dbg_qh(const char *label, struct fotg210_hcd *fotg210, struct fotg210_qh *qh)
 131{
 132        struct fotg210_qh_hw *hw = qh->hw;
 133
 134        fotg210_dbg(fotg210, "%s qh %p n%08x info %x %x qtd %x\n", label, qh,
 135                        hw->hw_next, hw->hw_info1, hw->hw_info2,
 136                        hw->hw_current);
 137
 138        dbg_qtd("overlay", fotg210, (struct fotg210_qtd *) &hw->hw_qtd_next);
 139}
 140
 141static void __maybe_unused
 142dbg_itd(const char *label, struct fotg210_hcd *fotg210, struct fotg210_itd *itd)
 143{
 144        fotg210_dbg(fotg210, "%s[%d] itd %p, next %08x, urb %p\n", label,
 145                        itd->frame, itd, hc32_to_cpu(fotg210, itd->hw_next),
 146                        itd->urb);
 147
 148        fotg210_dbg(fotg210,
 149                        "  trans: %08x %08x %08x %08x %08x %08x %08x %08x\n",
 150                        hc32_to_cpu(fotg210, itd->hw_transaction[0]),
 151                        hc32_to_cpu(fotg210, itd->hw_transaction[1]),
 152                        hc32_to_cpu(fotg210, itd->hw_transaction[2]),
 153                        hc32_to_cpu(fotg210, itd->hw_transaction[3]),
 154                        hc32_to_cpu(fotg210, itd->hw_transaction[4]),
 155                        hc32_to_cpu(fotg210, itd->hw_transaction[5]),
 156                        hc32_to_cpu(fotg210, itd->hw_transaction[6]),
 157                        hc32_to_cpu(fotg210, itd->hw_transaction[7]));
 158
 159        fotg210_dbg(fotg210,
 160                        "  buf:   %08x %08x %08x %08x %08x %08x %08x\n",
 161                        hc32_to_cpu(fotg210, itd->hw_bufp[0]),
 162                        hc32_to_cpu(fotg210, itd->hw_bufp[1]),
 163                        hc32_to_cpu(fotg210, itd->hw_bufp[2]),
 164                        hc32_to_cpu(fotg210, itd->hw_bufp[3]),
 165                        hc32_to_cpu(fotg210, itd->hw_bufp[4]),
 166                        hc32_to_cpu(fotg210, itd->hw_bufp[5]),
 167                        hc32_to_cpu(fotg210, itd->hw_bufp[6]));
 168
 169        fotg210_dbg(fotg210, "  index: %d %d %d %d %d %d %d %d\n",
 170                        itd->index[0], itd->index[1], itd->index[2],
 171                        itd->index[3], itd->index[4], itd->index[5],
 172                        itd->index[6], itd->index[7]);
 173}
 174
 175static int __maybe_unused
 176dbg_status_buf(char *buf, unsigned len, const char *label, u32 status)
 177{
 178        return scnprintf(buf, len, "%s%sstatus %04x%s%s%s%s%s%s%s%s%s%s",
 179                        label, label[0] ? " " : "", status,
 180                        (status & STS_ASS) ? " Async" : "",
 181                        (status & STS_PSS) ? " Periodic" : "",
 182                        (status & STS_RECL) ? " Recl" : "",
 183                        (status & STS_HALT) ? " Halt" : "",
 184                        (status & STS_IAA) ? " IAA" : "",
 185                        (status & STS_FATAL) ? " FATAL" : "",
 186                        (status & STS_FLR) ? " FLR" : "",
 187                        (status & STS_PCD) ? " PCD" : "",
 188                        (status & STS_ERR) ? " ERR" : "",
 189                        (status & STS_INT) ? " INT" : "");
 190}
 191
 192static int __maybe_unused
 193dbg_intr_buf(char *buf, unsigned len, const char *label, u32 enable)
 194{
 195        return scnprintf(buf, len, "%s%sintrenable %02x%s%s%s%s%s%s",
 196                        label, label[0] ? " " : "", enable,
 197                        (enable & STS_IAA) ? " IAA" : "",
 198                        (enable & STS_FATAL) ? " FATAL" : "",
 199                        (enable & STS_FLR) ? " FLR" : "",
 200                        (enable & STS_PCD) ? " PCD" : "",
 201                        (enable & STS_ERR) ? " ERR" : "",
 202                        (enable & STS_INT) ? " INT" : "");
 203}
 204
 205static const char *const fls_strings[] = { "1024", "512", "256", "??" };
 206
 207static int dbg_command_buf(char *buf, unsigned len, const char *label,
 208                u32 command)
 209{
 210        return scnprintf(buf, len,
 211                        "%s%scommand %07x %s=%d ithresh=%d%s%s%s period=%s%s %s",
 212                        label, label[0] ? " " : "", command,
 213                        (command & CMD_PARK) ? " park" : "(park)",
 214                        CMD_PARK_CNT(command),
 215                        (command >> 16) & 0x3f,
 216                        (command & CMD_IAAD) ? " IAAD" : "",
 217                        (command & CMD_ASE) ? " Async" : "",
 218                        (command & CMD_PSE) ? " Periodic" : "",
 219                        fls_strings[(command >> 2) & 0x3],
 220                        (command & CMD_RESET) ? " Reset" : "",
 221                        (command & CMD_RUN) ? "RUN" : "HALT");
 222}
 223
 224static char *dbg_port_buf(char *buf, unsigned len, const char *label, int port,
 225                u32 status)
 226{
 227        char *sig;
 228
 229        /* signaling state */
 230        switch (status & (3 << 10)) {
 231        case 0 << 10:
 232                sig = "se0";
 233                break;
 234        case 1 << 10:
 235                sig = "k";
 236                break; /* low speed */
 237        case 2 << 10:
 238                sig = "j";
 239                break;
 240        default:
 241                sig = "?";
 242                break;
 243        }
 244
 245        scnprintf(buf, len, "%s%sport:%d status %06x %d sig=%s%s%s%s%s%s%s%s",
 246                        label, label[0] ? " " : "", port, status,
 247                        status >> 25, /*device address */
 248                        sig,
 249                        (status & PORT_RESET) ? " RESET" : "",
 250                        (status & PORT_SUSPEND) ? " SUSPEND" : "",
 251                        (status & PORT_RESUME) ? " RESUME" : "",
 252                        (status & PORT_PEC) ? " PEC" : "",
 253                        (status & PORT_PE) ? " PE" : "",
 254                        (status & PORT_CSC) ? " CSC" : "",
 255                        (status & PORT_CONNECT) ? " CONNECT" : "");
 256
 257        return buf;
 258}
 259
 260/* functions have the "wrong" filename when they're output... */
 261#define dbg_status(fotg210, label, status) {                    \
 262        char _buf[80];                                          \
 263        dbg_status_buf(_buf, sizeof(_buf), label, status);      \
 264        fotg210_dbg(fotg210, "%s\n", _buf);                     \
 265}
 266
 267#define dbg_cmd(fotg210, label, command) {                      \
 268        char _buf[80];                                          \
 269        dbg_command_buf(_buf, sizeof(_buf), label, command);    \
 270        fotg210_dbg(fotg210, "%s\n", _buf);                     \
 271}
 272
 273#define dbg_port(fotg210, label, port, status) {                               \
 274        char _buf[80];                                                         \
 275        fotg210_dbg(fotg210, "%s\n",                                           \
 276                        dbg_port_buf(_buf, sizeof(_buf), label, port, status));\
 277}
 278
 279/* troubleshooting help: expose state in debugfs */
 280static int debug_async_open(struct inode *, struct file *);
 281static int debug_periodic_open(struct inode *, struct file *);
 282static int debug_registers_open(struct inode *, struct file *);
 283static int debug_async_open(struct inode *, struct file *);
 284
 285static ssize_t debug_output(struct file*, char __user*, size_t, loff_t*);
 286static int debug_close(struct inode *, struct file *);
 287
 288static const struct file_operations debug_async_fops = {
 289        .owner          = THIS_MODULE,
 290        .open           = debug_async_open,
 291        .read           = debug_output,
 292        .release        = debug_close,
 293        .llseek         = default_llseek,
 294};
 295static const struct file_operations debug_periodic_fops = {
 296        .owner          = THIS_MODULE,
 297        .open           = debug_periodic_open,
 298        .read           = debug_output,
 299        .release        = debug_close,
 300        .llseek         = default_llseek,
 301};
 302static const struct file_operations debug_registers_fops = {
 303        .owner          = THIS_MODULE,
 304        .open           = debug_registers_open,
 305        .read           = debug_output,
 306        .release        = debug_close,
 307        .llseek         = default_llseek,
 308};
 309
 310static struct dentry *fotg210_debug_root;
 311
 312struct debug_buffer {
 313        ssize_t (*fill_func)(struct debug_buffer *);    /* fill method */
 314        struct usb_bus *bus;
 315        struct mutex mutex;     /* protect filling of buffer */
 316        size_t count;           /* number of characters filled into buffer */
 317        char *output_buf;
 318        size_t alloc_size;
 319};
 320
 321static inline char speed_char(u32 scratch)
 322{
 323        switch (scratch & (3 << 12)) {
 324        case QH_FULL_SPEED:
 325                return 'f';
 326
 327        case QH_LOW_SPEED:
 328                return 'l';
 329
 330        case QH_HIGH_SPEED:
 331                return 'h';
 332
 333        default:
 334                return '?';
 335        }
 336}
 337
 338static inline char token_mark(struct fotg210_hcd *fotg210, __hc32 token)
 339{
 340        __u32 v = hc32_to_cpu(fotg210, token);
 341
 342        if (v & QTD_STS_ACTIVE)
 343                return '*';
 344        if (v & QTD_STS_HALT)
 345                return '-';
 346        if (!IS_SHORT_READ(v))
 347                return ' ';
 348        /* tries to advance through hw_alt_next */
 349        return '/';
 350}
 351
 352static void qh_lines(struct fotg210_hcd *fotg210, struct fotg210_qh *qh,
 353                char **nextp, unsigned *sizep)
 354{
 355        u32 scratch;
 356        u32 hw_curr;
 357        struct fotg210_qtd *td;
 358        unsigned temp;
 359        unsigned size = *sizep;
 360        char *next = *nextp;
 361        char mark;
 362        __le32 list_end = FOTG210_LIST_END(fotg210);
 363        struct fotg210_qh_hw *hw = qh->hw;
 364
 365        if (hw->hw_qtd_next == list_end) /* NEC does this */
 366                mark = '@';
 367        else
 368                mark = token_mark(fotg210, hw->hw_token);
 369        if (mark == '/') { /* qh_alt_next controls qh advance? */
 370                if ((hw->hw_alt_next & QTD_MASK(fotg210)) ==
 371                    fotg210->async->hw->hw_alt_next)
 372                        mark = '#'; /* blocked */
 373                else if (hw->hw_alt_next == list_end)
 374                        mark = '.'; /* use hw_qtd_next */
 375                /* else alt_next points to some other qtd */
 376        }
 377        scratch = hc32_to_cpup(fotg210, &hw->hw_info1);
 378        hw_curr = (mark == '*') ? hc32_to_cpup(fotg210, &hw->hw_current) : 0;
 379        temp = scnprintf(next, size,
 380                        "qh/%p dev%d %cs ep%d %08x %08x(%08x%c %s nak%d)",
 381                        qh, scratch & 0x007f,
 382                        speed_char(scratch),
 383                        (scratch >> 8) & 0x000f,
 384                        scratch, hc32_to_cpup(fotg210, &hw->hw_info2),
 385                        hc32_to_cpup(fotg210, &hw->hw_token), mark,
 386                        (cpu_to_hc32(fotg210, QTD_TOGGLE) & hw->hw_token)
 387                                ? "data1" : "data0",
 388                        (hc32_to_cpup(fotg210, &hw->hw_alt_next) >> 1) & 0x0f);
 389        size -= temp;
 390        next += temp;
 391
 392        /* hc may be modifying the list as we read it ... */
 393        list_for_each_entry(td, &qh->qtd_list, qtd_list) {
 394                scratch = hc32_to_cpup(fotg210, &td->hw_token);
 395                mark = ' ';
 396                if (hw_curr == td->qtd_dma)
 397                        mark = '*';
 398                else if (hw->hw_qtd_next == cpu_to_hc32(fotg210, td->qtd_dma))
 399                        mark = '+';
 400                else if (QTD_LENGTH(scratch)) {
 401                        if (td->hw_alt_next == fotg210->async->hw->hw_alt_next)
 402                                mark = '#';
 403                        else if (td->hw_alt_next != list_end)
 404                                mark = '/';
 405                }
 406                temp = snprintf(next, size,
 407                                "\n\t%p%c%s len=%d %08x urb %p",
 408                                td, mark, ({ char *tmp;
 409                                 switch ((scratch>>8)&0x03) {
 410                                 case 0:
 411                                        tmp = "out";
 412                                        break;
 413                                 case 1:
 414                                        tmp = "in";
 415                                        break;
 416                                 case 2:
 417                                        tmp = "setup";
 418                                        break;
 419                                 default:
 420                                        tmp = "?";
 421                                        break;
 422                                 } tmp; }),
 423                                (scratch >> 16) & 0x7fff,
 424                                scratch,
 425                                td->urb);
 426                if (size < temp)
 427                        temp = size;
 428                size -= temp;
 429                next += temp;
 430                if (temp == size)
 431                        goto done;
 432        }
 433
 434        temp = snprintf(next, size, "\n");
 435        if (size < temp)
 436                temp = size;
 437
 438        size -= temp;
 439        next += temp;
 440
 441done:
 442        *sizep = size;
 443        *nextp = next;
 444}
 445
 446static ssize_t fill_async_buffer(struct debug_buffer *buf)
 447{
 448        struct usb_hcd *hcd;
 449        struct fotg210_hcd *fotg210;
 450        unsigned long flags;
 451        unsigned temp, size;
 452        char *next;
 453        struct fotg210_qh *qh;
 454
 455        hcd = bus_to_hcd(buf->bus);
 456        fotg210 = hcd_to_fotg210(hcd);
 457        next = buf->output_buf;
 458        size = buf->alloc_size;
 459
 460        *next = 0;
 461
 462        /* dumps a snapshot of the async schedule.
 463         * usually empty except for long-term bulk reads, or head.
 464         * one QH per line, and TDs we know about
 465         */
 466        spin_lock_irqsave(&fotg210->lock, flags);
 467        for (qh = fotg210->async->qh_next.qh; size > 0 && qh;
 468                        qh = qh->qh_next.qh)
 469                qh_lines(fotg210, qh, &next, &size);
 470        if (fotg210->async_unlink && size > 0) {
 471                temp = scnprintf(next, size, "\nunlink =\n");
 472                size -= temp;
 473                next += temp;
 474
 475                for (qh = fotg210->async_unlink; size > 0 && qh;
 476                                qh = qh->unlink_next)
 477                        qh_lines(fotg210, qh, &next, &size);
 478        }
 479        spin_unlock_irqrestore(&fotg210->lock, flags);
 480
 481        return strlen(buf->output_buf);
 482}
 483
 484/* count tds, get ep direction */
 485static unsigned output_buf_tds_dir(char *buf, struct fotg210_hcd *fotg210,
 486                struct fotg210_qh_hw *hw, struct fotg210_qh *qh, unsigned size)
 487{
 488        u32 scratch = hc32_to_cpup(fotg210, &hw->hw_info1);
 489        struct fotg210_qtd *qtd;
 490        char *type = "";
 491        unsigned temp = 0;
 492
 493        /* count tds, get ep direction */
 494        list_for_each_entry(qtd, &qh->qtd_list, qtd_list) {
 495                temp++;
 496                switch ((hc32_to_cpu(fotg210, qtd->hw_token) >> 8) & 0x03) {
 497                case 0:
 498                        type = "out";
 499                        continue;
 500                case 1:
 501                        type = "in";
 502                        continue;
 503                }
 504        }
 505
 506        return scnprintf(buf, size, "(%c%d ep%d%s [%d/%d] q%d p%d)",
 507                        speed_char(scratch), scratch & 0x007f,
 508                        (scratch >> 8) & 0x000f, type, qh->usecs,
 509                        qh->c_usecs, temp, (scratch >> 16) & 0x7ff);
 510}
 511
 512#define DBG_SCHED_LIMIT 64
 513static ssize_t fill_periodic_buffer(struct debug_buffer *buf)
 514{
 515        struct usb_hcd *hcd;
 516        struct fotg210_hcd *fotg210;
 517        unsigned long flags;
 518        union fotg210_shadow p, *seen;
 519        unsigned temp, size, seen_count;
 520        char *next;
 521        unsigned i;
 522        __hc32 tag;
 523
 524        seen = kmalloc_array(DBG_SCHED_LIMIT, sizeof(*seen), GFP_ATOMIC);
 525        if (!seen)
 526                return 0;
 527
 528        seen_count = 0;
 529
 530        hcd = bus_to_hcd(buf->bus);
 531        fotg210 = hcd_to_fotg210(hcd);
 532        next = buf->output_buf;
 533        size = buf->alloc_size;
 534
 535        temp = scnprintf(next, size, "size = %d\n", fotg210->periodic_size);
 536        size -= temp;
 537        next += temp;
 538
 539        /* dump a snapshot of the periodic schedule.
 540         * iso changes, interrupt usually doesn't.
 541         */
 542        spin_lock_irqsave(&fotg210->lock, flags);
 543        for (i = 0; i < fotg210->periodic_size; i++) {
 544                p = fotg210->pshadow[i];
 545                if (likely(!p.ptr))
 546                        continue;
 547
 548                tag = Q_NEXT_TYPE(fotg210, fotg210->periodic[i]);
 549
 550                temp = scnprintf(next, size, "%4d: ", i);
 551                size -= temp;
 552                next += temp;
 553
 554                do {
 555                        struct fotg210_qh_hw *hw;
 556
 557                        switch (hc32_to_cpu(fotg210, tag)) {
 558                        case Q_TYPE_QH:
 559                                hw = p.qh->hw;
 560                                temp = scnprintf(next, size, " qh%d-%04x/%p",
 561                                                p.qh->period,
 562                                                hc32_to_cpup(fotg210,
 563                                                        &hw->hw_info2)
 564                                                        /* uframe masks */
 565                                                        & (QH_CMASK | QH_SMASK),
 566                                                p.qh);
 567                                size -= temp;
 568                                next += temp;
 569                                /* don't repeat what follows this qh */
 570                                for (temp = 0; temp < seen_count; temp++) {
 571                                        if (seen[temp].ptr != p.ptr)
 572                                                continue;
 573                                        if (p.qh->qh_next.ptr) {
 574                                                temp = scnprintf(next, size,
 575                                                                " ...");
 576                                                size -= temp;
 577                                                next += temp;
 578                                        }
 579                                        break;
 580                                }
 581                                /* show more info the first time around */
 582                                if (temp == seen_count) {
 583                                        temp = output_buf_tds_dir(next,
 584                                                        fotg210, hw,
 585                                                        p.qh, size);
 586
 587                                        if (seen_count < DBG_SCHED_LIMIT)
 588                                                seen[seen_count++].qh = p.qh;
 589                                } else
 590                                        temp = 0;
 591                                tag = Q_NEXT_TYPE(fotg210, hw->hw_next);
 592                                p = p.qh->qh_next;
 593                                break;
 594                        case Q_TYPE_FSTN:
 595                                temp = scnprintf(next, size,
 596                                                " fstn-%8x/%p",
 597                                                p.fstn->hw_prev, p.fstn);
 598                                tag = Q_NEXT_TYPE(fotg210, p.fstn->hw_next);
 599                                p = p.fstn->fstn_next;
 600                                break;
 601                        case Q_TYPE_ITD:
 602                                temp = scnprintf(next, size,
 603                                                " itd/%p", p.itd);
 604                                tag = Q_NEXT_TYPE(fotg210, p.itd->hw_next);
 605                                p = p.itd->itd_next;
 606                                break;
 607                        }
 608                        size -= temp;
 609                        next += temp;
 610                } while (p.ptr);
 611
 612                temp = scnprintf(next, size, "\n");
 613                size -= temp;
 614                next += temp;
 615        }
 616        spin_unlock_irqrestore(&fotg210->lock, flags);
 617        kfree(seen);
 618
 619        return buf->alloc_size - size;
 620}
 621#undef DBG_SCHED_LIMIT
 622
 623static const char *rh_state_string(struct fotg210_hcd *fotg210)
 624{
 625        switch (fotg210->rh_state) {
 626        case FOTG210_RH_HALTED:
 627                return "halted";
 628        case FOTG210_RH_SUSPENDED:
 629                return "suspended";
 630        case FOTG210_RH_RUNNING:
 631                return "running";
 632        case FOTG210_RH_STOPPING:
 633                return "stopping";
 634        }
 635        return "?";
 636}
 637
 638static ssize_t fill_registers_buffer(struct debug_buffer *buf)
 639{
 640        struct usb_hcd *hcd;
 641        struct fotg210_hcd *fotg210;
 642        unsigned long flags;
 643        unsigned temp, size, i;
 644        char *next, scratch[80];
 645        static const char fmt[] = "%*s\n";
 646        static const char label[] = "";
 647
 648        hcd = bus_to_hcd(buf->bus);
 649        fotg210 = hcd_to_fotg210(hcd);
 650        next = buf->output_buf;
 651        size = buf->alloc_size;
 652
 653        spin_lock_irqsave(&fotg210->lock, flags);
 654
 655        if (!HCD_HW_ACCESSIBLE(hcd)) {
 656                size = scnprintf(next, size,
 657                                "bus %s, device %s\n"
 658                                "%s\n"
 659                                "SUSPENDED(no register access)\n",
 660                                hcd->self.controller->bus->name,
 661                                dev_name(hcd->self.controller),
 662                                hcd->product_desc);
 663                goto done;
 664        }
 665
 666        /* Capability Registers */
 667        i = HC_VERSION(fotg210, fotg210_readl(fotg210,
 668                        &fotg210->caps->hc_capbase));
 669        temp = scnprintf(next, size,
 670                        "bus %s, device %s\n"
 671                        "%s\n"
 672                        "EHCI %x.%02x, rh state %s\n",
 673                        hcd->self.controller->bus->name,
 674                        dev_name(hcd->self.controller),
 675                        hcd->product_desc,
 676                        i >> 8, i & 0x0ff, rh_state_string(fotg210));
 677        size -= temp;
 678        next += temp;
 679
 680        /* FIXME interpret both types of params */
 681        i = fotg210_readl(fotg210, &fotg210->caps->hcs_params);
 682        temp = scnprintf(next, size, "structural params 0x%08x\n", i);
 683        size -= temp;
 684        next += temp;
 685
 686        i = fotg210_readl(fotg210, &fotg210->caps->hcc_params);
 687        temp = scnprintf(next, size, "capability params 0x%08x\n", i);
 688        size -= temp;
 689        next += temp;
 690
 691        /* Operational Registers */
 692        temp = dbg_status_buf(scratch, sizeof(scratch), label,
 693                        fotg210_readl(fotg210, &fotg210->regs->status));
 694        temp = scnprintf(next, size, fmt, temp, scratch);
 695        size -= temp;
 696        next += temp;
 697
 698        temp = dbg_command_buf(scratch, sizeof(scratch), label,
 699                        fotg210_readl(fotg210, &fotg210->regs->command));
 700        temp = scnprintf(next, size, fmt, temp, scratch);
 701        size -= temp;
 702        next += temp;
 703
 704        temp = dbg_intr_buf(scratch, sizeof(scratch), label,
 705                        fotg210_readl(fotg210, &fotg210->regs->intr_enable));
 706        temp = scnprintf(next, size, fmt, temp, scratch);
 707        size -= temp;
 708        next += temp;
 709
 710        temp = scnprintf(next, size, "uframe %04x\n",
 711                        fotg210_read_frame_index(fotg210));
 712        size -= temp;
 713        next += temp;
 714
 715        if (fotg210->async_unlink) {
 716                temp = scnprintf(next, size, "async unlink qh %p\n",
 717                                fotg210->async_unlink);
 718                size -= temp;
 719                next += temp;
 720        }
 721
 722#ifdef FOTG210_STATS
 723        temp = scnprintf(next, size,
 724                        "irq normal %ld err %ld iaa %ld(lost %ld)\n",
 725                        fotg210->stats.normal, fotg210->stats.error,
 726                        fotg210->stats.iaa, fotg210->stats.lost_iaa);
 727        size -= temp;
 728        next += temp;
 729
 730        temp = scnprintf(next, size, "complete %ld unlink %ld\n",
 731                        fotg210->stats.complete, fotg210->stats.unlink);
 732        size -= temp;
 733        next += temp;
 734#endif
 735
 736done:
 737        spin_unlock_irqrestore(&fotg210->lock, flags);
 738
 739        return buf->alloc_size - size;
 740}
 741
 742static struct debug_buffer
 743*alloc_buffer(struct usb_bus *bus, ssize_t (*fill_func)(struct debug_buffer *))
 744{
 745        struct debug_buffer *buf;
 746
 747        buf = kzalloc(sizeof(struct debug_buffer), GFP_KERNEL);
 748
 749        if (buf) {
 750                buf->bus = bus;
 751                buf->fill_func = fill_func;
 752                mutex_init(&buf->mutex);
 753                buf->alloc_size = PAGE_SIZE;
 754        }
 755
 756        return buf;
 757}
 758
 759static int fill_buffer(struct debug_buffer *buf)
 760{
 761        int ret = 0;
 762
 763        if (!buf->output_buf)
 764                buf->output_buf = vmalloc(buf->alloc_size);
 765
 766        if (!buf->output_buf) {
 767                ret = -ENOMEM;
 768                goto out;
 769        }
 770
 771        ret = buf->fill_func(buf);
 772
 773        if (ret >= 0) {
 774                buf->count = ret;
 775                ret = 0;
 776        }
 777
 778out:
 779        return ret;
 780}
 781
 782static ssize_t debug_output(struct file *file, char __user *user_buf,
 783                size_t len, loff_t *offset)
 784{
 785        struct debug_buffer *buf = file->private_data;
 786        int ret = 0;
 787
 788        mutex_lock(&buf->mutex);
 789        if (buf->count == 0) {
 790                ret = fill_buffer(buf);
 791                if (ret != 0) {
 792                        mutex_unlock(&buf->mutex);
 793                        goto out;
 794                }
 795        }
 796        mutex_unlock(&buf->mutex);
 797
 798        ret = simple_read_from_buffer(user_buf, len, offset,
 799                        buf->output_buf, buf->count);
 800
 801out:
 802        return ret;
 803
 804}
 805
 806static int debug_close(struct inode *inode, struct file *file)
 807{
 808        struct debug_buffer *buf = file->private_data;
 809
 810        if (buf) {
 811                vfree(buf->output_buf);
 812                kfree(buf);
 813        }
 814
 815        return 0;
 816}
 817static int debug_async_open(struct inode *inode, struct file *file)
 818{
 819        file->private_data = alloc_buffer(inode->i_private, fill_async_buffer);
 820
 821        return file->private_data ? 0 : -ENOMEM;
 822}
 823
 824static int debug_periodic_open(struct inode *inode, struct file *file)
 825{
 826        struct debug_buffer *buf;
 827
 828        buf = alloc_buffer(inode->i_private, fill_periodic_buffer);
 829        if (!buf)
 830                return -ENOMEM;
 831
 832        buf->alloc_size = (sizeof(void *) == 4 ? 6 : 8)*PAGE_SIZE;
 833        file->private_data = buf;
 834        return 0;
 835}
 836
 837static int debug_registers_open(struct inode *inode, struct file *file)
 838{
 839        file->private_data = alloc_buffer(inode->i_private,
 840                        fill_registers_buffer);
 841
 842        return file->private_data ? 0 : -ENOMEM;
 843}
 844
 845static inline void create_debug_files(struct fotg210_hcd *fotg210)
 846{
 847        struct usb_bus *bus = &fotg210_to_hcd(fotg210)->self;
 848        struct dentry *root;
 849
 850        root = debugfs_create_dir(bus->bus_name, fotg210_debug_root);
 851        fotg210->debug_dir = root;
 852
 853        debugfs_create_file("async", S_IRUGO, root, bus, &debug_async_fops);
 854        debugfs_create_file("periodic", S_IRUGO, root, bus,
 855                            &debug_periodic_fops);
 856        debugfs_create_file("registers", S_IRUGO, root, bus,
 857                            &debug_registers_fops);
 858}
 859
 860static inline void remove_debug_files(struct fotg210_hcd *fotg210)
 861{
 862        debugfs_remove_recursive(fotg210->debug_dir);
 863}
 864
 865/* handshake - spin reading hc until handshake completes or fails
 866 * @ptr: address of hc register to be read
 867 * @mask: bits to look at in result of read
 868 * @done: value of those bits when handshake succeeds
 869 * @usec: timeout in microseconds
 870 *
 871 * Returns negative errno, or zero on success
 872 *
 873 * Success happens when the "mask" bits have the specified value (hardware
 874 * handshake done).  There are two failure modes:  "usec" have passed (major
 875 * hardware flakeout), or the register reads as all-ones (hardware removed).
 876 *
 877 * That last failure should_only happen in cases like physical cardbus eject
 878 * before driver shutdown. But it also seems to be caused by bugs in cardbus
 879 * bridge shutdown:  shutting down the bridge before the devices using it.
 880 */
 881static int handshake(struct fotg210_hcd *fotg210, void __iomem *ptr,
 882                u32 mask, u32 done, int usec)
 883{
 884        u32 result;
 885
 886        do {
 887                result = fotg210_readl(fotg210, ptr);
 888                if (result == ~(u32)0)          /* card removed */
 889                        return -ENODEV;
 890                result &= mask;
 891                if (result == done)
 892                        return 0;
 893                udelay(1);
 894                usec--;
 895        } while (usec > 0);
 896        return -ETIMEDOUT;
 897}
 898
 899/* Force HC to halt state from unknown (EHCI spec section 2.3).
 900 * Must be called with interrupts enabled and the lock not held.
 901 */
 902static int fotg210_halt(struct fotg210_hcd *fotg210)
 903{
 904        u32 temp;
 905
 906        spin_lock_irq(&fotg210->lock);
 907
 908        /* disable any irqs left enabled by previous code */
 909        fotg210_writel(fotg210, 0, &fotg210->regs->intr_enable);
 910
 911        /*
 912         * This routine gets called during probe before fotg210->command
 913         * has been initialized, so we can't rely on its value.
 914         */
 915        fotg210->command &= ~CMD_RUN;
 916        temp = fotg210_readl(fotg210, &fotg210->regs->command);
 917        temp &= ~(CMD_RUN | CMD_IAAD);
 918        fotg210_writel(fotg210, temp, &fotg210->regs->command);
 919
 920        spin_unlock_irq(&fotg210->lock);
 921        synchronize_irq(fotg210_to_hcd(fotg210)->irq);
 922
 923        return handshake(fotg210, &fotg210->regs->status,
 924                        STS_HALT, STS_HALT, 16 * 125);
 925}
 926
 927/* Reset a non-running (STS_HALT == 1) controller.
 928 * Must be called with interrupts enabled and the lock not held.
 929 */
 930static int fotg210_reset(struct fotg210_hcd *fotg210)
 931{
 932        int retval;
 933        u32 command = fotg210_readl(fotg210, &fotg210->regs->command);
 934
 935        /* If the EHCI debug controller is active, special care must be
 936         * taken before and after a host controller reset
 937         */
 938        if (fotg210->debug && !dbgp_reset_prep(fotg210_to_hcd(fotg210)))
 939                fotg210->debug = NULL;
 940
 941        command |= CMD_RESET;
 942        dbg_cmd(fotg210, "reset", command);
 943        fotg210_writel(fotg210, command, &fotg210->regs->command);
 944        fotg210->rh_state = FOTG210_RH_HALTED;
 945        fotg210->next_statechange = jiffies;
 946        retval = handshake(fotg210, &fotg210->regs->command,
 947                        CMD_RESET, 0, 250 * 1000);
 948
 949        if (retval)
 950                return retval;
 951
 952        if (fotg210->debug)
 953                dbgp_external_startup(fotg210_to_hcd(fotg210));
 954
 955        fotg210->port_c_suspend = fotg210->suspended_ports =
 956                        fotg210->resuming_ports = 0;
 957        return retval;
 958}
 959
 960/* Idle the controller (turn off the schedules).
 961 * Must be called with interrupts enabled and the lock not held.
 962 */
 963static void fotg210_quiesce(struct fotg210_hcd *fotg210)
 964{
 965        u32 temp;
 966
 967        if (fotg210->rh_state != FOTG210_RH_RUNNING)
 968                return;
 969
 970        /* wait for any schedule enables/disables to take effect */
 971        temp = (fotg210->command << 10) & (STS_ASS | STS_PSS);
 972        handshake(fotg210, &fotg210->regs->status, STS_ASS | STS_PSS, temp,
 973                        16 * 125);
 974
 975        /* then disable anything that's still active */
 976        spin_lock_irq(&fotg210->lock);
 977        fotg210->command &= ~(CMD_ASE | CMD_PSE);
 978        fotg210_writel(fotg210, fotg210->command, &fotg210->regs->command);
 979        spin_unlock_irq(&fotg210->lock);
 980
 981        /* hardware can take 16 microframes to turn off ... */
 982        handshake(fotg210, &fotg210->regs->status, STS_ASS | STS_PSS, 0,
 983                        16 * 125);
 984}
 985
 986static void end_unlink_async(struct fotg210_hcd *fotg210);
 987static void unlink_empty_async(struct fotg210_hcd *fotg210);
 988static void fotg210_work(struct fotg210_hcd *fotg210);
 989static void start_unlink_intr(struct fotg210_hcd *fotg210,
 990                              struct fotg210_qh *qh);
 991static void end_unlink_intr(struct fotg210_hcd *fotg210, struct fotg210_qh *qh);
 992
 993/* Set a bit in the USBCMD register */
 994static void fotg210_set_command_bit(struct fotg210_hcd *fotg210, u32 bit)
 995{
 996        fotg210->command |= bit;
 997        fotg210_writel(fotg210, fotg210->command, &fotg210->regs->command);
 998
 999        /* unblock posted write */
1000        fotg210_readl(fotg210, &fotg210->regs->command);
1001}
1002
1003/* Clear a bit in the USBCMD register */
1004static void fotg210_clear_command_bit(struct fotg210_hcd *fotg210, u32 bit)
1005{
1006        fotg210->command &= ~bit;
1007        fotg210_writel(fotg210, fotg210->command, &fotg210->regs->command);
1008
1009        /* unblock posted write */
1010        fotg210_readl(fotg210, &fotg210->regs->command);
1011}
1012
1013/* EHCI timer support...  Now using hrtimers.
1014 *
1015 * Lots of different events are triggered from fotg210->hrtimer.  Whenever
1016 * the timer routine runs, it checks each possible event; events that are
1017 * currently enabled and whose expiration time has passed get handled.
1018 * The set of enabled events is stored as a collection of bitflags in
1019 * fotg210->enabled_hrtimer_events, and they are numbered in order of
1020 * increasing delay values (ranging between 1 ms and 100 ms).
1021 *
1022 * Rather than implementing a sorted list or tree of all pending events,
1023 * we keep track only of the lowest-numbered pending event, in
1024 * fotg210->next_hrtimer_event.  Whenever fotg210->hrtimer gets restarted, its
1025 * expiration time is set to the timeout value for this event.
1026 *
1027 * As a result, events might not get handled right away; the actual delay
1028 * could be anywhere up to twice the requested delay.  This doesn't
1029 * matter, because none of the events are especially time-critical.  The
1030 * ones that matter most all have a delay of 1 ms, so they will be
1031 * handled after 2 ms at most, which is okay.  In addition to this, we
1032 * allow for an expiration range of 1 ms.
1033 */
1034
1035/* Delay lengths for the hrtimer event types.
1036 * Keep this list sorted by delay length, in the same order as
1037 * the event types indexed by enum fotg210_hrtimer_event in fotg210.h.
1038 */
1039static unsigned event_delays_ns[] = {
1040        1 * NSEC_PER_MSEC,      /* FOTG210_HRTIMER_POLL_ASS */
1041        1 * NSEC_PER_MSEC,      /* FOTG210_HRTIMER_POLL_PSS */
1042        1 * NSEC_PER_MSEC,      /* FOTG210_HRTIMER_POLL_DEAD */
1043        1125 * NSEC_PER_USEC,   /* FOTG210_HRTIMER_UNLINK_INTR */
1044        2 * NSEC_PER_MSEC,      /* FOTG210_HRTIMER_FREE_ITDS */
1045        6 * NSEC_PER_MSEC,      /* FOTG210_HRTIMER_ASYNC_UNLINKS */
1046        10 * NSEC_PER_MSEC,     /* FOTG210_HRTIMER_IAA_WATCHDOG */
1047        10 * NSEC_PER_MSEC,     /* FOTG210_HRTIMER_DISABLE_PERIODIC */
1048        15 * NSEC_PER_MSEC,     /* FOTG210_HRTIMER_DISABLE_ASYNC */
1049        100 * NSEC_PER_MSEC,    /* FOTG210_HRTIMER_IO_WATCHDOG */
1050};
1051
1052/* Enable a pending hrtimer event */
1053static void fotg210_enable_event(struct fotg210_hcd *fotg210, unsigned event,
1054                bool resched)
1055{
1056        ktime_t *timeout = &fotg210->hr_timeouts[event];
1057
1058        if (resched)
1059                *timeout = ktime_add(ktime_get(), event_delays_ns[event]);
1060        fotg210->enabled_hrtimer_events |= (1 << event);
1061
1062        /* Track only the lowest-numbered pending event */
1063        if (event < fotg210->next_hrtimer_event) {
1064                fotg210->next_hrtimer_event = event;
1065                hrtimer_start_range_ns(&fotg210->hrtimer, *timeout,
1066                                NSEC_PER_MSEC, HRTIMER_MODE_ABS);
1067        }
1068}
1069
1070
1071/* Poll the STS_ASS status bit; see when it agrees with CMD_ASE */
1072static void fotg210_poll_ASS(struct fotg210_hcd *fotg210)
1073{
1074        unsigned actual, want;
1075
1076        /* Don't enable anything if the controller isn't running (e.g., died) */
1077        if (fotg210->rh_state != FOTG210_RH_RUNNING)
1078                return;
1079
1080        want = (fotg210->command & CMD_ASE) ? STS_ASS : 0;
1081        actual = fotg210_readl(fotg210, &fotg210->regs->status) & STS_ASS;
1082
1083        if (want != actual) {
1084
1085                /* Poll again later, but give up after about 20 ms */
1086                if (fotg210->ASS_poll_count++ < 20) {
1087                        fotg210_enable_event(fotg210, FOTG210_HRTIMER_POLL_ASS,
1088                                        true);
1089                        return;
1090                }
1091                fotg210_dbg(fotg210, "Waited too long for the async schedule status (%x/%x), giving up\n",
1092                                want, actual);
1093        }
1094        fotg210->ASS_poll_count = 0;
1095
1096        /* The status is up-to-date; restart or stop the schedule as needed */
1097        if (want == 0) {        /* Stopped */
1098                if (fotg210->async_count > 0)
1099                        fotg210_set_command_bit(fotg210, CMD_ASE);
1100
1101        } else {                /* Running */
1102                if (fotg210->async_count == 0) {
1103
1104                        /* Turn off the schedule after a while */
1105                        fotg210_enable_event(fotg210,
1106                                        FOTG210_HRTIMER_DISABLE_ASYNC,
1107                                        true);
1108                }
1109        }
1110}
1111
1112/* Turn off the async schedule after a brief delay */
1113static void fotg210_disable_ASE(struct fotg210_hcd *fotg210)
1114{
1115        fotg210_clear_command_bit(fotg210, CMD_ASE);
1116}
1117
1118
1119/* Poll the STS_PSS status bit; see when it agrees with CMD_PSE */
1120static void fotg210_poll_PSS(struct fotg210_hcd *fotg210)
1121{
1122        unsigned actual, want;
1123
1124        /* Don't do anything if the controller isn't running (e.g., died) */
1125        if (fotg210->rh_state != FOTG210_RH_RUNNING)
1126                return;
1127
1128        want = (fotg210->command & CMD_PSE) ? STS_PSS : 0;
1129        actual = fotg210_readl(fotg210, &fotg210->regs->status) & STS_PSS;
1130
1131        if (want != actual) {
1132
1133                /* Poll again later, but give up after about 20 ms */
1134                if (fotg210->PSS_poll_count++ < 20) {
1135                        fotg210_enable_event(fotg210, FOTG210_HRTIMER_POLL_PSS,
1136                                        true);
1137                        return;
1138                }
1139                fotg210_dbg(fotg210, "Waited too long for the periodic schedule status (%x/%x), giving up\n",
1140                                want, actual);
1141        }
1142        fotg210->PSS_poll_count = 0;
1143
1144        /* The status is up-to-date; restart or stop the schedule as needed */
1145        if (want == 0) {        /* Stopped */
1146                if (fotg210->periodic_count > 0)
1147                        fotg210_set_command_bit(fotg210, CMD_PSE);
1148
1149        } else {                /* Running */
1150                if (fotg210->periodic_count == 0) {
1151
1152                        /* Turn off the schedule after a while */
1153                        fotg210_enable_event(fotg210,
1154                                        FOTG210_HRTIMER_DISABLE_PERIODIC,
1155                                        true);
1156                }
1157        }
1158}
1159
1160/* Turn off the periodic schedule after a brief delay */
1161static void fotg210_disable_PSE(struct fotg210_hcd *fotg210)
1162{
1163        fotg210_clear_command_bit(fotg210, CMD_PSE);
1164}
1165
1166
1167/* Poll the STS_HALT status bit; see when a dead controller stops */
1168static void fotg210_handle_controller_death(struct fotg210_hcd *fotg210)
1169{
1170        if (!(fotg210_readl(fotg210, &fotg210->regs->status) & STS_HALT)) {
1171
1172                /* Give up after a few milliseconds */
1173                if (fotg210->died_poll_count++ < 5) {
1174                        /* Try again later */
1175                        fotg210_enable_event(fotg210,
1176                                        FOTG210_HRTIMER_POLL_DEAD, true);
1177                        return;
1178                }
1179                fotg210_warn(fotg210, "Waited too long for the controller to stop, giving up\n");
1180        }
1181
1182        /* Clean up the mess */
1183        fotg210->rh_state = FOTG210_RH_HALTED;
1184        fotg210_writel(fotg210, 0, &fotg210->regs->intr_enable);
1185        fotg210_work(fotg210);
1186        end_unlink_async(fotg210);
1187
1188        /* Not in process context, so don't try to reset the controller */
1189}
1190
1191
1192/* Handle unlinked interrupt QHs once they are gone from the hardware */
1193static void fotg210_handle_intr_unlinks(struct fotg210_hcd *fotg210)
1194{
1195        bool stopped = (fotg210->rh_state < FOTG210_RH_RUNNING);
1196
1197        /*
1198         * Process all the QHs on the intr_unlink list that were added
1199         * before the current unlink cycle began.  The list is in
1200         * temporal order, so stop when we reach the first entry in the
1201         * current cycle.  But if the root hub isn't running then
1202         * process all the QHs on the list.
1203         */
1204        fotg210->intr_unlinking = true;
1205        while (fotg210->intr_unlink) {
1206                struct fotg210_qh *qh = fotg210->intr_unlink;
1207
1208                if (!stopped && qh->unlink_cycle == fotg210->intr_unlink_cycle)
1209                        break;
1210                fotg210->intr_unlink = qh->unlink_next;
1211                qh->unlink_next = NULL;
1212                end_unlink_intr(fotg210, qh);
1213        }
1214
1215        /* Handle remaining entries later */
1216        if (fotg210->intr_unlink) {
1217                fotg210_enable_event(fotg210, FOTG210_HRTIMER_UNLINK_INTR,
1218                                true);
1219                ++fotg210->intr_unlink_cycle;
1220        }
1221        fotg210->intr_unlinking = false;
1222}
1223
1224
1225/* Start another free-iTDs/siTDs cycle */
1226static void start_free_itds(struct fotg210_hcd *fotg210)
1227{
1228        if (!(fotg210->enabled_hrtimer_events &
1229                        BIT(FOTG210_HRTIMER_FREE_ITDS))) {
1230                fotg210->last_itd_to_free = list_entry(
1231                                fotg210->cached_itd_list.prev,
1232                                struct fotg210_itd, itd_list);
1233                fotg210_enable_event(fotg210, FOTG210_HRTIMER_FREE_ITDS, true);
1234        }
1235}
1236
1237/* Wait for controller to stop using old iTDs and siTDs */
1238static void end_free_itds(struct fotg210_hcd *fotg210)
1239{
1240        struct fotg210_itd *itd, *n;
1241
1242        if (fotg210->rh_state < FOTG210_RH_RUNNING)
1243                fotg210->last_itd_to_free = NULL;
1244
1245        list_for_each_entry_safe(itd, n, &fotg210->cached_itd_list, itd_list) {
1246                list_del(&itd->itd_list);
1247                dma_pool_free(fotg210->itd_pool, itd, itd->itd_dma);
1248                if (itd == fotg210->last_itd_to_free)
1249                        break;
1250        }
1251
1252        if (!list_empty(&fotg210->cached_itd_list))
1253                start_free_itds(fotg210);
1254}
1255
1256
1257/* Handle lost (or very late) IAA interrupts */
1258static void fotg210_iaa_watchdog(struct fotg210_hcd *fotg210)
1259{
1260        if (fotg210->rh_state != FOTG210_RH_RUNNING)
1261                return;
1262
1263        /*
1264         * Lost IAA irqs wedge things badly; seen first with a vt8235.
1265         * So we need this watchdog, but must protect it against both
1266         * (a) SMP races against real IAA firing and retriggering, and
1267         * (b) clean HC shutdown, when IAA watchdog was pending.
1268         */
1269        if (fotg210->async_iaa) {
1270                u32 cmd, status;
1271
1272                /* If we get here, IAA is *REALLY* late.  It's barely
1273                 * conceivable that the system is so busy that CMD_IAAD
1274                 * is still legitimately set, so let's be sure it's
1275                 * clear before we read STS_IAA.  (The HC should clear
1276                 * CMD_IAAD when it sets STS_IAA.)
1277                 */
1278                cmd = fotg210_readl(fotg210, &fotg210->regs->command);
1279
1280                /*
1281                 * If IAA is set here it either legitimately triggered
1282                 * after the watchdog timer expired (_way_ late, so we'll
1283                 * still count it as lost) ... or a silicon erratum:
1284                 * - VIA seems to set IAA without triggering the IRQ;
1285                 * - IAAD potentially cleared without setting IAA.
1286                 */
1287                status = fotg210_readl(fotg210, &fotg210->regs->status);
1288                if ((status & STS_IAA) || !(cmd & CMD_IAAD)) {
1289                        INCR(fotg210->stats.lost_iaa);
1290                        fotg210_writel(fotg210, STS_IAA,
1291                                        &fotg210->regs->status);
1292                }
1293
1294                fotg210_dbg(fotg210, "IAA watchdog: status %x cmd %x\n",
1295                                status, cmd);
1296                end_unlink_async(fotg210);
1297        }
1298}
1299
1300
1301/* Enable the I/O watchdog, if appropriate */
1302static void turn_on_io_watchdog(struct fotg210_hcd *fotg210)
1303{
1304        /* Not needed if the controller isn't running or it's already enabled */
1305        if (fotg210->rh_state != FOTG210_RH_RUNNING ||
1306                        (fotg210->enabled_hrtimer_events &
1307                        BIT(FOTG210_HRTIMER_IO_WATCHDOG)))
1308                return;
1309
1310        /*
1311         * Isochronous transfers always need the watchdog.
1312         * For other sorts we use it only if the flag is set.
1313         */
1314        if (fotg210->isoc_count > 0 || (fotg210->need_io_watchdog &&
1315                        fotg210->async_count + fotg210->intr_count > 0))
1316                fotg210_enable_event(fotg210, FOTG210_HRTIMER_IO_WATCHDOG,
1317                                true);
1318}
1319
1320
1321/* Handler functions for the hrtimer event types.
1322 * Keep this array in the same order as the event types indexed by
1323 * enum fotg210_hrtimer_event in fotg210.h.
1324 */
1325static void (*event_handlers[])(struct fotg210_hcd *) = {
1326        fotg210_poll_ASS,                       /* FOTG210_HRTIMER_POLL_ASS */
1327        fotg210_poll_PSS,                       /* FOTG210_HRTIMER_POLL_PSS */
1328        fotg210_handle_controller_death,        /* FOTG210_HRTIMER_POLL_DEAD */
1329        fotg210_handle_intr_unlinks,    /* FOTG210_HRTIMER_UNLINK_INTR */
1330        end_free_itds,                  /* FOTG210_HRTIMER_FREE_ITDS */
1331        unlink_empty_async,             /* FOTG210_HRTIMER_ASYNC_UNLINKS */
1332        fotg210_iaa_watchdog,           /* FOTG210_HRTIMER_IAA_WATCHDOG */
1333        fotg210_disable_PSE,            /* FOTG210_HRTIMER_DISABLE_PERIODIC */
1334        fotg210_disable_ASE,            /* FOTG210_HRTIMER_DISABLE_ASYNC */
1335        fotg210_work,                   /* FOTG210_HRTIMER_IO_WATCHDOG */
1336};
1337
1338static enum hrtimer_restart fotg210_hrtimer_func(struct hrtimer *t)
1339{
1340        struct fotg210_hcd *fotg210 =
1341                        container_of(t, struct fotg210_hcd, hrtimer);
1342        ktime_t now;
1343        unsigned long events;
1344        unsigned long flags;
1345        unsigned e;
1346
1347        spin_lock_irqsave(&fotg210->lock, flags);
1348
1349        events = fotg210->enabled_hrtimer_events;
1350        fotg210->enabled_hrtimer_events = 0;
1351        fotg210->next_hrtimer_event = FOTG210_HRTIMER_NO_EVENT;
1352
1353        /*
1354         * Check each pending event.  If its time has expired, handle
1355         * the event; otherwise re-enable it.
1356         */
1357        now = ktime_get();
1358        for_each_set_bit(e, &events, FOTG210_HRTIMER_NUM_EVENTS) {
1359                if (ktime_compare(now, fotg210->hr_timeouts[e]) >= 0)
1360                        event_handlers[e](fotg210);
1361                else
1362                        fotg210_enable_event(fotg210, e, false);
1363        }
1364
1365        spin_unlock_irqrestore(&fotg210->lock, flags);
1366        return HRTIMER_NORESTART;
1367}
1368
1369#define fotg210_bus_suspend NULL
1370#define fotg210_bus_resume NULL
1371
1372static int check_reset_complete(struct fotg210_hcd *fotg210, int index,
1373                u32 __iomem *status_reg, int port_status)
1374{
1375        if (!(port_status & PORT_CONNECT))
1376                return port_status;
1377
1378        /* if reset finished and it's still not enabled -- handoff */
1379        if (!(port_status & PORT_PE))
1380                /* with integrated TT, there's nobody to hand it to! */
1381                fotg210_dbg(fotg210, "Failed to enable port %d on root hub TT\n",
1382                                index + 1);
1383        else
1384                fotg210_dbg(fotg210, "port %d reset complete, port enabled\n",
1385                                index + 1);
1386
1387        return port_status;
1388}
1389
1390
1391/* build "status change" packet (one or two bytes) from HC registers */
1392
1393static int fotg210_hub_status_data(struct usb_hcd *hcd, char *buf)
1394{
1395        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
1396        u32 temp, status;
1397        u32 mask;
1398        int retval = 1;
1399        unsigned long flags;
1400
1401        /* init status to no-changes */
1402        buf[0] = 0;
1403
1404        /* Inform the core about resumes-in-progress by returning
1405         * a non-zero value even if there are no status changes.
1406         */
1407        status = fotg210->resuming_ports;
1408
1409        mask = PORT_CSC | PORT_PEC;
1410        /* PORT_RESUME from hardware ~= PORT_STAT_C_SUSPEND */
1411
1412        /* no hub change reports (bit 0) for now (power, ...) */
1413
1414        /* port N changes (bit N)? */
1415        spin_lock_irqsave(&fotg210->lock, flags);
1416
1417        temp = fotg210_readl(fotg210, &fotg210->regs->port_status);
1418
1419        /*
1420         * Return status information even for ports with OWNER set.
1421         * Otherwise hub_wq wouldn't see the disconnect event when a
1422         * high-speed device is switched over to the companion
1423         * controller by the user.
1424         */
1425
1426        if ((temp & mask) != 0 || test_bit(0, &fotg210->port_c_suspend) ||
1427                        (fotg210->reset_done[0] &&
1428                        time_after_eq(jiffies, fotg210->reset_done[0]))) {
1429                buf[0] |= 1 << 1;
1430                status = STS_PCD;
1431        }
1432        /* FIXME autosuspend idle root hubs */
1433        spin_unlock_irqrestore(&fotg210->lock, flags);
1434        return status ? retval : 0;
1435}
1436
1437static void fotg210_hub_descriptor(struct fotg210_hcd *fotg210,
1438                struct usb_hub_descriptor *desc)
1439{
1440        int ports = HCS_N_PORTS(fotg210->hcs_params);
1441        u16 temp;
1442
1443        desc->bDescriptorType = USB_DT_HUB;
1444        desc->bPwrOn2PwrGood = 10;      /* fotg210 1.0, 2.3.9 says 20ms max */
1445        desc->bHubContrCurrent = 0;
1446
1447        desc->bNbrPorts = ports;
1448        temp = 1 + (ports / 8);
1449        desc->bDescLength = 7 + 2 * temp;
1450
1451        /* two bitmaps:  ports removable, and usb 1.0 legacy PortPwrCtrlMask */
1452        memset(&desc->u.hs.DeviceRemovable[0], 0, temp);
1453        memset(&desc->u.hs.DeviceRemovable[temp], 0xff, temp);
1454
1455        temp = HUB_CHAR_INDV_PORT_OCPM; /* per-port overcurrent reporting */
1456        temp |= HUB_CHAR_NO_LPSM;       /* no power switching */
1457        desc->wHubCharacteristics = cpu_to_le16(temp);
1458}
1459
1460static int fotg210_hub_control(struct usb_hcd *hcd, u16 typeReq, u16 wValue,
1461                u16 wIndex, char *buf, u16 wLength)
1462{
1463        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
1464        int ports = HCS_N_PORTS(fotg210->hcs_params);
1465        u32 __iomem *status_reg = &fotg210->regs->port_status;
1466        u32 temp, temp1, status;
1467        unsigned long flags;
1468        int retval = 0;
1469        unsigned selector;
1470
1471        /*
1472         * FIXME:  support SetPortFeatures USB_PORT_FEAT_INDICATOR.
1473         * HCS_INDICATOR may say we can change LEDs to off/amber/green.
1474         * (track current state ourselves) ... blink for diagnostics,
1475         * power, "this is the one", etc.  EHCI spec supports this.
1476         */
1477
1478        spin_lock_irqsave(&fotg210->lock, flags);
1479        switch (typeReq) {
1480        case ClearHubFeature:
1481                switch (wValue) {
1482                case C_HUB_LOCAL_POWER:
1483                case C_HUB_OVER_CURRENT:
1484                        /* no hub-wide feature/status flags */
1485                        break;
1486                default:
1487                        goto error;
1488                }
1489                break;
1490        case ClearPortFeature:
1491                if (!wIndex || wIndex > ports)
1492                        goto error;
1493                wIndex--;
1494                temp = fotg210_readl(fotg210, status_reg);
1495                temp &= ~PORT_RWC_BITS;
1496
1497                /*
1498                 * Even if OWNER is set, so the port is owned by the
1499                 * companion controller, hub_wq needs to be able to clear
1500                 * the port-change status bits (especially
1501                 * USB_PORT_STAT_C_CONNECTION).
1502                 */
1503
1504                switch (wValue) {
1505                case USB_PORT_FEAT_ENABLE:
1506                        fotg210_writel(fotg210, temp & ~PORT_PE, status_reg);
1507                        break;
1508                case USB_PORT_FEAT_C_ENABLE:
1509                        fotg210_writel(fotg210, temp | PORT_PEC, status_reg);
1510                        break;
1511                case USB_PORT_FEAT_SUSPEND:
1512                        if (temp & PORT_RESET)
1513                                goto error;
1514                        if (!(temp & PORT_SUSPEND))
1515                                break;
1516                        if ((temp & PORT_PE) == 0)
1517                                goto error;
1518
1519                        /* resume signaling for 20 msec */
1520                        fotg210_writel(fotg210, temp | PORT_RESUME, status_reg);
1521                        fotg210->reset_done[wIndex] = jiffies
1522                                        + msecs_to_jiffies(USB_RESUME_TIMEOUT);
1523                        break;
1524                case USB_PORT_FEAT_C_SUSPEND:
1525                        clear_bit(wIndex, &fotg210->port_c_suspend);
1526                        break;
1527                case USB_PORT_FEAT_C_CONNECTION:
1528                        fotg210_writel(fotg210, temp | PORT_CSC, status_reg);
1529                        break;
1530                case USB_PORT_FEAT_C_OVER_CURRENT:
1531                        fotg210_writel(fotg210, temp | OTGISR_OVC,
1532                                        &fotg210->regs->otgisr);
1533                        break;
1534                case USB_PORT_FEAT_C_RESET:
1535                        /* GetPortStatus clears reset */
1536                        break;
1537                default:
1538                        goto error;
1539                }
1540                fotg210_readl(fotg210, &fotg210->regs->command);
1541                break;
1542        case GetHubDescriptor:
1543                fotg210_hub_descriptor(fotg210, (struct usb_hub_descriptor *)
1544                                buf);
1545                break;
1546        case GetHubStatus:
1547                /* no hub-wide feature/status flags */
1548                memset(buf, 0, 4);
1549                /*cpu_to_le32s ((u32 *) buf); */
1550                break;
1551        case GetPortStatus:
1552                if (!wIndex || wIndex > ports)
1553                        goto error;
1554                wIndex--;
1555                status = 0;
1556                temp = fotg210_readl(fotg210, status_reg);
1557
1558                /* wPortChange bits */
1559                if (temp & PORT_CSC)
1560                        status |= USB_PORT_STAT_C_CONNECTION << 16;
1561                if (temp & PORT_PEC)
1562                        status |= USB_PORT_STAT_C_ENABLE << 16;
1563
1564                temp1 = fotg210_readl(fotg210, &fotg210->regs->otgisr);
1565                if (temp1 & OTGISR_OVC)
1566                        status |= USB_PORT_STAT_C_OVERCURRENT << 16;
1567
1568                /* whoever resumes must GetPortStatus to complete it!! */
1569                if (temp & PORT_RESUME) {
1570
1571                        /* Remote Wakeup received? */
1572                        if (!fotg210->reset_done[wIndex]) {
1573                                /* resume signaling for 20 msec */
1574                                fotg210->reset_done[wIndex] = jiffies
1575                                                + msecs_to_jiffies(20);
1576                                /* check the port again */
1577                                mod_timer(&fotg210_to_hcd(fotg210)->rh_timer,
1578                                                fotg210->reset_done[wIndex]);
1579                        }
1580
1581                        /* resume completed? */
1582                        else if (time_after_eq(jiffies,
1583                                        fotg210->reset_done[wIndex])) {
1584                                clear_bit(wIndex, &fotg210->suspended_ports);
1585                                set_bit(wIndex, &fotg210->port_c_suspend);
1586                                fotg210->reset_done[wIndex] = 0;
1587
1588                                /* stop resume signaling */
1589                                temp = fotg210_readl(fotg210, status_reg);
1590                                fotg210_writel(fotg210, temp &
1591                                                ~(PORT_RWC_BITS | PORT_RESUME),
1592                                                status_reg);
1593                                clear_bit(wIndex, &fotg210->resuming_ports);
1594                                retval = handshake(fotg210, status_reg,
1595                                                PORT_RESUME, 0, 2000);/* 2ms */
1596                                if (retval != 0) {
1597                                        fotg210_err(fotg210,
1598                                                        "port %d resume error %d\n",
1599                                                        wIndex + 1, retval);
1600                                        goto error;
1601                                }
1602                                temp &= ~(PORT_SUSPEND|PORT_RESUME|(3<<10));
1603                        }
1604                }
1605
1606                /* whoever resets must GetPortStatus to complete it!! */
1607                if ((temp & PORT_RESET) && time_after_eq(jiffies,
1608                                fotg210->reset_done[wIndex])) {
1609                        status |= USB_PORT_STAT_C_RESET << 16;
1610                        fotg210->reset_done[wIndex] = 0;
1611                        clear_bit(wIndex, &fotg210->resuming_ports);
1612
1613                        /* force reset to complete */
1614                        fotg210_writel(fotg210,
1615                                        temp & ~(PORT_RWC_BITS | PORT_RESET),
1616                                        status_reg);
1617                        /* REVISIT:  some hardware needs 550+ usec to clear
1618                         * this bit; seems too long to spin routinely...
1619                         */
1620                        retval = handshake(fotg210, status_reg,
1621                                        PORT_RESET, 0, 1000);
1622                        if (retval != 0) {
1623                                fotg210_err(fotg210, "port %d reset error %d\n",
1624                                                wIndex + 1, retval);
1625                                goto error;
1626                        }
1627
1628                        /* see what we found out */
1629                        temp = check_reset_complete(fotg210, wIndex, status_reg,
1630                                        fotg210_readl(fotg210, status_reg));
1631                }
1632
1633                if (!(temp & (PORT_RESUME|PORT_RESET))) {
1634                        fotg210->reset_done[wIndex] = 0;
1635                        clear_bit(wIndex, &fotg210->resuming_ports);
1636                }
1637
1638                /* transfer dedicated ports to the companion hc */
1639                if ((temp & PORT_CONNECT) &&
1640                                test_bit(wIndex, &fotg210->companion_ports)) {
1641                        temp &= ~PORT_RWC_BITS;
1642                        fotg210_writel(fotg210, temp, status_reg);
1643                        fotg210_dbg(fotg210, "port %d --> companion\n",
1644                                        wIndex + 1);
1645                        temp = fotg210_readl(fotg210, status_reg);
1646                }
1647
1648                /*
1649                 * Even if OWNER is set, there's no harm letting hub_wq
1650                 * see the wPortStatus values (they should all be 0 except
1651                 * for PORT_POWER anyway).
1652                 */
1653
1654                if (temp & PORT_CONNECT) {
1655                        status |= USB_PORT_STAT_CONNECTION;
1656                        status |= fotg210_port_speed(fotg210, temp);
1657                }
1658                if (temp & PORT_PE)
1659                        status |= USB_PORT_STAT_ENABLE;
1660
1661                /* maybe the port was unsuspended without our knowledge */
1662                if (temp & (PORT_SUSPEND|PORT_RESUME)) {
1663                        status |= USB_PORT_STAT_SUSPEND;
1664                } else if (test_bit(wIndex, &fotg210->suspended_ports)) {
1665                        clear_bit(wIndex, &fotg210->suspended_ports);
1666                        clear_bit(wIndex, &fotg210->resuming_ports);
1667                        fotg210->reset_done[wIndex] = 0;
1668                        if (temp & PORT_PE)
1669                                set_bit(wIndex, &fotg210->port_c_suspend);
1670                }
1671
1672                temp1 = fotg210_readl(fotg210, &fotg210->regs->otgisr);
1673                if (temp1 & OTGISR_OVC)
1674                        status |= USB_PORT_STAT_OVERCURRENT;
1675                if (temp & PORT_RESET)
1676                        status |= USB_PORT_STAT_RESET;
1677                if (test_bit(wIndex, &fotg210->port_c_suspend))
1678                        status |= USB_PORT_STAT_C_SUSPEND << 16;
1679
1680                if (status & ~0xffff)   /* only if wPortChange is interesting */
1681                        dbg_port(fotg210, "GetStatus", wIndex + 1, temp);
1682                put_unaligned_le32(status, buf);
1683                break;
1684        case SetHubFeature:
1685                switch (wValue) {
1686                case C_HUB_LOCAL_POWER:
1687                case C_HUB_OVER_CURRENT:
1688                        /* no hub-wide feature/status flags */
1689                        break;
1690                default:
1691                        goto error;
1692                }
1693                break;
1694        case SetPortFeature:
1695                selector = wIndex >> 8;
1696                wIndex &= 0xff;
1697
1698                if (!wIndex || wIndex > ports)
1699                        goto error;
1700                wIndex--;
1701                temp = fotg210_readl(fotg210, status_reg);
1702                temp &= ~PORT_RWC_BITS;
1703                switch (wValue) {
1704                case USB_PORT_FEAT_SUSPEND:
1705                        if ((temp & PORT_PE) == 0
1706                                        || (temp & PORT_RESET) != 0)
1707                                goto error;
1708
1709                        /* After above check the port must be connected.
1710                         * Set appropriate bit thus could put phy into low power
1711                         * mode if we have hostpc feature
1712                         */
1713                        fotg210_writel(fotg210, temp | PORT_SUSPEND,
1714                                        status_reg);
1715                        set_bit(wIndex, &fotg210->suspended_ports);
1716                        break;
1717                case USB_PORT_FEAT_RESET:
1718                        if (temp & PORT_RESUME)
1719                                goto error;
1720                        /* line status bits may report this as low speed,
1721                         * which can be fine if this root hub has a
1722                         * transaction translator built in.
1723                         */
1724                        fotg210_dbg(fotg210, "port %d reset\n", wIndex + 1);
1725                        temp |= PORT_RESET;
1726                        temp &= ~PORT_PE;
1727
1728                        /*
1729                         * caller must wait, then call GetPortStatus
1730                         * usb 2.0 spec says 50 ms resets on root
1731                         */
1732                        fotg210->reset_done[wIndex] = jiffies
1733                                        + msecs_to_jiffies(50);
1734                        fotg210_writel(fotg210, temp, status_reg);
1735                        break;
1736
1737                /* For downstream facing ports (these):  one hub port is put
1738                 * into test mode according to USB2 11.24.2.13, then the hub
1739                 * must be reset (which for root hub now means rmmod+modprobe,
1740                 * or else system reboot).  See EHCI 2.3.9 and 4.14 for info
1741                 * about the EHCI-specific stuff.
1742                 */
1743                case USB_PORT_FEAT_TEST:
1744                        if (!selector || selector > 5)
1745                                goto error;
1746                        spin_unlock_irqrestore(&fotg210->lock, flags);
1747                        fotg210_quiesce(fotg210);
1748                        spin_lock_irqsave(&fotg210->lock, flags);
1749
1750                        /* Put all enabled ports into suspend */
1751                        temp = fotg210_readl(fotg210, status_reg) &
1752                                ~PORT_RWC_BITS;
1753                        if (temp & PORT_PE)
1754                                fotg210_writel(fotg210, temp | PORT_SUSPEND,
1755                                                status_reg);
1756
1757                        spin_unlock_irqrestore(&fotg210->lock, flags);
1758                        fotg210_halt(fotg210);
1759                        spin_lock_irqsave(&fotg210->lock, flags);
1760
1761                        temp = fotg210_readl(fotg210, status_reg);
1762                        temp |= selector << 16;
1763                        fotg210_writel(fotg210, temp, status_reg);
1764                        break;
1765
1766                default:
1767                        goto error;
1768                }
1769                fotg210_readl(fotg210, &fotg210->regs->command);
1770                break;
1771
1772        default:
1773error:
1774                /* "stall" on error */
1775                retval = -EPIPE;
1776        }
1777        spin_unlock_irqrestore(&fotg210->lock, flags);
1778        return retval;
1779}
1780
1781static void __maybe_unused fotg210_relinquish_port(struct usb_hcd *hcd,
1782                int portnum)
1783{
1784        return;
1785}
1786
1787static int __maybe_unused fotg210_port_handed_over(struct usb_hcd *hcd,
1788                int portnum)
1789{
1790        return 0;
1791}
1792
1793/* There's basically three types of memory:
1794 *      - data used only by the HCD ... kmalloc is fine
1795 *      - async and periodic schedules, shared by HC and HCD ... these
1796 *        need to use dma_pool or dma_alloc_coherent
1797 *      - driver buffers, read/written by HC ... single shot DMA mapped
1798 *
1799 * There's also "register" data (e.g. PCI or SOC), which is memory mapped.
1800 * No memory seen by this driver is pageable.
1801 */
1802
1803/* Allocate the key transfer structures from the previously allocated pool */
1804static inline void fotg210_qtd_init(struct fotg210_hcd *fotg210,
1805                struct fotg210_qtd *qtd, dma_addr_t dma)
1806{
1807        memset(qtd, 0, sizeof(*qtd));
1808        qtd->qtd_dma = dma;
1809        qtd->hw_token = cpu_to_hc32(fotg210, QTD_STS_HALT);
1810        qtd->hw_next = FOTG210_LIST_END(fotg210);
1811        qtd->hw_alt_next = FOTG210_LIST_END(fotg210);
1812        INIT_LIST_HEAD(&qtd->qtd_list);
1813}
1814
1815static struct fotg210_qtd *fotg210_qtd_alloc(struct fotg210_hcd *fotg210,
1816                gfp_t flags)
1817{
1818        struct fotg210_qtd *qtd;
1819        dma_addr_t dma;
1820
1821        qtd = dma_pool_alloc(fotg210->qtd_pool, flags, &dma);
1822        if (qtd != NULL)
1823                fotg210_qtd_init(fotg210, qtd, dma);
1824
1825        return qtd;
1826}
1827
1828static inline void fotg210_qtd_free(struct fotg210_hcd *fotg210,
1829                struct fotg210_qtd *qtd)
1830{
1831        dma_pool_free(fotg210->qtd_pool, qtd, qtd->qtd_dma);
1832}
1833
1834
1835static void qh_destroy(struct fotg210_hcd *fotg210, struct fotg210_qh *qh)
1836{
1837        /* clean qtds first, and know this is not linked */
1838        if (!list_empty(&qh->qtd_list) || qh->qh_next.ptr) {
1839                fotg210_dbg(fotg210, "unused qh not empty!\n");
1840                BUG();
1841        }
1842        if (qh->dummy)
1843                fotg210_qtd_free(fotg210, qh->dummy);
1844        dma_pool_free(fotg210->qh_pool, qh->hw, qh->qh_dma);
1845        kfree(qh);
1846}
1847
1848static struct fotg210_qh *fotg210_qh_alloc(struct fotg210_hcd *fotg210,
1849                gfp_t flags)
1850{
1851        struct fotg210_qh *qh;
1852        dma_addr_t dma;
1853
1854        qh = kzalloc(sizeof(*qh), GFP_ATOMIC);
1855        if (!qh)
1856                goto done;
1857        qh->hw = dma_pool_zalloc(fotg210->qh_pool, flags, &dma);
1858        if (!qh->hw)
1859                goto fail;
1860        qh->qh_dma = dma;
1861        INIT_LIST_HEAD(&qh->qtd_list);
1862
1863        /* dummy td enables safe urb queuing */
1864        qh->dummy = fotg210_qtd_alloc(fotg210, flags);
1865        if (qh->dummy == NULL) {
1866                fotg210_dbg(fotg210, "no dummy td\n");
1867                goto fail1;
1868        }
1869done:
1870        return qh;
1871fail1:
1872        dma_pool_free(fotg210->qh_pool, qh->hw, qh->qh_dma);
1873fail:
1874        kfree(qh);
1875        return NULL;
1876}
1877
1878/* The queue heads and transfer descriptors are managed from pools tied
1879 * to each of the "per device" structures.
1880 * This is the initialisation and cleanup code.
1881 */
1882
1883static void fotg210_mem_cleanup(struct fotg210_hcd *fotg210)
1884{
1885        if (fotg210->async)
1886                qh_destroy(fotg210, fotg210->async);
1887        fotg210->async = NULL;
1888
1889        if (fotg210->dummy)
1890                qh_destroy(fotg210, fotg210->dummy);
1891        fotg210->dummy = NULL;
1892
1893        /* DMA consistent memory and pools */
1894        dma_pool_destroy(fotg210->qtd_pool);
1895        fotg210->qtd_pool = NULL;
1896
1897        dma_pool_destroy(fotg210->qh_pool);
1898        fotg210->qh_pool = NULL;
1899
1900        dma_pool_destroy(fotg210->itd_pool);
1901        fotg210->itd_pool = NULL;
1902
1903        if (fotg210->periodic)
1904                dma_free_coherent(fotg210_to_hcd(fotg210)->self.controller,
1905                                fotg210->periodic_size * sizeof(u32),
1906                                fotg210->periodic, fotg210->periodic_dma);
1907        fotg210->periodic = NULL;
1908
1909        /* shadow periodic table */
1910        kfree(fotg210->pshadow);
1911        fotg210->pshadow = NULL;
1912}
1913
1914/* remember to add cleanup code (above) if you add anything here */
1915static int fotg210_mem_init(struct fotg210_hcd *fotg210, gfp_t flags)
1916{
1917        int i;
1918
1919        /* QTDs for control/bulk/intr transfers */
1920        fotg210->qtd_pool = dma_pool_create("fotg210_qtd",
1921                        fotg210_to_hcd(fotg210)->self.controller,
1922                        sizeof(struct fotg210_qtd),
1923                        32 /* byte alignment (for hw parts) */,
1924                        4096 /* can't cross 4K */);
1925        if (!fotg210->qtd_pool)
1926                goto fail;
1927
1928        /* QHs for control/bulk/intr transfers */
1929        fotg210->qh_pool = dma_pool_create("fotg210_qh",
1930                        fotg210_to_hcd(fotg210)->self.controller,
1931                        sizeof(struct fotg210_qh_hw),
1932                        32 /* byte alignment (for hw parts) */,
1933                        4096 /* can't cross 4K */);
1934        if (!fotg210->qh_pool)
1935                goto fail;
1936
1937        fotg210->async = fotg210_qh_alloc(fotg210, flags);
1938        if (!fotg210->async)
1939                goto fail;
1940
1941        /* ITD for high speed ISO transfers */
1942        fotg210->itd_pool = dma_pool_create("fotg210_itd",
1943                        fotg210_to_hcd(fotg210)->self.controller,
1944                        sizeof(struct fotg210_itd),
1945                        64 /* byte alignment (for hw parts) */,
1946                        4096 /* can't cross 4K */);
1947        if (!fotg210->itd_pool)
1948                goto fail;
1949
1950        /* Hardware periodic table */
1951        fotg210->periodic = (__le32 *)
1952                dma_alloc_coherent(fotg210_to_hcd(fotg210)->self.controller,
1953                                fotg210->periodic_size * sizeof(__le32),
1954                                &fotg210->periodic_dma, 0);
1955        if (fotg210->periodic == NULL)
1956                goto fail;
1957
1958        for (i = 0; i < fotg210->periodic_size; i++)
1959                fotg210->periodic[i] = FOTG210_LIST_END(fotg210);
1960
1961        /* software shadow of hardware table */
1962        fotg210->pshadow = kcalloc(fotg210->periodic_size, sizeof(void *),
1963                        flags);
1964        if (fotg210->pshadow != NULL)
1965                return 0;
1966
1967fail:
1968        fotg210_dbg(fotg210, "couldn't init memory\n");
1969        fotg210_mem_cleanup(fotg210);
1970        return -ENOMEM;
1971}
1972/* EHCI hardware queue manipulation ... the core.  QH/QTD manipulation.
1973 *
1974 * Control, bulk, and interrupt traffic all use "qh" lists.  They list "qtd"
1975 * entries describing USB transactions, max 16-20kB/entry (with 4kB-aligned
1976 * buffers needed for the larger number).  We use one QH per endpoint, queue
1977 * multiple urbs (all three types) per endpoint.  URBs may need several qtds.
1978 *
1979 * ISO traffic uses "ISO TD" (itd) records, and (along with
1980 * interrupts) needs careful scheduling.  Performance improvements can be
1981 * an ongoing challenge.  That's in "ehci-sched.c".
1982 *
1983 * USB 1.1 devices are handled (a) by "companion" OHCI or UHCI root hubs,
1984 * or otherwise through transaction translators (TTs) in USB 2.0 hubs using
1985 * (b) special fields in qh entries or (c) split iso entries.  TTs will
1986 * buffer low/full speed data so the host collects it at high speed.
1987 */
1988
1989/* fill a qtd, returning how much of the buffer we were able to queue up */
1990static int qtd_fill(struct fotg210_hcd *fotg210, struct fotg210_qtd *qtd,
1991                dma_addr_t buf, size_t len, int token, int maxpacket)
1992{
1993        int i, count;
1994        u64 addr = buf;
1995
1996        /* one buffer entry per 4K ... first might be short or unaligned */
1997        qtd->hw_buf[0] = cpu_to_hc32(fotg210, (u32)addr);
1998        qtd->hw_buf_hi[0] = cpu_to_hc32(fotg210, (u32)(addr >> 32));
1999        count = 0x1000 - (buf & 0x0fff);        /* rest of that page */
2000        if (likely(len < count))                /* ... iff needed */
2001                count = len;
2002        else {
2003                buf +=  0x1000;
2004                buf &= ~0x0fff;
2005
2006                /* per-qtd limit: from 16K to 20K (best alignment) */
2007                for (i = 1; count < len && i < 5; i++) {
2008                        addr = buf;
2009                        qtd->hw_buf[i] = cpu_to_hc32(fotg210, (u32)addr);
2010                        qtd->hw_buf_hi[i] = cpu_to_hc32(fotg210,
2011                                        (u32)(addr >> 32));
2012                        buf += 0x1000;
2013                        if ((count + 0x1000) < len)
2014                                count += 0x1000;
2015                        else
2016                                count = len;
2017                }
2018
2019                /* short packets may only terminate transfers */
2020                if (count != len)
2021                        count -= (count % maxpacket);
2022        }
2023        qtd->hw_token = cpu_to_hc32(fotg210, (count << 16) | token);
2024        qtd->length = count;
2025
2026        return count;
2027}
2028
2029static inline void qh_update(struct fotg210_hcd *fotg210,
2030                struct fotg210_qh *qh, struct fotg210_qtd *qtd)
2031{
2032        struct fotg210_qh_hw *hw = qh->hw;
2033
2034        /* writes to an active overlay are unsafe */
2035        BUG_ON(qh->qh_state != QH_STATE_IDLE);
2036
2037        hw->hw_qtd_next = QTD_NEXT(fotg210, qtd->qtd_dma);
2038        hw->hw_alt_next = FOTG210_LIST_END(fotg210);
2039
2040        /* Except for control endpoints, we make hardware maintain data
2041         * toggle (like OHCI) ... here (re)initialize the toggle in the QH,
2042         * and set the pseudo-toggle in udev. Only usb_clear_halt() will
2043         * ever clear it.
2044         */
2045        if (!(hw->hw_info1 & cpu_to_hc32(fotg210, QH_TOGGLE_CTL))) {
2046                unsigned is_out, epnum;
2047
2048                is_out = qh->is_out;
2049                epnum = (hc32_to_cpup(fotg210, &hw->hw_info1) >> 8) & 0x0f;
2050                if (unlikely(!usb_gettoggle(qh->dev, epnum, is_out))) {
2051                        hw->hw_token &= ~cpu_to_hc32(fotg210, QTD_TOGGLE);
2052                        usb_settoggle(qh->dev, epnum, is_out, 1);
2053                }
2054        }
2055
2056        hw->hw_token &= cpu_to_hc32(fotg210, QTD_TOGGLE | QTD_STS_PING);
2057}
2058
2059/* if it weren't for a common silicon quirk (writing the dummy into the qh
2060 * overlay, so qh->hw_token wrongly becomes inactive/halted), only fault
2061 * recovery (including urb dequeue) would need software changes to a QH...
2062 */
2063static void qh_refresh(struct fotg210_hcd *fotg210, struct fotg210_qh *qh)
2064{
2065        struct fotg210_qtd *qtd;
2066
2067        if (list_empty(&qh->qtd_list))
2068                qtd = qh->dummy;
2069        else {
2070                qtd = list_entry(qh->qtd_list.next,
2071                                struct fotg210_qtd, qtd_list);
2072                /*
2073                 * first qtd may already be partially processed.
2074                 * If we come here during unlink, the QH overlay region
2075                 * might have reference to the just unlinked qtd. The
2076                 * qtd is updated in qh_completions(). Update the QH
2077                 * overlay here.
2078                 */
2079                if (cpu_to_hc32(fotg210, qtd->qtd_dma) == qh->hw->hw_current) {
2080                        qh->hw->hw_qtd_next = qtd->hw_next;
2081                        qtd = NULL;
2082                }
2083        }
2084
2085        if (qtd)
2086                qh_update(fotg210, qh, qtd);
2087}
2088
2089static void qh_link_async(struct fotg210_hcd *fotg210, struct fotg210_qh *qh);
2090
2091static void fotg210_clear_tt_buffer_complete(struct usb_hcd *hcd,
2092                struct usb_host_endpoint *ep)
2093{
2094        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
2095        struct fotg210_qh *qh = ep->hcpriv;
2096        unsigned long flags;
2097
2098        spin_lock_irqsave(&fotg210->lock, flags);
2099        qh->clearing_tt = 0;
2100        if (qh->qh_state == QH_STATE_IDLE && !list_empty(&qh->qtd_list)
2101                        && fotg210->rh_state == FOTG210_RH_RUNNING)
2102                qh_link_async(fotg210, qh);
2103        spin_unlock_irqrestore(&fotg210->lock, flags);
2104}
2105
2106static void fotg210_clear_tt_buffer(struct fotg210_hcd *fotg210,
2107                struct fotg210_qh *qh, struct urb *urb, u32 token)
2108{
2109
2110        /* If an async split transaction gets an error or is unlinked,
2111         * the TT buffer may be left in an indeterminate state.  We
2112         * have to clear the TT buffer.
2113         *
2114         * Note: this routine is never called for Isochronous transfers.
2115         */
2116        if (urb->dev->tt && !usb_pipeint(urb->pipe) && !qh->clearing_tt) {
2117                struct usb_device *tt = urb->dev->tt->hub;
2118
2119                dev_dbg(&tt->dev,
2120                                "clear tt buffer port %d, a%d ep%d t%08x\n",
2121                                urb->dev->ttport, urb->dev->devnum,
2122                                usb_pipeendpoint(urb->pipe), token);
2123
2124                if (urb->dev->tt->hub !=
2125                                fotg210_to_hcd(fotg210)->self.root_hub) {
2126                        if (usb_hub_clear_tt_buffer(urb) == 0)
2127                                qh->clearing_tt = 1;
2128                }
2129        }
2130}
2131
2132static int qtd_copy_status(struct fotg210_hcd *fotg210, struct urb *urb,
2133                size_t length, u32 token)
2134{
2135        int status = -EINPROGRESS;
2136
2137        /* count IN/OUT bytes, not SETUP (even short packets) */
2138        if (likely(QTD_PID(token) != 2))
2139                urb->actual_length += length - QTD_LENGTH(token);
2140
2141        /* don't modify error codes */
2142        if (unlikely(urb->unlinked))
2143                return status;
2144
2145        /* force cleanup after short read; not always an error */
2146        if (unlikely(IS_SHORT_READ(token)))
2147                status = -EREMOTEIO;
2148
2149        /* serious "can't proceed" faults reported by the hardware */
2150        if (token & QTD_STS_HALT) {
2151                if (token & QTD_STS_BABBLE) {
2152                        /* FIXME "must" disable babbling device's port too */
2153                        status = -EOVERFLOW;
2154                /* CERR nonzero + halt --> stall */
2155                } else if (QTD_CERR(token)) {
2156                        status = -EPIPE;
2157
2158                /* In theory, more than one of the following bits can be set
2159                 * since they are sticky and the transaction is retried.
2160                 * Which to test first is rather arbitrary.
2161                 */
2162                } else if (token & QTD_STS_MMF) {
2163                        /* fs/ls interrupt xfer missed the complete-split */
2164                        status = -EPROTO;
2165                } else if (token & QTD_STS_DBE) {
2166                        status = (QTD_PID(token) == 1) /* IN ? */
2167                                ? -ENOSR  /* hc couldn't read data */
2168                                : -ECOMM; /* hc couldn't write data */
2169                } else if (token & QTD_STS_XACT) {
2170                        /* timeout, bad CRC, wrong PID, etc */
2171                        fotg210_dbg(fotg210, "devpath %s ep%d%s 3strikes\n",
2172                                        urb->dev->devpath,
2173                                        usb_pipeendpoint(urb->pipe),
2174                                        usb_pipein(urb->pipe) ? "in" : "out");
2175                        status = -EPROTO;
2176                } else {        /* unknown */
2177                        status = -EPROTO;
2178                }
2179
2180                fotg210_dbg(fotg210,
2181                                "dev%d ep%d%s qtd token %08x --> status %d\n",
2182                                usb_pipedevice(urb->pipe),
2183                                usb_pipeendpoint(urb->pipe),
2184                                usb_pipein(urb->pipe) ? "in" : "out",
2185                                token, status);
2186        }
2187
2188        return status;
2189}
2190
2191static void fotg210_urb_done(struct fotg210_hcd *fotg210, struct urb *urb,
2192                int status)
2193__releases(fotg210->lock)
2194__acquires(fotg210->lock)
2195{
2196        if (likely(urb->hcpriv != NULL)) {
2197                struct fotg210_qh *qh = (struct fotg210_qh *) urb->hcpriv;
2198
2199                /* S-mask in a QH means it's an interrupt urb */
2200                if ((qh->hw->hw_info2 & cpu_to_hc32(fotg210, QH_SMASK)) != 0) {
2201
2202                        /* ... update hc-wide periodic stats (for usbfs) */
2203                        fotg210_to_hcd(fotg210)->self.bandwidth_int_reqs--;
2204                }
2205        }
2206
2207        if (unlikely(urb->unlinked)) {
2208                INCR(fotg210->stats.unlink);
2209        } else {
2210                /* report non-error and short read status as zero */
2211                if (status == -EINPROGRESS || status == -EREMOTEIO)
2212                        status = 0;
2213                INCR(fotg210->stats.complete);
2214        }
2215
2216#ifdef FOTG210_URB_TRACE
2217        fotg210_dbg(fotg210,
2218                        "%s %s urb %p ep%d%s status %d len %d/%d\n",
2219                        __func__, urb->dev->devpath, urb,
2220                        usb_pipeendpoint(urb->pipe),
2221                        usb_pipein(urb->pipe) ? "in" : "out",
2222                        status,
2223                        urb->actual_length, urb->transfer_buffer_length);
2224#endif
2225
2226        /* complete() can reenter this HCD */
2227        usb_hcd_unlink_urb_from_ep(fotg210_to_hcd(fotg210), urb);
2228        spin_unlock(&fotg210->lock);
2229        usb_hcd_giveback_urb(fotg210_to_hcd(fotg210), urb, status);
2230        spin_lock(&fotg210->lock);
2231}
2232
2233static int qh_schedule(struct fotg210_hcd *fotg210, struct fotg210_qh *qh);
2234
2235/* Process and free completed qtds for a qh, returning URBs to drivers.
2236 * Chases up to qh->hw_current.  Returns number of completions called,
2237 * indicating how much "real" work we did.
2238 */
2239static unsigned qh_completions(struct fotg210_hcd *fotg210,
2240                struct fotg210_qh *qh)
2241{
2242        struct fotg210_qtd *last, *end = qh->dummy;
2243        struct fotg210_qtd *qtd, *tmp;
2244        int last_status;
2245        int stopped;
2246        unsigned count = 0;
2247        u8 state;
2248        struct fotg210_qh_hw *hw = qh->hw;
2249
2250        if (unlikely(list_empty(&qh->qtd_list)))
2251                return count;
2252
2253        /* completions (or tasks on other cpus) must never clobber HALT
2254         * till we've gone through and cleaned everything up, even when
2255         * they add urbs to this qh's queue or mark them for unlinking.
2256         *
2257         * NOTE:  unlinking expects to be done in queue order.
2258         *
2259         * It's a bug for qh->qh_state to be anything other than
2260         * QH_STATE_IDLE, unless our caller is scan_async() or
2261         * scan_intr().
2262         */
2263        state = qh->qh_state;
2264        qh->qh_state = QH_STATE_COMPLETING;
2265        stopped = (state == QH_STATE_IDLE);
2266
2267rescan:
2268        last = NULL;
2269        last_status = -EINPROGRESS;
2270        qh->needs_rescan = 0;
2271
2272        /* remove de-activated QTDs from front of queue.
2273         * after faults (including short reads), cleanup this urb
2274         * then let the queue advance.
2275         * if queue is stopped, handles unlinks.
2276         */
2277        list_for_each_entry_safe(qtd, tmp, &qh->qtd_list, qtd_list) {
2278                struct urb *urb;
2279                u32 token = 0;
2280
2281                urb = qtd->urb;
2282
2283                /* clean up any state from previous QTD ...*/
2284                if (last) {
2285                        if (likely(last->urb != urb)) {
2286                                fotg210_urb_done(fotg210, last->urb,
2287                                                last_status);
2288                                count++;
2289                                last_status = -EINPROGRESS;
2290                        }
2291                        fotg210_qtd_free(fotg210, last);
2292                        last = NULL;
2293                }
2294
2295                /* ignore urbs submitted during completions we reported */
2296                if (qtd == end)
2297                        break;
2298
2299                /* hardware copies qtd out of qh overlay */
2300                rmb();
2301                token = hc32_to_cpu(fotg210, qtd->hw_token);
2302
2303                /* always clean up qtds the hc de-activated */
2304retry_xacterr:
2305                if ((token & QTD_STS_ACTIVE) == 0) {
2306
2307                        /* Report Data Buffer Error: non-fatal but useful */
2308                        if (token & QTD_STS_DBE)
2309                                fotg210_dbg(fotg210,
2310                                        "detected DataBufferErr for urb %p ep%d%s len %d, qtd %p [qh %p]\n",
2311                                        urb, usb_endpoint_num(&urb->ep->desc),
2312                                        usb_endpoint_dir_in(&urb->ep->desc)
2313                                                ? "in" : "out",
2314                                        urb->transfer_buffer_length, qtd, qh);
2315
2316                        /* on STALL, error, and short reads this urb must
2317                         * complete and all its qtds must be recycled.
2318                         */
2319                        if ((token & QTD_STS_HALT) != 0) {
2320
2321                                /* retry transaction errors until we
2322                                 * reach the software xacterr limit
2323                                 */
2324                                if ((token & QTD_STS_XACT) &&
2325                                                QTD_CERR(token) == 0 &&
2326                                                ++qh->xacterrs < QH_XACTERR_MAX &&
2327                                                !urb->unlinked) {
2328                                        fotg210_dbg(fotg210,
2329                                                "detected XactErr len %zu/%zu retry %d\n",
2330                                                qtd->length - QTD_LENGTH(token),
2331                                                qtd->length,
2332                                                qh->xacterrs);
2333
2334                                        /* reset the token in the qtd and the
2335                                         * qh overlay (which still contains
2336                                         * the qtd) so that we pick up from
2337                                         * where we left off
2338                                         */
2339                                        token &= ~QTD_STS_HALT;
2340                                        token |= QTD_STS_ACTIVE |
2341                                                 (FOTG210_TUNE_CERR << 10);
2342                                        qtd->hw_token = cpu_to_hc32(fotg210,
2343                                                        token);
2344                                        wmb();
2345                                        hw->hw_token = cpu_to_hc32(fotg210,
2346                                                        token);
2347                                        goto retry_xacterr;
2348                                }
2349                                stopped = 1;
2350
2351                        /* magic dummy for some short reads; qh won't advance.
2352                         * that silicon quirk can kick in with this dummy too.
2353                         *
2354                         * other short reads won't stop the queue, including
2355                         * control transfers (status stage handles that) or
2356                         * most other single-qtd reads ... the queue stops if
2357                         * URB_SHORT_NOT_OK was set so the driver submitting
2358                         * the urbs could clean it up.
2359                         */
2360                        } else if (IS_SHORT_READ(token) &&
2361                                        !(qtd->hw_alt_next &
2362                                        FOTG210_LIST_END(fotg210))) {
2363                                stopped = 1;
2364                        }
2365
2366                /* stop scanning when we reach qtds the hc is using */
2367                } else if (likely(!stopped
2368                                && fotg210->rh_state >= FOTG210_RH_RUNNING)) {
2369                        break;
2370
2371                /* scan the whole queue for unlinks whenever it stops */
2372                } else {
2373                        stopped = 1;
2374
2375                        /* cancel everything if we halt, suspend, etc */
2376                        if (fotg210->rh_state < FOTG210_RH_RUNNING)
2377                                last_status = -ESHUTDOWN;
2378
2379                        /* this qtd is active; skip it unless a previous qtd
2380                         * for its urb faulted, or its urb was canceled.
2381                         */
2382                        else if (last_status == -EINPROGRESS && !urb->unlinked)
2383                                continue;
2384
2385                        /* qh unlinked; token in overlay may be most current */
2386                        if (state == QH_STATE_IDLE &&
2387                                        cpu_to_hc32(fotg210, qtd->qtd_dma)
2388                                        == hw->hw_current) {
2389                                token = hc32_to_cpu(fotg210, hw->hw_token);
2390
2391                                /* An unlink may leave an incomplete
2392                                 * async transaction in the TT buffer.
2393                                 * We have to clear it.
2394                                 */
2395                                fotg210_clear_tt_buffer(fotg210, qh, urb,
2396                                                token);
2397                        }
2398                }
2399
2400                /* unless we already know the urb's status, collect qtd status
2401                 * and update count of bytes transferred.  in common short read
2402                 * cases with only one data qtd (including control transfers),
2403                 * queue processing won't halt.  but with two or more qtds (for
2404                 * example, with a 32 KB transfer), when the first qtd gets a
2405                 * short read the second must be removed by hand.
2406                 */
2407                if (last_status == -EINPROGRESS) {
2408                        last_status = qtd_copy_status(fotg210, urb,
2409                                        qtd->length, token);
2410                        if (last_status == -EREMOTEIO &&
2411                                        (qtd->hw_alt_next &
2412                                        FOTG210_LIST_END(fotg210)))
2413                                last_status = -EINPROGRESS;
2414
2415                        /* As part of low/full-speed endpoint-halt processing
2416                         * we must clear the TT buffer (11.17.5).
2417                         */
2418                        if (unlikely(last_status != -EINPROGRESS &&
2419                                        last_status != -EREMOTEIO)) {
2420                                /* The TT's in some hubs malfunction when they
2421                                 * receive this request following a STALL (they
2422                                 * stop sending isochronous packets).  Since a
2423                                 * STALL can't leave the TT buffer in a busy
2424                                 * state (if you believe Figures 11-48 - 11-51
2425                                 * in the USB 2.0 spec), we won't clear the TT
2426                                 * buffer in this case.  Strictly speaking this
2427                                 * is a violation of the spec.
2428                                 */
2429                                if (last_status != -EPIPE)
2430                                        fotg210_clear_tt_buffer(fotg210, qh,
2431                                                        urb, token);
2432                        }
2433                }
2434
2435                /* if we're removing something not at the queue head,
2436                 * patch the hardware queue pointer.
2437                 */
2438                if (stopped && qtd->qtd_list.prev != &qh->qtd_list) {
2439                        last = list_entry(qtd->qtd_list.prev,
2440                                        struct fotg210_qtd, qtd_list);
2441                        last->hw_next = qtd->hw_next;
2442                }
2443
2444                /* remove qtd; it's recycled after possible urb completion */
2445                list_del(&qtd->qtd_list);
2446                last = qtd;
2447
2448                /* reinit the xacterr counter for the next qtd */
2449                qh->xacterrs = 0;
2450        }
2451
2452        /* last urb's completion might still need calling */
2453        if (likely(last != NULL)) {
2454                fotg210_urb_done(fotg210, last->urb, last_status);
2455                count++;
2456                fotg210_qtd_free(fotg210, last);
2457        }
2458
2459        /* Do we need to rescan for URBs dequeued during a giveback? */
2460        if (unlikely(qh->needs_rescan)) {
2461                /* If the QH is already unlinked, do the rescan now. */
2462                if (state == QH_STATE_IDLE)
2463                        goto rescan;
2464
2465                /* Otherwise we have to wait until the QH is fully unlinked.
2466                 * Our caller will start an unlink if qh->needs_rescan is
2467                 * set.  But if an unlink has already started, nothing needs
2468                 * to be done.
2469                 */
2470                if (state != QH_STATE_LINKED)
2471                        qh->needs_rescan = 0;
2472        }
2473
2474        /* restore original state; caller must unlink or relink */
2475        qh->qh_state = state;
2476
2477        /* be sure the hardware's done with the qh before refreshing
2478         * it after fault cleanup, or recovering from silicon wrongly
2479         * overlaying the dummy qtd (which reduces DMA chatter).
2480         */
2481        if (stopped != 0 || hw->hw_qtd_next == FOTG210_LIST_END(fotg210)) {
2482                switch (state) {
2483                case QH_STATE_IDLE:
2484                        qh_refresh(fotg210, qh);
2485                        break;
2486                case QH_STATE_LINKED:
2487                        /* We won't refresh a QH that's linked (after the HC
2488                         * stopped the queue).  That avoids a race:
2489                         *  - HC reads first part of QH;
2490                         *  - CPU updates that first part and the token;
2491                         *  - HC reads rest of that QH, including token
2492                         * Result:  HC gets an inconsistent image, and then
2493                         * DMAs to/from the wrong memory (corrupting it).
2494                         *
2495                         * That should be rare for interrupt transfers,
2496                         * except maybe high bandwidth ...
2497                         */
2498
2499                        /* Tell the caller to start an unlink */
2500                        qh->needs_rescan = 1;
2501                        break;
2502                /* otherwise, unlink already started */
2503                }
2504        }
2505
2506        return count;
2507}
2508
2509/* high bandwidth multiplier, as encoded in highspeed endpoint descriptors */
2510#define hb_mult(wMaxPacketSize) (1 + (((wMaxPacketSize) >> 11) & 0x03))
2511/* ... and packet size, for any kind of endpoint descriptor */
2512#define max_packet(wMaxPacketSize) ((wMaxPacketSize) & 0x07ff)
2513
2514/* reverse of qh_urb_transaction:  free a list of TDs.
2515 * used for cleanup after errors, before HC sees an URB's TDs.
2516 */
2517static void qtd_list_free(struct fotg210_hcd *fotg210, struct urb *urb,
2518                struct list_head *head)
2519{
2520        struct fotg210_qtd *qtd, *temp;
2521
2522        list_for_each_entry_safe(qtd, temp, head, qtd_list) {
2523                list_del(&qtd->qtd_list);
2524                fotg210_qtd_free(fotg210, qtd);
2525        }
2526}
2527
2528/* create a list of filled qtds for this URB; won't link into qh.
2529 */
2530static struct list_head *qh_urb_transaction(struct fotg210_hcd *fotg210,
2531                struct urb *urb, struct list_head *head, gfp_t flags)
2532{
2533        struct fotg210_qtd *qtd, *qtd_prev;
2534        dma_addr_t buf;
2535        int len, this_sg_len, maxpacket;
2536        int is_input;
2537        u32 token;
2538        int i;
2539        struct scatterlist *sg;
2540
2541        /*
2542         * URBs map to sequences of QTDs:  one logical transaction
2543         */
2544        qtd = fotg210_qtd_alloc(fotg210, flags);
2545        if (unlikely(!qtd))
2546                return NULL;
2547        list_add_tail(&qtd->qtd_list, head);
2548        qtd->urb = urb;
2549
2550        token = QTD_STS_ACTIVE;
2551        token |= (FOTG210_TUNE_CERR << 10);
2552        /* for split transactions, SplitXState initialized to zero */
2553
2554        len = urb->transfer_buffer_length;
2555        is_input = usb_pipein(urb->pipe);
2556        if (usb_pipecontrol(urb->pipe)) {
2557                /* SETUP pid */
2558                qtd_fill(fotg210, qtd, urb->setup_dma,
2559                                sizeof(struct usb_ctrlrequest),
2560                                token | (2 /* "setup" */ << 8), 8);
2561
2562                /* ... and always at least one more pid */
2563                token ^= QTD_TOGGLE;
2564                qtd_prev = qtd;
2565                qtd = fotg210_qtd_alloc(fotg210, flags);
2566                if (unlikely(!qtd))
2567                        goto cleanup;
2568                qtd->urb = urb;
2569                qtd_prev->hw_next = QTD_NEXT(fotg210, qtd->qtd_dma);
2570                list_add_tail(&qtd->qtd_list, head);
2571
2572                /* for zero length DATA stages, STATUS is always IN */
2573                if (len == 0)
2574                        token |= (1 /* "in" */ << 8);
2575        }
2576
2577        /*
2578         * data transfer stage:  buffer setup
2579         */
2580        i = urb->num_mapped_sgs;
2581        if (len > 0 && i > 0) {
2582                sg = urb->sg;
2583                buf = sg_dma_address(sg);
2584
2585                /* urb->transfer_buffer_length may be smaller than the
2586                 * size of the scatterlist (or vice versa)
2587                 */
2588                this_sg_len = min_t(int, sg_dma_len(sg), len);
2589        } else {
2590                sg = NULL;
2591                buf = urb->transfer_dma;
2592                this_sg_len = len;
2593        }
2594
2595        if (is_input)
2596                token |= (1 /* "in" */ << 8);
2597        /* else it's already initted to "out" pid (0 << 8) */
2598
2599        maxpacket = max_packet(usb_maxpacket(urb->dev, urb->pipe, !is_input));
2600
2601        /*
2602         * buffer gets wrapped in one or more qtds;
2603         * last one may be "short" (including zero len)
2604         * and may serve as a control status ack
2605         */
2606        for (;;) {
2607                int this_qtd_len;
2608
2609                this_qtd_len = qtd_fill(fotg210, qtd, buf, this_sg_len, token,
2610                                maxpacket);
2611                this_sg_len -= this_qtd_len;
2612                len -= this_qtd_len;
2613                buf += this_qtd_len;
2614
2615                /*
2616                 * short reads advance to a "magic" dummy instead of the next
2617                 * qtd ... that forces the queue to stop, for manual cleanup.
2618                 * (this will usually be overridden later.)
2619                 */
2620                if (is_input)
2621                        qtd->hw_alt_next = fotg210->async->hw->hw_alt_next;
2622
2623                /* qh makes control packets use qtd toggle; maybe switch it */
2624                if ((maxpacket & (this_qtd_len + (maxpacket - 1))) == 0)
2625                        token ^= QTD_TOGGLE;
2626
2627                if (likely(this_sg_len <= 0)) {
2628                        if (--i <= 0 || len <= 0)
2629                                break;
2630                        sg = sg_next(sg);
2631                        buf = sg_dma_address(sg);
2632                        this_sg_len = min_t(int, sg_dma_len(sg), len);
2633                }
2634
2635                qtd_prev = qtd;
2636                qtd = fotg210_qtd_alloc(fotg210, flags);
2637                if (unlikely(!qtd))
2638                        goto cleanup;
2639                qtd->urb = urb;
2640                qtd_prev->hw_next = QTD_NEXT(fotg210, qtd->qtd_dma);
2641                list_add_tail(&qtd->qtd_list, head);
2642        }
2643
2644        /*
2645         * unless the caller requires manual cleanup after short reads,
2646         * have the alt_next mechanism keep the queue running after the
2647         * last data qtd (the only one, for control and most other cases).
2648         */
2649        if (likely((urb->transfer_flags & URB_SHORT_NOT_OK) == 0 ||
2650                        usb_pipecontrol(urb->pipe)))
2651                qtd->hw_alt_next = FOTG210_LIST_END(fotg210);
2652
2653        /*
2654         * control requests may need a terminating data "status" ack;
2655         * other OUT ones may need a terminating short packet
2656         * (zero length).
2657         */
2658        if (likely(urb->transfer_buffer_length != 0)) {
2659                int one_more = 0;
2660
2661                if (usb_pipecontrol(urb->pipe)) {
2662                        one_more = 1;
2663                        token ^= 0x0100;        /* "in" <--> "out"  */
2664                        token |= QTD_TOGGLE;    /* force DATA1 */
2665                } else if (usb_pipeout(urb->pipe)
2666                                && (urb->transfer_flags & URB_ZERO_PACKET)
2667                                && !(urb->transfer_buffer_length % maxpacket)) {
2668                        one_more = 1;
2669                }
2670                if (one_more) {
2671                        qtd_prev = qtd;
2672                        qtd = fotg210_qtd_alloc(fotg210, flags);
2673                        if (unlikely(!qtd))
2674                                goto cleanup;
2675                        qtd->urb = urb;
2676                        qtd_prev->hw_next = QTD_NEXT(fotg210, qtd->qtd_dma);
2677                        list_add_tail(&qtd->qtd_list, head);
2678
2679                        /* never any data in such packets */
2680                        qtd_fill(fotg210, qtd, 0, 0, token, 0);
2681                }
2682        }
2683
2684        /* by default, enable interrupt on urb completion */
2685        if (likely(!(urb->transfer_flags & URB_NO_INTERRUPT)))
2686                qtd->hw_token |= cpu_to_hc32(fotg210, QTD_IOC);
2687        return head;
2688
2689cleanup:
2690        qtd_list_free(fotg210, urb, head);
2691        return NULL;
2692}
2693
2694/* Would be best to create all qh's from config descriptors,
2695 * when each interface/altsetting is established.  Unlink
2696 * any previous qh and cancel its urbs first; endpoints are
2697 * implicitly reset then (data toggle too).
2698 * That'd mean updating how usbcore talks to HCDs. (2.7?)
2699*/
2700
2701
2702/* Each QH holds a qtd list; a QH is used for everything except iso.
2703 *
2704 * For interrupt urbs, the scheduler must set the microframe scheduling
2705 * mask(s) each time the QH gets scheduled.  For highspeed, that's
2706 * just one microframe in the s-mask.  For split interrupt transactions
2707 * there are additional complications: c-mask, maybe FSTNs.
2708 */
2709static struct fotg210_qh *qh_make(struct fotg210_hcd *fotg210, struct urb *urb,
2710                gfp_t flags)
2711{
2712        struct fotg210_qh *qh = fotg210_qh_alloc(fotg210, flags);
2713        u32 info1 = 0, info2 = 0;
2714        int is_input, type;
2715        int maxp = 0;
2716        struct usb_tt *tt = urb->dev->tt;
2717        struct fotg210_qh_hw *hw;
2718
2719        if (!qh)
2720                return qh;
2721
2722        /*
2723         * init endpoint/device data for this QH
2724         */
2725        info1 |= usb_pipeendpoint(urb->pipe) << 8;
2726        info1 |= usb_pipedevice(urb->pipe) << 0;
2727
2728        is_input = usb_pipein(urb->pipe);
2729        type = usb_pipetype(urb->pipe);
2730        maxp = usb_maxpacket(urb->dev, urb->pipe, !is_input);
2731
2732        /* 1024 byte maxpacket is a hardware ceiling.  High bandwidth
2733         * acts like up to 3KB, but is built from smaller packets.
2734         */
2735        if (max_packet(maxp) > 1024) {
2736                fotg210_dbg(fotg210, "bogus qh maxpacket %d\n",
2737                                max_packet(maxp));
2738                goto done;
2739        }
2740
2741        /* Compute interrupt scheduling parameters just once, and save.
2742         * - allowing for high bandwidth, how many nsec/uframe are used?
2743         * - split transactions need a second CSPLIT uframe; same question
2744         * - splits also need a schedule gap (for full/low speed I/O)
2745         * - qh has a polling interval
2746         *
2747         * For control/bulk requests, the HC or TT handles these.
2748         */
2749        if (type == PIPE_INTERRUPT) {
2750                qh->usecs = NS_TO_US(usb_calc_bus_time(USB_SPEED_HIGH,
2751                                is_input, 0,
2752                                hb_mult(maxp) * max_packet(maxp)));
2753                qh->start = NO_FRAME;
2754
2755                if (urb->dev->speed == USB_SPEED_HIGH) {
2756                        qh->c_usecs = 0;
2757                        qh->gap_uf = 0;
2758
2759                        qh->period = urb->interval >> 3;
2760                        if (qh->period == 0 && urb->interval != 1) {
2761                                /* NOTE interval 2 or 4 uframes could work.
2762                                 * But interval 1 scheduling is simpler, and
2763                                 * includes high bandwidth.
2764                                 */
2765                                urb->interval = 1;
2766                        } else if (qh->period > fotg210->periodic_size) {
2767                                qh->period = fotg210->periodic_size;
2768                                urb->interval = qh->period << 3;
2769                        }
2770                } else {
2771                        int think_time;
2772
2773                        /* gap is f(FS/LS transfer times) */
2774                        qh->gap_uf = 1 + usb_calc_bus_time(urb->dev->speed,
2775                                        is_input, 0, maxp) / (125 * 1000);
2776
2777                        /* FIXME this just approximates SPLIT/CSPLIT times */
2778                        if (is_input) {         /* SPLIT, gap, CSPLIT+DATA */
2779                                qh->c_usecs = qh->usecs + HS_USECS(0);
2780                                qh->usecs = HS_USECS(1);
2781                        } else {                /* SPLIT+DATA, gap, CSPLIT */
2782                                qh->usecs += HS_USECS(1);
2783                                qh->c_usecs = HS_USECS(0);
2784                        }
2785
2786                        think_time = tt ? tt->think_time : 0;
2787                        qh->tt_usecs = NS_TO_US(think_time +
2788                                        usb_calc_bus_time(urb->dev->speed,
2789                                        is_input, 0, max_packet(maxp)));
2790                        qh->period = urb->interval;
2791                        if (qh->period > fotg210->periodic_size) {
2792                                qh->period = fotg210->periodic_size;
2793                                urb->interval = qh->period;
2794                        }
2795                }
2796        }
2797
2798        /* support for tt scheduling, and access to toggles */
2799        qh->dev = urb->dev;
2800
2801        /* using TT? */
2802        switch (urb->dev->speed) {
2803        case USB_SPEED_LOW:
2804                info1 |= QH_LOW_SPEED;
2805                /* FALL THROUGH */
2806
2807        case USB_SPEED_FULL:
2808                /* EPS 0 means "full" */
2809                if (type != PIPE_INTERRUPT)
2810                        info1 |= (FOTG210_TUNE_RL_TT << 28);
2811                if (type == PIPE_CONTROL) {
2812                        info1 |= QH_CONTROL_EP;         /* for TT */
2813                        info1 |= QH_TOGGLE_CTL;         /* toggle from qtd */
2814                }
2815                info1 |= maxp << 16;
2816
2817                info2 |= (FOTG210_TUNE_MULT_TT << 30);
2818
2819                /* Some Freescale processors have an erratum in which the
2820                 * port number in the queue head was 0..N-1 instead of 1..N.
2821                 */
2822                if (fotg210_has_fsl_portno_bug(fotg210))
2823                        info2 |= (urb->dev->ttport-1) << 23;
2824                else
2825                        info2 |= urb->dev->ttport << 23;
2826
2827                /* set the address of the TT; for TDI's integrated
2828                 * root hub tt, leave it zeroed.
2829                 */
2830                if (tt && tt->hub != fotg210_to_hcd(fotg210)->self.root_hub)
2831                        info2 |= tt->hub->devnum << 16;
2832
2833                /* NOTE:  if (PIPE_INTERRUPT) { scheduler sets c-mask } */
2834
2835                break;
2836
2837        case USB_SPEED_HIGH:            /* no TT involved */
2838                info1 |= QH_HIGH_SPEED;
2839                if (type == PIPE_CONTROL) {
2840                        info1 |= (FOTG210_TUNE_RL_HS << 28);
2841                        info1 |= 64 << 16;      /* usb2 fixed maxpacket */
2842                        info1 |= QH_TOGGLE_CTL; /* toggle from qtd */
2843                        info2 |= (FOTG210_TUNE_MULT_HS << 30);
2844                } else if (type == PIPE_BULK) {
2845                        info1 |= (FOTG210_TUNE_RL_HS << 28);
2846                        /* The USB spec says that high speed bulk endpoints
2847                         * always use 512 byte maxpacket.  But some device
2848                         * vendors decided to ignore that, and MSFT is happy
2849                         * to help them do so.  So now people expect to use
2850                         * such nonconformant devices with Linux too; sigh.
2851                         */
2852                        info1 |= max_packet(maxp) << 16;
2853                        info2 |= (FOTG210_TUNE_MULT_HS << 30);
2854                } else {                /* PIPE_INTERRUPT */
2855                        info1 |= max_packet(maxp) << 16;
2856                        info2 |= hb_mult(maxp) << 30;
2857                }
2858                break;
2859        default:
2860                fotg210_dbg(fotg210, "bogus dev %p speed %d\n", urb->dev,
2861                                urb->dev->speed);
2862done:
2863                qh_destroy(fotg210, qh);
2864                return NULL;
2865        }
2866
2867        /* NOTE:  if (PIPE_INTERRUPT) { scheduler sets s-mask } */
2868
2869        /* init as live, toggle clear, advance to dummy */
2870        qh->qh_state = QH_STATE_IDLE;
2871        hw = qh->hw;
2872        hw->hw_info1 = cpu_to_hc32(fotg210, info1);
2873        hw->hw_info2 = cpu_to_hc32(fotg210, info2);
2874        qh->is_out = !is_input;
2875        usb_settoggle(urb->dev, usb_pipeendpoint(urb->pipe), !is_input, 1);
2876        qh_refresh(fotg210, qh);
2877        return qh;
2878}
2879
2880static void enable_async(struct fotg210_hcd *fotg210)
2881{
2882        if (fotg210->async_count++)
2883                return;
2884
2885        /* Stop waiting to turn off the async schedule */
2886        fotg210->enabled_hrtimer_events &= ~BIT(FOTG210_HRTIMER_DISABLE_ASYNC);
2887
2888        /* Don't start the schedule until ASS is 0 */
2889        fotg210_poll_ASS(fotg210);
2890        turn_on_io_watchdog(fotg210);
2891}
2892
2893static void disable_async(struct fotg210_hcd *fotg210)
2894{
2895        if (--fotg210->async_count)
2896                return;
2897
2898        /* The async schedule and async_unlink list are supposed to be empty */
2899        WARN_ON(fotg210->async->qh_next.qh || fotg210->async_unlink);
2900
2901        /* Don't turn off the schedule until ASS is 1 */
2902        fotg210_poll_ASS(fotg210);
2903}
2904
2905/* move qh (and its qtds) onto async queue; maybe enable queue.  */
2906
2907static void qh_link_async(struct fotg210_hcd *fotg210, struct fotg210_qh *qh)
2908{
2909        __hc32 dma = QH_NEXT(fotg210, qh->qh_dma);
2910        struct fotg210_qh *head;
2911
2912        /* Don't link a QH if there's a Clear-TT-Buffer pending */
2913        if (unlikely(qh->clearing_tt))
2914                return;
2915
2916        WARN_ON(qh->qh_state != QH_STATE_IDLE);
2917
2918        /* clear halt and/or toggle; and maybe recover from silicon quirk */
2919        qh_refresh(fotg210, qh);
2920
2921        /* splice right after start */
2922        head = fotg210->async;
2923        qh->qh_next = head->qh_next;
2924        qh->hw->hw_next = head->hw->hw_next;
2925        wmb();
2926
2927        head->qh_next.qh = qh;
2928        head->hw->hw_next = dma;
2929
2930        qh->xacterrs = 0;
2931        qh->qh_state = QH_STATE_LINKED;
2932        /* qtd completions reported later by interrupt */
2933
2934        enable_async(fotg210);
2935}
2936
2937/* For control/bulk/interrupt, return QH with these TDs appended.
2938 * Allocates and initializes the QH if necessary.
2939 * Returns null if it can't allocate a QH it needs to.
2940 * If the QH has TDs (urbs) already, that's great.
2941 */
2942static struct fotg210_qh *qh_append_tds(struct fotg210_hcd *fotg210,
2943                struct urb *urb, struct list_head *qtd_list,
2944                int epnum, void **ptr)
2945{
2946        struct fotg210_qh *qh = NULL;
2947        __hc32 qh_addr_mask = cpu_to_hc32(fotg210, 0x7f);
2948
2949        qh = (struct fotg210_qh *) *ptr;
2950        if (unlikely(qh == NULL)) {
2951                /* can't sleep here, we have fotg210->lock... */
2952                qh = qh_make(fotg210, urb, GFP_ATOMIC);
2953                *ptr = qh;
2954        }
2955        if (likely(qh != NULL)) {
2956                struct fotg210_qtd *qtd;
2957
2958                if (unlikely(list_empty(qtd_list)))
2959                        qtd = NULL;
2960                else
2961                        qtd = list_entry(qtd_list->next, struct fotg210_qtd,
2962                                        qtd_list);
2963
2964                /* control qh may need patching ... */
2965                if (unlikely(epnum == 0)) {
2966                        /* usb_reset_device() briefly reverts to address 0 */
2967                        if (usb_pipedevice(urb->pipe) == 0)
2968                                qh->hw->hw_info1 &= ~qh_addr_mask;
2969                }
2970
2971                /* just one way to queue requests: swap with the dummy qtd.
2972                 * only hc or qh_refresh() ever modify the overlay.
2973                 */
2974                if (likely(qtd != NULL)) {
2975                        struct fotg210_qtd *dummy;
2976                        dma_addr_t dma;
2977                        __hc32 token;
2978
2979                        /* to avoid racing the HC, use the dummy td instead of
2980                         * the first td of our list (becomes new dummy).  both
2981                         * tds stay deactivated until we're done, when the
2982                         * HC is allowed to fetch the old dummy (4.10.2).
2983                         */
2984                        token = qtd->hw_token;
2985                        qtd->hw_token = HALT_BIT(fotg210);
2986
2987                        dummy = qh->dummy;
2988
2989                        dma = dummy->qtd_dma;
2990                        *dummy = *qtd;
2991                        dummy->qtd_dma = dma;
2992
2993                        list_del(&qtd->qtd_list);
2994                        list_add(&dummy->qtd_list, qtd_list);
2995                        list_splice_tail(qtd_list, &qh->qtd_list);
2996
2997                        fotg210_qtd_init(fotg210, qtd, qtd->qtd_dma);
2998                        qh->dummy = qtd;
2999
3000                        /* hc must see the new dummy at list end */
3001                        dma = qtd->qtd_dma;
3002                        qtd = list_entry(qh->qtd_list.prev,
3003                                        struct fotg210_qtd, qtd_list);
3004                        qtd->hw_next = QTD_NEXT(fotg210, dma);
3005
3006                        /* let the hc process these next qtds */
3007                        wmb();
3008                        dummy->hw_token = token;
3009
3010                        urb->hcpriv = qh;
3011                }
3012        }
3013        return qh;
3014}
3015
3016static int submit_async(struct fotg210_hcd *fotg210, struct urb *urb,
3017                struct list_head *qtd_list, gfp_t mem_flags)
3018{
3019        int epnum;
3020        unsigned long flags;
3021        struct fotg210_qh *qh = NULL;
3022        int rc;
3023
3024        epnum = urb->ep->desc.bEndpointAddress;
3025
3026#ifdef FOTG210_URB_TRACE
3027        {
3028                struct fotg210_qtd *qtd;
3029
3030                qtd = list_entry(qtd_list->next, struct fotg210_qtd, qtd_list);
3031                fotg210_dbg(fotg210,
3032                                "%s %s urb %p ep%d%s len %d, qtd %p [qh %p]\n",
3033                                __func__, urb->dev->devpath, urb,
3034                                epnum & 0x0f, (epnum & USB_DIR_IN)
3035                                        ? "in" : "out",
3036                                urb->transfer_buffer_length,
3037                                qtd, urb->ep->hcpriv);
3038        }
3039#endif
3040
3041        spin_lock_irqsave(&fotg210->lock, flags);
3042        if (unlikely(!HCD_HW_ACCESSIBLE(fotg210_to_hcd(fotg210)))) {
3043                rc = -ESHUTDOWN;
3044                goto done;
3045        }
3046        rc = usb_hcd_link_urb_to_ep(fotg210_to_hcd(fotg210), urb);
3047        if (unlikely(rc))
3048                goto done;
3049
3050        qh = qh_append_tds(fotg210, urb, qtd_list, epnum, &urb->ep->hcpriv);
3051        if (unlikely(qh == NULL)) {
3052                usb_hcd_unlink_urb_from_ep(fotg210_to_hcd(fotg210), urb);
3053                rc = -ENOMEM;
3054                goto done;
3055        }
3056
3057        /* Control/bulk operations through TTs don't need scheduling,
3058         * the HC and TT handle it when the TT has a buffer ready.
3059         */
3060        if (likely(qh->qh_state == QH_STATE_IDLE))
3061                qh_link_async(fotg210, qh);
3062done:
3063        spin_unlock_irqrestore(&fotg210->lock, flags);
3064        if (unlikely(qh == NULL))
3065                qtd_list_free(fotg210, urb, qtd_list);
3066        return rc;
3067}
3068
3069static void single_unlink_async(struct fotg210_hcd *fotg210,
3070                struct fotg210_qh *qh)
3071{
3072        struct fotg210_qh *prev;
3073
3074        /* Add to the end of the list of QHs waiting for the next IAAD */
3075        qh->qh_state = QH_STATE_UNLINK;
3076        if (fotg210->async_unlink)
3077                fotg210->async_unlink_last->unlink_next = qh;
3078        else
3079                fotg210->async_unlink = qh;
3080        fotg210->async_unlink_last = qh;
3081
3082        /* Unlink it from the schedule */
3083        prev = fotg210->async;
3084        while (prev->qh_next.qh != qh)
3085                prev = prev->qh_next.qh;
3086
3087        prev->hw->hw_next = qh->hw->hw_next;
3088        prev->qh_next = qh->qh_next;
3089        if (fotg210->qh_scan_next == qh)
3090                fotg210->qh_scan_next = qh->qh_next.qh;
3091}
3092
3093static void start_iaa_cycle(struct fotg210_hcd *fotg210, bool nested)
3094{
3095        /*
3096         * Do nothing if an IAA cycle is already running or
3097         * if one will be started shortly.
3098         */
3099        if (fotg210->async_iaa || fotg210->async_unlinking)
3100                return;
3101
3102        /* Do all the waiting QHs at once */
3103        fotg210->async_iaa = fotg210->async_unlink;
3104        fotg210->async_unlink = NULL;
3105
3106        /* If the controller isn't running, we don't have to wait for it */
3107        if (unlikely(fotg210->rh_state < FOTG210_RH_RUNNING)) {
3108                if (!nested)            /* Avoid recursion */
3109                        end_unlink_async(fotg210);
3110
3111        /* Otherwise start a new IAA cycle */
3112        } else if (likely(fotg210->rh_state == FOTG210_RH_RUNNING)) {
3113                /* Make sure the unlinks are all visible to the hardware */
3114                wmb();
3115
3116                fotg210_writel(fotg210, fotg210->command | CMD_IAAD,
3117                                &fotg210->regs->command);
3118                fotg210_readl(fotg210, &fotg210->regs->command);
3119                fotg210_enable_event(fotg210, FOTG210_HRTIMER_IAA_WATCHDOG,
3120                                true);
3121        }
3122}
3123
3124/* the async qh for the qtds being unlinked are now gone from the HC */
3125
3126static void end_unlink_async(struct fotg210_hcd *fotg210)
3127{
3128        struct fotg210_qh *qh;
3129
3130        /* Process the idle QHs */
3131restart:
3132        fotg210->async_unlinking = true;
3133        while (fotg210->async_iaa) {
3134                qh = fotg210->async_iaa;
3135                fotg210->async_iaa = qh->unlink_next;
3136                qh->unlink_next = NULL;
3137
3138                qh->qh_state = QH_STATE_IDLE;
3139                qh->qh_next.qh = NULL;
3140
3141                qh_completions(fotg210, qh);
3142                if (!list_empty(&qh->qtd_list) &&
3143                                fotg210->rh_state == FOTG210_RH_RUNNING)
3144                        qh_link_async(fotg210, qh);
3145                disable_async(fotg210);
3146        }
3147        fotg210->async_unlinking = false;
3148
3149        /* Start a new IAA cycle if any QHs are waiting for it */
3150        if (fotg210->async_unlink) {
3151                start_iaa_cycle(fotg210, true);
3152                if (unlikely(fotg210->rh_state < FOTG210_RH_RUNNING))
3153                        goto restart;
3154        }
3155}
3156
3157static void unlink_empty_async(struct fotg210_hcd *fotg210)
3158{
3159        struct fotg210_qh *qh, *next;
3160        bool stopped = (fotg210->rh_state < FOTG210_RH_RUNNING);
3161        bool check_unlinks_later = false;
3162
3163        /* Unlink all the async QHs that have been empty for a timer cycle */
3164        next = fotg210->async->qh_next.qh;
3165        while (next) {
3166                qh = next;
3167                next = qh->qh_next.qh;
3168
3169                if (list_empty(&qh->qtd_list) &&
3170                                qh->qh_state == QH_STATE_LINKED) {
3171                        if (!stopped && qh->unlink_cycle ==
3172                                        fotg210->async_unlink_cycle)
3173                                check_unlinks_later = true;
3174                        else
3175                                single_unlink_async(fotg210, qh);
3176                }
3177        }
3178
3179        /* Start a new IAA cycle if any QHs are waiting for it */
3180        if (fotg210->async_unlink)
3181                start_iaa_cycle(fotg210, false);
3182
3183        /* QHs that haven't been empty for long enough will be handled later */
3184        if (check_unlinks_later) {
3185                fotg210_enable_event(fotg210, FOTG210_HRTIMER_ASYNC_UNLINKS,
3186                                true);
3187                ++fotg210->async_unlink_cycle;
3188        }
3189}
3190
3191/* makes sure the async qh will become idle */
3192/* caller must own fotg210->lock */
3193
3194static void start_unlink_async(struct fotg210_hcd *fotg210,
3195                struct fotg210_qh *qh)
3196{
3197        /*
3198         * If the QH isn't linked then there's nothing we can do
3199         * unless we were called during a giveback, in which case
3200         * qh_completions() has to deal with it.
3201         */
3202        if (qh->qh_state != QH_STATE_LINKED) {
3203                if (qh->qh_state == QH_STATE_COMPLETING)
3204                        qh->needs_rescan = 1;
3205                return;
3206        }
3207
3208        single_unlink_async(fotg210, qh);
3209        start_iaa_cycle(fotg210, false);
3210}
3211
3212static void scan_async(struct fotg210_hcd *fotg210)
3213{
3214        struct fotg210_qh *qh;
3215        bool check_unlinks_later = false;
3216
3217        fotg210->qh_scan_next = fotg210->async->qh_next.qh;
3218        while (fotg210->qh_scan_next) {
3219                qh = fotg210->qh_scan_next;
3220                fotg210->qh_scan_next = qh->qh_next.qh;
3221rescan:
3222                /* clean any finished work for this qh */
3223                if (!list_empty(&qh->qtd_list)) {
3224                        int temp;
3225
3226                        /*
3227                         * Unlinks could happen here; completion reporting
3228                         * drops the lock.  That's why fotg210->qh_scan_next
3229                         * always holds the next qh to scan; if the next qh
3230                         * gets unlinked then fotg210->qh_scan_next is adjusted
3231                         * in single_unlink_async().
3232                         */
3233                        temp = qh_completions(fotg210, qh);
3234                        if (qh->needs_rescan) {
3235                                start_unlink_async(fotg210, qh);
3236                        } else if (list_empty(&qh->qtd_list)
3237                                        && qh->qh_state == QH_STATE_LINKED) {
3238                                qh->unlink_cycle = fotg210->async_unlink_cycle;
3239                                check_unlinks_later = true;
3240                        } else if (temp != 0)
3241                                goto rescan;
3242                }
3243        }
3244
3245        /*
3246         * Unlink empty entries, reducing DMA usage as well
3247         * as HCD schedule-scanning costs.  Delay for any qh
3248         * we just scanned, there's a not-unusual case that it
3249         * doesn't stay idle for long.
3250         */
3251        if (check_unlinks_later && fotg210->rh_state == FOTG210_RH_RUNNING &&
3252                        !(fotg210->enabled_hrtimer_events &
3253                        BIT(FOTG210_HRTIMER_ASYNC_UNLINKS))) {
3254                fotg210_enable_event(fotg210,
3255                                FOTG210_HRTIMER_ASYNC_UNLINKS, true);
3256                ++fotg210->async_unlink_cycle;
3257        }
3258}
3259/* EHCI scheduled transaction support:  interrupt, iso, split iso
3260 * These are called "periodic" transactions in the EHCI spec.
3261 *
3262 * Note that for interrupt transfers, the QH/QTD manipulation is shared
3263 * with the "asynchronous" transaction support (control/bulk transfers).
3264 * The only real difference is in how interrupt transfers are scheduled.
3265 *
3266 * For ISO, we make an "iso_stream" head to serve the same role as a QH.
3267 * It keeps track of every ITD (or SITD) that's linked, and holds enough
3268 * pre-calculated schedule data to make appending to the queue be quick.
3269 */
3270static int fotg210_get_frame(struct usb_hcd *hcd);
3271
3272/* periodic_next_shadow - return "next" pointer on shadow list
3273 * @periodic: host pointer to qh/itd
3274 * @tag: hardware tag for type of this record
3275 */
3276static union fotg210_shadow *periodic_next_shadow(struct fotg210_hcd *fotg210,
3277                union fotg210_shadow *periodic, __hc32 tag)
3278{
3279        switch (hc32_to_cpu(fotg210, tag)) {
3280        case Q_TYPE_QH:
3281                return &periodic->qh->qh_next;
3282        case Q_TYPE_FSTN:
3283                return &periodic->fstn->fstn_next;
3284        default:
3285                return &periodic->itd->itd_next;
3286        }
3287}
3288
3289static __hc32 *shadow_next_periodic(struct fotg210_hcd *fotg210,
3290                union fotg210_shadow *periodic, __hc32 tag)
3291{
3292        switch (hc32_to_cpu(fotg210, tag)) {
3293        /* our fotg210_shadow.qh is actually software part */
3294        case Q_TYPE_QH:
3295                return &periodic->qh->hw->hw_next;
3296        /* others are hw parts */
3297        default:
3298                return periodic->hw_next;
3299        }
3300}
3301
3302/* caller must hold fotg210->lock */
3303static void periodic_unlink(struct fotg210_hcd *fotg210, unsigned frame,
3304                void *ptr)
3305{
3306        union fotg210_shadow *prev_p = &fotg210->pshadow[frame];
3307        __hc32 *hw_p = &fotg210->periodic[frame];
3308        union fotg210_shadow here = *prev_p;
3309
3310        /* find predecessor of "ptr"; hw and shadow lists are in sync */
3311        while (here.ptr && here.ptr != ptr) {
3312                prev_p = periodic_next_shadow(fotg210, prev_p,
3313                                Q_NEXT_TYPE(fotg210, *hw_p));
3314                hw_p = shadow_next_periodic(fotg210, &here,
3315                                Q_NEXT_TYPE(fotg210, *hw_p));
3316                here = *prev_p;
3317        }
3318        /* an interrupt entry (at list end) could have been shared */
3319        if (!here.ptr)
3320                return;
3321
3322        /* update shadow and hardware lists ... the old "next" pointers
3323         * from ptr may still be in use, the caller updates them.
3324         */
3325        *prev_p = *periodic_next_shadow(fotg210, &here,
3326                        Q_NEXT_TYPE(fotg210, *hw_p));
3327
3328        *hw_p = *shadow_next_periodic(fotg210, &here,
3329                        Q_NEXT_TYPE(fotg210, *hw_p));
3330}
3331
3332/* how many of the uframe's 125 usecs are allocated? */
3333static unsigned short periodic_usecs(struct fotg210_hcd *fotg210,
3334                unsigned frame, unsigned uframe)
3335{
3336        __hc32 *hw_p = &fotg210->periodic[frame];
3337        union fotg210_shadow *q = &fotg210->pshadow[frame];
3338        unsigned usecs = 0;
3339        struct fotg210_qh_hw *hw;
3340
3341        while (q->ptr) {
3342                switch (hc32_to_cpu(fotg210, Q_NEXT_TYPE(fotg210, *hw_p))) {
3343                case Q_TYPE_QH:
3344                        hw = q->qh->hw;
3345                        /* is it in the S-mask? */
3346                        if (hw->hw_info2 & cpu_to_hc32(fotg210, 1 << uframe))
3347                                usecs += q->qh->usecs;
3348                        /* ... or C-mask? */
3349                        if (hw->hw_info2 & cpu_to_hc32(fotg210,
3350                                        1 << (8 + uframe)))
3351                                usecs += q->qh->c_usecs;
3352                        hw_p = &hw->hw_next;
3353                        q = &q->qh->qh_next;
3354                        break;
3355                /* case Q_TYPE_FSTN: */
3356                default:
3357                        /* for "save place" FSTNs, count the relevant INTR
3358                         * bandwidth from the previous frame
3359                         */
3360                        if (q->fstn->hw_prev != FOTG210_LIST_END(fotg210))
3361                                fotg210_dbg(fotg210, "ignoring FSTN cost ...\n");
3362
3363                        hw_p = &q->fstn->hw_next;
3364                        q = &q->fstn->fstn_next;
3365                        break;
3366                case Q_TYPE_ITD:
3367                        if (q->itd->hw_transaction[uframe])
3368                                usecs += q->itd->stream->usecs;
3369                        hw_p = &q->itd->hw_next;
3370                        q = &q->itd->itd_next;
3371                        break;
3372                }
3373        }
3374        if (usecs > fotg210->uframe_periodic_max)
3375                fotg210_err(fotg210, "uframe %d sched overrun: %d usecs\n",
3376                                frame * 8 + uframe, usecs);
3377        return usecs;
3378}
3379
3380static int same_tt(struct usb_device *dev1, struct usb_device *dev2)
3381{
3382        if (!dev1->tt || !dev2->tt)
3383                return 0;
3384        if (dev1->tt != dev2->tt)
3385                return 0;
3386        if (dev1->tt->multi)
3387                return dev1->ttport == dev2->ttport;
3388        else
3389                return 1;
3390}
3391
3392/* return true iff the device's transaction translator is available
3393 * for a periodic transfer starting at the specified frame, using
3394 * all the uframes in the mask.
3395 */
3396static int tt_no_collision(struct fotg210_hcd *fotg210, unsigned period,
3397                struct usb_device *dev, unsigned frame, u32 uf_mask)
3398{
3399        if (period == 0)        /* error */
3400                return 0;
3401
3402        /* note bandwidth wastage:  split never follows csplit
3403         * (different dev or endpoint) until the next uframe.
3404         * calling convention doesn't make that distinction.
3405         */
3406        for (; frame < fotg210->periodic_size; frame += period) {
3407                union fotg210_shadow here;
3408                __hc32 type;
3409                struct fotg210_qh_hw *hw;
3410
3411                here = fotg210->pshadow[frame];
3412                type = Q_NEXT_TYPE(fotg210, fotg210->periodic[frame]);
3413                while (here.ptr) {
3414                        switch (hc32_to_cpu(fotg210, type)) {
3415                        case Q_TYPE_ITD:
3416                                type = Q_NEXT_TYPE(fotg210, here.itd->hw_next);
3417                                here = here.itd->itd_next;
3418                                continue;
3419                        case Q_TYPE_QH:
3420                                hw = here.qh->hw;
3421                                if (same_tt(dev, here.qh->dev)) {
3422                                        u32 mask;
3423
3424                                        mask = hc32_to_cpu(fotg210,
3425                                                        hw->hw_info2);
3426                                        /* "knows" no gap is needed */
3427                                        mask |= mask >> 8;
3428                                        if (mask & uf_mask)
3429                                                break;
3430                                }
3431                                type = Q_NEXT_TYPE(fotg210, hw->hw_next);
3432                                here = here.qh->qh_next;
3433                                continue;
3434                        /* case Q_TYPE_FSTN: */
3435                        default:
3436                                fotg210_dbg(fotg210,
3437                                                "periodic frame %d bogus type %d\n",
3438                                                frame, type);
3439                        }
3440
3441                        /* collision or error */
3442                        return 0;
3443                }
3444        }
3445
3446        /* no collision */
3447        return 1;
3448}
3449
3450static void enable_periodic(struct fotg210_hcd *fotg210)
3451{
3452        if (fotg210->periodic_count++)
3453                return;
3454
3455        /* Stop waiting to turn off the periodic schedule */
3456        fotg210->enabled_hrtimer_events &=
3457                ~BIT(FOTG210_HRTIMER_DISABLE_PERIODIC);
3458
3459        /* Don't start the schedule until PSS is 0 */
3460        fotg210_poll_PSS(fotg210);
3461        turn_on_io_watchdog(fotg210);
3462}
3463
3464static void disable_periodic(struct fotg210_hcd *fotg210)
3465{
3466        if (--fotg210->periodic_count)
3467                return;
3468
3469        /* Don't turn off the schedule until PSS is 1 */
3470        fotg210_poll_PSS(fotg210);
3471}
3472
3473/* periodic schedule slots have iso tds (normal or split) first, then a
3474 * sparse tree for active interrupt transfers.
3475 *
3476 * this just links in a qh; caller guarantees uframe masks are set right.
3477 * no FSTN support (yet; fotg210 0.96+)
3478 */
3479static void qh_link_periodic(struct fotg210_hcd *fotg210, struct fotg210_qh *qh)
3480{
3481        unsigned i;
3482        unsigned period = qh->period;
3483
3484        dev_dbg(&qh->dev->dev,
3485                        "link qh%d-%04x/%p start %d [%d/%d us]\n", period,
3486                        hc32_to_cpup(fotg210, &qh->hw->hw_info2) &
3487                        (QH_CMASK | QH_SMASK), qh, qh->start, qh->usecs,
3488                        qh->c_usecs);
3489
3490        /* high bandwidth, or otherwise every microframe */
3491        if (period == 0)
3492                period = 1;
3493
3494        for (i = qh->start; i < fotg210->periodic_size; i += period) {
3495                union fotg210_shadow *prev = &fotg210->pshadow[i];
3496                __hc32 *hw_p = &fotg210->periodic[i];
3497                union fotg210_shadow here = *prev;
3498                __hc32 type = 0;
3499
3500                /* skip the iso nodes at list head */
3501                while (here.ptr) {
3502                        type = Q_NEXT_TYPE(fotg210, *hw_p);
3503                        if (type == cpu_to_hc32(fotg210, Q_TYPE_QH))
3504                                break;
3505                        prev = periodic_next_shadow(fotg210, prev, type);
3506                        hw_p = shadow_next_periodic(fotg210, &here, type);
3507                        here = *prev;
3508                }
3509
3510                /* sorting each branch by period (slow-->fast)
3511                 * enables sharing interior tree nodes
3512                 */
3513                while (here.ptr && qh != here.qh) {
3514                        if (qh->period > here.qh->period)
3515                                break;
3516                        prev = &here.qh->qh_next;
3517                        hw_p = &here.qh->hw->hw_next;
3518                        here = *prev;
3519                }
3520                /* link in this qh, unless some earlier pass did that */
3521                if (qh != here.qh) {
3522                        qh->qh_next = here;
3523                        if (here.qh)
3524                                qh->hw->hw_next = *hw_p;
3525                        wmb();
3526                        prev->qh = qh;
3527                        *hw_p = QH_NEXT(fotg210, qh->qh_dma);
3528                }
3529        }
3530        qh->qh_state = QH_STATE_LINKED;
3531        qh->xacterrs = 0;
3532
3533        /* update per-qh bandwidth for usbfs */
3534        fotg210_to_hcd(fotg210)->self.bandwidth_allocated += qh->period
3535                ? ((qh->usecs + qh->c_usecs) / qh->period)
3536                : (qh->usecs * 8);
3537
3538        list_add(&qh->intr_node, &fotg210->intr_qh_list);
3539
3540        /* maybe enable periodic schedule processing */
3541        ++fotg210->intr_count;
3542        enable_periodic(fotg210);
3543}
3544
3545static void qh_unlink_periodic(struct fotg210_hcd *fotg210,
3546                struct fotg210_qh *qh)
3547{
3548        unsigned i;
3549        unsigned period;
3550
3551        /*
3552         * If qh is for a low/full-speed device, simply unlinking it
3553         * could interfere with an ongoing split transaction.  To unlink
3554         * it safely would require setting the QH_INACTIVATE bit and
3555         * waiting at least one frame, as described in EHCI 4.12.2.5.
3556         *
3557         * We won't bother with any of this.  Instead, we assume that the
3558         * only reason for unlinking an interrupt QH while the current URB
3559         * is still active is to dequeue all the URBs (flush the whole
3560         * endpoint queue).
3561         *
3562         * If rebalancing the periodic schedule is ever implemented, this
3563         * approach will no longer be valid.
3564         */
3565
3566        /* high bandwidth, or otherwise part of every microframe */
3567        period = qh->period;
3568        if (!period)
3569                period = 1;
3570
3571        for (i = qh->start; i < fotg210->periodic_size; i += period)
3572                periodic_unlink(fotg210, i, qh);
3573
3574        /* update per-qh bandwidth for usbfs */
3575        fotg210_to_hcd(fotg210)->self.bandwidth_allocated -= qh->period
3576                ? ((qh->usecs + qh->c_usecs) / qh->period)
3577                : (qh->usecs * 8);
3578
3579        dev_dbg(&qh->dev->dev,
3580                        "unlink qh%d-%04x/%p start %d [%d/%d us]\n",
3581                        qh->period, hc32_to_cpup(fotg210, &qh->hw->hw_info2) &
3582                        (QH_CMASK | QH_SMASK), qh, qh->start, qh->usecs,
3583                        qh->c_usecs);
3584
3585        /* qh->qh_next still "live" to HC */
3586        qh->qh_state = QH_STATE_UNLINK;
3587        qh->qh_next.ptr = NULL;
3588
3589        if (fotg210->qh_scan_next == qh)
3590                fotg210->qh_scan_next = list_entry(qh->intr_node.next,
3591                                struct fotg210_qh, intr_node);
3592        list_del(&qh->intr_node);
3593}
3594
3595static void start_unlink_intr(struct fotg210_hcd *fotg210,
3596                struct fotg210_qh *qh)
3597{
3598        /* If the QH isn't linked then there's nothing we can do
3599         * unless we were called during a giveback, in which case
3600         * qh_completions() has to deal with it.
3601         */
3602        if (qh->qh_state != QH_STATE_LINKED) {
3603                if (qh->qh_state == QH_STATE_COMPLETING)
3604                        qh->needs_rescan = 1;
3605                return;
3606        }
3607
3608        qh_unlink_periodic(fotg210, qh);
3609
3610        /* Make sure the unlinks are visible before starting the timer */
3611        wmb();
3612
3613        /*
3614         * The EHCI spec doesn't say how long it takes the controller to
3615         * stop accessing an unlinked interrupt QH.  The timer delay is
3616         * 9 uframes; presumably that will be long enough.
3617         */
3618        qh->unlink_cycle = fotg210->intr_unlink_cycle;
3619
3620        /* New entries go at the end of the intr_unlink list */
3621        if (fotg210->intr_unlink)
3622                fotg210->intr_unlink_last->unlink_next = qh;
3623        else
3624                fotg210->intr_unlink = qh;
3625        fotg210->intr_unlink_last = qh;
3626
3627        if (fotg210->intr_unlinking)
3628                ;       /* Avoid recursive calls */
3629        else if (fotg210->rh_state < FOTG210_RH_RUNNING)
3630                fotg210_handle_intr_unlinks(fotg210);
3631        else if (fotg210->intr_unlink == qh) {
3632                fotg210_enable_event(fotg210, FOTG210_HRTIMER_UNLINK_INTR,
3633                                true);
3634                ++fotg210->intr_unlink_cycle;
3635        }
3636}
3637
3638static void end_unlink_intr(struct fotg210_hcd *fotg210, struct fotg210_qh *qh)
3639{
3640        struct fotg210_qh_hw *hw = qh->hw;
3641        int rc;
3642
3643        qh->qh_state = QH_STATE_IDLE;
3644        hw->hw_next = FOTG210_LIST_END(fotg210);
3645
3646        qh_completions(fotg210, qh);
3647
3648        /* reschedule QH iff another request is queued */
3649        if (!list_empty(&qh->qtd_list) &&
3650                        fotg210->rh_state == FOTG210_RH_RUNNING) {
3651                rc = qh_schedule(fotg210, qh);
3652
3653                /* An error here likely indicates handshake failure
3654                 * or no space left in the schedule.  Neither fault
3655                 * should happen often ...
3656                 *
3657                 * FIXME kill the now-dysfunctional queued urbs
3658                 */
3659                if (rc != 0)
3660                        fotg210_err(fotg210, "can't reschedule qh %p, err %d\n",
3661                                        qh, rc);
3662        }
3663
3664        /* maybe turn off periodic schedule */
3665        --fotg210->intr_count;
3666        disable_periodic(fotg210);
3667}
3668
3669static int check_period(struct fotg210_hcd *fotg210, unsigned frame,
3670                unsigned uframe, unsigned period, unsigned usecs)
3671{
3672        int claimed;
3673
3674        /* complete split running into next frame?
3675         * given FSTN support, we could sometimes check...
3676         */
3677        if (uframe >= 8)
3678                return 0;
3679
3680        /* convert "usecs we need" to "max already claimed" */
3681        usecs = fotg210->uframe_periodic_max - usecs;
3682
3683        /* we "know" 2 and 4 uframe intervals were rejected; so
3684         * for period 0, check _every_ microframe in the schedule.
3685         */
3686        if (unlikely(period == 0)) {
3687                do {
3688                        for (uframe = 0; uframe < 7; uframe++) {
3689                                claimed = periodic_usecs(fotg210, frame,
3690                                                uframe);
3691                                if (claimed > usecs)
3692                                        return 0;
3693                        }
3694                } while ((frame += 1) < fotg210->periodic_size);
3695
3696        /* just check the specified uframe, at that period */
3697        } else {
3698                do {
3699                        claimed = periodic_usecs(fotg210, frame, uframe);
3700                        if (claimed > usecs)
3701                                return 0;
3702                } while ((frame += period) < fotg210->periodic_size);
3703        }
3704
3705        /* success! */
3706        return 1;
3707}
3708
3709static int check_intr_schedule(struct fotg210_hcd *fotg210, unsigned frame,
3710                unsigned uframe, const struct fotg210_qh *qh, __hc32 *c_maskp)
3711{
3712        int retval = -ENOSPC;
3713        u8 mask = 0;
3714
3715        if (qh->c_usecs && uframe >= 6)         /* FSTN territory? */
3716                goto done;
3717
3718        if (!check_period(fotg210, frame, uframe, qh->period, qh->usecs))
3719                goto done;
3720        if (!qh->c_usecs) {
3721                retval = 0;
3722                *c_maskp = 0;
3723                goto done;
3724        }
3725
3726        /* Make sure this tt's buffer is also available for CSPLITs.
3727         * We pessimize a bit; probably the typical full speed case
3728         * doesn't need the second CSPLIT.
3729         *
3730         * NOTE:  both SPLIT and CSPLIT could be checked in just
3731         * one smart pass...
3732         */
3733        mask = 0x03 << (uframe + qh->gap_uf);
3734        *c_maskp = cpu_to_hc32(fotg210, mask << 8);
3735
3736        mask |= 1 << uframe;
3737        if (tt_no_collision(fotg210, qh->period, qh->dev, frame, mask)) {
3738                if (!check_period(fotg210, frame, uframe + qh->gap_uf + 1,
3739                                qh->period, qh->c_usecs))
3740                        goto done;
3741                if (!check_period(fotg210, frame, uframe + qh->gap_uf,
3742                                qh->period, qh->c_usecs))
3743                        goto done;
3744                retval = 0;
3745        }
3746done:
3747        return retval;
3748}
3749
3750/* "first fit" scheduling policy used the first time through,
3751 * or when the previous schedule slot can't be re-used.
3752 */
3753static int qh_schedule(struct fotg210_hcd *fotg210, struct fotg210_qh *qh)
3754{
3755        int status;
3756        unsigned uframe;
3757        __hc32 c_mask;
3758        unsigned frame; /* 0..(qh->period - 1), or NO_FRAME */
3759        struct fotg210_qh_hw *hw = qh->hw;
3760
3761        qh_refresh(fotg210, qh);
3762        hw->hw_next = FOTG210_LIST_END(fotg210);
3763        frame = qh->start;
3764
3765        /* reuse the previous schedule slots, if we can */
3766        if (frame < qh->period) {
3767                uframe = ffs(hc32_to_cpup(fotg210, &hw->hw_info2) & QH_SMASK);
3768                status = check_intr_schedule(fotg210, frame, --uframe,
3769                                qh, &c_mask);
3770        } else {
3771                uframe = 0;
3772                c_mask = 0;
3773                status = -ENOSPC;
3774        }
3775
3776        /* else scan the schedule to find a group of slots such that all
3777         * uframes have enough periodic bandwidth available.
3778         */
3779        if (status) {
3780                /* "normal" case, uframing flexible except with splits */
3781                if (qh->period) {
3782                        int i;
3783
3784                        for (i = qh->period; status && i > 0; --i) {
3785                                frame = ++fotg210->random_frame % qh->period;
3786                                for (uframe = 0; uframe < 8; uframe++) {
3787                                        status = check_intr_schedule(fotg210,
3788                                                        frame, uframe, qh,
3789                                                        &c_mask);
3790                                        if (status == 0)
3791                                                break;
3792                                }
3793                        }
3794
3795                /* qh->period == 0 means every uframe */
3796                } else {
3797                        frame = 0;
3798                        status = check_intr_schedule(fotg210, 0, 0, qh,
3799                                        &c_mask);
3800                }
3801                if (status)
3802                        goto done;
3803                qh->start = frame;
3804
3805                /* reset S-frame and (maybe) C-frame masks */
3806                hw->hw_info2 &= cpu_to_hc32(fotg210, ~(QH_CMASK | QH_SMASK));
3807                hw->hw_info2 |= qh->period
3808                        ? cpu_to_hc32(fotg210, 1 << uframe)
3809                        : cpu_to_hc32(fotg210, QH_SMASK);
3810                hw->hw_info2 |= c_mask;
3811        } else
3812                fotg210_dbg(fotg210, "reused qh %p schedule\n", qh);
3813
3814        /* stuff into the periodic schedule */
3815        qh_link_periodic(fotg210, qh);
3816done:
3817        return status;
3818}
3819
3820static int intr_submit(struct fotg210_hcd *fotg210, struct urb *urb,
3821                struct list_head *qtd_list, gfp_t mem_flags)
3822{
3823        unsigned epnum;
3824        unsigned long flags;
3825        struct fotg210_qh *qh;
3826        int status;
3827        struct list_head empty;
3828
3829        /* get endpoint and transfer/schedule data */
3830        epnum = urb->ep->desc.bEndpointAddress;
3831
3832        spin_lock_irqsave(&fotg210->lock, flags);
3833
3834        if (unlikely(!HCD_HW_ACCESSIBLE(fotg210_to_hcd(fotg210)))) {
3835                status = -ESHUTDOWN;
3836                goto done_not_linked;
3837        }
3838        status = usb_hcd_link_urb_to_ep(fotg210_to_hcd(fotg210), urb);
3839        if (unlikely(status))
3840                goto done_not_linked;
3841
3842        /* get qh and force any scheduling errors */
3843        INIT_LIST_HEAD(&empty);
3844        qh = qh_append_tds(fotg210, urb, &empty, epnum, &urb->ep->hcpriv);
3845        if (qh == NULL) {
3846                status = -ENOMEM;
3847                goto done;
3848        }
3849        if (qh->qh_state == QH_STATE_IDLE) {
3850                status = qh_schedule(fotg210, qh);
3851                if (status)
3852                        goto done;
3853        }
3854
3855        /* then queue the urb's tds to the qh */
3856        qh = qh_append_tds(fotg210, urb, qtd_list, epnum, &urb->ep->hcpriv);
3857        BUG_ON(qh == NULL);
3858
3859        /* ... update usbfs periodic stats */
3860        fotg210_to_hcd(fotg210)->self.bandwidth_int_reqs++;
3861
3862done:
3863        if (unlikely(status))
3864                usb_hcd_unlink_urb_from_ep(fotg210_to_hcd(fotg210), urb);
3865done_not_linked:
3866        spin_unlock_irqrestore(&fotg210->lock, flags);
3867        if (status)
3868                qtd_list_free(fotg210, urb, qtd_list);
3869
3870        return status;
3871}
3872
3873static void scan_intr(struct fotg210_hcd *fotg210)
3874{
3875        struct fotg210_qh *qh;
3876
3877        list_for_each_entry_safe(qh, fotg210->qh_scan_next,
3878                        &fotg210->intr_qh_list, intr_node) {
3879rescan:
3880                /* clean any finished work for this qh */
3881                if (!list_empty(&qh->qtd_list)) {
3882                        int temp;
3883
3884                        /*
3885                         * Unlinks could happen here; completion reporting
3886                         * drops the lock.  That's why fotg210->qh_scan_next
3887                         * always holds the next qh to scan; if the next qh
3888                         * gets unlinked then fotg210->qh_scan_next is adjusted
3889                         * in qh_unlink_periodic().
3890                         */
3891                        temp = qh_completions(fotg210, qh);
3892                        if (unlikely(qh->needs_rescan ||
3893                                        (list_empty(&qh->qtd_list) &&
3894                                        qh->qh_state == QH_STATE_LINKED)))
3895                                start_unlink_intr(fotg210, qh);
3896                        else if (temp != 0)
3897                                goto rescan;
3898                }
3899        }
3900}
3901
3902/* fotg210_iso_stream ops work with both ITD and SITD */
3903
3904static struct fotg210_iso_stream *iso_stream_alloc(gfp_t mem_flags)
3905{
3906        struct fotg210_iso_stream *stream;
3907
3908        stream = kzalloc(sizeof(*stream), mem_flags);
3909        if (likely(stream != NULL)) {
3910                INIT_LIST_HEAD(&stream->td_list);
3911                INIT_LIST_HEAD(&stream->free_list);
3912                stream->next_uframe = -1;
3913        }
3914        return stream;
3915}
3916
3917static void iso_stream_init(struct fotg210_hcd *fotg210,
3918                struct fotg210_iso_stream *stream, struct usb_device *dev,
3919                int pipe, unsigned interval)
3920{
3921        u32 buf1;
3922        unsigned epnum, maxp;
3923        int is_input;
3924        long bandwidth;
3925        unsigned multi;
3926
3927        /*
3928         * this might be a "high bandwidth" highspeed endpoint,
3929         * as encoded in the ep descriptor's wMaxPacket field
3930         */
3931        epnum = usb_pipeendpoint(pipe);
3932        is_input = usb_pipein(pipe) ? USB_DIR_IN : 0;
3933        maxp = usb_maxpacket(dev, pipe, !is_input);
3934        if (is_input)
3935                buf1 = (1 << 11);
3936        else
3937                buf1 = 0;
3938
3939        maxp = max_packet(maxp);
3940        multi = hb_mult(maxp);
3941        buf1 |= maxp;
3942        maxp *= multi;
3943
3944        stream->buf0 = cpu_to_hc32(fotg210, (epnum << 8) | dev->devnum);
3945        stream->buf1 = cpu_to_hc32(fotg210, buf1);
3946        stream->buf2 = cpu_to_hc32(fotg210, multi);
3947
3948        /* usbfs wants to report the average usecs per frame tied up
3949         * when transfers on this endpoint are scheduled ...
3950         */
3951        if (dev->speed == USB_SPEED_FULL) {
3952                interval <<= 3;
3953                stream->usecs = NS_TO_US(usb_calc_bus_time(dev->speed,
3954                                is_input, 1, maxp));
3955                stream->usecs /= 8;
3956        } else {
3957                stream->highspeed = 1;
3958                stream->usecs = HS_USECS_ISO(maxp);
3959        }
3960        bandwidth = stream->usecs * 8;
3961        bandwidth /= interval;
3962
3963        stream->bandwidth = bandwidth;
3964        stream->udev = dev;
3965        stream->bEndpointAddress = is_input | epnum;
3966        stream->interval = interval;
3967        stream->maxp = maxp;
3968}
3969
3970static struct fotg210_iso_stream *iso_stream_find(struct fotg210_hcd *fotg210,
3971                struct urb *urb)
3972{
3973        unsigned epnum;
3974        struct fotg210_iso_stream *stream;
3975        struct usb_host_endpoint *ep;
3976        unsigned long flags;
3977
3978        epnum = usb_pipeendpoint(urb->pipe);
3979        if (usb_pipein(urb->pipe))
3980                ep = urb->dev->ep_in[epnum];
3981        else
3982                ep = urb->dev->ep_out[epnum];
3983
3984        spin_lock_irqsave(&fotg210->lock, flags);
3985        stream = ep->hcpriv;
3986
3987        if (unlikely(stream == NULL)) {
3988                stream = iso_stream_alloc(GFP_ATOMIC);
3989                if (likely(stream != NULL)) {
3990                        ep->hcpriv = stream;
3991                        stream->ep = ep;
3992                        iso_stream_init(fotg210, stream, urb->dev, urb->pipe,
3993                                        urb->interval);
3994                }
3995
3996        /* if dev->ep[epnum] is a QH, hw is set */
3997        } else if (unlikely(stream->hw != NULL)) {
3998                fotg210_dbg(fotg210, "dev %s ep%d%s, not iso??\n",
3999                                urb->dev->devpath, epnum,
4000                                usb_pipein(urb->pipe) ? "in" : "out");
4001                stream = NULL;
4002        }
4003
4004        spin_unlock_irqrestore(&fotg210->lock, flags);
4005        return stream;
4006}
4007
4008/* fotg210_iso_sched ops can be ITD-only or SITD-only */
4009
4010static struct fotg210_iso_sched *iso_sched_alloc(unsigned packets,
4011                gfp_t mem_flags)
4012{
4013        struct fotg210_iso_sched *iso_sched;
4014        int size = sizeof(*iso_sched);
4015
4016        size += packets * sizeof(struct fotg210_iso_packet);
4017        iso_sched = kzalloc(size, mem_flags);
4018        if (likely(iso_sched != NULL))
4019                INIT_LIST_HEAD(&iso_sched->td_list);
4020
4021        return iso_sched;
4022}
4023
4024static inline void itd_sched_init(struct fotg210_hcd *fotg210,
4025                struct fotg210_iso_sched *iso_sched,
4026                struct fotg210_iso_stream *stream, struct urb *urb)
4027{
4028        unsigned i;
4029        dma_addr_t dma = urb->transfer_dma;
4030
4031        /* how many uframes are needed for these transfers */
4032        iso_sched->span = urb->number_of_packets * stream->interval;
4033
4034        /* figure out per-uframe itd fields that we'll need later
4035         * when we fit new itds into the schedule.
4036         */
4037        for (i = 0; i < urb->number_of_packets; i++) {
4038                struct fotg210_iso_packet *uframe = &iso_sched->packet[i];
4039                unsigned length;
4040                dma_addr_t buf;
4041                u32 trans;
4042
4043                length = urb->iso_frame_desc[i].length;
4044                buf = dma + urb->iso_frame_desc[i].offset;
4045
4046                trans = FOTG210_ISOC_ACTIVE;
4047                trans |= buf & 0x0fff;
4048                if (unlikely(((i + 1) == urb->number_of_packets))
4049                                && !(urb->transfer_flags & URB_NO_INTERRUPT))
4050                        trans |= FOTG210_ITD_IOC;
4051                trans |= length << 16;
4052                uframe->transaction = cpu_to_hc32(fotg210, trans);
4053
4054                /* might need to cross a buffer page within a uframe */
4055                uframe->bufp = (buf & ~(u64)0x0fff);
4056                buf += length;
4057                if (unlikely((uframe->bufp != (buf & ~(u64)0x0fff))))
4058                        uframe->cross = 1;
4059        }
4060}
4061
4062static void iso_sched_free(struct fotg210_iso_stream *stream,
4063                struct fotg210_iso_sched *iso_sched)
4064{
4065        if (!iso_sched)
4066                return;
4067        /* caller must hold fotg210->lock!*/
4068        list_splice(&iso_sched->td_list, &stream->free_list);
4069        kfree(iso_sched);
4070}
4071
4072static int itd_urb_transaction(struct fotg210_iso_stream *stream,
4073                struct fotg210_hcd *fotg210, struct urb *urb, gfp_t mem_flags)
4074{
4075        struct fotg210_itd *itd;
4076        dma_addr_t itd_dma;
4077        int i;
4078        unsigned num_itds;
4079        struct fotg210_iso_sched *sched;
4080        unsigned long flags;
4081
4082        sched = iso_sched_alloc(urb->number_of_packets, mem_flags);
4083        if (unlikely(sched == NULL))
4084                return -ENOMEM;
4085
4086        itd_sched_init(fotg210, sched, stream, urb);
4087
4088        if (urb->interval < 8)
4089                num_itds = 1 + (sched->span + 7) / 8;
4090        else
4091                num_itds = urb->number_of_packets;
4092
4093        /* allocate/init ITDs */
4094        spin_lock_irqsave(&fotg210->lock, flags);
4095        for (i = 0; i < num_itds; i++) {
4096
4097                /*
4098                 * Use iTDs from the free list, but not iTDs that may
4099                 * still be in use by the hardware.
4100                 */
4101                if (likely(!list_empty(&stream->free_list))) {
4102                        itd = list_first_entry(&stream->free_list,
4103                                        struct fotg210_itd, itd_list);
4104                        if (itd->frame == fotg210->now_frame)
4105                                goto alloc_itd;
4106                        list_del(&itd->itd_list);
4107                        itd_dma = itd->itd_dma;
4108                } else {
4109alloc_itd:
4110                        spin_unlock_irqrestore(&fotg210->lock, flags);
4111                        itd = dma_pool_zalloc(fotg210->itd_pool, mem_flags,
4112                                        &itd_dma);
4113                        spin_lock_irqsave(&fotg210->lock, flags);
4114                        if (!itd) {
4115                                iso_sched_free(stream, sched);
4116                                spin_unlock_irqrestore(&fotg210->lock, flags);
4117                                return -ENOMEM;
4118                        }
4119                }
4120
4121                itd->itd_dma = itd_dma;
4122                list_add(&itd->itd_list, &sched->td_list);
4123        }
4124        spin_unlock_irqrestore(&fotg210->lock, flags);
4125
4126        /* temporarily store schedule info in hcpriv */
4127        urb->hcpriv = sched;
4128        urb->error_count = 0;
4129        return 0;
4130}
4131
4132static inline int itd_slot_ok(struct fotg210_hcd *fotg210, u32 mod, u32 uframe,
4133                u8 usecs, u32 period)
4134{
4135        uframe %= period;
4136        do {
4137                /* can't commit more than uframe_periodic_max usec */
4138                if (periodic_usecs(fotg210, uframe >> 3, uframe & 0x7)
4139                                > (fotg210->uframe_periodic_max - usecs))
4140                        return 0;
4141
4142                /* we know urb->interval is 2^N uframes */
4143                uframe += period;
4144        } while (uframe < mod);
4145        return 1;
4146}
4147
4148/* This scheduler plans almost as far into the future as it has actual
4149 * periodic schedule slots.  (Affected by TUNE_FLS, which defaults to
4150 * "as small as possible" to be cache-friendlier.)  That limits the size
4151 * transfers you can stream reliably; avoid more than 64 msec per urb.
4152 * Also avoid queue depths of less than fotg210's worst irq latency (affected
4153 * by the per-urb URB_NO_INTERRUPT hint, the log2_irq_thresh module parameter,
4154 * and other factors); or more than about 230 msec total (for portability,
4155 * given FOTG210_TUNE_FLS and the slop).  Or, write a smarter scheduler!
4156 */
4157
4158#define SCHEDULE_SLOP 80 /* microframes */
4159
4160static int iso_stream_schedule(struct fotg210_hcd *fotg210, struct urb *urb,
4161                struct fotg210_iso_stream *stream)
4162{
4163        u32 now, next, start, period, span;
4164        int status;
4165        unsigned mod = fotg210->periodic_size << 3;
4166        struct fotg210_iso_sched *sched = urb->hcpriv;
4167
4168        period = urb->interval;
4169        span = sched->span;
4170
4171        if (span > mod - SCHEDULE_SLOP) {
4172                fotg210_dbg(fotg210, "iso request %p too long\n", urb);
4173                status = -EFBIG;
4174                goto fail;
4175        }
4176
4177        now = fotg210_read_frame_index(fotg210) & (mod - 1);
4178
4179        /* Typical case: reuse current schedule, stream is still active.
4180         * Hopefully there are no gaps from the host falling behind
4181         * (irq delays etc), but if there are we'll take the next
4182         * slot in the schedule, implicitly assuming URB_ISO_ASAP.
4183         */
4184        if (likely(!list_empty(&stream->td_list))) {
4185                u32 excess;
4186
4187                /* For high speed devices, allow scheduling within the
4188                 * isochronous scheduling threshold.  For full speed devices
4189                 * and Intel PCI-based controllers, don't (work around for
4190                 * Intel ICH9 bug).
4191                 */
4192                if (!stream->highspeed && fotg210->fs_i_thresh)
4193                        next = now + fotg210->i_thresh;
4194                else
4195                        next = now;
4196
4197                /* Fell behind (by up to twice the slop amount)?
4198                 * We decide based on the time of the last currently-scheduled
4199                 * slot, not the time of the next available slot.
4200                 */
4201                excess = (stream->next_uframe - period - next) & (mod - 1);
4202                if (excess >= mod - 2 * SCHEDULE_SLOP)
4203                        start = next + excess - mod + period *
4204                                        DIV_ROUND_UP(mod - excess, period);
4205                else
4206                        start = next + excess + period;
4207                if (start - now >= mod) {
4208                        fotg210_dbg(fotg210, "request %p would overflow (%d+%d >= %d)\n",
4209                                        urb, start - now - period, period,
4210                                        mod);
4211                        status = -EFBIG;
4212                        goto fail;
4213                }
4214        }
4215
4216        /* need to schedule; when's the next (u)frame we could start?
4217         * this is bigger than fotg210->i_thresh allows; scheduling itself
4218         * isn't free, the slop should handle reasonably slow cpus.  it
4219         * can also help high bandwidth if the dma and irq loads don't
4220         * jump until after the queue is primed.
4221         */
4222        else {
4223                int done = 0;
4224
4225                start = SCHEDULE_SLOP + (now & ~0x07);
4226
4227                /* NOTE:  assumes URB_ISO_ASAP, to limit complexity/bugs */
4228
4229                /* find a uframe slot with enough bandwidth.
4230                 * Early uframes are more precious because full-speed
4231                 * iso IN transfers can't use late uframes,
4232                 * and therefore they should be allocated last.
4233                 */
4234                next = start;
4235                start += period;
4236                do {
4237                        start--;
4238                        /* check schedule: enough space? */
4239                        if (itd_slot_ok(fotg210, mod, start,
4240                                        stream->usecs, period))
4241                                done = 1;
4242                } while (start > next && !done);
4243
4244                /* no room in the schedule */
4245                if (!done) {
4246                        fotg210_dbg(fotg210, "iso resched full %p (now %d max %d)\n",
4247                                        urb, now, now + mod);
4248                        status = -ENOSPC;
4249                        goto fail;
4250                }
4251        }
4252
4253        /* Tried to schedule too far into the future? */
4254        if (unlikely(start - now + span - period >=
4255                        mod - 2 * SCHEDULE_SLOP)) {
4256                fotg210_dbg(fotg210, "request %p would overflow (%d+%d >= %d)\n",
4257                                urb, start - now, span - period,
4258                                mod - 2 * SCHEDULE_SLOP);
4259                status = -EFBIG;
4260                goto fail;
4261        }
4262
4263        stream->next_uframe = start & (mod - 1);
4264
4265        /* report high speed start in uframes; full speed, in frames */
4266        urb->start_frame = stream->next_uframe;
4267        if (!stream->highspeed)
4268                urb->start_frame >>= 3;
4269
4270        /* Make sure scan_isoc() sees these */
4271        if (fotg210->isoc_count == 0)
4272                fotg210->next_frame = now >> 3;
4273        return 0;
4274
4275fail:
4276        iso_sched_free(stream, sched);
4277        urb->hcpriv = NULL;
4278        return status;
4279}
4280
4281static inline void itd_init(struct fotg210_hcd *fotg210,
4282                struct fotg210_iso_stream *stream, struct fotg210_itd *itd)
4283{
4284        int i;
4285
4286        /* it's been recently zeroed */
4287        itd->hw_next = FOTG210_LIST_END(fotg210);
4288        itd->hw_bufp[0] = stream->buf0;
4289        itd->hw_bufp[1] = stream->buf1;
4290        itd->hw_bufp[2] = stream->buf2;
4291
4292        for (i = 0; i < 8; i++)
4293                itd->index[i] = -1;
4294
4295        /* All other fields are filled when scheduling */
4296}
4297
4298static inline void itd_patch(struct fotg210_hcd *fotg210,
4299                struct fotg210_itd *itd, struct fotg210_iso_sched *iso_sched,
4300                unsigned index, u16 uframe)
4301{
4302        struct fotg210_iso_packet *uf = &iso_sched->packet[index];
4303        unsigned pg = itd->pg;
4304
4305        uframe &= 0x07;
4306        itd->index[uframe] = index;
4307
4308        itd->hw_transaction[uframe] = uf->transaction;
4309        itd->hw_transaction[uframe] |= cpu_to_hc32(fotg210, pg << 12);
4310        itd->hw_bufp[pg] |= cpu_to_hc32(fotg210, uf->bufp & ~(u32)0);
4311        itd->hw_bufp_hi[pg] |= cpu_to_hc32(fotg210, (u32)(uf->bufp >> 32));
4312
4313        /* iso_frame_desc[].offset must be strictly increasing */
4314        if (unlikely(uf->cross)) {
4315                u64 bufp = uf->bufp + 4096;
4316
4317                itd->pg = ++pg;
4318                itd->hw_bufp[pg] |= cpu_to_hc32(fotg210, bufp & ~(u32)0);
4319                itd->hw_bufp_hi[pg] |= cpu_to_hc32(fotg210, (u32)(bufp >> 32));
4320        }
4321}
4322
4323static inline void itd_link(struct fotg210_hcd *fotg210, unsigned frame,
4324                struct fotg210_itd *itd)
4325{
4326        union fotg210_shadow *prev = &fotg210->pshadow[frame];
4327        __hc32 *hw_p = &fotg210->periodic[frame];
4328        union fotg210_shadow here = *prev;
4329        __hc32 type = 0;
4330
4331        /* skip any iso nodes which might belong to previous microframes */
4332        while (here.ptr) {
4333                type = Q_NEXT_TYPE(fotg210, *hw_p);
4334                if (type == cpu_to_hc32(fotg210, Q_TYPE_QH))
4335                        break;
4336                prev = periodic_next_shadow(fotg210, prev, type);
4337                hw_p = shadow_next_periodic(fotg210, &here, type);
4338                here = *prev;
4339        }
4340
4341        itd->itd_next = here;
4342        itd->hw_next = *hw_p;
4343        prev->itd = itd;
4344        itd->frame = frame;
4345        wmb();
4346        *hw_p = cpu_to_hc32(fotg210, itd->itd_dma | Q_TYPE_ITD);
4347}
4348
4349/* fit urb's itds into the selected schedule slot; activate as needed */
4350static void itd_link_urb(struct fotg210_hcd *fotg210, struct urb *urb,
4351                unsigned mod, struct fotg210_iso_stream *stream)
4352{
4353        int packet;
4354        unsigned next_uframe, uframe, frame;
4355        struct fotg210_iso_sched *iso_sched = urb->hcpriv;
4356        struct fotg210_itd *itd;
4357
4358        next_uframe = stream->next_uframe & (mod - 1);
4359
4360        if (unlikely(list_empty(&stream->td_list))) {
4361                fotg210_to_hcd(fotg210)->self.bandwidth_allocated
4362                                += stream->bandwidth;
4363                fotg210_dbg(fotg210,
4364                        "schedule devp %s ep%d%s-iso period %d start %d.%d\n",
4365                        urb->dev->devpath, stream->bEndpointAddress & 0x0f,
4366                        (stream->bEndpointAddress & USB_DIR_IN) ? "in" : "out",
4367                        urb->interval,
4368                        next_uframe >> 3, next_uframe & 0x7);
4369        }
4370
4371        /* fill iTDs uframe by uframe */
4372        for (packet = 0, itd = NULL; packet < urb->number_of_packets;) {
4373                if (itd == NULL) {
4374                        /* ASSERT:  we have all necessary itds */
4375
4376                        /* ASSERT:  no itds for this endpoint in this uframe */
4377
4378                        itd = list_entry(iso_sched->td_list.next,
4379                                        struct fotg210_itd, itd_list);
4380                        list_move_tail(&itd->itd_list, &stream->td_list);
4381                        itd->stream = stream;
4382                        itd->urb = urb;
4383                        itd_init(fotg210, stream, itd);
4384                }
4385
4386                uframe = next_uframe & 0x07;
4387                frame = next_uframe >> 3;
4388
4389                itd_patch(fotg210, itd, iso_sched, packet, uframe);
4390
4391                next_uframe += stream->interval;
4392                next_uframe &= mod - 1;
4393                packet++;
4394
4395                /* link completed itds into the schedule */
4396                if (((next_uframe >> 3) != frame)
4397                                || packet == urb->number_of_packets) {
4398                        itd_link(fotg210, frame & (fotg210->periodic_size - 1),
4399                                        itd);
4400                        itd = NULL;
4401                }
4402        }
4403        stream->next_uframe = next_uframe;
4404
4405        /* don't need that schedule data any more */
4406        iso_sched_free(stream, iso_sched);
4407        urb->hcpriv = NULL;
4408
4409        ++fotg210->isoc_count;
4410        enable_periodic(fotg210);
4411}
4412
4413#define ISO_ERRS (FOTG210_ISOC_BUF_ERR | FOTG210_ISOC_BABBLE |\
4414                FOTG210_ISOC_XACTERR)
4415
4416/* Process and recycle a completed ITD.  Return true iff its urb completed,
4417 * and hence its completion callback probably added things to the hardware
4418 * schedule.
4419 *
4420 * Note that we carefully avoid recycling this descriptor until after any
4421 * completion callback runs, so that it won't be reused quickly.  That is,
4422 * assuming (a) no more than two urbs per frame on this endpoint, and also
4423 * (b) only this endpoint's completions submit URBs.  It seems some silicon
4424 * corrupts things if you reuse completed descriptors very quickly...
4425 */
4426static bool itd_complete(struct fotg210_hcd *fotg210, struct fotg210_itd *itd)
4427{
4428        struct urb *urb = itd->urb;
4429        struct usb_iso_packet_descriptor *desc;
4430        u32 t;
4431        unsigned uframe;
4432        int urb_index = -1;
4433        struct fotg210_iso_stream *stream = itd->stream;
4434        struct usb_device *dev;
4435        bool retval = false;
4436
4437        /* for each uframe with a packet */
4438        for (uframe = 0; uframe < 8; uframe++) {
4439                if (likely(itd->index[uframe] == -1))
4440                        continue;
4441                urb_index = itd->index[uframe];
4442                desc = &urb->iso_frame_desc[urb_index];
4443
4444                t = hc32_to_cpup(fotg210, &itd->hw_transaction[uframe]);
4445                itd->hw_transaction[uframe] = 0;
4446
4447                /* report transfer status */
4448                if (unlikely(t & ISO_ERRS)) {
4449                        urb->error_count++;
4450                        if (t & FOTG210_ISOC_BUF_ERR)
4451                                desc->status = usb_pipein(urb->pipe)
4452                                        ? -ENOSR  /* hc couldn't read */
4453                                        : -ECOMM; /* hc couldn't write */
4454                        else if (t & FOTG210_ISOC_BABBLE)
4455                                desc->status = -EOVERFLOW;
4456                        else /* (t & FOTG210_ISOC_XACTERR) */
4457                                desc->status = -EPROTO;
4458
4459                        /* HC need not update length with this error */
4460                        if (!(t & FOTG210_ISOC_BABBLE)) {
4461                                desc->actual_length =
4462                                        fotg210_itdlen(urb, desc, t);
4463                                urb->actual_length += desc->actual_length;
4464                        }
4465                } else if (likely((t & FOTG210_ISOC_ACTIVE) == 0)) {
4466                        desc->status = 0;
4467                        desc->actual_length = fotg210_itdlen(urb, desc, t);
4468                        urb->actual_length += desc->actual_length;
4469                } else {
4470                        /* URB was too late */
4471                        desc->status = -EXDEV;
4472                }
4473        }
4474
4475        /* handle completion now? */
4476        if (likely((urb_index + 1) != urb->number_of_packets))
4477                goto done;
4478
4479        /* ASSERT: it's really the last itd for this urb
4480         * list_for_each_entry (itd, &stream->td_list, itd_list)
4481         *      BUG_ON (itd->urb == urb);
4482         */
4483
4484        /* give urb back to the driver; completion often (re)submits */
4485        dev = urb->dev;
4486        fotg210_urb_done(fotg210, urb, 0);
4487        retval = true;
4488        urb = NULL;
4489
4490        --fotg210->isoc_count;
4491        disable_periodic(fotg210);
4492
4493        if (unlikely(list_is_singular(&stream->td_list))) {
4494                fotg210_to_hcd(fotg210)->self.bandwidth_allocated
4495                                -= stream->bandwidth;
4496                fotg210_dbg(fotg210,
4497                        "deschedule devp %s ep%d%s-iso\n",
4498                        dev->devpath, stream->bEndpointAddress & 0x0f,
4499                        (stream->bEndpointAddress & USB_DIR_IN) ? "in" : "out");
4500        }
4501
4502done:
4503        itd->urb = NULL;
4504
4505        /* Add to the end of the free list for later reuse */
4506        list_move_tail(&itd->itd_list, &stream->free_list);
4507
4508        /* Recycle the iTDs when the pipeline is empty (ep no longer in use) */
4509        if (list_empty(&stream->td_list)) {
4510                list_splice_tail_init(&stream->free_list,
4511                                &fotg210->cached_itd_list);
4512                start_free_itds(fotg210);
4513        }
4514
4515        return retval;
4516}
4517
4518static int itd_submit(struct fotg210_hcd *fotg210, struct urb *urb,
4519                gfp_t mem_flags)
4520{
4521        int status = -EINVAL;
4522        unsigned long flags;
4523        struct fotg210_iso_stream *stream;
4524
4525        /* Get iso_stream head */
4526        stream = iso_stream_find(fotg210, urb);
4527        if (unlikely(stream == NULL)) {
4528                fotg210_dbg(fotg210, "can't get iso stream\n");
4529                return -ENOMEM;
4530        }
4531        if (unlikely(urb->interval != stream->interval &&
4532                        fotg210_port_speed(fotg210, 0) ==
4533                        USB_PORT_STAT_HIGH_SPEED)) {
4534                fotg210_dbg(fotg210, "can't change iso interval %d --> %d\n",
4535                                stream->interval, urb->interval);
4536                goto done;
4537        }
4538
4539#ifdef FOTG210_URB_TRACE
4540        fotg210_dbg(fotg210,
4541                        "%s %s urb %p ep%d%s len %d, %d pkts %d uframes[%p]\n",
4542                        __func__, urb->dev->devpath, urb,
4543                        usb_pipeendpoint(urb->pipe),
4544                        usb_pipein(urb->pipe) ? "in" : "out",
4545                        urb->transfer_buffer_length,
4546                        urb->number_of_packets, urb->interval,
4547                        stream);
4548#endif
4549
4550        /* allocate ITDs w/o locking anything */
4551        status = itd_urb_transaction(stream, fotg210, urb, mem_flags);
4552        if (unlikely(status < 0)) {
4553                fotg210_dbg(fotg210, "can't init itds\n");
4554                goto done;
4555        }
4556
4557        /* schedule ... need to lock */
4558        spin_lock_irqsave(&fotg210->lock, flags);
4559        if (unlikely(!HCD_HW_ACCESSIBLE(fotg210_to_hcd(fotg210)))) {
4560                status = -ESHUTDOWN;
4561                goto done_not_linked;
4562        }
4563        status = usb_hcd_link_urb_to_ep(fotg210_to_hcd(fotg210), urb);
4564        if (unlikely(status))
4565                goto done_not_linked;
4566        status = iso_stream_schedule(fotg210, urb, stream);
4567        if (likely(status == 0))
4568                itd_link_urb(fotg210, urb, fotg210->periodic_size << 3, stream);
4569        else
4570                usb_hcd_unlink_urb_from_ep(fotg210_to_hcd(fotg210), urb);
4571done_not_linked:
4572        spin_unlock_irqrestore(&fotg210->lock, flags);
4573done:
4574        return status;
4575}
4576
4577static inline int scan_frame_queue(struct fotg210_hcd *fotg210, unsigned frame,
4578                unsigned now_frame, bool live)
4579{
4580        unsigned uf;
4581        bool modified;
4582        union fotg210_shadow q, *q_p;
4583        __hc32 type, *hw_p;
4584
4585        /* scan each element in frame's queue for completions */
4586        q_p = &fotg210->pshadow[frame];
4587        hw_p = &fotg210->periodic[frame];
4588        q.ptr = q_p->ptr;
4589        type = Q_NEXT_TYPE(fotg210, *hw_p);
4590        modified = false;
4591
4592        while (q.ptr) {
4593                switch (hc32_to_cpu(fotg210, type)) {
4594                case Q_TYPE_ITD:
4595                        /* If this ITD is still active, leave it for
4596                         * later processing ... check the next entry.
4597                         * No need to check for activity unless the
4598                         * frame is current.
4599                         */
4600                        if (frame == now_frame && live) {
4601                                rmb();
4602                                for (uf = 0; uf < 8; uf++) {
4603                                        if (q.itd->hw_transaction[uf] &
4604                                                        ITD_ACTIVE(fotg210))
4605                                                break;
4606                                }
4607                                if (uf < 8) {
4608                                        q_p = &q.itd->itd_next;
4609                                        hw_p = &q.itd->hw_next;
4610                                        type = Q_NEXT_TYPE(fotg210,
4611                                                        q.itd->hw_next);
4612                                        q = *q_p;
4613                                        break;
4614                                }
4615                        }
4616
4617                        /* Take finished ITDs out of the schedule
4618                         * and process them:  recycle, maybe report
4619                         * URB completion.  HC won't cache the
4620                         * pointer for much longer, if at all.
4621                         */
4622                        *q_p = q.itd->itd_next;
4623                        *hw_p = q.itd->hw_next;
4624                        type = Q_NEXT_TYPE(fotg210, q.itd->hw_next);
4625                        wmb();
4626                        modified = itd_complete(fotg210, q.itd);
4627                        q = *q_p;
4628                        break;
4629                default:
4630                        fotg210_dbg(fotg210, "corrupt type %d frame %d shadow %p\n",
4631                                        type, frame, q.ptr);
4632                        /* FALL THROUGH */
4633                case Q_TYPE_QH:
4634                case Q_TYPE_FSTN:
4635                        /* End of the iTDs and siTDs */
4636                        q.ptr = NULL;
4637                        break;
4638                }
4639
4640                /* assume completion callbacks modify the queue */
4641                if (unlikely(modified && fotg210->isoc_count > 0))
4642                        return -EINVAL;
4643        }
4644        return 0;
4645}
4646
4647static void scan_isoc(struct fotg210_hcd *fotg210)
4648{
4649        unsigned uf, now_frame, frame, ret;
4650        unsigned fmask = fotg210->periodic_size - 1;
4651        bool live;
4652
4653        /*
4654         * When running, scan from last scan point up to "now"
4655         * else clean up by scanning everything that's left.
4656         * Touches as few pages as possible:  cache-friendly.
4657         */
4658        if (fotg210->rh_state >= FOTG210_RH_RUNNING) {
4659                uf = fotg210_read_frame_index(fotg210);
4660                now_frame = (uf >> 3) & fmask;
4661                live = true;
4662        } else  {
4663                now_frame = (fotg210->next_frame - 1) & fmask;
4664                live = false;
4665        }
4666        fotg210->now_frame = now_frame;
4667
4668        frame = fotg210->next_frame;
4669        for (;;) {
4670                ret = 1;
4671                while (ret != 0)
4672                        ret = scan_frame_queue(fotg210, frame,
4673                                        now_frame, live);
4674
4675                /* Stop when we have reached the current frame */
4676                if (frame == now_frame)
4677                        break;
4678                frame = (frame + 1) & fmask;
4679        }
4680        fotg210->next_frame = now_frame;
4681}
4682
4683/* Display / Set uframe_periodic_max
4684 */
4685static ssize_t uframe_periodic_max_show(struct device *dev,
4686                struct device_attribute *attr, char *buf)
4687{
4688        struct fotg210_hcd *fotg210;
4689        int n;
4690
4691        fotg210 = hcd_to_fotg210(bus_to_hcd(dev_get_drvdata(dev)));
4692        n = scnprintf(buf, PAGE_SIZE, "%d\n", fotg210->uframe_periodic_max);
4693        return n;
4694}
4695
4696
4697static ssize_t uframe_periodic_max_store(struct device *dev,
4698                struct device_attribute *attr, const char *buf, size_t count)
4699{
4700        struct fotg210_hcd *fotg210;
4701        unsigned uframe_periodic_max;
4702        unsigned frame, uframe;
4703        unsigned short allocated_max;
4704        unsigned long flags;
4705        ssize_t ret;
4706
4707        fotg210 = hcd_to_fotg210(bus_to_hcd(dev_get_drvdata(dev)));
4708        if (kstrtouint(buf, 0, &uframe_periodic_max) < 0)
4709                return -EINVAL;
4710
4711        if (uframe_periodic_max < 100 || uframe_periodic_max >= 125) {
4712                fotg210_info(fotg210, "rejecting invalid request for uframe_periodic_max=%u\n",
4713                                uframe_periodic_max);
4714                return -EINVAL;
4715        }
4716
4717        ret = -EINVAL;
4718
4719        /*
4720         * lock, so that our checking does not race with possible periodic
4721         * bandwidth allocation through submitting new urbs.
4722         */
4723        spin_lock_irqsave(&fotg210->lock, flags);
4724
4725        /*
4726         * for request to decrease max periodic bandwidth, we have to check
4727         * every microframe in the schedule to see whether the decrease is
4728         * possible.
4729         */
4730        if (uframe_periodic_max < fotg210->uframe_periodic_max) {
4731                allocated_max = 0;
4732
4733                for (frame = 0; frame < fotg210->periodic_size; ++frame)
4734                        for (uframe = 0; uframe < 7; ++uframe)
4735                                allocated_max = max(allocated_max,
4736                                                periodic_usecs(fotg210, frame,
4737                                                uframe));
4738
4739                if (allocated_max > uframe_periodic_max) {
4740                        fotg210_info(fotg210,
4741                                        "cannot decrease uframe_periodic_max because periodic bandwidth is already allocated (%u > %u)\n",
4742                                        allocated_max, uframe_periodic_max);
4743                        goto out_unlock;
4744                }
4745        }
4746
4747        /* increasing is always ok */
4748
4749        fotg210_info(fotg210,
4750                        "setting max periodic bandwidth to %u%% (== %u usec/uframe)\n",
4751                        100 * uframe_periodic_max/125, uframe_periodic_max);
4752
4753        if (uframe_periodic_max != 100)
4754                fotg210_warn(fotg210, "max periodic bandwidth set is non-standard\n");
4755
4756        fotg210->uframe_periodic_max = uframe_periodic_max;
4757        ret = count;
4758
4759out_unlock:
4760        spin_unlock_irqrestore(&fotg210->lock, flags);
4761        return ret;
4762}
4763
4764static DEVICE_ATTR_RW(uframe_periodic_max);
4765
4766static inline int create_sysfs_files(struct fotg210_hcd *fotg210)
4767{
4768        struct device *controller = fotg210_to_hcd(fotg210)->self.controller;
4769
4770        return device_create_file(controller, &dev_attr_uframe_periodic_max);
4771}
4772
4773static inline void remove_sysfs_files(struct fotg210_hcd *fotg210)
4774{
4775        struct device *controller = fotg210_to_hcd(fotg210)->self.controller;
4776
4777        device_remove_file(controller, &dev_attr_uframe_periodic_max);
4778}
4779/* On some systems, leaving remote wakeup enabled prevents system shutdown.
4780 * The firmware seems to think that powering off is a wakeup event!
4781 * This routine turns off remote wakeup and everything else, on all ports.
4782 */
4783static void fotg210_turn_off_all_ports(struct fotg210_hcd *fotg210)
4784{
4785        u32 __iomem *status_reg = &fotg210->regs->port_status;
4786
4787        fotg210_writel(fotg210, PORT_RWC_BITS, status_reg);
4788}
4789
4790/* Halt HC, turn off all ports, and let the BIOS use the companion controllers.
4791 * Must be called with interrupts enabled and the lock not held.
4792 */
4793static void fotg210_silence_controller(struct fotg210_hcd *fotg210)
4794{
4795        fotg210_halt(fotg210);
4796
4797        spin_lock_irq(&fotg210->lock);
4798        fotg210->rh_state = FOTG210_RH_HALTED;
4799        fotg210_turn_off_all_ports(fotg210);
4800        spin_unlock_irq(&fotg210->lock);
4801}
4802
4803/* fotg210_shutdown kick in for silicon on any bus (not just pci, etc).
4804 * This forcibly disables dma and IRQs, helping kexec and other cases
4805 * where the next system software may expect clean state.
4806 */
4807static void fotg210_shutdown(struct usb_hcd *hcd)
4808{
4809        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
4810
4811        spin_lock_irq(&fotg210->lock);
4812        fotg210->shutdown = true;
4813        fotg210->rh_state = FOTG210_RH_STOPPING;
4814        fotg210->enabled_hrtimer_events = 0;
4815        spin_unlock_irq(&fotg210->lock);
4816
4817        fotg210_silence_controller(fotg210);
4818
4819        hrtimer_cancel(&fotg210->hrtimer);
4820}
4821
4822/* fotg210_work is called from some interrupts, timers, and so on.
4823 * it calls driver completion functions, after dropping fotg210->lock.
4824 */
4825static void fotg210_work(struct fotg210_hcd *fotg210)
4826{
4827        /* another CPU may drop fotg210->lock during a schedule scan while
4828         * it reports urb completions.  this flag guards against bogus
4829         * attempts at re-entrant schedule scanning.
4830         */
4831        if (fotg210->scanning) {
4832                fotg210->need_rescan = true;
4833                return;
4834        }
4835        fotg210->scanning = true;
4836
4837rescan:
4838        fotg210->need_rescan = false;
4839        if (fotg210->async_count)
4840                scan_async(fotg210);
4841        if (fotg210->intr_count > 0)
4842                scan_intr(fotg210);
4843        if (fotg210->isoc_count > 0)
4844                scan_isoc(fotg210);
4845        if (fotg210->need_rescan)
4846                goto rescan;
4847        fotg210->scanning = false;
4848
4849        /* the IO watchdog guards against hardware or driver bugs that
4850         * misplace IRQs, and should let us run completely without IRQs.
4851         * such lossage has been observed on both VT6202 and VT8235.
4852         */
4853        turn_on_io_watchdog(fotg210);
4854}
4855
4856/* Called when the fotg210_hcd module is removed.
4857 */
4858static void fotg210_stop(struct usb_hcd *hcd)
4859{
4860        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
4861
4862        fotg210_dbg(fotg210, "stop\n");
4863
4864        /* no more interrupts ... */
4865
4866        spin_lock_irq(&fotg210->lock);
4867        fotg210->enabled_hrtimer_events = 0;
4868        spin_unlock_irq(&fotg210->lock);
4869
4870        fotg210_quiesce(fotg210);
4871        fotg210_silence_controller(fotg210);
4872        fotg210_reset(fotg210);
4873
4874        hrtimer_cancel(&fotg210->hrtimer);
4875        remove_sysfs_files(fotg210);
4876        remove_debug_files(fotg210);
4877
4878        /* root hub is shut down separately (first, when possible) */
4879        spin_lock_irq(&fotg210->lock);
4880        end_free_itds(fotg210);
4881        spin_unlock_irq(&fotg210->lock);
4882        fotg210_mem_cleanup(fotg210);
4883
4884#ifdef FOTG210_STATS
4885        fotg210_dbg(fotg210, "irq normal %ld err %ld iaa %ld (lost %ld)\n",
4886                        fotg210->stats.normal, fotg210->stats.error,
4887                        fotg210->stats.iaa, fotg210->stats.lost_iaa);
4888        fotg210_dbg(fotg210, "complete %ld unlink %ld\n",
4889                        fotg210->stats.complete, fotg210->stats.unlink);
4890#endif
4891
4892        dbg_status(fotg210, "fotg210_stop completed",
4893                        fotg210_readl(fotg210, &fotg210->regs->status));
4894}
4895
4896/* one-time init, only for memory state */
4897static int hcd_fotg210_init(struct usb_hcd *hcd)
4898{
4899        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
4900        u32 temp;
4901        int retval;
4902        u32 hcc_params;
4903        struct fotg210_qh_hw *hw;
4904
4905        spin_lock_init(&fotg210->lock);
4906
4907        /*
4908         * keep io watchdog by default, those good HCDs could turn off it later
4909         */
4910        fotg210->need_io_watchdog = 1;
4911
4912        hrtimer_init(&fotg210->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS);
4913        fotg210->hrtimer.function = fotg210_hrtimer_func;
4914        fotg210->next_hrtimer_event = FOTG210_HRTIMER_NO_EVENT;
4915
4916        hcc_params = fotg210_readl(fotg210, &fotg210->caps->hcc_params);
4917
4918        /*
4919         * by default set standard 80% (== 100 usec/uframe) max periodic
4920         * bandwidth as required by USB 2.0
4921         */
4922        fotg210->uframe_periodic_max = 100;
4923
4924        /*
4925         * hw default: 1K periodic list heads, one per frame.
4926         * periodic_size can shrink by USBCMD update if hcc_params allows.
4927         */
4928        fotg210->periodic_size = DEFAULT_I_TDPS;
4929        INIT_LIST_HEAD(&fotg210->intr_qh_list);
4930        INIT_LIST_HEAD(&fotg210->cached_itd_list);
4931
4932        if (HCC_PGM_FRAMELISTLEN(hcc_params)) {
4933                /* periodic schedule size can be smaller than default */
4934                switch (FOTG210_TUNE_FLS) {
4935                case 0:
4936                        fotg210->periodic_size = 1024;
4937                        break;
4938                case 1:
4939                        fotg210->periodic_size = 512;
4940                        break;
4941                case 2:
4942                        fotg210->periodic_size = 256;
4943                        break;
4944                default:
4945                        BUG();
4946                }
4947        }
4948        retval = fotg210_mem_init(fotg210, GFP_KERNEL);
4949        if (retval < 0)
4950                return retval;
4951
4952        /* controllers may cache some of the periodic schedule ... */
4953        fotg210->i_thresh = 2;
4954
4955        /*
4956         * dedicate a qh for the async ring head, since we couldn't unlink
4957         * a 'real' qh without stopping the async schedule [4.8].  use it
4958         * as the 'reclamation list head' too.
4959         * its dummy is used in hw_alt_next of many tds, to prevent the qh
4960         * from automatically advancing to the next td after short reads.
4961         */
4962        fotg210->async->qh_next.qh = NULL;
4963        hw = fotg210->async->hw;
4964        hw->hw_next = QH_NEXT(fotg210, fotg210->async->qh_dma);
4965        hw->hw_info1 = cpu_to_hc32(fotg210, QH_HEAD);
4966        hw->hw_token = cpu_to_hc32(fotg210, QTD_STS_HALT);
4967        hw->hw_qtd_next = FOTG210_LIST_END(fotg210);
4968        fotg210->async->qh_state = QH_STATE_LINKED;
4969        hw->hw_alt_next = QTD_NEXT(fotg210, fotg210->async->dummy->qtd_dma);
4970
4971        /* clear interrupt enables, set irq latency */
4972        if (log2_irq_thresh < 0 || log2_irq_thresh > 6)
4973                log2_irq_thresh = 0;
4974        temp = 1 << (16 + log2_irq_thresh);
4975        if (HCC_CANPARK(hcc_params)) {
4976                /* HW default park == 3, on hardware that supports it (like
4977                 * NVidia and ALI silicon), maximizes throughput on the async
4978                 * schedule by avoiding QH fetches between transfers.
4979                 *
4980                 * With fast usb storage devices and NForce2, "park" seems to
4981                 * make problems:  throughput reduction (!), data errors...
4982                 */
4983                if (park) {
4984                        park = min_t(unsigned, park, 3);
4985                        temp |= CMD_PARK;
4986                        temp |= park << 8;
4987                }
4988                fotg210_dbg(fotg210, "park %d\n", park);
4989        }
4990        if (HCC_PGM_FRAMELISTLEN(hcc_params)) {
4991                /* periodic schedule size can be smaller than default */
4992                temp &= ~(3 << 2);
4993                temp |= (FOTG210_TUNE_FLS << 2);
4994        }
4995        fotg210->command = temp;
4996
4997        /* Accept arbitrarily long scatter-gather lists */
4998        if (!(hcd->driver->flags & HCD_LOCAL_MEM))
4999                hcd->self.sg_tablesize = ~0;
5000        return 0;
5001}
5002
5003/* start HC running; it's halted, hcd_fotg210_init() has been run (once) */
5004static int fotg210_run(struct usb_hcd *hcd)
5005{
5006        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
5007        u32 temp;
5008        u32 hcc_params;
5009
5010        hcd->uses_new_polling = 1;
5011
5012        /* EHCI spec section 4.1 */
5013
5014        fotg210_writel(fotg210, fotg210->periodic_dma,
5015                        &fotg210->regs->frame_list);
5016        fotg210_writel(fotg210, (u32)fotg210->async->qh_dma,
5017                        &fotg210->regs->async_next);
5018
5019        /*
5020         * hcc_params controls whether fotg210->regs->segment must (!!!)
5021         * be used; it constrains QH/ITD/SITD and QTD locations.
5022         * dma_pool consistent memory always uses segment zero.
5023         * streaming mappings for I/O buffers, like pci_map_single(),
5024         * can return segments above 4GB, if the device allows.
5025         *
5026         * NOTE:  the dma mask is visible through dev->dma_mask, so
5027         * drivers can pass this info along ... like NETIF_F_HIGHDMA,
5028         * Scsi_Host.highmem_io, and so forth.  It's readonly to all
5029         * host side drivers though.
5030         */
5031        hcc_params = fotg210_readl(fotg210, &fotg210->caps->hcc_params);
5032
5033        /*
5034         * Philips, Intel, and maybe others need CMD_RUN before the
5035         * root hub will detect new devices (why?); NEC doesn't
5036         */
5037        fotg210->command &= ~(CMD_IAAD|CMD_PSE|CMD_ASE|CMD_RESET);
5038        fotg210->command |= CMD_RUN;
5039        fotg210_writel(fotg210, fotg210->command, &fotg210->regs->command);
5040        dbg_cmd(fotg210, "init", fotg210->command);
5041
5042        /*
5043         * Start, enabling full USB 2.0 functionality ... usb 1.1 devices
5044         * are explicitly handed to companion controller(s), so no TT is
5045         * involved with the root hub.  (Except where one is integrated,
5046         * and there's no companion controller unless maybe for USB OTG.)
5047         *
5048         * Turning on the CF flag will transfer ownership of all ports
5049         * from the companions to the EHCI controller.  If any of the
5050         * companions are in the middle of a port reset at the time, it
5051         * could cause trouble.  Write-locking ehci_cf_port_reset_rwsem
5052         * guarantees that no resets are in progress.  After we set CF,
5053         * a short delay lets the hardware catch up; new resets shouldn't
5054         * be started before the port switching actions could complete.
5055         */
5056        down_write(&ehci_cf_port_reset_rwsem);
5057        fotg210->rh_state = FOTG210_RH_RUNNING;
5058        /* unblock posted writes */
5059        fotg210_readl(fotg210, &fotg210->regs->command);
5060        usleep_range(5000, 10000);
5061        up_write(&ehci_cf_port_reset_rwsem);
5062        fotg210->last_periodic_enable = ktime_get_real();
5063
5064        temp = HC_VERSION(fotg210,
5065                        fotg210_readl(fotg210, &fotg210->caps->hc_capbase));
5066        fotg210_info(fotg210,
5067                        "USB %x.%x started, EHCI %x.%02x\n",
5068                        ((fotg210->sbrn & 0xf0) >> 4), (fotg210->sbrn & 0x0f),
5069                        temp >> 8, temp & 0xff);
5070
5071        fotg210_writel(fotg210, INTR_MASK,
5072                        &fotg210->regs->intr_enable); /* Turn On Interrupts */
5073
5074        /* GRR this is run-once init(), being done every time the HC starts.
5075         * So long as they're part of class devices, we can't do it init()
5076         * since the class device isn't created that early.
5077         */
5078        create_debug_files(fotg210);
5079        create_sysfs_files(fotg210);
5080
5081        return 0;
5082}
5083
5084static int fotg210_setup(struct usb_hcd *hcd)
5085{
5086        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
5087        int retval;
5088
5089        fotg210->regs = (void __iomem *)fotg210->caps +
5090                        HC_LENGTH(fotg210,
5091                        fotg210_readl(fotg210, &fotg210->caps->hc_capbase));
5092        dbg_hcs_params(fotg210, "reset");
5093        dbg_hcc_params(fotg210, "reset");
5094
5095        /* cache this readonly data; minimize chip reads */
5096        fotg210->hcs_params = fotg210_readl(fotg210,
5097                        &fotg210->caps->hcs_params);
5098
5099        fotg210->sbrn = HCD_USB2;
5100
5101        /* data structure init */
5102        retval = hcd_fotg210_init(hcd);
5103        if (retval)
5104                return retval;
5105
5106        retval = fotg210_halt(fotg210);
5107        if (retval)
5108                return retval;
5109
5110        fotg210_reset(fotg210);
5111
5112        return 0;
5113}
5114
5115static irqreturn_t fotg210_irq(struct usb_hcd *hcd)
5116{
5117        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
5118        u32 status, masked_status, pcd_status = 0, cmd;
5119        int bh;
5120
5121        spin_lock(&fotg210->lock);
5122
5123        status = fotg210_readl(fotg210, &fotg210->regs->status);
5124
5125        /* e.g. cardbus physical eject */
5126        if (status == ~(u32) 0) {
5127                fotg210_dbg(fotg210, "device removed\n");
5128                goto dead;
5129        }
5130
5131        /*
5132         * We don't use STS_FLR, but some controllers don't like it to
5133         * remain on, so mask it out along with the other status bits.
5134         */
5135        masked_status = status & (INTR_MASK | STS_FLR);
5136
5137        /* Shared IRQ? */
5138        if (!masked_status ||
5139                        unlikely(fotg210->rh_state == FOTG210_RH_HALTED)) {
5140                spin_unlock(&fotg210->lock);
5141                return IRQ_NONE;
5142        }
5143
5144        /* clear (just) interrupts */
5145        fotg210_writel(fotg210, masked_status, &fotg210->regs->status);
5146        cmd = fotg210_readl(fotg210, &fotg210->regs->command);
5147        bh = 0;
5148
5149        /* unrequested/ignored: Frame List Rollover */
5150        dbg_status(fotg210, "irq", status);
5151
5152        /* INT, ERR, and IAA interrupt rates can be throttled */
5153
5154        /* normal [4.15.1.2] or error [4.15.1.1] completion */
5155        if (likely((status & (STS_INT|STS_ERR)) != 0)) {
5156                if (likely((status & STS_ERR) == 0))
5157                        INCR(fotg210->stats.normal);
5158                else
5159                        INCR(fotg210->stats.error);
5160                bh = 1;
5161        }
5162
5163        /* complete the unlinking of some qh [4.15.2.3] */
5164        if (status & STS_IAA) {
5165
5166                /* Turn off the IAA watchdog */
5167                fotg210->enabled_hrtimer_events &=
5168                        ~BIT(FOTG210_HRTIMER_IAA_WATCHDOG);
5169
5170                /*
5171                 * Mild optimization: Allow another IAAD to reset the
5172                 * hrtimer, if one occurs before the next expiration.
5173                 * In theory we could always cancel the hrtimer, but
5174                 * tests show that about half the time it will be reset
5175                 * for some other event anyway.
5176                 */
5177                if (fotg210->next_hrtimer_event == FOTG210_HRTIMER_IAA_WATCHDOG)
5178                        ++fotg210->next_hrtimer_event;
5179
5180                /* guard against (alleged) silicon errata */
5181                if (cmd & CMD_IAAD)
5182                        fotg210_dbg(fotg210, "IAA with IAAD still set?\n");
5183                if (fotg210->async_iaa) {
5184                        INCR(fotg210->stats.iaa);
5185                        end_unlink_async(fotg210);
5186                } else
5187                        fotg210_dbg(fotg210, "IAA with nothing unlinked?\n");
5188        }
5189
5190        /* remote wakeup [4.3.1] */
5191        if (status & STS_PCD) {
5192                int pstatus;
5193                u32 __iomem *status_reg = &fotg210->regs->port_status;
5194
5195                /* kick root hub later */
5196                pcd_status = status;
5197
5198                /* resume root hub? */
5199                if (fotg210->rh_state == FOTG210_RH_SUSPENDED)
5200                        usb_hcd_resume_root_hub(hcd);
5201
5202                pstatus = fotg210_readl(fotg210, status_reg);
5203
5204                if (test_bit(0, &fotg210->suspended_ports) &&
5205                                ((pstatus & PORT_RESUME) ||
5206                                !(pstatus & PORT_SUSPEND)) &&
5207                                (pstatus & PORT_PE) &&
5208                                fotg210->reset_done[0] == 0) {
5209
5210                        /* start 20 msec resume signaling from this port,
5211                         * and make hub_wq collect PORT_STAT_C_SUSPEND to
5212                         * stop that signaling.  Use 5 ms extra for safety,
5213                         * like usb_port_resume() does.
5214                         */
5215                        fotg210->reset_done[0] = jiffies + msecs_to_jiffies(25);
5216                        set_bit(0, &fotg210->resuming_ports);
5217                        fotg210_dbg(fotg210, "port 1 remote wakeup\n");
5218                        mod_timer(&hcd->rh_timer, fotg210->reset_done[0]);
5219                }
5220        }
5221
5222        /* PCI errors [4.15.2.4] */
5223        if (unlikely((status & STS_FATAL) != 0)) {
5224                fotg210_err(fotg210, "fatal error\n");
5225                dbg_cmd(fotg210, "fatal", cmd);
5226                dbg_status(fotg210, "fatal", status);
5227dead:
5228                usb_hc_died(hcd);
5229
5230                /* Don't let the controller do anything more */
5231                fotg210->shutdown = true;
5232                fotg210->rh_state = FOTG210_RH_STOPPING;
5233                fotg210->command &= ~(CMD_RUN | CMD_ASE | CMD_PSE);
5234                fotg210_writel(fotg210, fotg210->command,
5235                                &fotg210->regs->command);
5236                fotg210_writel(fotg210, 0, &fotg210->regs->intr_enable);
5237                fotg210_handle_controller_death(fotg210);
5238
5239                /* Handle completions when the controller stops */
5240                bh = 0;
5241        }
5242
5243        if (bh)
5244                fotg210_work(fotg210);
5245        spin_unlock(&fotg210->lock);
5246        if (pcd_status)
5247                usb_hcd_poll_rh_status(hcd);
5248        return IRQ_HANDLED;
5249}
5250
5251/* non-error returns are a promise to giveback() the urb later
5252 * we drop ownership so next owner (or urb unlink) can get it
5253 *
5254 * urb + dev is in hcd.self.controller.urb_list
5255 * we're queueing TDs onto software and hardware lists
5256 *
5257 * hcd-specific init for hcpriv hasn't been done yet
5258 *
5259 * NOTE:  control, bulk, and interrupt share the same code to append TDs
5260 * to a (possibly active) QH, and the same QH scanning code.
5261 */
5262static int fotg210_urb_enqueue(struct usb_hcd *hcd, struct urb *urb,
5263                gfp_t mem_flags)
5264{
5265        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
5266        struct list_head qtd_list;
5267
5268        INIT_LIST_HEAD(&qtd_list);
5269
5270        switch (usb_pipetype(urb->pipe)) {
5271        case PIPE_CONTROL:
5272                /* qh_completions() code doesn't handle all the fault cases
5273                 * in multi-TD control transfers.  Even 1KB is rare anyway.
5274                 */
5275                if (urb->transfer_buffer_length > (16 * 1024))
5276                        return -EMSGSIZE;
5277                /* FALLTHROUGH */
5278        /* case PIPE_BULK: */
5279        default:
5280                if (!qh_urb_transaction(fotg210, urb, &qtd_list, mem_flags))
5281                        return -ENOMEM;
5282                return submit_async(fotg210, urb, &qtd_list, mem_flags);
5283
5284        case PIPE_INTERRUPT:
5285                if (!qh_urb_transaction(fotg210, urb, &qtd_list, mem_flags))
5286                        return -ENOMEM;
5287                return intr_submit(fotg210, urb, &qtd_list, mem_flags);
5288
5289        case PIPE_ISOCHRONOUS:
5290                return itd_submit(fotg210, urb, mem_flags);
5291        }
5292}
5293
5294/* remove from hardware lists
5295 * completions normally happen asynchronously
5296 */
5297
5298static int fotg210_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
5299{
5300        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
5301        struct fotg210_qh *qh;
5302        unsigned long flags;
5303        int rc;
5304
5305        spin_lock_irqsave(&fotg210->lock, flags);
5306        rc = usb_hcd_check_unlink_urb(hcd, urb, status);
5307        if (rc)
5308                goto done;
5309
5310        switch (usb_pipetype(urb->pipe)) {
5311        /* case PIPE_CONTROL: */
5312        /* case PIPE_BULK:*/
5313        default:
5314                qh = (struct fotg210_qh *) urb->hcpriv;
5315                if (!qh)
5316                        break;
5317                switch (qh->qh_state) {
5318                case QH_STATE_LINKED:
5319                case QH_STATE_COMPLETING:
5320                        start_unlink_async(fotg210, qh);
5321                        break;
5322                case QH_STATE_UNLINK:
5323                case QH_STATE_UNLINK_WAIT:
5324                        /* already started */
5325                        break;
5326                case QH_STATE_IDLE:
5327                        /* QH might be waiting for a Clear-TT-Buffer */
5328                        qh_completions(fotg210, qh);
5329                        break;
5330                }
5331                break;
5332
5333        case PIPE_INTERRUPT:
5334                qh = (struct fotg210_qh *) urb->hcpriv;
5335                if (!qh)
5336                        break;
5337                switch (qh->qh_state) {
5338                case QH_STATE_LINKED:
5339                case QH_STATE_COMPLETING:
5340                        start_unlink_intr(fotg210, qh);
5341                        break;
5342                case QH_STATE_IDLE:
5343                        qh_completions(fotg210, qh);
5344                        break;
5345                default:
5346                        fotg210_dbg(fotg210, "bogus qh %p state %d\n",
5347                                        qh, qh->qh_state);
5348                        goto done;
5349                }
5350                break;
5351
5352        case PIPE_ISOCHRONOUS:
5353                /* itd... */
5354
5355                /* wait till next completion, do it then. */
5356                /* completion irqs can wait up to 1024 msec, */
5357                break;
5358        }
5359done:
5360        spin_unlock_irqrestore(&fotg210->lock, flags);
5361        return rc;
5362}
5363
5364/* bulk qh holds the data toggle */
5365
5366static void fotg210_endpoint_disable(struct usb_hcd *hcd,
5367                struct usb_host_endpoint *ep)
5368{
5369        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
5370        unsigned long flags;
5371        struct fotg210_qh *qh, *tmp;
5372
5373        /* ASSERT:  any requests/urbs are being unlinked */
5374        /* ASSERT:  nobody can be submitting urbs for this any more */
5375
5376rescan:
5377        spin_lock_irqsave(&fotg210->lock, flags);
5378        qh = ep->hcpriv;
5379        if (!qh)
5380                goto done;
5381
5382        /* endpoints can be iso streams.  for now, we don't
5383         * accelerate iso completions ... so spin a while.
5384         */
5385        if (qh->hw == NULL) {
5386                struct fotg210_iso_stream *stream = ep->hcpriv;
5387
5388                if (!list_empty(&stream->td_list))
5389                        goto idle_timeout;
5390
5391                /* BUG_ON(!list_empty(&stream->free_list)); */
5392                kfree(stream);
5393                goto done;
5394        }
5395
5396        if (fotg210->rh_state < FOTG210_RH_RUNNING)
5397                qh->qh_state = QH_STATE_IDLE;
5398        switch (qh->qh_state) {
5399        case QH_STATE_LINKED:
5400        case QH_STATE_COMPLETING:
5401                for (tmp = fotg210->async->qh_next.qh;
5402                                tmp && tmp != qh;
5403                                tmp = tmp->qh_next.qh)
5404                        continue;
5405                /* periodic qh self-unlinks on empty, and a COMPLETING qh
5406                 * may already be unlinked.
5407                 */
5408                if (tmp)
5409                        start_unlink_async(fotg210, qh);
5410                /* FALL THROUGH */
5411        case QH_STATE_UNLINK:           /* wait for hw to finish? */
5412        case QH_STATE_UNLINK_WAIT:
5413idle_timeout:
5414                spin_unlock_irqrestore(&fotg210->lock, flags);
5415                schedule_timeout_uninterruptible(1);
5416                goto rescan;
5417        case QH_STATE_IDLE:             /* fully unlinked */
5418                if (qh->clearing_tt)
5419                        goto idle_timeout;
5420                if (list_empty(&qh->qtd_list)) {
5421                        qh_destroy(fotg210, qh);
5422                        break;
5423                }
5424                /* fall through */
5425        default:
5426                /* caller was supposed to have unlinked any requests;
5427                 * that's not our job.  just leak this memory.
5428                 */
5429                fotg210_err(fotg210, "qh %p (#%02x) state %d%s\n",
5430                                qh, ep->desc.bEndpointAddress, qh->qh_state,
5431                                list_empty(&qh->qtd_list) ? "" : "(has tds)");
5432                break;
5433        }
5434done:
5435        ep->hcpriv = NULL;
5436        spin_unlock_irqrestore(&fotg210->lock, flags);
5437}
5438
5439static void fotg210_endpoint_reset(struct usb_hcd *hcd,
5440                struct usb_host_endpoint *ep)
5441{
5442        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
5443        struct fotg210_qh *qh;
5444        int eptype = usb_endpoint_type(&ep->desc);
5445        int epnum = usb_endpoint_num(&ep->desc);
5446        int is_out = usb_endpoint_dir_out(&ep->desc);
5447        unsigned long flags;
5448
5449        if (eptype != USB_ENDPOINT_XFER_BULK && eptype != USB_ENDPOINT_XFER_INT)
5450                return;
5451
5452        spin_lock_irqsave(&fotg210->lock, flags);
5453        qh = ep->hcpriv;
5454
5455        /* For Bulk and Interrupt endpoints we maintain the toggle state
5456         * in the hardware; the toggle bits in udev aren't used at all.
5457         * When an endpoint is reset by usb_clear_halt() we must reset
5458         * the toggle bit in the QH.
5459         */
5460        if (qh) {
5461                usb_settoggle(qh->dev, epnum, is_out, 0);
5462                if (!list_empty(&qh->qtd_list)) {
5463                        WARN_ONCE(1, "clear_halt for a busy endpoint\n");
5464                } else if (qh->qh_state == QH_STATE_LINKED ||
5465                                qh->qh_state == QH_STATE_COMPLETING) {
5466
5467                        /* The toggle value in the QH can't be updated
5468                         * while the QH is active.  Unlink it now;
5469                         * re-linking will call qh_refresh().
5470                         */
5471                        if (eptype == USB_ENDPOINT_XFER_BULK)
5472                                start_unlink_async(fotg210, qh);
5473                        else
5474                                start_unlink_intr(fotg210, qh);
5475                }
5476        }
5477        spin_unlock_irqrestore(&fotg210->lock, flags);
5478}
5479
5480static int fotg210_get_frame(struct usb_hcd *hcd)
5481{
5482        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
5483
5484        return (fotg210_read_frame_index(fotg210) >> 3) %
5485                fotg210->periodic_size;
5486}
5487
5488/* The EHCI in ChipIdea HDRC cannot be a separate module or device,
5489 * because its registers (and irq) are shared between host/gadget/otg
5490 * functions  and in order to facilitate role switching we cannot
5491 * give the fotg210 driver exclusive access to those.
5492 */
5493MODULE_DESCRIPTION(DRIVER_DESC);
5494MODULE_AUTHOR(DRIVER_AUTHOR);
5495MODULE_LICENSE("GPL");
5496
5497static const struct hc_driver fotg210_fotg210_hc_driver = {
5498        .description            = hcd_name,
5499        .product_desc           = "Faraday USB2.0 Host Controller",
5500        .hcd_priv_size          = sizeof(struct fotg210_hcd),
5501
5502        /*
5503         * generic hardware linkage
5504         */
5505        .irq                    = fotg210_irq,
5506        .flags                  = HCD_MEMORY | HCD_USB2,
5507
5508        /*
5509         * basic lifecycle operations
5510         */
5511        .reset                  = hcd_fotg210_init,
5512        .start                  = fotg210_run,
5513        .stop                   = fotg210_stop,
5514        .shutdown               = fotg210_shutdown,
5515
5516        /*
5517         * managing i/o requests and associated device resources
5518         */
5519        .urb_enqueue            = fotg210_urb_enqueue,
5520        .urb_dequeue            = fotg210_urb_dequeue,
5521        .endpoint_disable       = fotg210_endpoint_disable,
5522        .endpoint_reset         = fotg210_endpoint_reset,
5523
5524        /*
5525         * scheduling support
5526         */
5527        .get_frame_number       = fotg210_get_frame,
5528
5529        /*
5530         * root hub support
5531         */
5532        .hub_status_data        = fotg210_hub_status_data,
5533        .hub_control            = fotg210_hub_control,
5534        .bus_suspend            = fotg210_bus_suspend,
5535        .bus_resume             = fotg210_bus_resume,
5536
5537        .relinquish_port        = fotg210_relinquish_port,
5538        .port_handed_over       = fotg210_port_handed_over,
5539
5540        .clear_tt_buffer_complete = fotg210_clear_tt_buffer_complete,
5541};
5542
5543static void fotg210_init(struct fotg210_hcd *fotg210)
5544{
5545        u32 value;
5546
5547        iowrite32(GMIR_MDEV_INT | GMIR_MOTG_INT | GMIR_INT_POLARITY,
5548                        &fotg210->regs->gmir);
5549
5550        value = ioread32(&fotg210->regs->otgcsr);
5551        value &= ~OTGCSR_A_BUS_DROP;
5552        value |= OTGCSR_A_BUS_REQ;
5553        iowrite32(value, &fotg210->regs->otgcsr);
5554}
5555
5556/**
5557 * fotg210_hcd_probe - initialize faraday FOTG210 HCDs
5558 *
5559 * Allocates basic resources for this USB host controller, and
5560 * then invokes the start() method for the HCD associated with it
5561 * through the hotplug entry's driver_data.
5562 */
5563static int fotg210_hcd_probe(struct platform_device *pdev)
5564{
5565        struct device *dev = &pdev->dev;
5566        struct usb_hcd *hcd;
5567        struct resource *res;
5568        int irq;
5569        int retval = -ENODEV;
5570        struct fotg210_hcd *fotg210;
5571
5572        if (usb_disabled())
5573                return -ENODEV;
5574
5575        pdev->dev.power.power_state = PMSG_ON;
5576
5577        res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
5578        if (!res) {
5579                dev_err(dev, "Found HC with no IRQ. Check %s setup!\n",
5580                                dev_name(dev));
5581                return -ENODEV;
5582        }
5583
5584        irq = res->start;
5585
5586        hcd = usb_create_hcd(&fotg210_fotg210_hc_driver, dev,
5587                        dev_name(dev));
5588        if (!hcd) {
5589                dev_err(dev, "failed to create hcd with err %d\n", retval);
5590                retval = -ENOMEM;
5591                goto fail_create_hcd;
5592        }
5593
5594        hcd->has_tt = 1;
5595
5596        res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
5597        hcd->regs = devm_ioremap_resource(&pdev->dev, res);
5598        if (IS_ERR(hcd->regs)) {
5599                retval = PTR_ERR(hcd->regs);
5600                goto failed_put_hcd;
5601        }
5602
5603        hcd->rsrc_start = res->start;
5604        hcd->rsrc_len = resource_size(res);
5605
5606        fotg210 = hcd_to_fotg210(hcd);
5607
5608        fotg210->caps = hcd->regs;
5609
5610        /* It's OK not to supply this clock */
5611        fotg210->pclk = clk_get(dev, "PCLK");
5612        if (!IS_ERR(fotg210->pclk)) {
5613                retval = clk_prepare_enable(fotg210->pclk);
5614                if (retval) {
5615                        dev_err(dev, "failed to enable PCLK\n");
5616                        goto failed_put_hcd;
5617                }
5618        } else if (PTR_ERR(fotg210->pclk) == -EPROBE_DEFER) {
5619                /*
5620                 * Percolate deferrals, for anything else,
5621                 * just live without the clocking.
5622                 */
5623                retval = PTR_ERR(fotg210->pclk);
5624                goto failed_dis_clk;
5625        }
5626
5627        retval = fotg210_setup(hcd);
5628        if (retval)
5629                goto failed_dis_clk;
5630
5631        fotg210_init(fotg210);
5632
5633        retval = usb_add_hcd(hcd, irq, IRQF_SHARED);
5634        if (retval) {
5635                dev_err(dev, "failed to add hcd with err %d\n", retval);
5636                goto failed_dis_clk;
5637        }
5638        device_wakeup_enable(hcd->self.controller);
5639        platform_set_drvdata(pdev, hcd);
5640
5641        return retval;
5642
5643failed_dis_clk:
5644        if (!IS_ERR(fotg210->pclk))
5645                clk_disable_unprepare(fotg210->pclk);
5646failed_put_hcd:
5647        usb_put_hcd(hcd);
5648fail_create_hcd:
5649        dev_err(dev, "init %s fail, %d\n", dev_name(dev), retval);
5650        return retval;
5651}
5652
5653/**
5654 * fotg210_hcd_remove - shutdown processing for EHCI HCDs
5655 * @dev: USB Host Controller being removed
5656 *
5657 */
5658static int fotg210_hcd_remove(struct platform_device *pdev)
5659{
5660        struct usb_hcd *hcd = platform_get_drvdata(pdev);
5661        struct fotg210_hcd *fotg210 = hcd_to_fotg210(hcd);
5662
5663        if (!IS_ERR(fotg210->pclk))
5664                clk_disable_unprepare(fotg210->pclk);
5665
5666        usb_remove_hcd(hcd);
5667        usb_put_hcd(hcd);
5668
5669        return 0;
5670}
5671
5672static struct platform_driver fotg210_hcd_driver = {
5673        .driver = {
5674                .name   = "fotg210-hcd",
5675        },
5676        .probe  = fotg210_hcd_probe,
5677        .remove = fotg210_hcd_remove,
5678};
5679
5680static int __init fotg210_hcd_init(void)
5681{
5682        int retval = 0;
5683
5684        if (usb_disabled())
5685                return -ENODEV;
5686
5687        pr_info("%s: " DRIVER_DESC "\n", hcd_name);
5688        set_bit(USB_EHCI_LOADED, &usb_hcds_loaded);
5689        if (test_bit(USB_UHCI_LOADED, &usb_hcds_loaded) ||
5690                        test_bit(USB_OHCI_LOADED, &usb_hcds_loaded))
5691                pr_warn("Warning! fotg210_hcd should always be loaded before uhci_hcd and ohci_hcd, not after\n");
5692
5693        pr_debug("%s: block sizes: qh %zd qtd %zd itd %zd\n",
5694                        hcd_name, sizeof(struct fotg210_qh),
5695                        sizeof(struct fotg210_qtd),
5696                        sizeof(struct fotg210_itd));
5697
5698        fotg210_debug_root = debugfs_create_dir("fotg210", usb_debug_root);
5699
5700        retval = platform_driver_register(&fotg210_hcd_driver);
5701        if (retval < 0)
5702                goto clean;
5703        return retval;
5704
5705clean:
5706        debugfs_remove(fotg210_debug_root);
5707        fotg210_debug_root = NULL;
5708
5709        clear_bit(USB_EHCI_LOADED, &usb_hcds_loaded);
5710        return retval;
5711}
5712module_init(fotg210_hcd_init);
5713
5714static void __exit fotg210_hcd_cleanup(void)
5715{
5716        platform_driver_unregister(&fotg210_hcd_driver);
5717        debugfs_remove(fotg210_debug_root);
5718        clear_bit(USB_EHCI_LOADED, &usb_hcds_loaded);
5719}
5720module_exit(fotg210_hcd_cleanup);
5721