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