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