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