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