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