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