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