Linux Audio

Check our new training course

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