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