Linux Audio

Check our new training course

Loading...
v3.1
   1/*
   2 * Copyright (c) 2008 Rodolfo Giometti <giometti@linux.it>
   3 * Copyright (c) 2008 Eurotech S.p.A. <info@eurtech.it>
   4 *
   5 * This code is *strongly* based on EHCI-HCD code by David Brownell since
   6 * the chip is a quasi-EHCI compatible.
   7 *
   8 * This program is free software; you can redistribute it and/or modify it
   9 * under the terms of the GNU General Public License as published by the
  10 * Free Software Foundation; either version 2 of the License, or (at your
  11 * option) any later version.
  12 *
  13 * This program is distributed in the hope that it will be useful, but
  14 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  15 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  16 * for more details.
  17 *
  18 * You should have received a copy of the GNU General Public License
  19 * along with this program; if not, write to the Free Software Foundation,
  20 * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  21 */
  22
  23#include <linux/module.h>
  24#include <linux/pci.h>
  25#include <linux/dmapool.h>
  26#include <linux/kernel.h>
  27#include <linux/delay.h>
  28#include <linux/ioport.h>
  29#include <linux/sched.h>
  30#include <linux/slab.h>
  31#include <linux/errno.h>
  32#include <linux/init.h>
  33#include <linux/timer.h>
  34#include <linux/list.h>
  35#include <linux/interrupt.h>
  36#include <linux/usb.h>
  37#include <linux/usb/hcd.h>
  38#include <linux/moduleparam.h>
  39#include <linux/dma-mapping.h>
  40#include <linux/io.h>
  41
  42#include <asm/irq.h>
  43#include <asm/system.h>
  44#include <asm/unaligned.h>
  45
  46#include <linux/irq.h>
  47#include <linux/platform_device.h>
  48
  49#include "oxu210hp.h"
  50
  51#define DRIVER_VERSION "0.0.50"
  52
  53/*
  54 * Main defines
  55 */
  56
  57#define oxu_dbg(oxu, fmt, args...) \
  58		dev_dbg(oxu_to_hcd(oxu)->self.controller , fmt , ## args)
  59#define oxu_err(oxu, fmt, args...) \
  60		dev_err(oxu_to_hcd(oxu)->self.controller , fmt , ## args)
  61#define oxu_info(oxu, fmt, args...) \
  62		dev_info(oxu_to_hcd(oxu)->self.controller , fmt , ## args)
  63
 
 
 
 
  64static inline struct usb_hcd *oxu_to_hcd(struct oxu_hcd *oxu)
  65{
  66	return container_of((void *) oxu, struct usb_hcd, hcd_priv);
  67}
  68
  69static inline struct oxu_hcd *hcd_to_oxu(struct usb_hcd *hcd)
  70{
  71	return (struct oxu_hcd *) (hcd->hcd_priv);
  72}
  73
  74/*
  75 * Debug stuff
  76 */
  77
  78#undef OXU_URB_TRACE
  79#undef OXU_VERBOSE_DEBUG
  80
  81#ifdef OXU_VERBOSE_DEBUG
  82#define oxu_vdbg			oxu_dbg
  83#else
  84#define oxu_vdbg(oxu, fmt, args...)	/* Nop */
  85#endif
  86
  87#ifdef DEBUG
  88
  89static int __attribute__((__unused__))
  90dbg_status_buf(char *buf, unsigned len, const char *label, u32 status)
  91{
  92	return scnprintf(buf, len, "%s%sstatus %04x%s%s%s%s%s%s%s%s%s%s",
  93		label, label[0] ? " " : "", status,
  94		(status & STS_ASS) ? " Async" : "",
  95		(status & STS_PSS) ? " Periodic" : "",
  96		(status & STS_RECL) ? " Recl" : "",
  97		(status & STS_HALT) ? " Halt" : "",
  98		(status & STS_IAA) ? " IAA" : "",
  99		(status & STS_FATAL) ? " FATAL" : "",
 100		(status & STS_FLR) ? " FLR" : "",
 101		(status & STS_PCD) ? " PCD" : "",
 102		(status & STS_ERR) ? " ERR" : "",
 103		(status & STS_INT) ? " INT" : ""
 104		);
 105}
 106
 107static int __attribute__((__unused__))
 108dbg_intr_buf(char *buf, unsigned len, const char *label, u32 enable)
 109{
 110	return scnprintf(buf, len, "%s%sintrenable %02x%s%s%s%s%s%s",
 111		label, label[0] ? " " : "", enable,
 112		(enable & STS_IAA) ? " IAA" : "",
 113		(enable & STS_FATAL) ? " FATAL" : "",
 114		(enable & STS_FLR) ? " FLR" : "",
 115		(enable & STS_PCD) ? " PCD" : "",
 116		(enable & STS_ERR) ? " ERR" : "",
 117		(enable & STS_INT) ? " INT" : ""
 118		);
 119}
 120
 121static const char *const fls_strings[] =
 122    { "1024", "512", "256", "??" };
 123
 124static int dbg_command_buf(char *buf, unsigned len,
 125				const char *label, u32 command)
 126{
 127	return scnprintf(buf, len,
 128		"%s%scommand %06x %s=%d ithresh=%d%s%s%s%s period=%s%s %s",
 129		label, label[0] ? " " : "", command,
 130		(command & CMD_PARK) ? "park" : "(park)",
 131		CMD_PARK_CNT(command),
 132		(command >> 16) & 0x3f,
 133		(command & CMD_LRESET) ? " LReset" : "",
 134		(command & CMD_IAAD) ? " IAAD" : "",
 135		(command & CMD_ASE) ? " Async" : "",
 136		(command & CMD_PSE) ? " Periodic" : "",
 137		fls_strings[(command >> 2) & 0x3],
 138		(command & CMD_RESET) ? " Reset" : "",
 139		(command & CMD_RUN) ? "RUN" : "HALT"
 140		);
 141}
 142
 143static int dbg_port_buf(char *buf, unsigned len, const char *label,
 144				int port, u32 status)
 145{
 146	char	*sig;
 147
 148	/* signaling state */
 149	switch (status & (3 << 10)) {
 150	case 0 << 10:
 151		sig = "se0";
 152		break;
 153	case 1 << 10:
 154		sig = "k";	/* low speed */
 155		break;
 156	case 2 << 10:
 157		sig = "j";
 158		break;
 159	default:
 160		sig = "?";
 161		break;
 162	}
 163
 164	return scnprintf(buf, len,
 165		"%s%sport %d status %06x%s%s sig=%s%s%s%s%s%s%s%s%s%s",
 166		label, label[0] ? " " : "", port, status,
 167		(status & PORT_POWER) ? " POWER" : "",
 168		(status & PORT_OWNER) ? " OWNER" : "",
 169		sig,
 170		(status & PORT_RESET) ? " RESET" : "",
 171		(status & PORT_SUSPEND) ? " SUSPEND" : "",
 172		(status & PORT_RESUME) ? " RESUME" : "",
 173		(status & PORT_OCC) ? " OCC" : "",
 174		(status & PORT_OC) ? " OC" : "",
 175		(status & PORT_PEC) ? " PEC" : "",
 176		(status & PORT_PE) ? " PE" : "",
 177		(status & PORT_CSC) ? " CSC" : "",
 178		(status & PORT_CONNECT) ? " CONNECT" : ""
 179	    );
 180}
 181
 182#else
 183
 184static inline int __attribute__((__unused__))
 185dbg_status_buf(char *buf, unsigned len, const char *label, u32 status)
 186{ return 0; }
 187
 188static inline int __attribute__((__unused__))
 189dbg_command_buf(char *buf, unsigned len, const char *label, u32 command)
 190{ return 0; }
 191
 192static inline int __attribute__((__unused__))
 193dbg_intr_buf(char *buf, unsigned len, const char *label, u32 enable)
 194{ return 0; }
 195
 196static inline int __attribute__((__unused__))
 197dbg_port_buf(char *buf, unsigned len, const char *label, int port, u32 status)
 198{ return 0; }
 199
 200#endif /* DEBUG */
 201
 202/* functions have the "wrong" filename when they're output... */
 203#define dbg_status(oxu, label, status) { \
 204	char _buf[80]; \
 205	dbg_status_buf(_buf, sizeof _buf, label, status); \
 206	oxu_dbg(oxu, "%s\n", _buf); \
 207}
 208
 209#define dbg_cmd(oxu, label, command) { \
 210	char _buf[80]; \
 211	dbg_command_buf(_buf, sizeof _buf, label, command); \
 212	oxu_dbg(oxu, "%s\n", _buf); \
 213}
 214
 215#define dbg_port(oxu, label, port, status) { \
 216	char _buf[80]; \
 217	dbg_port_buf(_buf, sizeof _buf, label, port, status); \
 218	oxu_dbg(oxu, "%s\n", _buf); \
 219}
 220
 221/*
 222 * Module parameters
 223 */
 224
 225/* Initial IRQ latency: faster than hw default */
 226static int log2_irq_thresh;			/* 0 to 6 */
 227module_param(log2_irq_thresh, int, S_IRUGO);
 228MODULE_PARM_DESC(log2_irq_thresh, "log2 IRQ latency, 1-64 microframes");
 229
 230/* Initial park setting: slower than hw default */
 231static unsigned park;
 232module_param(park, uint, S_IRUGO);
 233MODULE_PARM_DESC(park, "park setting; 1-3 back-to-back async packets");
 234
 235/* For flakey hardware, ignore overcurrent indicators */
 236static int ignore_oc;
 237module_param(ignore_oc, bool, S_IRUGO);
 238MODULE_PARM_DESC(ignore_oc, "ignore bogus hardware overcurrent indications");
 239
 240
 241static void ehci_work(struct oxu_hcd *oxu);
 242static int oxu_hub_control(struct usb_hcd *hcd,
 243				u16 typeReq, u16 wValue, u16 wIndex,
 244				char *buf, u16 wLength);
 245
 246/*
 247 * Local functions
 248 */
 249
 250/* Low level read/write registers functions */
 251static inline u32 oxu_readl(void *base, u32 reg)
 252{
 253	return readl(base + reg);
 254}
 255
 256static inline void oxu_writel(void *base, u32 reg, u32 val)
 257{
 258	writel(val, base + reg);
 259}
 260
 261static inline void timer_action_done(struct oxu_hcd *oxu,
 262					enum ehci_timer_action action)
 263{
 264	clear_bit(action, &oxu->actions);
 265}
 266
 267static inline void timer_action(struct oxu_hcd *oxu,
 268					enum ehci_timer_action action)
 269{
 270	if (!test_and_set_bit(action, &oxu->actions)) {
 271		unsigned long t;
 272
 273		switch (action) {
 274		case TIMER_IAA_WATCHDOG:
 275			t = EHCI_IAA_JIFFIES;
 276			break;
 277		case TIMER_IO_WATCHDOG:
 278			t = EHCI_IO_JIFFIES;
 279			break;
 280		case TIMER_ASYNC_OFF:
 281			t = EHCI_ASYNC_JIFFIES;
 282			break;
 283		case TIMER_ASYNC_SHRINK:
 284		default:
 285			t = EHCI_SHRINK_JIFFIES;
 286			break;
 287		}
 288		t += jiffies;
 289		/* all timings except IAA watchdog can be overridden.
 290		 * async queue SHRINK often precedes IAA.  while it's ready
 291		 * to go OFF neither can matter, and afterwards the IO
 292		 * watchdog stops unless there's still periodic traffic.
 293		 */
 294		if (action != TIMER_IAA_WATCHDOG
 295				&& t > oxu->watchdog.expires
 296				&& timer_pending(&oxu->watchdog))
 297			return;
 298		mod_timer(&oxu->watchdog, t);
 299	}
 300}
 301
 302/*
 303 * handshake - spin reading hc until handshake completes or fails
 304 * @ptr: address of hc register to be read
 305 * @mask: bits to look at in result of read
 306 * @done: value of those bits when handshake succeeds
 307 * @usec: timeout in microseconds
 308 *
 309 * Returns negative errno, or zero on success
 310 *
 311 * Success happens when the "mask" bits have the specified value (hardware
 312 * handshake done).  There are two failure modes:  "usec" have passed (major
 313 * hardware flakeout), or the register reads as all-ones (hardware removed).
 314 *
 315 * That last failure should_only happen in cases like physical cardbus eject
 316 * before driver shutdown. But it also seems to be caused by bugs in cardbus
 317 * bridge shutdown:  shutting down the bridge before the devices using it.
 318 */
 319static int handshake(struct oxu_hcd *oxu, void __iomem *ptr,
 320					u32 mask, u32 done, int usec)
 321{
 322	u32 result;
 323
 324	do {
 325		result = readl(ptr);
 326		if (result == ~(u32)0)		/* card removed */
 327			return -ENODEV;
 328		result &= mask;
 329		if (result == done)
 330			return 0;
 331		udelay(1);
 332		usec--;
 333	} while (usec > 0);
 334	return -ETIMEDOUT;
 335}
 336
 337/* Force HC to halt state from unknown (EHCI spec section 2.3) */
 338static int ehci_halt(struct oxu_hcd *oxu)
 339{
 340	u32	temp = readl(&oxu->regs->status);
 341
 342	/* disable any irqs left enabled by previous code */
 343	writel(0, &oxu->regs->intr_enable);
 344
 345	if ((temp & STS_HALT) != 0)
 346		return 0;
 347
 348	temp = readl(&oxu->regs->command);
 349	temp &= ~CMD_RUN;
 350	writel(temp, &oxu->regs->command);
 351	return handshake(oxu, &oxu->regs->status,
 352			  STS_HALT, STS_HALT, 16 * 125);
 353}
 354
 355/* Put TDI/ARC silicon into EHCI mode */
 356static void tdi_reset(struct oxu_hcd *oxu)
 357{
 358	u32 __iomem *reg_ptr;
 359	u32 tmp;
 360
 361	reg_ptr = (u32 __iomem *)(((u8 __iomem *)oxu->regs) + 0x68);
 362	tmp = readl(reg_ptr);
 363	tmp |= 0x3;
 364	writel(tmp, reg_ptr);
 365}
 366
 367/* Reset a non-running (STS_HALT == 1) controller */
 368static int ehci_reset(struct oxu_hcd *oxu)
 369{
 370	int	retval;
 371	u32	command = readl(&oxu->regs->command);
 372
 373	command |= CMD_RESET;
 374	dbg_cmd(oxu, "reset", command);
 375	writel(command, &oxu->regs->command);
 376	oxu_to_hcd(oxu)->state = HC_STATE_HALT;
 377	oxu->next_statechange = jiffies;
 378	retval = handshake(oxu, &oxu->regs->command,
 379			    CMD_RESET, 0, 250 * 1000);
 380
 381	if (retval)
 382		return retval;
 383
 384	tdi_reset(oxu);
 385
 386	return retval;
 387}
 388
 389/* Idle the controller (from running) */
 390static void ehci_quiesce(struct oxu_hcd *oxu)
 391{
 392	u32	temp;
 393
 394#ifdef DEBUG
 395	if (!HC_IS_RUNNING(oxu_to_hcd(oxu)->state))
 396		BUG();
 397#endif
 398
 399	/* wait for any schedule enables/disables to take effect */
 400	temp = readl(&oxu->regs->command) << 10;
 401	temp &= STS_ASS | STS_PSS;
 402	if (handshake(oxu, &oxu->regs->status, STS_ASS | STS_PSS,
 403				temp, 16 * 125) != 0) {
 404		oxu_to_hcd(oxu)->state = HC_STATE_HALT;
 405		return;
 406	}
 407
 408	/* then disable anything that's still active */
 409	temp = readl(&oxu->regs->command);
 410	temp &= ~(CMD_ASE | CMD_IAAD | CMD_PSE);
 411	writel(temp, &oxu->regs->command);
 412
 413	/* hardware can take 16 microframes to turn off ... */
 414	if (handshake(oxu, &oxu->regs->status, STS_ASS | STS_PSS,
 415				0, 16 * 125) != 0) {
 416		oxu_to_hcd(oxu)->state = HC_STATE_HALT;
 417		return;
 418	}
 419}
 420
 421static int check_reset_complete(struct oxu_hcd *oxu, int index,
 422				u32 __iomem *status_reg, int port_status)
 423{
 424	if (!(port_status & PORT_CONNECT)) {
 425		oxu->reset_done[index] = 0;
 426		return port_status;
 427	}
 428
 429	/* if reset finished and it's still not enabled -- handoff */
 430	if (!(port_status & PORT_PE)) {
 431		oxu_dbg(oxu, "Failed to enable port %d on root hub TT\n",
 432				index+1);
 433		return port_status;
 434	} else
 435		oxu_dbg(oxu, "port %d high speed\n", index + 1);
 436
 437	return port_status;
 438}
 439
 440static void ehci_hub_descriptor(struct oxu_hcd *oxu,
 441				struct usb_hub_descriptor *desc)
 442{
 443	int ports = HCS_N_PORTS(oxu->hcs_params);
 444	u16 temp;
 445
 446	desc->bDescriptorType = 0x29;
 447	desc->bPwrOn2PwrGood = 10;	/* oxu 1.0, 2.3.9 says 20ms max */
 448	desc->bHubContrCurrent = 0;
 449
 450	desc->bNbrPorts = ports;
 451	temp = 1 + (ports / 8);
 452	desc->bDescLength = 7 + 2 * temp;
 453
 454	/* ports removable, and usb 1.0 legacy PortPwrCtrlMask */
 455	memset(&desc->u.hs.DeviceRemovable[0], 0, temp);
 456	memset(&desc->u.hs.DeviceRemovable[temp], 0xff, temp);
 457
 458	temp = 0x0008;			/* per-port overcurrent reporting */
 459	if (HCS_PPC(oxu->hcs_params))
 460		temp |= 0x0001;		/* per-port power control */
 461	else
 462		temp |= 0x0002;		/* no power switching */
 463	desc->wHubCharacteristics = (__force __u16)cpu_to_le16(temp);
 464}
 465
 466
 467/* Allocate an OXU210HP on-chip memory data buffer
 468 *
 469 * An on-chip memory data buffer is required for each OXU210HP USB transfer.
 470 * Each transfer descriptor has one or more on-chip memory data buffers.
 471 *
 472 * Data buffers are allocated from a fix sized pool of data blocks.
 473 * To minimise fragmentation and give reasonable memory utlisation,
 474 * data buffers are allocated with sizes the power of 2 multiples of
 475 * the block size, starting on an address a multiple of the allocated size.
 476 *
 477 * FIXME: callers of this function require a buffer to be allocated for
 478 * len=0. This is a waste of on-chip memory and should be fix. Then this
 479 * function should be changed to not allocate a buffer for len=0.
 480 */
 481static int oxu_buf_alloc(struct oxu_hcd *oxu, struct ehci_qtd *qtd, int len)
 482{
 483	int n_blocks;	/* minium blocks needed to hold len */
 484	int a_blocks;	/* blocks allocated */
 485	int i, j;
 486
 487	/* Don't allocte bigger than supported */
 488	if (len > BUFFER_SIZE * BUFFER_NUM) {
 489		oxu_err(oxu, "buffer too big (%d)\n", len);
 490		return -ENOMEM;
 491	}
 492
 493	spin_lock(&oxu->mem_lock);
 494
 495	/* Number of blocks needed to hold len */
 496	n_blocks = (len + BUFFER_SIZE - 1) / BUFFER_SIZE;
 497
 498	/* Round the number of blocks up to the power of 2 */
 499	for (a_blocks = 1; a_blocks < n_blocks; a_blocks <<= 1)
 500		;
 501
 502	/* Find a suitable available data buffer */
 503	for (i = 0; i < BUFFER_NUM;
 504			i += max(a_blocks, (int)oxu->db_used[i])) {
 505
 506		/* Check all the required blocks are available */
 507		for (j = 0; j < a_blocks; j++)
 508			if (oxu->db_used[i + j])
 509				break;
 510
 511		if (j != a_blocks)
 512			continue;
 513
 514		/* Allocate blocks found! */
 515		qtd->buffer = (void *) &oxu->mem->db_pool[i];
 516		qtd->buffer_dma = virt_to_phys(qtd->buffer);
 517
 518		qtd->qtd_buffer_len = BUFFER_SIZE * a_blocks;
 519		oxu->db_used[i] = a_blocks;
 520
 521		spin_unlock(&oxu->mem_lock);
 522
 523		return 0;
 524	}
 525
 526	/* Failed */
 527
 528	spin_unlock(&oxu->mem_lock);
 529
 530	return -ENOMEM;
 531}
 532
 533static void oxu_buf_free(struct oxu_hcd *oxu, struct ehci_qtd *qtd)
 534{
 535	int index;
 536
 537	spin_lock(&oxu->mem_lock);
 538
 539	index = (qtd->buffer - (void *) &oxu->mem->db_pool[0])
 540							 / BUFFER_SIZE;
 541	oxu->db_used[index] = 0;
 542	qtd->qtd_buffer_len = 0;
 543	qtd->buffer_dma = 0;
 544	qtd->buffer = NULL;
 545
 546	spin_unlock(&oxu->mem_lock);
 547}
 548
 549static inline void ehci_qtd_init(struct ehci_qtd *qtd, dma_addr_t dma)
 550{
 551	memset(qtd, 0, sizeof *qtd);
 552	qtd->qtd_dma = dma;
 553	qtd->hw_token = cpu_to_le32(QTD_STS_HALT);
 554	qtd->hw_next = EHCI_LIST_END;
 555	qtd->hw_alt_next = EHCI_LIST_END;
 556	INIT_LIST_HEAD(&qtd->qtd_list);
 557}
 558
 559static inline void oxu_qtd_free(struct oxu_hcd *oxu, struct ehci_qtd *qtd)
 560{
 561	int index;
 562
 563	if (qtd->buffer)
 564		oxu_buf_free(oxu, qtd);
 565
 566	spin_lock(&oxu->mem_lock);
 567
 568	index = qtd - &oxu->mem->qtd_pool[0];
 569	oxu->qtd_used[index] = 0;
 570
 571	spin_unlock(&oxu->mem_lock);
 572}
 573
 574static struct ehci_qtd *ehci_qtd_alloc(struct oxu_hcd *oxu)
 575{
 576	int i;
 577	struct ehci_qtd *qtd = NULL;
 578
 579	spin_lock(&oxu->mem_lock);
 580
 581	for (i = 0; i < QTD_NUM; i++)
 582		if (!oxu->qtd_used[i])
 583			break;
 584
 585	if (i < QTD_NUM) {
 586		qtd = (struct ehci_qtd *) &oxu->mem->qtd_pool[i];
 587		memset(qtd, 0, sizeof *qtd);
 588
 589		qtd->hw_token = cpu_to_le32(QTD_STS_HALT);
 590		qtd->hw_next = EHCI_LIST_END;
 591		qtd->hw_alt_next = EHCI_LIST_END;
 592		INIT_LIST_HEAD(&qtd->qtd_list);
 593
 594		qtd->qtd_dma = virt_to_phys(qtd);
 595
 596		oxu->qtd_used[i] = 1;
 597	}
 598
 599	spin_unlock(&oxu->mem_lock);
 600
 601	return qtd;
 602}
 603
 604static void oxu_qh_free(struct oxu_hcd *oxu, struct ehci_qh *qh)
 605{
 606	int index;
 607
 608	spin_lock(&oxu->mem_lock);
 609
 610	index = qh - &oxu->mem->qh_pool[0];
 611	oxu->qh_used[index] = 0;
 612
 613	spin_unlock(&oxu->mem_lock);
 614}
 615
 616static void qh_destroy(struct kref *kref)
 617{
 618	struct ehci_qh *qh = container_of(kref, struct ehci_qh, kref);
 619	struct oxu_hcd *oxu = qh->oxu;
 620
 621	/* clean qtds first, and know this is not linked */
 622	if (!list_empty(&qh->qtd_list) || qh->qh_next.ptr) {
 623		oxu_dbg(oxu, "unused qh not empty!\n");
 624		BUG();
 625	}
 626	if (qh->dummy)
 627		oxu_qtd_free(oxu, qh->dummy);
 628	oxu_qh_free(oxu, qh);
 629}
 630
 631static struct ehci_qh *oxu_qh_alloc(struct oxu_hcd *oxu)
 632{
 633	int i;
 634	struct ehci_qh *qh = NULL;
 635
 636	spin_lock(&oxu->mem_lock);
 637
 638	for (i = 0; i < QHEAD_NUM; i++)
 639		if (!oxu->qh_used[i])
 640			break;
 641
 642	if (i < QHEAD_NUM) {
 643		qh = (struct ehci_qh *) &oxu->mem->qh_pool[i];
 644		memset(qh, 0, sizeof *qh);
 645
 646		kref_init(&qh->kref);
 647		qh->oxu = oxu;
 648		qh->qh_dma = virt_to_phys(qh);
 649		INIT_LIST_HEAD(&qh->qtd_list);
 650
 651		/* dummy td enables safe urb queuing */
 652		qh->dummy = ehci_qtd_alloc(oxu);
 653		if (qh->dummy == NULL) {
 654			oxu_dbg(oxu, "no dummy td\n");
 655			oxu->qh_used[i] = 0;
 656			qh = NULL;
 657			goto unlock;
 658		}
 659
 660		oxu->qh_used[i] = 1;
 661	}
 662unlock:
 663	spin_unlock(&oxu->mem_lock);
 664
 665	return qh;
 666}
 667
 668/* to share a qh (cpu threads, or hc) */
 669static inline struct ehci_qh *qh_get(struct ehci_qh *qh)
 670{
 671	kref_get(&qh->kref);
 672	return qh;
 673}
 674
 675static inline void qh_put(struct ehci_qh *qh)
 676{
 677	kref_put(&qh->kref, qh_destroy);
 678}
 679
 680static void oxu_murb_free(struct oxu_hcd *oxu, struct oxu_murb *murb)
 681{
 682	int index;
 683
 684	spin_lock(&oxu->mem_lock);
 685
 686	index = murb - &oxu->murb_pool[0];
 687	oxu->murb_used[index] = 0;
 688
 689	spin_unlock(&oxu->mem_lock);
 690}
 691
 692static struct oxu_murb *oxu_murb_alloc(struct oxu_hcd *oxu)
 693
 694{
 695	int i;
 696	struct oxu_murb *murb = NULL;
 697
 698	spin_lock(&oxu->mem_lock);
 699
 700	for (i = 0; i < MURB_NUM; i++)
 701		if (!oxu->murb_used[i])
 702			break;
 703
 704	if (i < MURB_NUM) {
 705		murb = &(oxu->murb_pool)[i];
 706
 707		oxu->murb_used[i] = 1;
 708	}
 709
 710	spin_unlock(&oxu->mem_lock);
 711
 712	return murb;
 713}
 714
 715/* The queue heads and transfer descriptors are managed from pools tied
 716 * to each of the "per device" structures.
 717 * This is the initialisation and cleanup code.
 718 */
 719static void ehci_mem_cleanup(struct oxu_hcd *oxu)
 720{
 721	kfree(oxu->murb_pool);
 722	oxu->murb_pool = NULL;
 723
 724	if (oxu->async)
 725		qh_put(oxu->async);
 726	oxu->async = NULL;
 727
 728	del_timer(&oxu->urb_timer);
 729
 730	oxu->periodic = NULL;
 731
 732	/* shadow periodic table */
 733	kfree(oxu->pshadow);
 734	oxu->pshadow = NULL;
 735}
 736
 737/* Remember to add cleanup code (above) if you add anything here.
 738 */
 739static int ehci_mem_init(struct oxu_hcd *oxu, gfp_t flags)
 740{
 741	int i;
 742
 743	for (i = 0; i < oxu->periodic_size; i++)
 744		oxu->mem->frame_list[i] = EHCI_LIST_END;
 745	for (i = 0; i < QHEAD_NUM; i++)
 746		oxu->qh_used[i] = 0;
 747	for (i = 0; i < QTD_NUM; i++)
 748		oxu->qtd_used[i] = 0;
 749
 750	oxu->murb_pool = kcalloc(MURB_NUM, sizeof(struct oxu_murb), flags);
 751	if (!oxu->murb_pool)
 752		goto fail;
 753
 754	for (i = 0; i < MURB_NUM; i++)
 755		oxu->murb_used[i] = 0;
 756
 757	oxu->async = oxu_qh_alloc(oxu);
 758	if (!oxu->async)
 759		goto fail;
 760
 761	oxu->periodic = (__le32 *) &oxu->mem->frame_list;
 762	oxu->periodic_dma = virt_to_phys(oxu->periodic);
 763
 764	for (i = 0; i < oxu->periodic_size; i++)
 765		oxu->periodic[i] = EHCI_LIST_END;
 766
 767	/* software shadow of hardware table */
 768	oxu->pshadow = kcalloc(oxu->periodic_size, sizeof(void *), flags);
 769	if (oxu->pshadow != NULL)
 770		return 0;
 771
 772fail:
 773	oxu_dbg(oxu, "couldn't init memory\n");
 774	ehci_mem_cleanup(oxu);
 775	return -ENOMEM;
 776}
 777
 778/* Fill a qtd, returning how much of the buffer we were able to queue up.
 779 */
 780static int qtd_fill(struct ehci_qtd *qtd, dma_addr_t buf, size_t len,
 781				int token, int maxpacket)
 782{
 783	int i, count;
 784	u64 addr = buf;
 785
 786	/* one buffer entry per 4K ... first might be short or unaligned */
 787	qtd->hw_buf[0] = cpu_to_le32((u32)addr);
 788	qtd->hw_buf_hi[0] = cpu_to_le32((u32)(addr >> 32));
 789	count = 0x1000 - (buf & 0x0fff);	/* rest of that page */
 790	if (likely(len < count))		/* ... iff needed */
 791		count = len;
 792	else {
 793		buf +=  0x1000;
 794		buf &= ~0x0fff;
 795
 796		/* per-qtd limit: from 16K to 20K (best alignment) */
 797		for (i = 1; count < len && i < 5; i++) {
 798			addr = buf;
 799			qtd->hw_buf[i] = cpu_to_le32((u32)addr);
 800			qtd->hw_buf_hi[i] = cpu_to_le32((u32)(addr >> 32));
 801			buf += 0x1000;
 802			if ((count + 0x1000) < len)
 803				count += 0x1000;
 804			else
 805				count = len;
 806		}
 807
 808		/* short packets may only terminate transfers */
 809		if (count != len)
 810			count -= (count % maxpacket);
 811	}
 812	qtd->hw_token = cpu_to_le32((count << 16) | token);
 813	qtd->length = count;
 814
 815	return count;
 816}
 817
 818static inline void qh_update(struct oxu_hcd *oxu,
 819				struct ehci_qh *qh, struct ehci_qtd *qtd)
 820{
 821	/* writes to an active overlay are unsafe */
 822	BUG_ON(qh->qh_state != QH_STATE_IDLE);
 823
 824	qh->hw_qtd_next = QTD_NEXT(qtd->qtd_dma);
 825	qh->hw_alt_next = EHCI_LIST_END;
 826
 827	/* Except for control endpoints, we make hardware maintain data
 828	 * toggle (like OHCI) ... here (re)initialize the toggle in the QH,
 829	 * and set the pseudo-toggle in udev. Only usb_clear_halt() will
 830	 * ever clear it.
 831	 */
 832	if (!(qh->hw_info1 & cpu_to_le32(1 << 14))) {
 833		unsigned	is_out, epnum;
 834
 835		is_out = !(qtd->hw_token & cpu_to_le32(1 << 8));
 836		epnum = (le32_to_cpup(&qh->hw_info1) >> 8) & 0x0f;
 837		if (unlikely(!usb_gettoggle(qh->dev, epnum, is_out))) {
 838			qh->hw_token &= ~cpu_to_le32(QTD_TOGGLE);
 839			usb_settoggle(qh->dev, epnum, is_out, 1);
 840		}
 841	}
 842
 843	/* HC must see latest qtd and qh data before we clear ACTIVE+HALT */
 844	wmb();
 845	qh->hw_token &= cpu_to_le32(QTD_TOGGLE | QTD_STS_PING);
 846}
 847
 848/* If it weren't for a common silicon quirk (writing the dummy into the qh
 849 * overlay, so qh->hw_token wrongly becomes inactive/halted), only fault
 850 * recovery (including urb dequeue) would need software changes to a QH...
 851 */
 852static void qh_refresh(struct oxu_hcd *oxu, struct ehci_qh *qh)
 853{
 854	struct ehci_qtd *qtd;
 855
 856	if (list_empty(&qh->qtd_list))
 857		qtd = qh->dummy;
 858	else {
 859		qtd = list_entry(qh->qtd_list.next,
 860				struct ehci_qtd, qtd_list);
 861		/* first qtd may already be partially processed */
 862		if (cpu_to_le32(qtd->qtd_dma) == qh->hw_current)
 863			qtd = NULL;
 864	}
 865
 866	if (qtd)
 867		qh_update(oxu, qh, qtd);
 868}
 869
 870static void qtd_copy_status(struct oxu_hcd *oxu, struct urb *urb,
 871				size_t length, u32 token)
 872{
 873	/* count IN/OUT bytes, not SETUP (even short packets) */
 874	if (likely(QTD_PID(token) != 2))
 875		urb->actual_length += length - QTD_LENGTH(token);
 876
 877	/* don't modify error codes */
 878	if (unlikely(urb->status != -EINPROGRESS))
 879		return;
 880
 881	/* force cleanup after short read; not always an error */
 882	if (unlikely(IS_SHORT_READ(token)))
 883		urb->status = -EREMOTEIO;
 884
 885	/* serious "can't proceed" faults reported by the hardware */
 886	if (token & QTD_STS_HALT) {
 887		if (token & QTD_STS_BABBLE) {
 888			/* FIXME "must" disable babbling device's port too */
 889			urb->status = -EOVERFLOW;
 890		} else if (token & QTD_STS_MMF) {
 891			/* fs/ls interrupt xfer missed the complete-split */
 892			urb->status = -EPROTO;
 893		} else if (token & QTD_STS_DBE) {
 894			urb->status = (QTD_PID(token) == 1) /* IN ? */
 895				? -ENOSR  /* hc couldn't read data */
 896				: -ECOMM; /* hc couldn't write data */
 897		} else if (token & QTD_STS_XACT) {
 898			/* timeout, bad crc, wrong PID, etc; retried */
 899			if (QTD_CERR(token))
 900				urb->status = -EPIPE;
 901			else {
 902				oxu_dbg(oxu, "devpath %s ep%d%s 3strikes\n",
 903					urb->dev->devpath,
 904					usb_pipeendpoint(urb->pipe),
 905					usb_pipein(urb->pipe) ? "in" : "out");
 906				urb->status = -EPROTO;
 907			}
 908		/* CERR nonzero + no errors + halt --> stall */
 909		} else if (QTD_CERR(token))
 910			urb->status = -EPIPE;
 911		else	/* unknown */
 912			urb->status = -EPROTO;
 913
 914		oxu_vdbg(oxu, "dev%d ep%d%s qtd token %08x --> status %d\n",
 915			usb_pipedevice(urb->pipe),
 916			usb_pipeendpoint(urb->pipe),
 917			usb_pipein(urb->pipe) ? "in" : "out",
 918			token, urb->status);
 919	}
 920}
 921
 922static void ehci_urb_done(struct oxu_hcd *oxu, struct urb *urb)
 923__releases(oxu->lock)
 924__acquires(oxu->lock)
 925{
 926	if (likely(urb->hcpriv != NULL)) {
 927		struct ehci_qh	*qh = (struct ehci_qh *) urb->hcpriv;
 928
 929		/* S-mask in a QH means it's an interrupt urb */
 930		if ((qh->hw_info2 & cpu_to_le32(QH_SMASK)) != 0) {
 931
 932			/* ... update hc-wide periodic stats (for usbfs) */
 933			oxu_to_hcd(oxu)->self.bandwidth_int_reqs--;
 934		}
 935		qh_put(qh);
 936	}
 937
 938	urb->hcpriv = NULL;
 939	switch (urb->status) {
 940	case -EINPROGRESS:		/* success */
 941		urb->status = 0;
 942	default:			/* fault */
 943		break;
 944	case -EREMOTEIO:		/* fault or normal */
 945		if (!(urb->transfer_flags & URB_SHORT_NOT_OK))
 946			urb->status = 0;
 947		break;
 948	case -ECONNRESET:		/* canceled */
 949	case -ENOENT:
 950		break;
 951	}
 952
 953#ifdef OXU_URB_TRACE
 954	oxu_dbg(oxu, "%s %s urb %p ep%d%s status %d len %d/%d\n",
 955		__func__, urb->dev->devpath, urb,
 956		usb_pipeendpoint(urb->pipe),
 957		usb_pipein(urb->pipe) ? "in" : "out",
 958		urb->status,
 959		urb->actual_length, urb->transfer_buffer_length);
 960#endif
 961
 962	/* complete() can reenter this HCD */
 963	spin_unlock(&oxu->lock);
 964	usb_hcd_giveback_urb(oxu_to_hcd(oxu), urb, urb->status);
 965	spin_lock(&oxu->lock);
 966}
 967
 968static void start_unlink_async(struct oxu_hcd *oxu, struct ehci_qh *qh);
 969static void unlink_async(struct oxu_hcd *oxu, struct ehci_qh *qh);
 970
 971static void intr_deschedule(struct oxu_hcd *oxu, struct ehci_qh *qh);
 972static int qh_schedule(struct oxu_hcd *oxu, struct ehci_qh *qh);
 973
 974#define HALT_BIT cpu_to_le32(QTD_STS_HALT)
 975
 976/* Process and free completed qtds for a qh, returning URBs to drivers.
 977 * Chases up to qh->hw_current.  Returns number of completions called,
 978 * indicating how much "real" work we did.
 979 */
 980static unsigned qh_completions(struct oxu_hcd *oxu, struct ehci_qh *qh)
 981{
 982	struct ehci_qtd *last = NULL, *end = qh->dummy;
 983	struct list_head *entry, *tmp;
 984	int stopped;
 985	unsigned count = 0;
 986	int do_status = 0;
 987	u8 state;
 988	struct oxu_murb *murb = NULL;
 989
 990	if (unlikely(list_empty(&qh->qtd_list)))
 991		return count;
 992
 993	/* completions (or tasks on other cpus) must never clobber HALT
 994	 * till we've gone through and cleaned everything up, even when
 995	 * they add urbs to this qh's queue or mark them for unlinking.
 996	 *
 997	 * NOTE:  unlinking expects to be done in queue order.
 998	 */
 999	state = qh->qh_state;
1000	qh->qh_state = QH_STATE_COMPLETING;
1001	stopped = (state == QH_STATE_IDLE);
1002
1003	/* remove de-activated QTDs from front of queue.
1004	 * after faults (including short reads), cleanup this urb
1005	 * then let the queue advance.
1006	 * if queue is stopped, handles unlinks.
1007	 */
1008	list_for_each_safe(entry, tmp, &qh->qtd_list) {
1009		struct ehci_qtd	*qtd;
1010		struct urb *urb;
1011		u32 token = 0;
1012
1013		qtd = list_entry(entry, struct ehci_qtd, qtd_list);
1014		urb = qtd->urb;
1015
1016		/* Clean up any state from previous QTD ...*/
1017		if (last) {
1018			if (likely(last->urb != urb)) {
1019				if (last->urb->complete == NULL) {
1020					murb = (struct oxu_murb *) last->urb;
1021					last->urb = murb->main;
1022					if (murb->last) {
1023						ehci_urb_done(oxu, last->urb);
1024						count++;
1025					}
1026					oxu_murb_free(oxu, murb);
1027				} else {
1028					ehci_urb_done(oxu, last->urb);
1029					count++;
1030				}
1031			}
1032			oxu_qtd_free(oxu, last);
1033			last = NULL;
1034		}
1035
1036		/* ignore urbs submitted during completions we reported */
1037		if (qtd == end)
1038			break;
1039
1040		/* hardware copies qtd out of qh overlay */
1041		rmb();
1042		token = le32_to_cpu(qtd->hw_token);
1043
1044		/* always clean up qtds the hc de-activated */
1045		if ((token & QTD_STS_ACTIVE) == 0) {
1046
1047			if ((token & QTD_STS_HALT) != 0) {
1048				stopped = 1;
1049
1050			/* magic dummy for some short reads; qh won't advance.
1051			 * that silicon quirk can kick in with this dummy too.
1052			 */
1053			} else if (IS_SHORT_READ(token) &&
1054					!(qtd->hw_alt_next & EHCI_LIST_END)) {
1055				stopped = 1;
1056				goto halt;
1057			}
1058
1059		/* stop scanning when we reach qtds the hc is using */
1060		} else if (likely(!stopped &&
1061				HC_IS_RUNNING(oxu_to_hcd(oxu)->state))) {
1062			break;
1063
1064		} else {
1065			stopped = 1;
1066
1067			if (unlikely(!HC_IS_RUNNING(oxu_to_hcd(oxu)->state)))
1068				urb->status = -ESHUTDOWN;
1069
1070			/* ignore active urbs unless some previous qtd
1071			 * for the urb faulted (including short read) or
1072			 * its urb was canceled.  we may patch qh or qtds.
1073			 */
1074			if (likely(urb->status == -EINPROGRESS))
1075				continue;
1076
1077			/* issue status after short control reads */
1078			if (unlikely(do_status != 0)
1079					&& QTD_PID(token) == 0 /* OUT */) {
1080				do_status = 0;
1081				continue;
1082			}
1083
1084			/* token in overlay may be most current */
1085			if (state == QH_STATE_IDLE
1086					&& cpu_to_le32(qtd->qtd_dma)
1087						== qh->hw_current)
1088				token = le32_to_cpu(qh->hw_token);
1089
1090			/* force halt for unlinked or blocked qh, so we'll
1091			 * patch the qh later and so that completions can't
1092			 * activate it while we "know" it's stopped.
1093			 */
1094			if ((HALT_BIT & qh->hw_token) == 0) {
1095halt:
1096				qh->hw_token |= HALT_BIT;
1097				wmb();
1098			}
1099		}
1100
1101		/* Remove it from the queue */
1102		qtd_copy_status(oxu, urb->complete ?
1103					urb : ((struct oxu_murb *) urb)->main,
1104				qtd->length, token);
1105		if ((usb_pipein(qtd->urb->pipe)) &&
1106				(NULL != qtd->transfer_buffer))
1107			memcpy(qtd->transfer_buffer, qtd->buffer, qtd->length);
1108		do_status = (urb->status == -EREMOTEIO)
1109				&& usb_pipecontrol(urb->pipe);
1110
1111		if (stopped && qtd->qtd_list.prev != &qh->qtd_list) {
1112			last = list_entry(qtd->qtd_list.prev,
1113					struct ehci_qtd, qtd_list);
1114			last->hw_next = qtd->hw_next;
1115		}
1116		list_del(&qtd->qtd_list);
1117		last = qtd;
1118	}
1119
1120	/* last urb's completion might still need calling */
1121	if (likely(last != NULL)) {
1122		if (last->urb->complete == NULL) {
1123			murb = (struct oxu_murb *) last->urb;
1124			last->urb = murb->main;
1125			if (murb->last) {
1126				ehci_urb_done(oxu, last->urb);
1127				count++;
1128			}
1129			oxu_murb_free(oxu, murb);
1130		} else {
1131			ehci_urb_done(oxu, last->urb);
1132			count++;
1133		}
1134		oxu_qtd_free(oxu, last);
1135	}
1136
1137	/* restore original state; caller must unlink or relink */
1138	qh->qh_state = state;
1139
1140	/* be sure the hardware's done with the qh before refreshing
1141	 * it after fault cleanup, or recovering from silicon wrongly
1142	 * overlaying the dummy qtd (which reduces DMA chatter).
1143	 */
1144	if (stopped != 0 || qh->hw_qtd_next == EHCI_LIST_END) {
1145		switch (state) {
1146		case QH_STATE_IDLE:
1147			qh_refresh(oxu, qh);
1148			break;
1149		case QH_STATE_LINKED:
1150			/* should be rare for periodic transfers,
1151			 * except maybe high bandwidth ...
1152			 */
1153			if ((cpu_to_le32(QH_SMASK)
1154					& qh->hw_info2) != 0) {
1155				intr_deschedule(oxu, qh);
1156				(void) qh_schedule(oxu, qh);
1157			} else
1158				unlink_async(oxu, qh);
1159			break;
1160		/* otherwise, unlink already started */
1161		}
1162	}
1163
1164	return count;
1165}
1166
1167/* High bandwidth multiplier, as encoded in highspeed endpoint descriptors */
1168#define hb_mult(wMaxPacketSize)		(1 + (((wMaxPacketSize) >> 11) & 0x03))
1169/* ... and packet size, for any kind of endpoint descriptor */
1170#define max_packet(wMaxPacketSize)	((wMaxPacketSize) & 0x07ff)
1171
1172/* Reverse of qh_urb_transaction: free a list of TDs.
1173 * used for cleanup after errors, before HC sees an URB's TDs.
1174 */
1175static void qtd_list_free(struct oxu_hcd *oxu,
1176				struct urb *urb, struct list_head *qtd_list)
1177{
1178	struct list_head *entry, *temp;
1179
1180	list_for_each_safe(entry, temp, qtd_list) {
1181		struct ehci_qtd	*qtd;
1182
1183		qtd = list_entry(entry, struct ehci_qtd, qtd_list);
1184		list_del(&qtd->qtd_list);
1185		oxu_qtd_free(oxu, qtd);
1186	}
1187}
1188
1189/* Create a list of filled qtds for this URB; won't link into qh.
1190 */
1191static struct list_head *qh_urb_transaction(struct oxu_hcd *oxu,
1192						struct urb *urb,
1193						struct list_head *head,
1194						gfp_t flags)
1195{
1196	struct ehci_qtd	*qtd, *qtd_prev;
1197	dma_addr_t buf;
1198	int len, maxpacket;
1199	int is_input;
1200	u32 token;
1201	void *transfer_buf = NULL;
1202	int ret;
1203
1204	/*
1205	 * URBs map to sequences of QTDs: one logical transaction
1206	 */
1207	qtd = ehci_qtd_alloc(oxu);
1208	if (unlikely(!qtd))
1209		return NULL;
1210	list_add_tail(&qtd->qtd_list, head);
1211	qtd->urb = urb;
1212
1213	token = QTD_STS_ACTIVE;
1214	token |= (EHCI_TUNE_CERR << 10);
1215	/* for split transactions, SplitXState initialized to zero */
1216
1217	len = urb->transfer_buffer_length;
1218	is_input = usb_pipein(urb->pipe);
1219	if (!urb->transfer_buffer && urb->transfer_buffer_length && is_input)
1220		urb->transfer_buffer = phys_to_virt(urb->transfer_dma);
1221
1222	if (usb_pipecontrol(urb->pipe)) {
1223		/* SETUP pid */
1224		ret = oxu_buf_alloc(oxu, qtd, sizeof(struct usb_ctrlrequest));
1225		if (ret)
1226			goto cleanup;
1227
1228		qtd_fill(qtd, qtd->buffer_dma, sizeof(struct usb_ctrlrequest),
1229				token | (2 /* "setup" */ << 8), 8);
1230		memcpy(qtd->buffer, qtd->urb->setup_packet,
1231				sizeof(struct usb_ctrlrequest));
1232
1233		/* ... and always at least one more pid */
1234		token ^= QTD_TOGGLE;
1235		qtd_prev = qtd;
1236		qtd = ehci_qtd_alloc(oxu);
1237		if (unlikely(!qtd))
1238			goto cleanup;
1239		qtd->urb = urb;
1240		qtd_prev->hw_next = QTD_NEXT(qtd->qtd_dma);
1241		list_add_tail(&qtd->qtd_list, head);
1242
1243		/* for zero length DATA stages, STATUS is always IN */
1244		if (len == 0)
1245			token |= (1 /* "in" */ << 8);
1246	}
1247
1248	/*
1249	 * Data transfer stage: buffer setup
1250	 */
1251
1252	ret = oxu_buf_alloc(oxu, qtd, len);
1253	if (ret)
1254		goto cleanup;
1255
1256	buf = qtd->buffer_dma;
1257	transfer_buf = urb->transfer_buffer;
1258
1259	if (!is_input)
1260		memcpy(qtd->buffer, qtd->urb->transfer_buffer, len);
1261
1262	if (is_input)
1263		token |= (1 /* "in" */ << 8);
1264	/* else it's already initted to "out" pid (0 << 8) */
1265
1266	maxpacket = max_packet(usb_maxpacket(urb->dev, urb->pipe, !is_input));
1267
1268	/*
1269	 * buffer gets wrapped in one or more qtds;
1270	 * last one may be "short" (including zero len)
1271	 * and may serve as a control status ack
1272	 */
1273	for (;;) {
1274		int this_qtd_len;
1275
1276		this_qtd_len = qtd_fill(qtd, buf, len, token, maxpacket);
1277		qtd->transfer_buffer = transfer_buf;
1278		len -= this_qtd_len;
1279		buf += this_qtd_len;
1280		transfer_buf += this_qtd_len;
1281		if (is_input)
1282			qtd->hw_alt_next = oxu->async->hw_alt_next;
1283
1284		/* qh makes control packets use qtd toggle; maybe switch it */
1285		if ((maxpacket & (this_qtd_len + (maxpacket - 1))) == 0)
1286			token ^= QTD_TOGGLE;
1287
1288		if (likely(len <= 0))
1289			break;
1290
1291		qtd_prev = qtd;
1292		qtd = ehci_qtd_alloc(oxu);
1293		if (unlikely(!qtd))
1294			goto cleanup;
1295		if (likely(len > 0)) {
1296			ret = oxu_buf_alloc(oxu, qtd, len);
1297			if (ret)
1298				goto cleanup;
1299		}
1300		qtd->urb = urb;
1301		qtd_prev->hw_next = QTD_NEXT(qtd->qtd_dma);
1302		list_add_tail(&qtd->qtd_list, head);
1303	}
1304
1305	/* unless the bulk/interrupt caller wants a chance to clean
1306	 * up after short reads, hc should advance qh past this urb
1307	 */
1308	if (likely((urb->transfer_flags & URB_SHORT_NOT_OK) == 0
1309				|| usb_pipecontrol(urb->pipe)))
1310		qtd->hw_alt_next = EHCI_LIST_END;
1311
1312	/*
1313	 * control requests may need a terminating data "status" ack;
1314	 * bulk ones may need a terminating short packet (zero length).
1315	 */
1316	if (likely(urb->transfer_buffer_length != 0)) {
1317		int	one_more = 0;
1318
1319		if (usb_pipecontrol(urb->pipe)) {
1320			one_more = 1;
1321			token ^= 0x0100;	/* "in" <--> "out"  */
1322			token |= QTD_TOGGLE;	/* force DATA1 */
1323		} else if (usb_pipebulk(urb->pipe)
1324				&& (urb->transfer_flags & URB_ZERO_PACKET)
1325				&& !(urb->transfer_buffer_length % maxpacket)) {
1326			one_more = 1;
1327		}
1328		if (one_more) {
1329			qtd_prev = qtd;
1330			qtd = ehci_qtd_alloc(oxu);
1331			if (unlikely(!qtd))
1332				goto cleanup;
1333			qtd->urb = urb;
1334			qtd_prev->hw_next = QTD_NEXT(qtd->qtd_dma);
1335			list_add_tail(&qtd->qtd_list, head);
1336
1337			/* never any data in such packets */
1338			qtd_fill(qtd, 0, 0, token, 0);
1339		}
1340	}
1341
1342	/* by default, enable interrupt on urb completion */
1343		qtd->hw_token |= cpu_to_le32(QTD_IOC);
1344	return head;
1345
1346cleanup:
1347	qtd_list_free(oxu, urb, head);
1348	return NULL;
1349}
1350
1351/* Each QH holds a qtd list; a QH is used for everything except iso.
1352 *
1353 * For interrupt urbs, the scheduler must set the microframe scheduling
1354 * mask(s) each time the QH gets scheduled.  For highspeed, that's
1355 * just one microframe in the s-mask.  For split interrupt transactions
1356 * there are additional complications: c-mask, maybe FSTNs.
1357 */
1358static struct ehci_qh *qh_make(struct oxu_hcd *oxu,
1359				struct urb *urb, gfp_t flags)
1360{
1361	struct ehci_qh *qh = oxu_qh_alloc(oxu);
1362	u32 info1 = 0, info2 = 0;
1363	int is_input, type;
1364	int maxp = 0;
1365
1366	if (!qh)
1367		return qh;
1368
1369	/*
1370	 * init endpoint/device data for this QH
1371	 */
1372	info1 |= usb_pipeendpoint(urb->pipe) << 8;
1373	info1 |= usb_pipedevice(urb->pipe) << 0;
1374
1375	is_input = usb_pipein(urb->pipe);
1376	type = usb_pipetype(urb->pipe);
1377	maxp = usb_maxpacket(urb->dev, urb->pipe, !is_input);
1378
1379	/* Compute interrupt scheduling parameters just once, and save.
1380	 * - allowing for high bandwidth, how many nsec/uframe are used?
1381	 * - split transactions need a second CSPLIT uframe; same question
1382	 * - splits also need a schedule gap (for full/low speed I/O)
1383	 * - qh has a polling interval
1384	 *
1385	 * For control/bulk requests, the HC or TT handles these.
1386	 */
1387	if (type == PIPE_INTERRUPT) {
1388		qh->usecs = NS_TO_US(usb_calc_bus_time(USB_SPEED_HIGH,
1389								is_input, 0,
1390				hb_mult(maxp) * max_packet(maxp)));
1391		qh->start = NO_FRAME;
1392
1393		if (urb->dev->speed == USB_SPEED_HIGH) {
1394			qh->c_usecs = 0;
1395			qh->gap_uf = 0;
1396
1397			qh->period = urb->interval >> 3;
1398			if (qh->period == 0 && urb->interval != 1) {
1399				/* NOTE interval 2 or 4 uframes could work.
1400				 * But interval 1 scheduling is simpler, and
1401				 * includes high bandwidth.
1402				 */
1403				dbg("intr period %d uframes, NYET!",
1404						urb->interval);
1405				goto done;
1406			}
1407		} else {
1408			struct usb_tt	*tt = urb->dev->tt;
1409			int		think_time;
1410
1411			/* gap is f(FS/LS transfer times) */
1412			qh->gap_uf = 1 + usb_calc_bus_time(urb->dev->speed,
1413					is_input, 0, maxp) / (125 * 1000);
1414
1415			/* FIXME this just approximates SPLIT/CSPLIT times */
1416			if (is_input) {		/* SPLIT, gap, CSPLIT+DATA */
1417				qh->c_usecs = qh->usecs + HS_USECS(0);
1418				qh->usecs = HS_USECS(1);
1419			} else {		/* SPLIT+DATA, gap, CSPLIT */
1420				qh->usecs += HS_USECS(1);
1421				qh->c_usecs = HS_USECS(0);
1422			}
1423
1424			think_time = tt ? tt->think_time : 0;
1425			qh->tt_usecs = NS_TO_US(think_time +
1426					usb_calc_bus_time(urb->dev->speed,
1427					is_input, 0, max_packet(maxp)));
1428			qh->period = urb->interval;
1429		}
1430	}
1431
1432	/* support for tt scheduling, and access to toggles */
1433	qh->dev = urb->dev;
1434
1435	/* using TT? */
1436	switch (urb->dev->speed) {
1437	case USB_SPEED_LOW:
1438		info1 |= (1 << 12);	/* EPS "low" */
1439		/* FALL THROUGH */
1440
1441	case USB_SPEED_FULL:
1442		/* EPS 0 means "full" */
1443		if (type != PIPE_INTERRUPT)
1444			info1 |= (EHCI_TUNE_RL_TT << 28);
1445		if (type == PIPE_CONTROL) {
1446			info1 |= (1 << 27);	/* for TT */
1447			info1 |= 1 << 14;	/* toggle from qtd */
1448		}
1449		info1 |= maxp << 16;
1450
1451		info2 |= (EHCI_TUNE_MULT_TT << 30);
1452		info2 |= urb->dev->ttport << 23;
1453
1454		/* NOTE:  if (PIPE_INTERRUPT) { scheduler sets c-mask } */
1455
1456		break;
1457
1458	case USB_SPEED_HIGH:		/* no TT involved */
1459		info1 |= (2 << 12);	/* EPS "high" */
1460		if (type == PIPE_CONTROL) {
1461			info1 |= (EHCI_TUNE_RL_HS << 28);
1462			info1 |= 64 << 16;	/* usb2 fixed maxpacket */
1463			info1 |= 1 << 14;	/* toggle from qtd */
1464			info2 |= (EHCI_TUNE_MULT_HS << 30);
1465		} else if (type == PIPE_BULK) {
1466			info1 |= (EHCI_TUNE_RL_HS << 28);
1467			info1 |= 512 << 16;	/* usb2 fixed maxpacket */
1468			info2 |= (EHCI_TUNE_MULT_HS << 30);
1469		} else {		/* PIPE_INTERRUPT */
1470			info1 |= max_packet(maxp) << 16;
1471			info2 |= hb_mult(maxp) << 30;
1472		}
1473		break;
1474	default:
1475		dbg("bogus dev %p speed %d", urb->dev, urb->dev->speed);
1476done:
1477		qh_put(qh);
1478		return NULL;
1479	}
1480
1481	/* NOTE:  if (PIPE_INTERRUPT) { scheduler sets s-mask } */
1482
1483	/* init as live, toggle clear, advance to dummy */
1484	qh->qh_state = QH_STATE_IDLE;
1485	qh->hw_info1 = cpu_to_le32(info1);
1486	qh->hw_info2 = cpu_to_le32(info2);
1487	usb_settoggle(urb->dev, usb_pipeendpoint(urb->pipe), !is_input, 1);
1488	qh_refresh(oxu, qh);
1489	return qh;
1490}
1491
1492/* Move qh (and its qtds) onto async queue; maybe enable queue.
1493 */
1494static void qh_link_async(struct oxu_hcd *oxu, struct ehci_qh *qh)
1495{
1496	__le32 dma = QH_NEXT(qh->qh_dma);
1497	struct ehci_qh *head;
1498
1499	/* (re)start the async schedule? */
1500	head = oxu->async;
1501	timer_action_done(oxu, TIMER_ASYNC_OFF);
1502	if (!head->qh_next.qh) {
1503		u32	cmd = readl(&oxu->regs->command);
1504
1505		if (!(cmd & CMD_ASE)) {
1506			/* in case a clear of CMD_ASE didn't take yet */
1507			(void)handshake(oxu, &oxu->regs->status,
1508					STS_ASS, 0, 150);
1509			cmd |= CMD_ASE | CMD_RUN;
1510			writel(cmd, &oxu->regs->command);
1511			oxu_to_hcd(oxu)->state = HC_STATE_RUNNING;
1512			/* posted write need not be known to HC yet ... */
1513		}
1514	}
1515
1516	/* clear halt and/or toggle; and maybe recover from silicon quirk */
1517	if (qh->qh_state == QH_STATE_IDLE)
1518		qh_refresh(oxu, qh);
1519
1520	/* splice right after start */
1521	qh->qh_next = head->qh_next;
1522	qh->hw_next = head->hw_next;
1523	wmb();
1524
1525	head->qh_next.qh = qh;
1526	head->hw_next = dma;
1527
1528	qh->qh_state = QH_STATE_LINKED;
1529	/* qtd completions reported later by interrupt */
1530}
1531
1532#define	QH_ADDR_MASK	cpu_to_le32(0x7f)
1533
1534/*
1535 * For control/bulk/interrupt, return QH with these TDs appended.
1536 * Allocates and initializes the QH if necessary.
1537 * Returns null if it can't allocate a QH it needs to.
1538 * If the QH has TDs (urbs) already, that's great.
1539 */
1540static struct ehci_qh *qh_append_tds(struct oxu_hcd *oxu,
1541				struct urb *urb, struct list_head *qtd_list,
1542				int epnum, void	**ptr)
1543{
1544	struct ehci_qh *qh = NULL;
1545
1546	qh = (struct ehci_qh *) *ptr;
1547	if (unlikely(qh == NULL)) {
1548		/* can't sleep here, we have oxu->lock... */
1549		qh = qh_make(oxu, urb, GFP_ATOMIC);
1550		*ptr = qh;
1551	}
1552	if (likely(qh != NULL)) {
1553		struct ehci_qtd	*qtd;
1554
1555		if (unlikely(list_empty(qtd_list)))
1556			qtd = NULL;
1557		else
1558			qtd = list_entry(qtd_list->next, struct ehci_qtd,
1559					qtd_list);
1560
1561		/* control qh may need patching ... */
1562		if (unlikely(epnum == 0)) {
1563
1564			/* usb_reset_device() briefly reverts to address 0 */
1565			if (usb_pipedevice(urb->pipe) == 0)
1566				qh->hw_info1 &= ~QH_ADDR_MASK;
1567		}
1568
1569		/* just one way to queue requests: swap with the dummy qtd.
1570		 * only hc or qh_refresh() ever modify the overlay.
1571		 */
1572		if (likely(qtd != NULL)) {
1573			struct ehci_qtd	*dummy;
1574			dma_addr_t dma;
1575			__le32 token;
1576
1577			/* to avoid racing the HC, use the dummy td instead of
1578			 * the first td of our list (becomes new dummy).  both
1579			 * tds stay deactivated until we're done, when the
1580			 * HC is allowed to fetch the old dummy (4.10.2).
1581			 */
1582			token = qtd->hw_token;
1583			qtd->hw_token = HALT_BIT;
1584			wmb();
1585			dummy = qh->dummy;
1586
1587			dma = dummy->qtd_dma;
1588			*dummy = *qtd;
1589			dummy->qtd_dma = dma;
1590
1591			list_del(&qtd->qtd_list);
1592			list_add(&dummy->qtd_list, qtd_list);
1593			list_splice(qtd_list, qh->qtd_list.prev);
1594
1595			ehci_qtd_init(qtd, qtd->qtd_dma);
1596			qh->dummy = qtd;
1597
1598			/* hc must see the new dummy at list end */
1599			dma = qtd->qtd_dma;
1600			qtd = list_entry(qh->qtd_list.prev,
1601					struct ehci_qtd, qtd_list);
1602			qtd->hw_next = QTD_NEXT(dma);
1603
1604			/* let the hc process these next qtds */
1605			dummy->hw_token = (token & ~(0x80));
1606			wmb();
1607			dummy->hw_token = token;
1608
1609			urb->hcpriv = qh_get(qh);
1610		}
1611	}
1612	return qh;
1613}
1614
1615static int submit_async(struct oxu_hcd	*oxu, struct urb *urb,
1616			struct list_head *qtd_list, gfp_t mem_flags)
1617{
1618	struct ehci_qtd	*qtd;
1619	int epnum;
1620	unsigned long flags;
1621	struct ehci_qh *qh = NULL;
1622	int rc = 0;
1623
1624	qtd = list_entry(qtd_list->next, struct ehci_qtd, qtd_list);
1625	epnum = urb->ep->desc.bEndpointAddress;
1626
1627#ifdef OXU_URB_TRACE
1628	oxu_dbg(oxu, "%s %s urb %p ep%d%s len %d, qtd %p [qh %p]\n",
1629		__func__, urb->dev->devpath, urb,
1630		epnum & 0x0f, (epnum & USB_DIR_IN) ? "in" : "out",
1631		urb->transfer_buffer_length,
1632		qtd, urb->ep->hcpriv);
1633#endif
1634
1635	spin_lock_irqsave(&oxu->lock, flags);
1636	if (unlikely(!HCD_HW_ACCESSIBLE(oxu_to_hcd(oxu)))) {
1637		rc = -ESHUTDOWN;
1638		goto done;
1639	}
1640
1641	qh = qh_append_tds(oxu, urb, qtd_list, epnum, &urb->ep->hcpriv);
1642	if (unlikely(qh == NULL)) {
1643		rc = -ENOMEM;
1644		goto done;
1645	}
1646
1647	/* Control/bulk operations through TTs don't need scheduling,
1648	 * the HC and TT handle it when the TT has a buffer ready.
1649	 */
1650	if (likely(qh->qh_state == QH_STATE_IDLE))
1651		qh_link_async(oxu, qh_get(qh));
1652done:
1653	spin_unlock_irqrestore(&oxu->lock, flags);
1654	if (unlikely(qh == NULL))
1655		qtd_list_free(oxu, urb, qtd_list);
1656	return rc;
1657}
1658
1659/* The async qh for the qtds being reclaimed are now unlinked from the HC */
1660
1661static void end_unlink_async(struct oxu_hcd *oxu)
1662{
1663	struct ehci_qh *qh = oxu->reclaim;
1664	struct ehci_qh *next;
1665
1666	timer_action_done(oxu, TIMER_IAA_WATCHDOG);
1667
1668	qh->qh_state = QH_STATE_IDLE;
1669	qh->qh_next.qh = NULL;
1670	qh_put(qh);			/* refcount from reclaim */
1671
1672	/* other unlink(s) may be pending (in QH_STATE_UNLINK_WAIT) */
1673	next = qh->reclaim;
1674	oxu->reclaim = next;
1675	oxu->reclaim_ready = 0;
1676	qh->reclaim = NULL;
1677
1678	qh_completions(oxu, qh);
1679
1680	if (!list_empty(&qh->qtd_list)
1681			&& HC_IS_RUNNING(oxu_to_hcd(oxu)->state))
1682		qh_link_async(oxu, qh);
1683	else {
1684		qh_put(qh);		/* refcount from async list */
1685
1686		/* it's not free to turn the async schedule on/off; leave it
1687		 * active but idle for a while once it empties.
1688		 */
1689		if (HC_IS_RUNNING(oxu_to_hcd(oxu)->state)
1690				&& oxu->async->qh_next.qh == NULL)
1691			timer_action(oxu, TIMER_ASYNC_OFF);
1692	}
1693
1694	if (next) {
1695		oxu->reclaim = NULL;
1696		start_unlink_async(oxu, next);
1697	}
1698}
1699
1700/* makes sure the async qh will become idle */
1701/* caller must own oxu->lock */
1702
1703static void start_unlink_async(struct oxu_hcd *oxu, struct ehci_qh *qh)
1704{
1705	int cmd = readl(&oxu->regs->command);
1706	struct ehci_qh *prev;
1707
1708#ifdef DEBUG
1709	assert_spin_locked(&oxu->lock);
1710	if (oxu->reclaim || (qh->qh_state != QH_STATE_LINKED
1711				&& qh->qh_state != QH_STATE_UNLINK_WAIT))
1712		BUG();
1713#endif
1714
1715	/* stop async schedule right now? */
1716	if (unlikely(qh == oxu->async)) {
1717		/* can't get here without STS_ASS set */
1718		if (oxu_to_hcd(oxu)->state != HC_STATE_HALT
1719				&& !oxu->reclaim) {
1720			/* ... and CMD_IAAD clear */
1721			writel(cmd & ~CMD_ASE, &oxu->regs->command);
1722			wmb();
1723			/* handshake later, if we need to */
1724			timer_action_done(oxu, TIMER_ASYNC_OFF);
1725		}
1726		return;
1727	}
1728
1729	qh->qh_state = QH_STATE_UNLINK;
1730	oxu->reclaim = qh = qh_get(qh);
1731
1732	prev = oxu->async;
1733	while (prev->qh_next.qh != qh)
1734		prev = prev->qh_next.qh;
1735
1736	prev->hw_next = qh->hw_next;
1737	prev->qh_next = qh->qh_next;
1738	wmb();
1739
1740	if (unlikely(oxu_to_hcd(oxu)->state == HC_STATE_HALT)) {
1741		/* if (unlikely(qh->reclaim != 0))
1742		 *	this will recurse, probably not much
1743		 */
1744		end_unlink_async(oxu);
1745		return;
1746	}
1747
1748	oxu->reclaim_ready = 0;
1749	cmd |= CMD_IAAD;
1750	writel(cmd, &oxu->regs->command);
1751	(void) readl(&oxu->regs->command);
1752	timer_action(oxu, TIMER_IAA_WATCHDOG);
1753}
1754
1755static void scan_async(struct oxu_hcd *oxu)
1756{
1757	struct ehci_qh *qh;
1758	enum ehci_timer_action action = TIMER_IO_WATCHDOG;
1759
1760	if (!++(oxu->stamp))
1761		oxu->stamp++;
1762	timer_action_done(oxu, TIMER_ASYNC_SHRINK);
1763rescan:
1764	qh = oxu->async->qh_next.qh;
1765	if (likely(qh != NULL)) {
1766		do {
1767			/* clean any finished work for this qh */
1768			if (!list_empty(&qh->qtd_list)
1769					&& qh->stamp != oxu->stamp) {
1770				int temp;
1771
1772				/* unlinks could happen here; completion
1773				 * reporting drops the lock.  rescan using
1774				 * the latest schedule, but don't rescan
1775				 * qhs we already finished (no looping).
1776				 */
1777				qh = qh_get(qh);
1778				qh->stamp = oxu->stamp;
1779				temp = qh_completions(oxu, qh);
1780				qh_put(qh);
1781				if (temp != 0)
1782					goto rescan;
1783			}
1784
1785			/* unlink idle entries, reducing HC PCI usage as well
1786			 * as HCD schedule-scanning costs.  delay for any qh
1787			 * we just scanned, there's a not-unusual case that it
1788			 * doesn't stay idle for long.
1789			 * (plus, avoids some kind of re-activation race.)
1790			 */
1791			if (list_empty(&qh->qtd_list)) {
1792				if (qh->stamp == oxu->stamp)
1793					action = TIMER_ASYNC_SHRINK;
1794				else if (!oxu->reclaim
1795					    && qh->qh_state == QH_STATE_LINKED)
1796					start_unlink_async(oxu, qh);
1797			}
1798
1799			qh = qh->qh_next.qh;
1800		} while (qh);
1801	}
1802	if (action == TIMER_ASYNC_SHRINK)
1803		timer_action(oxu, TIMER_ASYNC_SHRINK);
1804}
1805
1806/*
1807 * periodic_next_shadow - return "next" pointer on shadow list
1808 * @periodic: host pointer to qh/itd/sitd
1809 * @tag: hardware tag for type of this record
1810 */
1811static union ehci_shadow *periodic_next_shadow(union ehci_shadow *periodic,
1812						__le32 tag)
1813{
1814	switch (tag) {
1815	default:
1816	case Q_TYPE_QH:
1817		return &periodic->qh->qh_next;
1818	}
1819}
1820
1821/* caller must hold oxu->lock */
1822static void periodic_unlink(struct oxu_hcd *oxu, unsigned frame, void *ptr)
1823{
1824	union ehci_shadow *prev_p = &oxu->pshadow[frame];
1825	__le32 *hw_p = &oxu->periodic[frame];
1826	union ehci_shadow here = *prev_p;
1827
1828	/* find predecessor of "ptr"; hw and shadow lists are in sync */
1829	while (here.ptr && here.ptr != ptr) {
1830		prev_p = periodic_next_shadow(prev_p, Q_NEXT_TYPE(*hw_p));
1831		hw_p = here.hw_next;
1832		here = *prev_p;
1833	}
1834	/* an interrupt entry (at list end) could have been shared */
1835	if (!here.ptr)
1836		return;
1837
1838	/* update shadow and hardware lists ... the old "next" pointers
1839	 * from ptr may still be in use, the caller updates them.
1840	 */
1841	*prev_p = *periodic_next_shadow(&here, Q_NEXT_TYPE(*hw_p));
1842	*hw_p = *here.hw_next;
1843}
1844
1845/* how many of the uframe's 125 usecs are allocated? */
1846static unsigned short periodic_usecs(struct oxu_hcd *oxu,
1847					unsigned frame, unsigned uframe)
1848{
1849	__le32 *hw_p = &oxu->periodic[frame];
1850	union ehci_shadow *q = &oxu->pshadow[frame];
1851	unsigned usecs = 0;
1852
1853	while (q->ptr) {
1854		switch (Q_NEXT_TYPE(*hw_p)) {
1855		case Q_TYPE_QH:
1856		default:
1857			/* is it in the S-mask? */
1858			if (q->qh->hw_info2 & cpu_to_le32(1 << uframe))
1859				usecs += q->qh->usecs;
1860			/* ... or C-mask? */
1861			if (q->qh->hw_info2 & cpu_to_le32(1 << (8 + uframe)))
1862				usecs += q->qh->c_usecs;
1863			hw_p = &q->qh->hw_next;
1864			q = &q->qh->qh_next;
1865			break;
1866		}
1867	}
1868#ifdef DEBUG
1869	if (usecs > 100)
1870		oxu_err(oxu, "uframe %d sched overrun: %d usecs\n",
1871						frame * 8 + uframe, usecs);
1872#endif
1873	return usecs;
1874}
1875
1876static int enable_periodic(struct oxu_hcd *oxu)
1877{
1878	u32 cmd;
1879	int status;
1880
1881	/* did clearing PSE did take effect yet?
1882	 * takes effect only at frame boundaries...
1883	 */
1884	status = handshake(oxu, &oxu->regs->status, STS_PSS, 0, 9 * 125);
1885	if (status != 0) {
1886		oxu_to_hcd(oxu)->state = HC_STATE_HALT;
1887		usb_hc_died(oxu_to_hcd(oxu));
1888		return status;
1889	}
1890
1891	cmd = readl(&oxu->regs->command) | CMD_PSE;
1892	writel(cmd, &oxu->regs->command);
1893	/* posted write ... PSS happens later */
1894	oxu_to_hcd(oxu)->state = HC_STATE_RUNNING;
1895
1896	/* make sure ehci_work scans these */
1897	oxu->next_uframe = readl(&oxu->regs->frame_index)
1898		% (oxu->periodic_size << 3);
1899	return 0;
1900}
1901
1902static int disable_periodic(struct oxu_hcd *oxu)
1903{
1904	u32 cmd;
1905	int status;
1906
1907	/* did setting PSE not take effect yet?
1908	 * takes effect only at frame boundaries...
1909	 */
1910	status = handshake(oxu, &oxu->regs->status, STS_PSS, STS_PSS, 9 * 125);
1911	if (status != 0) {
1912		oxu_to_hcd(oxu)->state = HC_STATE_HALT;
1913		usb_hc_died(oxu_to_hcd(oxu));
1914		return status;
1915	}
1916
1917	cmd = readl(&oxu->regs->command) & ~CMD_PSE;
1918	writel(cmd, &oxu->regs->command);
1919	/* posted write ... */
1920
1921	oxu->next_uframe = -1;
1922	return 0;
1923}
1924
1925/* periodic schedule slots have iso tds (normal or split) first, then a
1926 * sparse tree for active interrupt transfers.
1927 *
1928 * this just links in a qh; caller guarantees uframe masks are set right.
1929 * no FSTN support (yet; oxu 0.96+)
1930 */
1931static int qh_link_periodic(struct oxu_hcd *oxu, struct ehci_qh *qh)
1932{
1933	unsigned i;
1934	unsigned period = qh->period;
1935
1936	dev_dbg(&qh->dev->dev,
1937		"link qh%d-%04x/%p start %d [%d/%d us]\n",
1938		period, le32_to_cpup(&qh->hw_info2) & (QH_CMASK | QH_SMASK),
1939		qh, qh->start, qh->usecs, qh->c_usecs);
1940
1941	/* high bandwidth, or otherwise every microframe */
1942	if (period == 0)
1943		period = 1;
1944
1945	for (i = qh->start; i < oxu->periodic_size; i += period) {
1946		union ehci_shadow	*prev = &oxu->pshadow[i];
1947		__le32			*hw_p = &oxu->periodic[i];
1948		union ehci_shadow	here = *prev;
1949		__le32			type = 0;
1950
1951		/* skip the iso nodes at list head */
1952		while (here.ptr) {
1953			type = Q_NEXT_TYPE(*hw_p);
1954			if (type == Q_TYPE_QH)
1955				break;
1956			prev = periodic_next_shadow(prev, type);
1957			hw_p = &here.qh->hw_next;
1958			here = *prev;
1959		}
1960
1961		/* sorting each branch by period (slow-->fast)
1962		 * enables sharing interior tree nodes
1963		 */
1964		while (here.ptr && qh != here.qh) {
1965			if (qh->period > here.qh->period)
1966				break;
1967			prev = &here.qh->qh_next;
1968			hw_p = &here.qh->hw_next;
1969			here = *prev;
1970		}
1971		/* link in this qh, unless some earlier pass did that */
1972		if (qh != here.qh) {
1973			qh->qh_next = here;
1974			if (here.qh)
1975				qh->hw_next = *hw_p;
1976			wmb();
1977			prev->qh = qh;
1978			*hw_p = QH_NEXT(qh->qh_dma);
1979		}
1980	}
1981	qh->qh_state = QH_STATE_LINKED;
1982	qh_get(qh);
1983
1984	/* update per-qh bandwidth for usbfs */
1985	oxu_to_hcd(oxu)->self.bandwidth_allocated += qh->period
1986		? ((qh->usecs + qh->c_usecs) / qh->period)
1987		: (qh->usecs * 8);
1988
1989	/* maybe enable periodic schedule processing */
1990	if (!oxu->periodic_sched++)
1991		return enable_periodic(oxu);
1992
1993	return 0;
1994}
1995
1996static void qh_unlink_periodic(struct oxu_hcd *oxu, struct ehci_qh *qh)
1997{
1998	unsigned i;
1999	unsigned period;
2000
2001	/* FIXME:
2002	 *   IF this isn't high speed
2003	 *   and this qh is active in the current uframe
2004	 *   (and overlay token SplitXstate is false?)
2005	 * THEN
2006	 *   qh->hw_info1 |= cpu_to_le32(1 << 7 "ignore");
2007	 */
2008
2009	/* high bandwidth, or otherwise part of every microframe */
2010	period = qh->period;
2011	if (period == 0)
2012		period = 1;
2013
2014	for (i = qh->start; i < oxu->periodic_size; i += period)
2015		periodic_unlink(oxu, i, qh);
2016
2017	/* update per-qh bandwidth for usbfs */
2018	oxu_to_hcd(oxu)->self.bandwidth_allocated -= qh->period
2019		? ((qh->usecs + qh->c_usecs) / qh->period)
2020		: (qh->usecs * 8);
2021
2022	dev_dbg(&qh->dev->dev,
2023		"unlink qh%d-%04x/%p start %d [%d/%d us]\n",
2024		qh->period,
2025		le32_to_cpup(&qh->hw_info2) & (QH_CMASK | QH_SMASK),
2026		qh, qh->start, qh->usecs, qh->c_usecs);
2027
2028	/* qh->qh_next still "live" to HC */
2029	qh->qh_state = QH_STATE_UNLINK;
2030	qh->qh_next.ptr = NULL;
2031	qh_put(qh);
2032
2033	/* maybe turn off periodic schedule */
2034	oxu->periodic_sched--;
2035	if (!oxu->periodic_sched)
2036		(void) disable_periodic(oxu);
2037}
2038
2039static void intr_deschedule(struct oxu_hcd *oxu, struct ehci_qh *qh)
2040{
2041	unsigned wait;
2042
2043	qh_unlink_periodic(oxu, qh);
2044
2045	/* simple/paranoid:  always delay, expecting the HC needs to read
2046	 * qh->hw_next or finish a writeback after SPLIT/CSPLIT ... and
2047	 * expect khubd to clean up after any CSPLITs we won't issue.
2048	 * active high speed queues may need bigger delays...
2049	 */
2050	if (list_empty(&qh->qtd_list)
2051		|| (cpu_to_le32(QH_CMASK) & qh->hw_info2) != 0)
2052		wait = 2;
2053	else
2054		wait = 55;	/* worst case: 3 * 1024 */
2055
2056	udelay(wait);
2057	qh->qh_state = QH_STATE_IDLE;
2058	qh->hw_next = EHCI_LIST_END;
2059	wmb();
2060}
2061
2062static int check_period(struct oxu_hcd *oxu,
2063			unsigned frame, unsigned uframe,
2064			unsigned period, unsigned usecs)
2065{
2066	int claimed;
2067
2068	/* complete split running into next frame?
2069	 * given FSTN support, we could sometimes check...
2070	 */
2071	if (uframe >= 8)
2072		return 0;
2073
2074	/*
2075	 * 80% periodic == 100 usec/uframe available
2076	 * convert "usecs we need" to "max already claimed"
2077	 */
2078	usecs = 100 - usecs;
2079
2080	/* we "know" 2 and 4 uframe intervals were rejected; so
2081	 * for period 0, check _every_ microframe in the schedule.
2082	 */
2083	if (unlikely(period == 0)) {
2084		do {
2085			for (uframe = 0; uframe < 7; uframe++) {
2086				claimed = periodic_usecs(oxu, frame, uframe);
2087				if (claimed > usecs)
2088					return 0;
2089			}
2090		} while ((frame += 1) < oxu->periodic_size);
2091
2092	/* just check the specified uframe, at that period */
2093	} else {
2094		do {
2095			claimed = periodic_usecs(oxu, frame, uframe);
2096			if (claimed > usecs)
2097				return 0;
2098		} while ((frame += period) < oxu->periodic_size);
2099	}
2100
2101	return 1;
2102}
2103
2104static int check_intr_schedule(struct oxu_hcd	*oxu,
2105				unsigned frame, unsigned uframe,
2106				const struct ehci_qh *qh, __le32 *c_maskp)
2107{
2108	int retval = -ENOSPC;
2109
2110	if (qh->c_usecs && uframe >= 6)		/* FSTN territory? */
2111		goto done;
2112
2113	if (!check_period(oxu, frame, uframe, qh->period, qh->usecs))
2114		goto done;
2115	if (!qh->c_usecs) {
2116		retval = 0;
2117		*c_maskp = 0;
2118		goto done;
2119	}
2120
2121done:
2122	return retval;
2123}
2124
2125/* "first fit" scheduling policy used the first time through,
2126 * or when the previous schedule slot can't be re-used.
2127 */
2128static int qh_schedule(struct oxu_hcd *oxu, struct ehci_qh *qh)
2129{
2130	int		status;
2131	unsigned	uframe;
2132	__le32		c_mask;
2133	unsigned	frame;		/* 0..(qh->period - 1), or NO_FRAME */
2134
2135	qh_refresh(oxu, qh);
2136	qh->hw_next = EHCI_LIST_END;
2137	frame = qh->start;
2138
2139	/* reuse the previous schedule slots, if we can */
2140	if (frame < qh->period) {
2141		uframe = ffs(le32_to_cpup(&qh->hw_info2) & QH_SMASK);
2142		status = check_intr_schedule(oxu, frame, --uframe,
2143				qh, &c_mask);
2144	} else {
2145		uframe = 0;
2146		c_mask = 0;
2147		status = -ENOSPC;
2148	}
2149
2150	/* else scan the schedule to find a group of slots such that all
2151	 * uframes have enough periodic bandwidth available.
2152	 */
2153	if (status) {
2154		/* "normal" case, uframing flexible except with splits */
2155		if (qh->period) {
2156			frame = qh->period - 1;
2157			do {
2158				for (uframe = 0; uframe < 8; uframe++) {
2159					status = check_intr_schedule(oxu,
2160							frame, uframe, qh,
2161							&c_mask);
2162					if (status == 0)
2163						break;
2164				}
2165			} while (status && frame--);
2166
2167		/* qh->period == 0 means every uframe */
2168		} else {
2169			frame = 0;
2170			status = check_intr_schedule(oxu, 0, 0, qh, &c_mask);
2171		}
2172		if (status)
2173			goto done;
2174		qh->start = frame;
2175
2176		/* reset S-frame and (maybe) C-frame masks */
2177		qh->hw_info2 &= cpu_to_le32(~(QH_CMASK | QH_SMASK));
2178		qh->hw_info2 |= qh->period
2179			? cpu_to_le32(1 << uframe)
2180			: cpu_to_le32(QH_SMASK);
2181		qh->hw_info2 |= c_mask;
2182	} else
2183		oxu_dbg(oxu, "reused qh %p schedule\n", qh);
2184
2185	/* stuff into the periodic schedule */
2186	status = qh_link_periodic(oxu, qh);
2187done:
2188	return status;
2189}
2190
2191static int intr_submit(struct oxu_hcd *oxu, struct urb *urb,
2192			struct list_head *qtd_list, gfp_t mem_flags)
2193{
2194	unsigned epnum;
2195	unsigned long flags;
2196	struct ehci_qh *qh;
2197	int status = 0;
2198	struct list_head	empty;
2199
2200	/* get endpoint and transfer/schedule data */
2201	epnum = urb->ep->desc.bEndpointAddress;
2202
2203	spin_lock_irqsave(&oxu->lock, flags);
2204
2205	if (unlikely(!HCD_HW_ACCESSIBLE(oxu_to_hcd(oxu)))) {
2206		status = -ESHUTDOWN;
2207		goto done;
2208	}
2209
2210	/* get qh and force any scheduling errors */
2211	INIT_LIST_HEAD(&empty);
2212	qh = qh_append_tds(oxu, urb, &empty, epnum, &urb->ep->hcpriv);
2213	if (qh == NULL) {
2214		status = -ENOMEM;
2215		goto done;
2216	}
2217	if (qh->qh_state == QH_STATE_IDLE) {
2218		status = qh_schedule(oxu, qh);
2219		if (status != 0)
2220			goto done;
2221	}
2222
2223	/* then queue the urb's tds to the qh */
2224	qh = qh_append_tds(oxu, urb, qtd_list, epnum, &urb->ep->hcpriv);
2225	BUG_ON(qh == NULL);
2226
2227	/* ... update usbfs periodic stats */
2228	oxu_to_hcd(oxu)->self.bandwidth_int_reqs++;
2229
2230done:
2231	spin_unlock_irqrestore(&oxu->lock, flags);
2232	if (status)
2233		qtd_list_free(oxu, urb, qtd_list);
2234
2235	return status;
2236}
2237
2238static inline int itd_submit(struct oxu_hcd *oxu, struct urb *urb,
2239						gfp_t mem_flags)
2240{
2241	oxu_dbg(oxu, "iso support is missing!\n");
2242	return -ENOSYS;
2243}
2244
2245static inline int sitd_submit(struct oxu_hcd *oxu, struct urb *urb,
2246						gfp_t mem_flags)
2247{
2248	oxu_dbg(oxu, "split iso support is missing!\n");
2249	return -ENOSYS;
2250}
2251
2252static void scan_periodic(struct oxu_hcd *oxu)
2253{
2254	unsigned frame, clock, now_uframe, mod;
2255	unsigned modified;
2256
2257	mod = oxu->periodic_size << 3;
2258
2259	/*
2260	 * When running, scan from last scan point up to "now"
2261	 * else clean up by scanning everything that's left.
2262	 * Touches as few pages as possible:  cache-friendly.
2263	 */
2264	now_uframe = oxu->next_uframe;
2265	if (HC_IS_RUNNING(oxu_to_hcd(oxu)->state))
2266		clock = readl(&oxu->regs->frame_index);
2267	else
2268		clock = now_uframe + mod - 1;
2269	clock %= mod;
2270
2271	for (;;) {
2272		union ehci_shadow	q, *q_p;
2273		__le32			type, *hw_p;
2274		unsigned		uframes;
2275
2276		/* don't scan past the live uframe */
2277		frame = now_uframe >> 3;
2278		if (frame == (clock >> 3))
2279			uframes = now_uframe & 0x07;
2280		else {
2281			/* safe to scan the whole frame at once */
2282			now_uframe |= 0x07;
2283			uframes = 8;
2284		}
2285
2286restart:
2287		/* scan each element in frame's queue for completions */
2288		q_p = &oxu->pshadow[frame];
2289		hw_p = &oxu->periodic[frame];
2290		q.ptr = q_p->ptr;
2291		type = Q_NEXT_TYPE(*hw_p);
2292		modified = 0;
2293
2294		while (q.ptr != NULL) {
2295			union ehci_shadow temp;
2296			int live;
2297
2298			live = HC_IS_RUNNING(oxu_to_hcd(oxu)->state);
2299			switch (type) {
2300			case Q_TYPE_QH:
2301				/* handle any completions */
2302				temp.qh = qh_get(q.qh);
2303				type = Q_NEXT_TYPE(q.qh->hw_next);
2304				q = q.qh->qh_next;
2305				modified = qh_completions(oxu, temp.qh);
2306				if (unlikely(list_empty(&temp.qh->qtd_list)))
2307					intr_deschedule(oxu, temp.qh);
2308				qh_put(temp.qh);
2309				break;
2310			default:
2311				dbg("corrupt type %d frame %d shadow %p",
2312					type, frame, q.ptr);
2313				q.ptr = NULL;
2314			}
2315
2316			/* assume completion callbacks modify the queue */
2317			if (unlikely(modified))
2318				goto restart;
2319		}
2320
2321		/* Stop when we catch up to the HC */
2322
2323		/* FIXME:  this assumes we won't get lapped when
2324		 * latencies climb; that should be rare, but...
2325		 * detect it, and just go all the way around.
2326		 * FLR might help detect this case, so long as latencies
2327		 * don't exceed periodic_size msec (default 1.024 sec).
2328		 */
2329
2330		/* FIXME: likewise assumes HC doesn't halt mid-scan */
2331
2332		if (now_uframe == clock) {
2333			unsigned	now;
2334
2335			if (!HC_IS_RUNNING(oxu_to_hcd(oxu)->state))
2336				break;
2337			oxu->next_uframe = now_uframe;
2338			now = readl(&oxu->regs->frame_index) % mod;
2339			if (now_uframe == now)
2340				break;
2341
2342			/* rescan the rest of this frame, then ... */
2343			clock = now;
2344		} else {
2345			now_uframe++;
2346			now_uframe %= mod;
2347		}
2348	}
2349}
2350
2351/* On some systems, leaving remote wakeup enabled prevents system shutdown.
2352 * The firmware seems to think that powering off is a wakeup event!
2353 * This routine turns off remote wakeup and everything else, on all ports.
2354 */
2355static void ehci_turn_off_all_ports(struct oxu_hcd *oxu)
2356{
2357	int port = HCS_N_PORTS(oxu->hcs_params);
2358
2359	while (port--)
2360		writel(PORT_RWC_BITS, &oxu->regs->port_status[port]);
2361}
2362
2363static void ehci_port_power(struct oxu_hcd *oxu, int is_on)
2364{
2365	unsigned port;
2366
2367	if (!HCS_PPC(oxu->hcs_params))
2368		return;
2369
2370	oxu_dbg(oxu, "...power%s ports...\n", is_on ? "up" : "down");
2371	for (port = HCS_N_PORTS(oxu->hcs_params); port > 0; )
2372		(void) oxu_hub_control(oxu_to_hcd(oxu),
2373				is_on ? SetPortFeature : ClearPortFeature,
2374				USB_PORT_FEAT_POWER,
2375				port--, NULL, 0);
2376	msleep(20);
2377}
2378
2379/* Called from some interrupts, timers, and so on.
2380 * It calls driver completion functions, after dropping oxu->lock.
2381 */
2382static void ehci_work(struct oxu_hcd *oxu)
2383{
2384	timer_action_done(oxu, TIMER_IO_WATCHDOG);
2385	if (oxu->reclaim_ready)
2386		end_unlink_async(oxu);
2387
2388	/* another CPU may drop oxu->lock during a schedule scan while
2389	 * it reports urb completions.  this flag guards against bogus
2390	 * attempts at re-entrant schedule scanning.
2391	 */
2392	if (oxu->scanning)
2393		return;
2394	oxu->scanning = 1;
2395	scan_async(oxu);
2396	if (oxu->next_uframe != -1)
2397		scan_periodic(oxu);
2398	oxu->scanning = 0;
2399
2400	/* the IO watchdog guards against hardware or driver bugs that
2401	 * misplace IRQs, and should let us run completely without IRQs.
2402	 * such lossage has been observed on both VT6202 and VT8235.
2403	 */
2404	if (HC_IS_RUNNING(oxu_to_hcd(oxu)->state) &&
2405			(oxu->async->qh_next.ptr != NULL ||
2406			 oxu->periodic_sched != 0))
2407		timer_action(oxu, TIMER_IO_WATCHDOG);
2408}
2409
2410static void unlink_async(struct oxu_hcd *oxu, struct ehci_qh *qh)
2411{
2412	/* if we need to use IAA and it's busy, defer */
2413	if (qh->qh_state == QH_STATE_LINKED
2414			&& oxu->reclaim
2415			&& HC_IS_RUNNING(oxu_to_hcd(oxu)->state)) {
2416		struct ehci_qh		*last;
2417
2418		for (last = oxu->reclaim;
2419				last->reclaim;
2420				last = last->reclaim)
2421			continue;
2422		qh->qh_state = QH_STATE_UNLINK_WAIT;
2423		last->reclaim = qh;
2424
2425	/* bypass IAA if the hc can't care */
2426	} else if (!HC_IS_RUNNING(oxu_to_hcd(oxu)->state) && oxu->reclaim)
2427		end_unlink_async(oxu);
2428
2429	/* something else might have unlinked the qh by now */
2430	if (qh->qh_state == QH_STATE_LINKED)
2431		start_unlink_async(oxu, qh);
2432}
2433
2434/*
2435 * USB host controller methods
2436 */
2437
2438static irqreturn_t oxu210_hcd_irq(struct usb_hcd *hcd)
2439{
2440	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2441	u32 status, pcd_status = 0;
2442	int bh;
2443
2444	spin_lock(&oxu->lock);
2445
2446	status = readl(&oxu->regs->status);
2447
2448	/* e.g. cardbus physical eject */
2449	if (status == ~(u32) 0) {
2450		oxu_dbg(oxu, "device removed\n");
2451		goto dead;
2452	}
2453
2454	/* Shared IRQ? */
2455	status &= INTR_MASK;
2456	if (!status || unlikely(hcd->state == HC_STATE_HALT)) {
2457		spin_unlock(&oxu->lock);
2458		return IRQ_NONE;
2459	}
2460
2461	/* clear (just) interrupts */
2462	writel(status, &oxu->regs->status);
2463	readl(&oxu->regs->command);	/* unblock posted write */
2464	bh = 0;
2465
2466#ifdef OXU_VERBOSE_DEBUG
2467	/* unrequested/ignored: Frame List Rollover */
2468	dbg_status(oxu, "irq", status);
2469#endif
2470
2471	/* INT, ERR, and IAA interrupt rates can be throttled */
2472
2473	/* normal [4.15.1.2] or error [4.15.1.1] completion */
2474	if (likely((status & (STS_INT|STS_ERR)) != 0))
2475		bh = 1;
2476
2477	/* complete the unlinking of some qh [4.15.2.3] */
2478	if (status & STS_IAA) {
2479		oxu->reclaim_ready = 1;
2480		bh = 1;
2481	}
2482
2483	/* remote wakeup [4.3.1] */
2484	if (status & STS_PCD) {
2485		unsigned i = HCS_N_PORTS(oxu->hcs_params);
2486		pcd_status = status;
2487
2488		/* resume root hub? */
2489		if (!(readl(&oxu->regs->command) & CMD_RUN))
2490			usb_hcd_resume_root_hub(hcd);
2491
2492		while (i--) {
2493			int pstatus = readl(&oxu->regs->port_status[i]);
2494
2495			if (pstatus & PORT_OWNER)
2496				continue;
2497			if (!(pstatus & PORT_RESUME)
2498					|| oxu->reset_done[i] != 0)
2499				continue;
2500
2501			/* start 20 msec resume signaling from this port,
2502			 * and make khubd collect PORT_STAT_C_SUSPEND to
2503			 * stop that signaling.
2504			 */
2505			oxu->reset_done[i] = jiffies + msecs_to_jiffies(20);
2506			oxu_dbg(oxu, "port %d remote wakeup\n", i + 1);
2507			mod_timer(&hcd->rh_timer, oxu->reset_done[i]);
2508		}
2509	}
2510
2511	/* PCI errors [4.15.2.4] */
2512	if (unlikely((status & STS_FATAL) != 0)) {
2513		/* bogus "fatal" IRQs appear on some chips... why?  */
2514		status = readl(&oxu->regs->status);
2515		dbg_cmd(oxu, "fatal", readl(&oxu->regs->command));
2516		dbg_status(oxu, "fatal", status);
2517		if (status & STS_HALT) {
2518			oxu_err(oxu, "fatal error\n");
2519dead:
2520			ehci_reset(oxu);
2521			writel(0, &oxu->regs->configured_flag);
2522			usb_hc_died(hcd);
2523			/* generic layer kills/unlinks all urbs, then
2524			 * uses oxu_stop to clean up the rest
2525			 */
2526			bh = 1;
2527		}
2528	}
2529
2530	if (bh)
2531		ehci_work(oxu);
2532	spin_unlock(&oxu->lock);
2533	if (pcd_status & STS_PCD)
2534		usb_hcd_poll_rh_status(hcd);
2535	return IRQ_HANDLED;
2536}
2537
2538static irqreturn_t oxu_irq(struct usb_hcd *hcd)
2539{
2540	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2541	int ret = IRQ_HANDLED;
2542
2543	u32 status = oxu_readl(hcd->regs, OXU_CHIPIRQSTATUS);
2544	u32 enable = oxu_readl(hcd->regs, OXU_CHIPIRQEN_SET);
2545
2546	/* Disable all interrupt */
2547	oxu_writel(hcd->regs, OXU_CHIPIRQEN_CLR, enable);
2548
2549	if ((oxu->is_otg && (status & OXU_USBOTGI)) ||
2550		(!oxu->is_otg && (status & OXU_USBSPHI)))
2551		oxu210_hcd_irq(hcd);
2552	else
2553		ret = IRQ_NONE;
2554
2555	/* Enable all interrupt back */
2556	oxu_writel(hcd->regs, OXU_CHIPIRQEN_SET, enable);
2557
2558	return ret;
2559}
2560
2561static void oxu_watchdog(unsigned long param)
2562{
2563	struct oxu_hcd	*oxu = (struct oxu_hcd *) param;
2564	unsigned long flags;
2565
2566	spin_lock_irqsave(&oxu->lock, flags);
2567
2568	/* lost IAA irqs wedge things badly; seen with a vt8235 */
2569	if (oxu->reclaim) {
2570		u32 status = readl(&oxu->regs->status);
2571		if (status & STS_IAA) {
2572			oxu_vdbg(oxu, "lost IAA\n");
2573			writel(STS_IAA, &oxu->regs->status);
2574			oxu->reclaim_ready = 1;
2575		}
2576	}
2577
2578	/* stop async processing after it's idled a bit */
2579	if (test_bit(TIMER_ASYNC_OFF, &oxu->actions))
2580		start_unlink_async(oxu, oxu->async);
2581
2582	/* oxu could run by timer, without IRQs ... */
2583	ehci_work(oxu);
2584
2585	spin_unlock_irqrestore(&oxu->lock, flags);
2586}
2587
2588/* One-time init, only for memory state.
2589 */
2590static int oxu_hcd_init(struct usb_hcd *hcd)
2591{
2592	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2593	u32 temp;
2594	int retval;
2595	u32 hcc_params;
2596
2597	spin_lock_init(&oxu->lock);
2598
2599	init_timer(&oxu->watchdog);
2600	oxu->watchdog.function = oxu_watchdog;
2601	oxu->watchdog.data = (unsigned long) oxu;
2602
2603	/*
2604	 * hw default: 1K periodic list heads, one per frame.
2605	 * periodic_size can shrink by USBCMD update if hcc_params allows.
2606	 */
2607	oxu->periodic_size = DEFAULT_I_TDPS;
2608	retval = ehci_mem_init(oxu, GFP_KERNEL);
2609	if (retval < 0)
2610		return retval;
2611
2612	/* controllers may cache some of the periodic schedule ... */
2613	hcc_params = readl(&oxu->caps->hcc_params);
2614	if (HCC_ISOC_CACHE(hcc_params))		/* full frame cache */
2615		oxu->i_thresh = 8;
2616	else					/* N microframes cached */
2617		oxu->i_thresh = 2 + HCC_ISOC_THRES(hcc_params);
2618
2619	oxu->reclaim = NULL;
2620	oxu->reclaim_ready = 0;
2621	oxu->next_uframe = -1;
2622
2623	/*
2624	 * dedicate a qh for the async ring head, since we couldn't unlink
2625	 * a 'real' qh without stopping the async schedule [4.8].  use it
2626	 * as the 'reclamation list head' too.
2627	 * its dummy is used in hw_alt_next of many tds, to prevent the qh
2628	 * from automatically advancing to the next td after short reads.
2629	 */
2630	oxu->async->qh_next.qh = NULL;
2631	oxu->async->hw_next = QH_NEXT(oxu->async->qh_dma);
2632	oxu->async->hw_info1 = cpu_to_le32(QH_HEAD);
2633	oxu->async->hw_token = cpu_to_le32(QTD_STS_HALT);
2634	oxu->async->hw_qtd_next = EHCI_LIST_END;
2635	oxu->async->qh_state = QH_STATE_LINKED;
2636	oxu->async->hw_alt_next = QTD_NEXT(oxu->async->dummy->qtd_dma);
2637
2638	/* clear interrupt enables, set irq latency */
2639	if (log2_irq_thresh < 0 || log2_irq_thresh > 6)
2640		log2_irq_thresh = 0;
2641	temp = 1 << (16 + log2_irq_thresh);
2642	if (HCC_CANPARK(hcc_params)) {
2643		/* HW default park == 3, on hardware that supports it (like
2644		 * NVidia and ALI silicon), maximizes throughput on the async
2645		 * schedule by avoiding QH fetches between transfers.
2646		 *
2647		 * With fast usb storage devices and NForce2, "park" seems to
2648		 * make problems:  throughput reduction (!), data errors...
2649		 */
2650		if (park) {
2651			park = min(park, (unsigned) 3);
2652			temp |= CMD_PARK;
2653			temp |= park << 8;
2654		}
2655		oxu_dbg(oxu, "park %d\n", park);
2656	}
2657	if (HCC_PGM_FRAMELISTLEN(hcc_params)) {
2658		/* periodic schedule size can be smaller than default */
2659		temp &= ~(3 << 2);
2660		temp |= (EHCI_TUNE_FLS << 2);
2661	}
2662	oxu->command = temp;
2663
2664	return 0;
2665}
2666
2667/* Called during probe() after chip reset completes.
2668 */
2669static int oxu_reset(struct usb_hcd *hcd)
2670{
2671	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2672	int ret;
2673
2674	spin_lock_init(&oxu->mem_lock);
2675	INIT_LIST_HEAD(&oxu->urb_list);
2676	oxu->urb_len = 0;
2677
2678	/* FIMXE */
2679	hcd->self.controller->dma_mask = NULL;
2680
2681	if (oxu->is_otg) {
2682		oxu->caps = hcd->regs + OXU_OTG_CAP_OFFSET;
2683		oxu->regs = hcd->regs + OXU_OTG_CAP_OFFSET + \
2684			HC_LENGTH(readl(&oxu->caps->hc_capbase));
2685
2686		oxu->mem = hcd->regs + OXU_SPH_MEM;
2687	} else {
2688		oxu->caps = hcd->regs + OXU_SPH_CAP_OFFSET;
2689		oxu->regs = hcd->regs + OXU_SPH_CAP_OFFSET + \
2690			HC_LENGTH(readl(&oxu->caps->hc_capbase));
2691
2692		oxu->mem = hcd->regs + OXU_OTG_MEM;
2693	}
2694
2695	oxu->hcs_params = readl(&oxu->caps->hcs_params);
2696	oxu->sbrn = 0x20;
2697
2698	ret = oxu_hcd_init(hcd);
2699	if (ret)
2700		return ret;
2701
2702	return 0;
2703}
2704
2705static int oxu_run(struct usb_hcd *hcd)
2706{
2707	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2708	int retval;
2709	u32 temp, hcc_params;
2710
2711	hcd->uses_new_polling = 1;
2712
2713	/* EHCI spec section 4.1 */
2714	retval = ehci_reset(oxu);
2715	if (retval != 0) {
2716		ehci_mem_cleanup(oxu);
2717		return retval;
2718	}
2719	writel(oxu->periodic_dma, &oxu->regs->frame_list);
2720	writel((u32) oxu->async->qh_dma, &oxu->regs->async_next);
2721
2722	/* hcc_params controls whether oxu->regs->segment must (!!!)
2723	 * be used; it constrains QH/ITD/SITD and QTD locations.
2724	 * pci_pool consistent memory always uses segment zero.
2725	 * streaming mappings for I/O buffers, like pci_map_single(),
2726	 * can return segments above 4GB, if the device allows.
2727	 *
2728	 * NOTE:  the dma mask is visible through dma_supported(), so
2729	 * drivers can pass this info along ... like NETIF_F_HIGHDMA,
2730	 * Scsi_Host.highmem_io, and so forth.  It's readonly to all
2731	 * host side drivers though.
2732	 */
2733	hcc_params = readl(&oxu->caps->hcc_params);
2734	if (HCC_64BIT_ADDR(hcc_params))
2735		writel(0, &oxu->regs->segment);
2736
2737	oxu->command &= ~(CMD_LRESET | CMD_IAAD | CMD_PSE |
2738				CMD_ASE | CMD_RESET);
2739	oxu->command |= CMD_RUN;
2740	writel(oxu->command, &oxu->regs->command);
2741	dbg_cmd(oxu, "init", oxu->command);
2742
2743	/*
2744	 * Start, enabling full USB 2.0 functionality ... usb 1.1 devices
2745	 * are explicitly handed to companion controller(s), so no TT is
2746	 * involved with the root hub.  (Except where one is integrated,
2747	 * and there's no companion controller unless maybe for USB OTG.)
2748	 */
2749	hcd->state = HC_STATE_RUNNING;
2750	writel(FLAG_CF, &oxu->regs->configured_flag);
2751	readl(&oxu->regs->command);	/* unblock posted writes */
2752
2753	temp = HC_VERSION(readl(&oxu->caps->hc_capbase));
2754	oxu_info(oxu, "USB %x.%x started, quasi-EHCI %x.%02x, driver %s%s\n",
2755		((oxu->sbrn & 0xf0)>>4), (oxu->sbrn & 0x0f),
2756		temp >> 8, temp & 0xff, DRIVER_VERSION,
2757		ignore_oc ? ", overcurrent ignored" : "");
2758
2759	writel(INTR_MASK, &oxu->regs->intr_enable); /* Turn On Interrupts */
2760
2761	return 0;
2762}
2763
2764static void oxu_stop(struct usb_hcd *hcd)
2765{
2766	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2767
2768	/* Turn off port power on all root hub ports. */
2769	ehci_port_power(oxu, 0);
2770
2771	/* no more interrupts ... */
2772	del_timer_sync(&oxu->watchdog);
2773
2774	spin_lock_irq(&oxu->lock);
2775	if (HC_IS_RUNNING(hcd->state))
2776		ehci_quiesce(oxu);
2777
2778	ehci_reset(oxu);
2779	writel(0, &oxu->regs->intr_enable);
2780	spin_unlock_irq(&oxu->lock);
2781
2782	/* let companion controllers work when we aren't */
2783	writel(0, &oxu->regs->configured_flag);
2784
2785	/* root hub is shut down separately (first, when possible) */
2786	spin_lock_irq(&oxu->lock);
2787	if (oxu->async)
2788		ehci_work(oxu);
2789	spin_unlock_irq(&oxu->lock);
2790	ehci_mem_cleanup(oxu);
2791
2792	dbg_status(oxu, "oxu_stop completed", readl(&oxu->regs->status));
2793}
2794
2795/* Kick in for silicon on any bus (not just pci, etc).
2796 * This forcibly disables dma and IRQs, helping kexec and other cases
2797 * where the next system software may expect clean state.
2798 */
2799static void oxu_shutdown(struct usb_hcd *hcd)
2800{
2801	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2802
2803	(void) ehci_halt(oxu);
2804	ehci_turn_off_all_ports(oxu);
2805
2806	/* make BIOS/etc use companion controller during reboot */
2807	writel(0, &oxu->regs->configured_flag);
2808
2809	/* unblock posted writes */
2810	readl(&oxu->regs->configured_flag);
2811}
2812
2813/* Non-error returns are a promise to giveback() the urb later
2814 * we drop ownership so next owner (or urb unlink) can get it
2815 *
2816 * urb + dev is in hcd.self.controller.urb_list
2817 * we're queueing TDs onto software and hardware lists
2818 *
2819 * hcd-specific init for hcpriv hasn't been done yet
2820 *
2821 * NOTE:  control, bulk, and interrupt share the same code to append TDs
2822 * to a (possibly active) QH, and the same QH scanning code.
2823 */
2824static int __oxu_urb_enqueue(struct usb_hcd *hcd, struct urb *urb,
2825				gfp_t mem_flags)
2826{
2827	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2828	struct list_head qtd_list;
2829
2830	INIT_LIST_HEAD(&qtd_list);
2831
2832	switch (usb_pipetype(urb->pipe)) {
2833	case PIPE_CONTROL:
2834	case PIPE_BULK:
2835	default:
2836		if (!qh_urb_transaction(oxu, urb, &qtd_list, mem_flags))
2837			return -ENOMEM;
2838		return submit_async(oxu, urb, &qtd_list, mem_flags);
2839
2840	case PIPE_INTERRUPT:
2841		if (!qh_urb_transaction(oxu, urb, &qtd_list, mem_flags))
2842			return -ENOMEM;
2843		return intr_submit(oxu, urb, &qtd_list, mem_flags);
2844
2845	case PIPE_ISOCHRONOUS:
2846		if (urb->dev->speed == USB_SPEED_HIGH)
2847			return itd_submit(oxu, urb, mem_flags);
2848		else
2849			return sitd_submit(oxu, urb, mem_flags);
2850	}
2851}
2852
2853/* This function is responsible for breaking URBs with big data size
2854 * into smaller size and processing small urbs in sequence.
2855 */
2856static int oxu_urb_enqueue(struct usb_hcd *hcd, struct urb *urb,
2857				gfp_t mem_flags)
2858{
2859	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2860	int num, rem;
2861	int transfer_buffer_length;
2862	void *transfer_buffer;
2863	struct urb *murb;
2864	int i, ret;
2865
2866	/* If not bulk pipe just enqueue the URB */
2867	if (!usb_pipebulk(urb->pipe))
2868		return __oxu_urb_enqueue(hcd, urb, mem_flags);
2869
2870	/* Otherwise we should verify the USB transfer buffer size! */
2871	transfer_buffer = urb->transfer_buffer;
2872	transfer_buffer_length = urb->transfer_buffer_length;
2873
2874	num = urb->transfer_buffer_length / 4096;
2875	rem = urb->transfer_buffer_length % 4096;
2876	if (rem != 0)
2877		num++;
2878
2879	/* If URB is smaller than 4096 bytes just enqueue it! */
2880	if (num == 1)
2881		return __oxu_urb_enqueue(hcd, urb, mem_flags);
2882
2883	/* Ok, we have more job to do! :) */
2884
2885	for (i = 0; i < num - 1; i++) {
2886		/* Get free micro URB poll till a free urb is received */
2887
2888		do {
2889			murb = (struct urb *) oxu_murb_alloc(oxu);
2890			if (!murb)
2891				schedule();
2892		} while (!murb);
2893
2894		/* Coping the urb */
2895		memcpy(murb, urb, sizeof(struct urb));
2896
2897		murb->transfer_buffer_length = 4096;
2898		murb->transfer_buffer = transfer_buffer + i * 4096;
2899
2900		/* Null pointer for the encodes that this is a micro urb */
2901		murb->complete = NULL;
2902
2903		((struct oxu_murb *) murb)->main = urb;
2904		((struct oxu_murb *) murb)->last = 0;
2905
2906		/* This loop is to guarantee urb to be processed when there's
2907		 * not enough resources at a particular time by retrying.
2908		 */
2909		do {
2910			ret  = __oxu_urb_enqueue(hcd, murb, mem_flags);
2911			if (ret)
2912				schedule();
2913		} while (ret);
2914	}
2915
2916	/* Last urb requires special handling  */
2917
2918	/* Get free micro URB poll till a free urb is received */
2919	do {
2920		murb = (struct urb *) oxu_murb_alloc(oxu);
2921		if (!murb)
2922			schedule();
2923	} while (!murb);
2924
2925	/* Coping the urb */
2926	memcpy(murb, urb, sizeof(struct urb));
2927
2928	murb->transfer_buffer_length = rem > 0 ? rem : 4096;
2929	murb->transfer_buffer = transfer_buffer + (num - 1) * 4096;
2930
2931	/* Null pointer for the encodes that this is a micro urb */
2932	murb->complete = NULL;
2933
2934	((struct oxu_murb *) murb)->main = urb;
2935	((struct oxu_murb *) murb)->last = 1;
2936
2937	do {
2938		ret = __oxu_urb_enqueue(hcd, murb, mem_flags);
2939		if (ret)
2940			schedule();
2941	} while (ret);
2942
2943	return ret;
2944}
2945
2946/* Remove from hardware lists.
2947 * Completions normally happen asynchronously
2948 */
2949static int oxu_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
2950{
2951	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2952	struct ehci_qh *qh;
2953	unsigned long flags;
2954
2955	spin_lock_irqsave(&oxu->lock, flags);
2956	switch (usb_pipetype(urb->pipe)) {
2957	case PIPE_CONTROL:
2958	case PIPE_BULK:
2959	default:
2960		qh = (struct ehci_qh *) urb->hcpriv;
2961		if (!qh)
2962			break;
2963		unlink_async(oxu, qh);
2964		break;
2965
2966	case PIPE_INTERRUPT:
2967		qh = (struct ehci_qh *) urb->hcpriv;
2968		if (!qh)
2969			break;
2970		switch (qh->qh_state) {
2971		case QH_STATE_LINKED:
2972			intr_deschedule(oxu, qh);
2973			/* FALL THROUGH */
2974		case QH_STATE_IDLE:
2975			qh_completions(oxu, qh);
2976			break;
2977		default:
2978			oxu_dbg(oxu, "bogus qh %p state %d\n",
2979					qh, qh->qh_state);
2980			goto done;
2981		}
2982
2983		/* reschedule QH iff another request is queued */
2984		if (!list_empty(&qh->qtd_list)
2985				&& HC_IS_RUNNING(hcd->state)) {
2986			int status;
2987
2988			status = qh_schedule(oxu, qh);
2989			spin_unlock_irqrestore(&oxu->lock, flags);
2990
2991			if (status != 0) {
2992				/* shouldn't happen often, but ...
2993				 * FIXME kill those tds' urbs
2994				 */
2995				err("can't reschedule qh %p, err %d",
2996					qh, status);
 
2997			}
2998			return status;
2999		}
3000		break;
3001	}
3002done:
3003	spin_unlock_irqrestore(&oxu->lock, flags);
3004	return 0;
3005}
3006
3007/* Bulk qh holds the data toggle */
3008static void oxu_endpoint_disable(struct usb_hcd *hcd,
3009					struct usb_host_endpoint *ep)
3010{
3011	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3012	unsigned long		flags;
3013	struct ehci_qh		*qh, *tmp;
3014
3015	/* ASSERT:  any requests/urbs are being unlinked */
3016	/* ASSERT:  nobody can be submitting urbs for this any more */
3017
3018rescan:
3019	spin_lock_irqsave(&oxu->lock, flags);
3020	qh = ep->hcpriv;
3021	if (!qh)
3022		goto done;
3023
3024	/* endpoints can be iso streams.  for now, we don't
3025	 * accelerate iso completions ... so spin a while.
3026	 */
3027	if (qh->hw_info1 == 0) {
3028		oxu_vdbg(oxu, "iso delay\n");
3029		goto idle_timeout;
3030	}
3031
3032	if (!HC_IS_RUNNING(hcd->state))
3033		qh->qh_state = QH_STATE_IDLE;
3034	switch (qh->qh_state) {
3035	case QH_STATE_LINKED:
3036		for (tmp = oxu->async->qh_next.qh;
3037				tmp && tmp != qh;
3038				tmp = tmp->qh_next.qh)
3039			continue;
3040		/* periodic qh self-unlinks on empty */
3041		if (!tmp)
3042			goto nogood;
3043		unlink_async(oxu, qh);
3044		/* FALL THROUGH */
3045	case QH_STATE_UNLINK:		/* wait for hw to finish? */
3046idle_timeout:
3047		spin_unlock_irqrestore(&oxu->lock, flags);
3048		schedule_timeout_uninterruptible(1);
3049		goto rescan;
3050	case QH_STATE_IDLE:		/* fully unlinked */
3051		if (list_empty(&qh->qtd_list)) {
3052			qh_put(qh);
3053			break;
3054		}
3055		/* else FALL THROUGH */
3056	default:
3057nogood:
3058		/* caller was supposed to have unlinked any requests;
3059		 * that's not our job.  just leak this memory.
3060		 */
3061		oxu_err(oxu, "qh %p (#%02x) state %d%s\n",
3062			qh, ep->desc.bEndpointAddress, qh->qh_state,
3063			list_empty(&qh->qtd_list) ? "" : "(has tds)");
3064		break;
3065	}
3066	ep->hcpriv = NULL;
3067done:
3068	spin_unlock_irqrestore(&oxu->lock, flags);
3069}
3070
3071static int oxu_get_frame(struct usb_hcd *hcd)
3072{
3073	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3074
3075	return (readl(&oxu->regs->frame_index) >> 3) %
3076		oxu->periodic_size;
3077}
3078
3079/* Build "status change" packet (one or two bytes) from HC registers */
3080static int oxu_hub_status_data(struct usb_hcd *hcd, char *buf)
3081{
3082	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3083	u32 temp, mask, status = 0;
3084	int ports, i, retval = 1;
3085	unsigned long flags;
3086
3087	/* if !USB_SUSPEND, root hub timers won't get shut down ... */
3088	if (!HC_IS_RUNNING(hcd->state))
3089		return 0;
3090
3091	/* init status to no-changes */
3092	buf[0] = 0;
3093	ports = HCS_N_PORTS(oxu->hcs_params);
3094	if (ports > 7) {
3095		buf[1] = 0;
3096		retval++;
3097	}
3098
3099	/* Some boards (mostly VIA?) report bogus overcurrent indications,
3100	 * causing massive log spam unless we completely ignore them.  It
3101	 * may be relevant that VIA VT8235 controllers, where PORT_POWER is
3102	 * always set, seem to clear PORT_OCC and PORT_CSC when writing to
3103	 * PORT_POWER; that's surprising, but maybe within-spec.
3104	 */
3105	if (!ignore_oc)
3106		mask = PORT_CSC | PORT_PEC | PORT_OCC;
3107	else
3108		mask = PORT_CSC | PORT_PEC;
3109
3110	/* no hub change reports (bit 0) for now (power, ...) */
3111
3112	/* port N changes (bit N)? */
3113	spin_lock_irqsave(&oxu->lock, flags);
3114	for (i = 0; i < ports; i++) {
3115		temp = readl(&oxu->regs->port_status[i]);
3116
3117		/*
3118		 * Return status information even for ports with OWNER set.
3119		 * Otherwise khubd wouldn't see the disconnect event when a
3120		 * high-speed device is switched over to the companion
3121		 * controller by the user.
3122		 */
3123
3124		if (!(temp & PORT_CONNECT))
3125			oxu->reset_done[i] = 0;
3126		if ((temp & mask) != 0 || ((temp & PORT_RESUME) != 0 &&
3127				time_after_eq(jiffies, oxu->reset_done[i]))) {
3128			if (i < 7)
3129				buf[0] |= 1 << (i + 1);
3130			else
3131				buf[1] |= 1 << (i - 7);
3132			status = STS_PCD;
3133		}
3134	}
3135	/* FIXME autosuspend idle root hubs */
3136	spin_unlock_irqrestore(&oxu->lock, flags);
3137	return status ? retval : 0;
3138}
3139
3140/* Returns the speed of a device attached to a port on the root hub. */
3141static inline unsigned int oxu_port_speed(struct oxu_hcd *oxu,
3142						unsigned int portsc)
3143{
3144	switch ((portsc >> 26) & 3) {
3145	case 0:
3146		return 0;
3147	case 1:
3148		return USB_PORT_STAT_LOW_SPEED;
3149	case 2:
3150	default:
3151		return USB_PORT_STAT_HIGH_SPEED;
3152	}
3153}
3154
3155#define	PORT_WAKE_BITS	(PORT_WKOC_E|PORT_WKDISC_E|PORT_WKCONN_E)
3156static int oxu_hub_control(struct usb_hcd *hcd, u16 typeReq,
3157				u16 wValue, u16 wIndex, char *buf, u16 wLength)
3158{
3159	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3160	int ports = HCS_N_PORTS(oxu->hcs_params);
3161	u32 __iomem *status_reg = &oxu->regs->port_status[wIndex - 1];
3162	u32 temp, status;
3163	unsigned long	flags;
3164	int retval = 0;
3165	unsigned selector;
3166
3167	/*
3168	 * FIXME:  support SetPortFeatures USB_PORT_FEAT_INDICATOR.
3169	 * HCS_INDICATOR may say we can change LEDs to off/amber/green.
3170	 * (track current state ourselves) ... blink for diagnostics,
3171	 * power, "this is the one", etc.  EHCI spec supports this.
3172	 */
3173
3174	spin_lock_irqsave(&oxu->lock, flags);
3175	switch (typeReq) {
3176	case ClearHubFeature:
3177		switch (wValue) {
3178		case C_HUB_LOCAL_POWER:
3179		case C_HUB_OVER_CURRENT:
3180			/* no hub-wide feature/status flags */
3181			break;
3182		default:
3183			goto error;
3184		}
3185		break;
3186	case ClearPortFeature:
3187		if (!wIndex || wIndex > ports)
3188			goto error;
3189		wIndex--;
3190		temp = readl(status_reg);
3191
3192		/*
3193		 * Even if OWNER is set, so the port is owned by the
3194		 * companion controller, khubd needs to be able to clear
3195		 * the port-change status bits (especially
3196		 * USB_PORT_STAT_C_CONNECTION).
3197		 */
3198
3199		switch (wValue) {
3200		case USB_PORT_FEAT_ENABLE:
3201			writel(temp & ~PORT_PE, status_reg);
3202			break;
3203		case USB_PORT_FEAT_C_ENABLE:
3204			writel((temp & ~PORT_RWC_BITS) | PORT_PEC, status_reg);
3205			break;
3206		case USB_PORT_FEAT_SUSPEND:
3207			if (temp & PORT_RESET)
3208				goto error;
3209			if (temp & PORT_SUSPEND) {
3210				if ((temp & PORT_PE) == 0)
3211					goto error;
3212				/* resume signaling for 20 msec */
3213				temp &= ~(PORT_RWC_BITS | PORT_WAKE_BITS);
3214				writel(temp | PORT_RESUME, status_reg);
3215				oxu->reset_done[wIndex] = jiffies
3216						+ msecs_to_jiffies(20);
3217			}
3218			break;
3219		case USB_PORT_FEAT_C_SUSPEND:
3220			/* we auto-clear this feature */
3221			break;
3222		case USB_PORT_FEAT_POWER:
3223			if (HCS_PPC(oxu->hcs_params))
3224				writel(temp & ~(PORT_RWC_BITS | PORT_POWER),
3225					  status_reg);
3226			break;
3227		case USB_PORT_FEAT_C_CONNECTION:
3228			writel((temp & ~PORT_RWC_BITS) | PORT_CSC, status_reg);
3229			break;
3230		case USB_PORT_FEAT_C_OVER_CURRENT:
3231			writel((temp & ~PORT_RWC_BITS) | PORT_OCC, status_reg);
3232			break;
3233		case USB_PORT_FEAT_C_RESET:
3234			/* GetPortStatus clears reset */
3235			break;
3236		default:
3237			goto error;
3238		}
3239		readl(&oxu->regs->command);	/* unblock posted write */
3240		break;
3241	case GetHubDescriptor:
3242		ehci_hub_descriptor(oxu, (struct usb_hub_descriptor *)
3243			buf);
3244		break;
3245	case GetHubStatus:
3246		/* no hub-wide feature/status flags */
3247		memset(buf, 0, 4);
3248		break;
3249	case GetPortStatus:
3250		if (!wIndex || wIndex > ports)
3251			goto error;
3252		wIndex--;
3253		status = 0;
3254		temp = readl(status_reg);
3255
3256		/* wPortChange bits */
3257		if (temp & PORT_CSC)
3258			status |= USB_PORT_STAT_C_CONNECTION << 16;
3259		if (temp & PORT_PEC)
3260			status |= USB_PORT_STAT_C_ENABLE << 16;
3261		if ((temp & PORT_OCC) && !ignore_oc)
3262			status |= USB_PORT_STAT_C_OVERCURRENT << 16;
3263
3264		/* whoever resumes must GetPortStatus to complete it!! */
3265		if (temp & PORT_RESUME) {
3266
3267			/* Remote Wakeup received? */
3268			if (!oxu->reset_done[wIndex]) {
3269				/* resume signaling for 20 msec */
3270				oxu->reset_done[wIndex] = jiffies
3271						+ msecs_to_jiffies(20);
3272				/* check the port again */
3273				mod_timer(&oxu_to_hcd(oxu)->rh_timer,
3274						oxu->reset_done[wIndex]);
3275			}
3276
3277			/* resume completed? */
3278			else if (time_after_eq(jiffies,
3279					oxu->reset_done[wIndex])) {
3280				status |= USB_PORT_STAT_C_SUSPEND << 16;
3281				oxu->reset_done[wIndex] = 0;
3282
3283				/* stop resume signaling */
3284				temp = readl(status_reg);
3285				writel(temp & ~(PORT_RWC_BITS | PORT_RESUME),
3286					status_reg);
3287				retval = handshake(oxu, status_reg,
3288					   PORT_RESUME, 0, 2000 /* 2msec */);
3289				if (retval != 0) {
3290					oxu_err(oxu,
3291						"port %d resume error %d\n",
3292						wIndex + 1, retval);
3293					goto error;
3294				}
3295				temp &= ~(PORT_SUSPEND|PORT_RESUME|(3<<10));
3296			}
3297		}
3298
3299		/* whoever resets must GetPortStatus to complete it!! */
3300		if ((temp & PORT_RESET)
3301				&& time_after_eq(jiffies,
3302					oxu->reset_done[wIndex])) {
3303			status |= USB_PORT_STAT_C_RESET << 16;
3304			oxu->reset_done[wIndex] = 0;
3305
3306			/* force reset to complete */
3307			writel(temp & ~(PORT_RWC_BITS | PORT_RESET),
3308					status_reg);
3309			/* REVISIT:  some hardware needs 550+ usec to clear
3310			 * this bit; seems too long to spin routinely...
3311			 */
3312			retval = handshake(oxu, status_reg,
3313					PORT_RESET, 0, 750);
3314			if (retval != 0) {
3315				oxu_err(oxu, "port %d reset error %d\n",
3316					wIndex + 1, retval);
3317				goto error;
3318			}
3319
3320			/* see what we found out */
3321			temp = check_reset_complete(oxu, wIndex, status_reg,
3322					readl(status_reg));
3323		}
3324
3325		/* transfer dedicated ports to the companion hc */
3326		if ((temp & PORT_CONNECT) &&
3327				test_bit(wIndex, &oxu->companion_ports)) {
3328			temp &= ~PORT_RWC_BITS;
3329			temp |= PORT_OWNER;
3330			writel(temp, status_reg);
3331			oxu_dbg(oxu, "port %d --> companion\n", wIndex + 1);
3332			temp = readl(status_reg);
3333		}
3334
3335		/*
3336		 * Even if OWNER is set, there's no harm letting khubd
3337		 * see the wPortStatus values (they should all be 0 except
3338		 * for PORT_POWER anyway).
3339		 */
3340
3341		if (temp & PORT_CONNECT) {
3342			status |= USB_PORT_STAT_CONNECTION;
3343			/* status may be from integrated TT */
3344			status |= oxu_port_speed(oxu, temp);
3345		}
3346		if (temp & PORT_PE)
3347			status |= USB_PORT_STAT_ENABLE;
3348		if (temp & (PORT_SUSPEND|PORT_RESUME))
3349			status |= USB_PORT_STAT_SUSPEND;
3350		if (temp & PORT_OC)
3351			status |= USB_PORT_STAT_OVERCURRENT;
3352		if (temp & PORT_RESET)
3353			status |= USB_PORT_STAT_RESET;
3354		if (temp & PORT_POWER)
3355			status |= USB_PORT_STAT_POWER;
3356
3357#ifndef	OXU_VERBOSE_DEBUG
3358	if (status & ~0xffff)	/* only if wPortChange is interesting */
3359#endif
3360		dbg_port(oxu, "GetStatus", wIndex + 1, temp);
3361		put_unaligned(cpu_to_le32(status), (__le32 *) buf);
3362		break;
3363	case SetHubFeature:
3364		switch (wValue) {
3365		case C_HUB_LOCAL_POWER:
3366		case C_HUB_OVER_CURRENT:
3367			/* no hub-wide feature/status flags */
3368			break;
3369		default:
3370			goto error;
3371		}
3372		break;
3373	case SetPortFeature:
3374		selector = wIndex >> 8;
3375		wIndex &= 0xff;
3376		if (!wIndex || wIndex > ports)
3377			goto error;
3378		wIndex--;
3379		temp = readl(status_reg);
3380		if (temp & PORT_OWNER)
3381			break;
3382
3383		temp &= ~PORT_RWC_BITS;
3384		switch (wValue) {
3385		case USB_PORT_FEAT_SUSPEND:
3386			if ((temp & PORT_PE) == 0
3387					|| (temp & PORT_RESET) != 0)
3388				goto error;
3389			if (device_may_wakeup(&hcd->self.root_hub->dev))
3390				temp |= PORT_WAKE_BITS;
3391			writel(temp | PORT_SUSPEND, status_reg);
3392			break;
3393		case USB_PORT_FEAT_POWER:
3394			if (HCS_PPC(oxu->hcs_params))
3395				writel(temp | PORT_POWER, status_reg);
3396			break;
3397		case USB_PORT_FEAT_RESET:
3398			if (temp & PORT_RESUME)
3399				goto error;
3400			/* line status bits may report this as low speed,
3401			 * which can be fine if this root hub has a
3402			 * transaction translator built in.
3403			 */
3404			oxu_vdbg(oxu, "port %d reset\n", wIndex + 1);
3405			temp |= PORT_RESET;
3406			temp &= ~PORT_PE;
3407
3408			/*
3409			 * caller must wait, then call GetPortStatus
3410			 * usb 2.0 spec says 50 ms resets on root
3411			 */
3412			oxu->reset_done[wIndex] = jiffies
3413					+ msecs_to_jiffies(50);
3414			writel(temp, status_reg);
3415			break;
3416
3417		/* For downstream facing ports (these):  one hub port is put
3418		 * into test mode according to USB2 11.24.2.13, then the hub
3419		 * must be reset (which for root hub now means rmmod+modprobe,
3420		 * or else system reboot).  See EHCI 2.3.9 and 4.14 for info
3421		 * about the EHCI-specific stuff.
3422		 */
3423		case USB_PORT_FEAT_TEST:
3424			if (!selector || selector > 5)
3425				goto error;
3426			ehci_quiesce(oxu);
3427			ehci_halt(oxu);
3428			temp |= selector << 16;
3429			writel(temp, status_reg);
3430			break;
3431
3432		default:
3433			goto error;
3434		}
3435		readl(&oxu->regs->command);	/* unblock posted writes */
3436		break;
3437
3438	default:
3439error:
3440		/* "stall" on error */
3441		retval = -EPIPE;
3442	}
3443	spin_unlock_irqrestore(&oxu->lock, flags);
3444	return retval;
3445}
3446
3447#ifdef CONFIG_PM
3448
3449static int oxu_bus_suspend(struct usb_hcd *hcd)
3450{
3451	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3452	int port;
3453	int mask;
3454
3455	oxu_dbg(oxu, "suspend root hub\n");
3456
3457	if (time_before(jiffies, oxu->next_statechange))
3458		msleep(5);
3459
3460	port = HCS_N_PORTS(oxu->hcs_params);
3461	spin_lock_irq(&oxu->lock);
3462
3463	/* stop schedules, clean any completed work */
3464	if (HC_IS_RUNNING(hcd->state)) {
3465		ehci_quiesce(oxu);
3466		hcd->state = HC_STATE_QUIESCING;
3467	}
3468	oxu->command = readl(&oxu->regs->command);
3469	if (oxu->reclaim)
3470		oxu->reclaim_ready = 1;
3471	ehci_work(oxu);
3472
3473	/* Unlike other USB host controller types, EHCI doesn't have
3474	 * any notion of "global" or bus-wide suspend.  The driver has
3475	 * to manually suspend all the active unsuspended ports, and
3476	 * then manually resume them in the bus_resume() routine.
3477	 */
3478	oxu->bus_suspended = 0;
3479	while (port--) {
3480		u32 __iomem *reg = &oxu->regs->port_status[port];
3481		u32 t1 = readl(reg) & ~PORT_RWC_BITS;
3482		u32 t2 = t1;
3483
3484		/* keep track of which ports we suspend */
3485		if ((t1 & PORT_PE) && !(t1 & PORT_OWNER) &&
3486				!(t1 & PORT_SUSPEND)) {
3487			t2 |= PORT_SUSPEND;
3488			set_bit(port, &oxu->bus_suspended);
3489		}
3490
3491		/* enable remote wakeup on all ports */
3492		if (device_may_wakeup(&hcd->self.root_hub->dev))
3493			t2 |= PORT_WKOC_E|PORT_WKDISC_E|PORT_WKCONN_E;
3494		else
3495			t2 &= ~(PORT_WKOC_E|PORT_WKDISC_E|PORT_WKCONN_E);
3496
3497		if (t1 != t2) {
3498			oxu_vdbg(oxu, "port %d, %08x -> %08x\n",
3499				port + 1, t1, t2);
3500			writel(t2, reg);
3501		}
3502	}
3503
3504	/* turn off now-idle HC */
3505	del_timer_sync(&oxu->watchdog);
3506	ehci_halt(oxu);
3507	hcd->state = HC_STATE_SUSPENDED;
3508
3509	/* allow remote wakeup */
3510	mask = INTR_MASK;
3511	if (!device_may_wakeup(&hcd->self.root_hub->dev))
3512		mask &= ~STS_PCD;
3513	writel(mask, &oxu->regs->intr_enable);
3514	readl(&oxu->regs->intr_enable);
3515
3516	oxu->next_statechange = jiffies + msecs_to_jiffies(10);
3517	spin_unlock_irq(&oxu->lock);
3518	return 0;
3519}
3520
3521/* Caller has locked the root hub, and should reset/reinit on error */
3522static int oxu_bus_resume(struct usb_hcd *hcd)
3523{
3524	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3525	u32 temp;
3526	int i;
3527
3528	if (time_before(jiffies, oxu->next_statechange))
3529		msleep(5);
3530	spin_lock_irq(&oxu->lock);
3531
3532	/* Ideally and we've got a real resume here, and no port's power
3533	 * was lost.  (For PCI, that means Vaux was maintained.)  But we
3534	 * could instead be restoring a swsusp snapshot -- so that BIOS was
3535	 * the last user of the controller, not reset/pm hardware keeping
3536	 * state we gave to it.
3537	 */
3538	temp = readl(&oxu->regs->intr_enable);
3539	oxu_dbg(oxu, "resume root hub%s\n", temp ? "" : " after power loss");
3540
3541	/* at least some APM implementations will try to deliver
3542	 * IRQs right away, so delay them until we're ready.
3543	 */
3544	writel(0, &oxu->regs->intr_enable);
3545
3546	/* re-init operational registers */
3547	writel(0, &oxu->regs->segment);
3548	writel(oxu->periodic_dma, &oxu->regs->frame_list);
3549	writel((u32) oxu->async->qh_dma, &oxu->regs->async_next);
3550
3551	/* restore CMD_RUN, framelist size, and irq threshold */
3552	writel(oxu->command, &oxu->regs->command);
3553
3554	/* Some controller/firmware combinations need a delay during which
3555	 * they set up the port statuses.  See Bugzilla #8190. */
3556	mdelay(8);
3557
3558	/* manually resume the ports we suspended during bus_suspend() */
3559	i = HCS_N_PORTS(oxu->hcs_params);
3560	while (i--) {
3561		temp = readl(&oxu->regs->port_status[i]);
3562		temp &= ~(PORT_RWC_BITS
3563			| PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E);
3564		if (test_bit(i, &oxu->bus_suspended) && (temp & PORT_SUSPEND)) {
3565			oxu->reset_done[i] = jiffies + msecs_to_jiffies(20);
3566			temp |= PORT_RESUME;
3567		}
3568		writel(temp, &oxu->regs->port_status[i]);
3569	}
3570	i = HCS_N_PORTS(oxu->hcs_params);
3571	mdelay(20);
3572	while (i--) {
3573		temp = readl(&oxu->regs->port_status[i]);
3574		if (test_bit(i, &oxu->bus_suspended) && (temp & PORT_SUSPEND)) {
3575			temp &= ~(PORT_RWC_BITS | PORT_RESUME);
3576			writel(temp, &oxu->regs->port_status[i]);
3577			oxu_vdbg(oxu, "resumed port %d\n", i + 1);
3578		}
3579	}
3580	(void) readl(&oxu->regs->command);
3581
3582	/* maybe re-activate the schedule(s) */
3583	temp = 0;
3584	if (oxu->async->qh_next.qh)
3585		temp |= CMD_ASE;
3586	if (oxu->periodic_sched)
3587		temp |= CMD_PSE;
3588	if (temp) {
3589		oxu->command |= temp;
3590		writel(oxu->command, &oxu->regs->command);
3591	}
3592
3593	oxu->next_statechange = jiffies + msecs_to_jiffies(5);
3594	hcd->state = HC_STATE_RUNNING;
3595
3596	/* Now we can safely re-enable irqs */
3597	writel(INTR_MASK, &oxu->regs->intr_enable);
3598
3599	spin_unlock_irq(&oxu->lock);
3600	return 0;
3601}
3602
3603#else
3604
3605static int oxu_bus_suspend(struct usb_hcd *hcd)
3606{
3607	return 0;
3608}
3609
3610static int oxu_bus_resume(struct usb_hcd *hcd)
3611{
3612	return 0;
3613}
3614
3615#endif	/* CONFIG_PM */
3616
3617static const struct hc_driver oxu_hc_driver = {
3618	.description =		"oxu210hp_hcd",
3619	.product_desc =		"oxu210hp HCD",
3620	.hcd_priv_size =	sizeof(struct oxu_hcd),
3621
3622	/*
3623	 * Generic hardware linkage
3624	 */
3625	.irq =			oxu_irq,
3626	.flags =		HCD_MEMORY | HCD_USB2,
3627
3628	/*
3629	 * Basic lifecycle operations
3630	 */
3631	.reset =		oxu_reset,
3632	.start =		oxu_run,
3633	.stop =			oxu_stop,
3634	.shutdown =		oxu_shutdown,
3635
3636	/*
3637	 * Managing i/o requests and associated device resources
3638	 */
3639	.urb_enqueue =		oxu_urb_enqueue,
3640	.urb_dequeue =		oxu_urb_dequeue,
3641	.endpoint_disable =	oxu_endpoint_disable,
3642
3643	/*
3644	 * Scheduling support
3645	 */
3646	.get_frame_number =	oxu_get_frame,
3647
3648	/*
3649	 * Root hub support
3650	 */
3651	.hub_status_data =	oxu_hub_status_data,
3652	.hub_control =		oxu_hub_control,
3653	.bus_suspend =		oxu_bus_suspend,
3654	.bus_resume =		oxu_bus_resume,
3655};
3656
3657/*
3658 * Module stuff
3659 */
3660
3661static void oxu_configuration(struct platform_device *pdev, void *base)
3662{
3663	u32 tmp;
3664
3665	/* Initialize top level registers.
3666	 * First write ever
3667	 */
3668	oxu_writel(base, OXU_HOSTIFCONFIG, 0x0000037D);
3669	oxu_writel(base, OXU_SOFTRESET, OXU_SRESET);
3670	oxu_writel(base, OXU_HOSTIFCONFIG, 0x0000037D);
3671
3672	tmp = oxu_readl(base, OXU_PIOBURSTREADCTRL);
3673	oxu_writel(base, OXU_PIOBURSTREADCTRL, tmp | 0x0040);
3674
3675	oxu_writel(base, OXU_ASO, OXU_SPHPOEN | OXU_OVRCCURPUPDEN |
3676					OXU_COMPARATOR | OXU_ASO_OP);
3677
3678	tmp = oxu_readl(base, OXU_CLKCTRL_SET);
3679	oxu_writel(base, OXU_CLKCTRL_SET, tmp | OXU_SYSCLKEN | OXU_USBOTGCLKEN);
3680
3681	/* Clear all top interrupt enable */
3682	oxu_writel(base, OXU_CHIPIRQEN_CLR, 0xff);
3683
3684	/* Clear all top interrupt status */
3685	oxu_writel(base, OXU_CHIPIRQSTATUS, 0xff);
3686
3687	/* Enable all needed top interrupt except OTG SPH core */
3688	oxu_writel(base, OXU_CHIPIRQEN_SET, OXU_USBSPHLPWUI | OXU_USBOTGLPWUI);
3689}
3690
3691static int oxu_verify_id(struct platform_device *pdev, void *base)
3692{
3693	u32 id;
3694	static const char * const bo[] = {
3695		"reserved",
3696		"128-pin LQFP",
3697		"84-pin TFBGA",
3698		"reserved",
3699	};
3700
3701	/* Read controller signature register to find a match */
3702	id = oxu_readl(base, OXU_DEVICEID);
3703	dev_info(&pdev->dev, "device ID %x\n", id);
3704	if ((id & OXU_REV_MASK) != (OXU_REV_2100 << OXU_REV_SHIFT))
3705		return -1;
3706
3707	dev_info(&pdev->dev, "found device %x %s (%04x:%04x)\n",
3708		id >> OXU_REV_SHIFT,
3709		bo[(id & OXU_BO_MASK) >> OXU_BO_SHIFT],
3710		(id & OXU_MAJ_REV_MASK) >> OXU_MAJ_REV_SHIFT,
3711		(id & OXU_MIN_REV_MASK) >> OXU_MIN_REV_SHIFT);
3712
3713	return 0;
3714}
3715
3716static const struct hc_driver oxu_hc_driver;
3717static struct usb_hcd *oxu_create(struct platform_device *pdev,
3718				unsigned long memstart, unsigned long memlen,
3719				void *base, int irq, int otg)
3720{
3721	struct device *dev = &pdev->dev;
3722
3723	struct usb_hcd *hcd;
3724	struct oxu_hcd *oxu;
3725	int ret;
3726
3727	/* Set endian mode and host mode */
3728	oxu_writel(base + (otg ? OXU_OTG_CORE_OFFSET : OXU_SPH_CORE_OFFSET),
3729				OXU_USBMODE,
3730				OXU_CM_HOST_ONLY | OXU_ES_LITTLE | OXU_VBPS);
3731
3732	hcd = usb_create_hcd(&oxu_hc_driver, dev,
3733				otg ? "oxu210hp_otg" : "oxu210hp_sph");
3734	if (!hcd)
3735		return ERR_PTR(-ENOMEM);
3736
3737	hcd->rsrc_start = memstart;
3738	hcd->rsrc_len = memlen;
3739	hcd->regs = base;
3740	hcd->irq = irq;
3741	hcd->state = HC_STATE_HALT;
3742
3743	oxu = hcd_to_oxu(hcd);
3744	oxu->is_otg = otg;
3745
3746	ret = usb_add_hcd(hcd, irq, IRQF_SHARED);
3747	if (ret < 0)
3748		return ERR_PTR(ret);
3749
 
3750	return hcd;
3751}
3752
3753static int oxu_init(struct platform_device *pdev,
3754				unsigned long memstart, unsigned long memlen,
3755				void *base, int irq)
3756{
3757	struct oxu_info *info = platform_get_drvdata(pdev);
3758	struct usb_hcd *hcd;
3759	int ret;
3760
3761	/* First time configuration at start up */
3762	oxu_configuration(pdev, base);
3763
3764	ret = oxu_verify_id(pdev, base);
3765	if (ret) {
3766		dev_err(&pdev->dev, "no devices found!\n");
3767		return -ENODEV;
3768	}
3769
3770	/* Create the OTG controller */
3771	hcd = oxu_create(pdev, memstart, memlen, base, irq, 1);
3772	if (IS_ERR(hcd)) {
3773		dev_err(&pdev->dev, "cannot create OTG controller!\n");
3774		ret = PTR_ERR(hcd);
3775		goto error_create_otg;
3776	}
3777	info->hcd[0] = hcd;
3778
3779	/* Create the SPH host controller */
3780	hcd = oxu_create(pdev, memstart, memlen, base, irq, 0);
3781	if (IS_ERR(hcd)) {
3782		dev_err(&pdev->dev, "cannot create SPH controller!\n");
3783		ret = PTR_ERR(hcd);
3784		goto error_create_sph;
3785	}
3786	info->hcd[1] = hcd;
3787
3788	oxu_writel(base, OXU_CHIPIRQEN_SET,
3789		oxu_readl(base, OXU_CHIPIRQEN_SET) | 3);
3790
3791	return 0;
3792
3793error_create_sph:
3794	usb_remove_hcd(info->hcd[0]);
3795	usb_put_hcd(info->hcd[0]);
3796
3797error_create_otg:
3798	return ret;
3799}
3800
3801static int oxu_drv_probe(struct platform_device *pdev)
3802{
3803	struct resource *res;
3804	void *base;
3805	unsigned long memstart, memlen;
3806	int irq, ret;
3807	struct oxu_info *info;
3808
3809	if (usb_disabled())
3810		return -ENODEV;
3811
3812	/*
3813	 * Get the platform resources
3814	 */
3815	res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
3816	if (!res) {
3817		dev_err(&pdev->dev,
3818			"no IRQ! Check %s setup!\n", dev_name(&pdev->dev));
3819		return -ENODEV;
3820	}
3821	irq = res->start;
3822	dev_dbg(&pdev->dev, "IRQ resource %d\n", irq);
3823
3824	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
3825	if (!res) {
3826		dev_err(&pdev->dev, "no registers address! Check %s setup!\n",
3827			dev_name(&pdev->dev));
3828		return -ENODEV;
3829	}
3830	memstart = res->start;
3831	memlen = resource_size(res);
3832	dev_dbg(&pdev->dev, "MEM resource %lx-%lx\n", memstart, memlen);
3833	if (!request_mem_region(memstart, memlen,
3834				oxu_hc_driver.description)) {
3835		dev_dbg(&pdev->dev, "memory area already in use\n");
3836		return -EBUSY;
3837	}
3838
3839	ret = irq_set_irq_type(irq, IRQF_TRIGGER_FALLING);
3840	if (ret) {
3841		dev_err(&pdev->dev, "error setting irq type\n");
3842		ret = -EFAULT;
3843		goto error_set_irq_type;
3844	}
3845
3846	base = ioremap(memstart, memlen);
3847	if (!base) {
3848		dev_dbg(&pdev->dev, "error mapping memory\n");
3849		ret = -EFAULT;
3850		goto error_ioremap;
3851	}
3852
3853	/* Allocate a driver data struct to hold useful info for both
3854	 * SPH & OTG devices
3855	 */
3856	info = kzalloc(sizeof(struct oxu_info), GFP_KERNEL);
3857	if (!info) {
3858		dev_dbg(&pdev->dev, "error allocating memory\n");
3859		ret = -EFAULT;
3860		goto error_alloc;
3861	}
3862	platform_set_drvdata(pdev, info);
3863
3864	ret = oxu_init(pdev, memstart, memlen, base, irq);
3865	if (ret < 0) {
3866		dev_dbg(&pdev->dev, "cannot init USB devices\n");
3867		goto error_init;
3868	}
3869
3870	dev_info(&pdev->dev, "devices enabled and running\n");
3871	platform_set_drvdata(pdev, info);
3872
3873	return 0;
3874
3875error_init:
3876	kfree(info);
3877	platform_set_drvdata(pdev, NULL);
3878
3879error_alloc:
3880	iounmap(base);
3881
3882error_set_irq_type:
3883error_ioremap:
3884	release_mem_region(memstart, memlen);
3885
3886	dev_err(&pdev->dev, "init %s fail, %d\n", dev_name(&pdev->dev), ret);
3887	return ret;
3888}
3889
3890static void oxu_remove(struct platform_device *pdev, struct usb_hcd *hcd)
3891{
3892	usb_remove_hcd(hcd);
3893	usb_put_hcd(hcd);
3894}
3895
3896static int oxu_drv_remove(struct platform_device *pdev)
3897{
3898	struct oxu_info *info = platform_get_drvdata(pdev);
3899	unsigned long memstart = info->hcd[0]->rsrc_start,
3900			memlen = info->hcd[0]->rsrc_len;
3901	void *base = info->hcd[0]->regs;
3902
3903	oxu_remove(pdev, info->hcd[0]);
3904	oxu_remove(pdev, info->hcd[1]);
3905
3906	iounmap(base);
3907	release_mem_region(memstart, memlen);
3908
3909	kfree(info);
3910	platform_set_drvdata(pdev, NULL);
3911
3912	return 0;
3913}
3914
3915static void oxu_drv_shutdown(struct platform_device *pdev)
3916{
3917	oxu_drv_remove(pdev);
3918}
3919
3920#if 0
3921/* FIXME: TODO */
3922static int oxu_drv_suspend(struct device *dev)
3923{
3924	struct platform_device *pdev = to_platform_device(dev);
3925	struct usb_hcd *hcd = dev_get_drvdata(dev);
3926
3927	return 0;
3928}
3929
3930static int oxu_drv_resume(struct device *dev)
3931{
3932	struct platform_device *pdev = to_platform_device(dev);
3933	struct usb_hcd *hcd = dev_get_drvdata(dev);
3934
3935	return 0;
3936}
3937#else
3938#define oxu_drv_suspend	NULL
3939#define oxu_drv_resume	NULL
3940#endif
3941
3942static struct platform_driver oxu_driver = {
3943	.probe		= oxu_drv_probe,
3944	.remove		= oxu_drv_remove,
3945	.shutdown	= oxu_drv_shutdown,
3946	.suspend	= oxu_drv_suspend,
3947	.resume		= oxu_drv_resume,
3948	.driver = {
3949		.name = "oxu210hp-hcd",
3950		.bus = &platform_bus_type
3951	}
3952};
3953
3954static int __init oxu_module_init(void)
3955{
3956	int retval = 0;
3957
3958	retval = platform_driver_register(&oxu_driver);
3959	if (retval < 0)
3960		return retval;
3961
3962	return retval;
3963}
3964
3965static void __exit oxu_module_cleanup(void)
3966{
3967	platform_driver_unregister(&oxu_driver);
3968}
3969
3970module_init(oxu_module_init);
3971module_exit(oxu_module_cleanup);
3972
3973MODULE_DESCRIPTION("Oxford OXU210HP HCD driver - ver. " DRIVER_VERSION);
3974MODULE_AUTHOR("Rodolfo Giometti <giometti@linux.it>");
3975MODULE_LICENSE("GPL");
v3.15
   1/*
   2 * Copyright (c) 2008 Rodolfo Giometti <giometti@linux.it>
   3 * Copyright (c) 2008 Eurotech S.p.A. <info@eurtech.it>
   4 *
   5 * This code is *strongly* based on EHCI-HCD code by David Brownell since
   6 * the chip is a quasi-EHCI compatible.
   7 *
   8 * This program is free software; you can redistribute it and/or modify it
   9 * under the terms of the GNU General Public License as published by the
  10 * Free Software Foundation; either version 2 of the License, or (at your
  11 * option) any later version.
  12 *
  13 * This program is distributed in the hope that it will be useful, but
  14 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  15 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  16 * for more details.
  17 *
  18 * You should have received a copy of the GNU General Public License
  19 * along with this program; if not, write to the Free Software Foundation,
  20 * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  21 */
  22
  23#include <linux/module.h>
  24#include <linux/pci.h>
  25#include <linux/dmapool.h>
  26#include <linux/kernel.h>
  27#include <linux/delay.h>
  28#include <linux/ioport.h>
  29#include <linux/sched.h>
  30#include <linux/slab.h>
  31#include <linux/errno.h>
 
  32#include <linux/timer.h>
  33#include <linux/list.h>
  34#include <linux/interrupt.h>
  35#include <linux/usb.h>
  36#include <linux/usb/hcd.h>
  37#include <linux/moduleparam.h>
  38#include <linux/dma-mapping.h>
  39#include <linux/io.h>
  40
  41#include <asm/irq.h>
 
  42#include <asm/unaligned.h>
  43
  44#include <linux/irq.h>
  45#include <linux/platform_device.h>
  46
  47#include "oxu210hp.h"
  48
  49#define DRIVER_VERSION "0.0.50"
  50
  51/*
  52 * Main defines
  53 */
  54
  55#define oxu_dbg(oxu, fmt, args...) \
  56		dev_dbg(oxu_to_hcd(oxu)->self.controller , fmt , ## args)
  57#define oxu_err(oxu, fmt, args...) \
  58		dev_err(oxu_to_hcd(oxu)->self.controller , fmt , ## args)
  59#define oxu_info(oxu, fmt, args...) \
  60		dev_info(oxu_to_hcd(oxu)->self.controller , fmt , ## args)
  61
  62#ifdef CONFIG_DYNAMIC_DEBUG
  63#define DEBUG
  64#endif
  65
  66static inline struct usb_hcd *oxu_to_hcd(struct oxu_hcd *oxu)
  67{
  68	return container_of((void *) oxu, struct usb_hcd, hcd_priv);
  69}
  70
  71static inline struct oxu_hcd *hcd_to_oxu(struct usb_hcd *hcd)
  72{
  73	return (struct oxu_hcd *) (hcd->hcd_priv);
  74}
  75
  76/*
  77 * Debug stuff
  78 */
  79
  80#undef OXU_URB_TRACE
  81#undef OXU_VERBOSE_DEBUG
  82
  83#ifdef OXU_VERBOSE_DEBUG
  84#define oxu_vdbg			oxu_dbg
  85#else
  86#define oxu_vdbg(oxu, fmt, args...)	/* Nop */
  87#endif
  88
  89#ifdef DEBUG
  90
  91static int __attribute__((__unused__))
  92dbg_status_buf(char *buf, unsigned len, const char *label, u32 status)
  93{
  94	return scnprintf(buf, len, "%s%sstatus %04x%s%s%s%s%s%s%s%s%s%s",
  95		label, label[0] ? " " : "", status,
  96		(status & STS_ASS) ? " Async" : "",
  97		(status & STS_PSS) ? " Periodic" : "",
  98		(status & STS_RECL) ? " Recl" : "",
  99		(status & STS_HALT) ? " Halt" : "",
 100		(status & STS_IAA) ? " IAA" : "",
 101		(status & STS_FATAL) ? " FATAL" : "",
 102		(status & STS_FLR) ? " FLR" : "",
 103		(status & STS_PCD) ? " PCD" : "",
 104		(status & STS_ERR) ? " ERR" : "",
 105		(status & STS_INT) ? " INT" : ""
 106		);
 107}
 108
 109static int __attribute__((__unused__))
 110dbg_intr_buf(char *buf, unsigned len, const char *label, u32 enable)
 111{
 112	return scnprintf(buf, len, "%s%sintrenable %02x%s%s%s%s%s%s",
 113		label, label[0] ? " " : "", enable,
 114		(enable & STS_IAA) ? " IAA" : "",
 115		(enable & STS_FATAL) ? " FATAL" : "",
 116		(enable & STS_FLR) ? " FLR" : "",
 117		(enable & STS_PCD) ? " PCD" : "",
 118		(enable & STS_ERR) ? " ERR" : "",
 119		(enable & STS_INT) ? " INT" : ""
 120		);
 121}
 122
 123static const char *const fls_strings[] =
 124    { "1024", "512", "256", "??" };
 125
 126static int dbg_command_buf(char *buf, unsigned len,
 127				const char *label, u32 command)
 128{
 129	return scnprintf(buf, len,
 130		"%s%scommand %06x %s=%d ithresh=%d%s%s%s%s period=%s%s %s",
 131		label, label[0] ? " " : "", command,
 132		(command & CMD_PARK) ? "park" : "(park)",
 133		CMD_PARK_CNT(command),
 134		(command >> 16) & 0x3f,
 135		(command & CMD_LRESET) ? " LReset" : "",
 136		(command & CMD_IAAD) ? " IAAD" : "",
 137		(command & CMD_ASE) ? " Async" : "",
 138		(command & CMD_PSE) ? " Periodic" : "",
 139		fls_strings[(command >> 2) & 0x3],
 140		(command & CMD_RESET) ? " Reset" : "",
 141		(command & CMD_RUN) ? "RUN" : "HALT"
 142		);
 143}
 144
 145static int dbg_port_buf(char *buf, unsigned len, const char *label,
 146				int port, u32 status)
 147{
 148	char	*sig;
 149
 150	/* signaling state */
 151	switch (status & (3 << 10)) {
 152	case 0 << 10:
 153		sig = "se0";
 154		break;
 155	case 1 << 10:
 156		sig = "k";	/* low speed */
 157		break;
 158	case 2 << 10:
 159		sig = "j";
 160		break;
 161	default:
 162		sig = "?";
 163		break;
 164	}
 165
 166	return scnprintf(buf, len,
 167		"%s%sport %d status %06x%s%s sig=%s%s%s%s%s%s%s%s%s%s",
 168		label, label[0] ? " " : "", port, status,
 169		(status & PORT_POWER) ? " POWER" : "",
 170		(status & PORT_OWNER) ? " OWNER" : "",
 171		sig,
 172		(status & PORT_RESET) ? " RESET" : "",
 173		(status & PORT_SUSPEND) ? " SUSPEND" : "",
 174		(status & PORT_RESUME) ? " RESUME" : "",
 175		(status & PORT_OCC) ? " OCC" : "",
 176		(status & PORT_OC) ? " OC" : "",
 177		(status & PORT_PEC) ? " PEC" : "",
 178		(status & PORT_PE) ? " PE" : "",
 179		(status & PORT_CSC) ? " CSC" : "",
 180		(status & PORT_CONNECT) ? " CONNECT" : ""
 181	    );
 182}
 183
 184#else
 185
 186static inline int __attribute__((__unused__))
 187dbg_status_buf(char *buf, unsigned len, const char *label, u32 status)
 188{ return 0; }
 189
 190static inline int __attribute__((__unused__))
 191dbg_command_buf(char *buf, unsigned len, const char *label, u32 command)
 192{ return 0; }
 193
 194static inline int __attribute__((__unused__))
 195dbg_intr_buf(char *buf, unsigned len, const char *label, u32 enable)
 196{ return 0; }
 197
 198static inline int __attribute__((__unused__))
 199dbg_port_buf(char *buf, unsigned len, const char *label, int port, u32 status)
 200{ return 0; }
 201
 202#endif /* DEBUG */
 203
 204/* functions have the "wrong" filename when they're output... */
 205#define dbg_status(oxu, label, status) { \
 206	char _buf[80]; \
 207	dbg_status_buf(_buf, sizeof _buf, label, status); \
 208	oxu_dbg(oxu, "%s\n", _buf); \
 209}
 210
 211#define dbg_cmd(oxu, label, command) { \
 212	char _buf[80]; \
 213	dbg_command_buf(_buf, sizeof _buf, label, command); \
 214	oxu_dbg(oxu, "%s\n", _buf); \
 215}
 216
 217#define dbg_port(oxu, label, port, status) { \
 218	char _buf[80]; \
 219	dbg_port_buf(_buf, sizeof _buf, label, port, status); \
 220	oxu_dbg(oxu, "%s\n", _buf); \
 221}
 222
 223/*
 224 * Module parameters
 225 */
 226
 227/* Initial IRQ latency: faster than hw default */
 228static int log2_irq_thresh;			/* 0 to 6 */
 229module_param(log2_irq_thresh, int, S_IRUGO);
 230MODULE_PARM_DESC(log2_irq_thresh, "log2 IRQ latency, 1-64 microframes");
 231
 232/* Initial park setting: slower than hw default */
 233static unsigned park;
 234module_param(park, uint, S_IRUGO);
 235MODULE_PARM_DESC(park, "park setting; 1-3 back-to-back async packets");
 236
 237/* For flakey hardware, ignore overcurrent indicators */
 238static bool ignore_oc;
 239module_param(ignore_oc, bool, S_IRUGO);
 240MODULE_PARM_DESC(ignore_oc, "ignore bogus hardware overcurrent indications");
 241
 242
 243static void ehci_work(struct oxu_hcd *oxu);
 244static int oxu_hub_control(struct usb_hcd *hcd,
 245				u16 typeReq, u16 wValue, u16 wIndex,
 246				char *buf, u16 wLength);
 247
 248/*
 249 * Local functions
 250 */
 251
 252/* Low level read/write registers functions */
 253static inline u32 oxu_readl(void *base, u32 reg)
 254{
 255	return readl(base + reg);
 256}
 257
 258static inline void oxu_writel(void *base, u32 reg, u32 val)
 259{
 260	writel(val, base + reg);
 261}
 262
 263static inline void timer_action_done(struct oxu_hcd *oxu,
 264					enum ehci_timer_action action)
 265{
 266	clear_bit(action, &oxu->actions);
 267}
 268
 269static inline void timer_action(struct oxu_hcd *oxu,
 270					enum ehci_timer_action action)
 271{
 272	if (!test_and_set_bit(action, &oxu->actions)) {
 273		unsigned long t;
 274
 275		switch (action) {
 276		case TIMER_IAA_WATCHDOG:
 277			t = EHCI_IAA_JIFFIES;
 278			break;
 279		case TIMER_IO_WATCHDOG:
 280			t = EHCI_IO_JIFFIES;
 281			break;
 282		case TIMER_ASYNC_OFF:
 283			t = EHCI_ASYNC_JIFFIES;
 284			break;
 285		case TIMER_ASYNC_SHRINK:
 286		default:
 287			t = EHCI_SHRINK_JIFFIES;
 288			break;
 289		}
 290		t += jiffies;
 291		/* all timings except IAA watchdog can be overridden.
 292		 * async queue SHRINK often precedes IAA.  while it's ready
 293		 * to go OFF neither can matter, and afterwards the IO
 294		 * watchdog stops unless there's still periodic traffic.
 295		 */
 296		if (action != TIMER_IAA_WATCHDOG
 297				&& t > oxu->watchdog.expires
 298				&& timer_pending(&oxu->watchdog))
 299			return;
 300		mod_timer(&oxu->watchdog, t);
 301	}
 302}
 303
 304/*
 305 * handshake - spin reading hc until handshake completes or fails
 306 * @ptr: address of hc register to be read
 307 * @mask: bits to look at in result of read
 308 * @done: value of those bits when handshake succeeds
 309 * @usec: timeout in microseconds
 310 *
 311 * Returns negative errno, or zero on success
 312 *
 313 * Success happens when the "mask" bits have the specified value (hardware
 314 * handshake done).  There are two failure modes:  "usec" have passed (major
 315 * hardware flakeout), or the register reads as all-ones (hardware removed).
 316 *
 317 * That last failure should_only happen in cases like physical cardbus eject
 318 * before driver shutdown. But it also seems to be caused by bugs in cardbus
 319 * bridge shutdown:  shutting down the bridge before the devices using it.
 320 */
 321static int handshake(struct oxu_hcd *oxu, void __iomem *ptr,
 322					u32 mask, u32 done, int usec)
 323{
 324	u32 result;
 325
 326	do {
 327		result = readl(ptr);
 328		if (result == ~(u32)0)		/* card removed */
 329			return -ENODEV;
 330		result &= mask;
 331		if (result == done)
 332			return 0;
 333		udelay(1);
 334		usec--;
 335	} while (usec > 0);
 336	return -ETIMEDOUT;
 337}
 338
 339/* Force HC to halt state from unknown (EHCI spec section 2.3) */
 340static int ehci_halt(struct oxu_hcd *oxu)
 341{
 342	u32	temp = readl(&oxu->regs->status);
 343
 344	/* disable any irqs left enabled by previous code */
 345	writel(0, &oxu->regs->intr_enable);
 346
 347	if ((temp & STS_HALT) != 0)
 348		return 0;
 349
 350	temp = readl(&oxu->regs->command);
 351	temp &= ~CMD_RUN;
 352	writel(temp, &oxu->regs->command);
 353	return handshake(oxu, &oxu->regs->status,
 354			  STS_HALT, STS_HALT, 16 * 125);
 355}
 356
 357/* Put TDI/ARC silicon into EHCI mode */
 358static void tdi_reset(struct oxu_hcd *oxu)
 359{
 360	u32 __iomem *reg_ptr;
 361	u32 tmp;
 362
 363	reg_ptr = (u32 __iomem *)(((u8 __iomem *)oxu->regs) + 0x68);
 364	tmp = readl(reg_ptr);
 365	tmp |= 0x3;
 366	writel(tmp, reg_ptr);
 367}
 368
 369/* Reset a non-running (STS_HALT == 1) controller */
 370static int ehci_reset(struct oxu_hcd *oxu)
 371{
 372	int	retval;
 373	u32	command = readl(&oxu->regs->command);
 374
 375	command |= CMD_RESET;
 376	dbg_cmd(oxu, "reset", command);
 377	writel(command, &oxu->regs->command);
 378	oxu_to_hcd(oxu)->state = HC_STATE_HALT;
 379	oxu->next_statechange = jiffies;
 380	retval = handshake(oxu, &oxu->regs->command,
 381			    CMD_RESET, 0, 250 * 1000);
 382
 383	if (retval)
 384		return retval;
 385
 386	tdi_reset(oxu);
 387
 388	return retval;
 389}
 390
 391/* Idle the controller (from running) */
 392static void ehci_quiesce(struct oxu_hcd *oxu)
 393{
 394	u32	temp;
 395
 396#ifdef DEBUG
 397	if (!HC_IS_RUNNING(oxu_to_hcd(oxu)->state))
 398		BUG();
 399#endif
 400
 401	/* wait for any schedule enables/disables to take effect */
 402	temp = readl(&oxu->regs->command) << 10;
 403	temp &= STS_ASS | STS_PSS;
 404	if (handshake(oxu, &oxu->regs->status, STS_ASS | STS_PSS,
 405				temp, 16 * 125) != 0) {
 406		oxu_to_hcd(oxu)->state = HC_STATE_HALT;
 407		return;
 408	}
 409
 410	/* then disable anything that's still active */
 411	temp = readl(&oxu->regs->command);
 412	temp &= ~(CMD_ASE | CMD_IAAD | CMD_PSE);
 413	writel(temp, &oxu->regs->command);
 414
 415	/* hardware can take 16 microframes to turn off ... */
 416	if (handshake(oxu, &oxu->regs->status, STS_ASS | STS_PSS,
 417				0, 16 * 125) != 0) {
 418		oxu_to_hcd(oxu)->state = HC_STATE_HALT;
 419		return;
 420	}
 421}
 422
 423static int check_reset_complete(struct oxu_hcd *oxu, int index,
 424				u32 __iomem *status_reg, int port_status)
 425{
 426	if (!(port_status & PORT_CONNECT)) {
 427		oxu->reset_done[index] = 0;
 428		return port_status;
 429	}
 430
 431	/* if reset finished and it's still not enabled -- handoff */
 432	if (!(port_status & PORT_PE)) {
 433		oxu_dbg(oxu, "Failed to enable port %d on root hub TT\n",
 434				index+1);
 435		return port_status;
 436	} else
 437		oxu_dbg(oxu, "port %d high speed\n", index + 1);
 438
 439	return port_status;
 440}
 441
 442static void ehci_hub_descriptor(struct oxu_hcd *oxu,
 443				struct usb_hub_descriptor *desc)
 444{
 445	int ports = HCS_N_PORTS(oxu->hcs_params);
 446	u16 temp;
 447
 448	desc->bDescriptorType = 0x29;
 449	desc->bPwrOn2PwrGood = 10;	/* oxu 1.0, 2.3.9 says 20ms max */
 450	desc->bHubContrCurrent = 0;
 451
 452	desc->bNbrPorts = ports;
 453	temp = 1 + (ports / 8);
 454	desc->bDescLength = 7 + 2 * temp;
 455
 456	/* ports removable, and usb 1.0 legacy PortPwrCtrlMask */
 457	memset(&desc->u.hs.DeviceRemovable[0], 0, temp);
 458	memset(&desc->u.hs.DeviceRemovable[temp], 0xff, temp);
 459
 460	temp = 0x0008;			/* per-port overcurrent reporting */
 461	if (HCS_PPC(oxu->hcs_params))
 462		temp |= 0x0001;		/* per-port power control */
 463	else
 464		temp |= 0x0002;		/* no power switching */
 465	desc->wHubCharacteristics = (__force __u16)cpu_to_le16(temp);
 466}
 467
 468
 469/* Allocate an OXU210HP on-chip memory data buffer
 470 *
 471 * An on-chip memory data buffer is required for each OXU210HP USB transfer.
 472 * Each transfer descriptor has one or more on-chip memory data buffers.
 473 *
 474 * Data buffers are allocated from a fix sized pool of data blocks.
 475 * To minimise fragmentation and give reasonable memory utlisation,
 476 * data buffers are allocated with sizes the power of 2 multiples of
 477 * the block size, starting on an address a multiple of the allocated size.
 478 *
 479 * FIXME: callers of this function require a buffer to be allocated for
 480 * len=0. This is a waste of on-chip memory and should be fix. Then this
 481 * function should be changed to not allocate a buffer for len=0.
 482 */
 483static int oxu_buf_alloc(struct oxu_hcd *oxu, struct ehci_qtd *qtd, int len)
 484{
 485	int n_blocks;	/* minium blocks needed to hold len */
 486	int a_blocks;	/* blocks allocated */
 487	int i, j;
 488
 489	/* Don't allocte bigger than supported */
 490	if (len > BUFFER_SIZE * BUFFER_NUM) {
 491		oxu_err(oxu, "buffer too big (%d)\n", len);
 492		return -ENOMEM;
 493	}
 494
 495	spin_lock(&oxu->mem_lock);
 496
 497	/* Number of blocks needed to hold len */
 498	n_blocks = (len + BUFFER_SIZE - 1) / BUFFER_SIZE;
 499
 500	/* Round the number of blocks up to the power of 2 */
 501	for (a_blocks = 1; a_blocks < n_blocks; a_blocks <<= 1)
 502		;
 503
 504	/* Find a suitable available data buffer */
 505	for (i = 0; i < BUFFER_NUM;
 506			i += max(a_blocks, (int)oxu->db_used[i])) {
 507
 508		/* Check all the required blocks are available */
 509		for (j = 0; j < a_blocks; j++)
 510			if (oxu->db_used[i + j])
 511				break;
 512
 513		if (j != a_blocks)
 514			continue;
 515
 516		/* Allocate blocks found! */
 517		qtd->buffer = (void *) &oxu->mem->db_pool[i];
 518		qtd->buffer_dma = virt_to_phys(qtd->buffer);
 519
 520		qtd->qtd_buffer_len = BUFFER_SIZE * a_blocks;
 521		oxu->db_used[i] = a_blocks;
 522
 523		spin_unlock(&oxu->mem_lock);
 524
 525		return 0;
 526	}
 527
 528	/* Failed */
 529
 530	spin_unlock(&oxu->mem_lock);
 531
 532	return -ENOMEM;
 533}
 534
 535static void oxu_buf_free(struct oxu_hcd *oxu, struct ehci_qtd *qtd)
 536{
 537	int index;
 538
 539	spin_lock(&oxu->mem_lock);
 540
 541	index = (qtd->buffer - (void *) &oxu->mem->db_pool[0])
 542							 / BUFFER_SIZE;
 543	oxu->db_used[index] = 0;
 544	qtd->qtd_buffer_len = 0;
 545	qtd->buffer_dma = 0;
 546	qtd->buffer = NULL;
 547
 548	spin_unlock(&oxu->mem_lock);
 549}
 550
 551static inline void ehci_qtd_init(struct ehci_qtd *qtd, dma_addr_t dma)
 552{
 553	memset(qtd, 0, sizeof *qtd);
 554	qtd->qtd_dma = dma;
 555	qtd->hw_token = cpu_to_le32(QTD_STS_HALT);
 556	qtd->hw_next = EHCI_LIST_END;
 557	qtd->hw_alt_next = EHCI_LIST_END;
 558	INIT_LIST_HEAD(&qtd->qtd_list);
 559}
 560
 561static inline void oxu_qtd_free(struct oxu_hcd *oxu, struct ehci_qtd *qtd)
 562{
 563	int index;
 564
 565	if (qtd->buffer)
 566		oxu_buf_free(oxu, qtd);
 567
 568	spin_lock(&oxu->mem_lock);
 569
 570	index = qtd - &oxu->mem->qtd_pool[0];
 571	oxu->qtd_used[index] = 0;
 572
 573	spin_unlock(&oxu->mem_lock);
 574}
 575
 576static struct ehci_qtd *ehci_qtd_alloc(struct oxu_hcd *oxu)
 577{
 578	int i;
 579	struct ehci_qtd *qtd = NULL;
 580
 581	spin_lock(&oxu->mem_lock);
 582
 583	for (i = 0; i < QTD_NUM; i++)
 584		if (!oxu->qtd_used[i])
 585			break;
 586
 587	if (i < QTD_NUM) {
 588		qtd = (struct ehci_qtd *) &oxu->mem->qtd_pool[i];
 589		memset(qtd, 0, sizeof *qtd);
 590
 591		qtd->hw_token = cpu_to_le32(QTD_STS_HALT);
 592		qtd->hw_next = EHCI_LIST_END;
 593		qtd->hw_alt_next = EHCI_LIST_END;
 594		INIT_LIST_HEAD(&qtd->qtd_list);
 595
 596		qtd->qtd_dma = virt_to_phys(qtd);
 597
 598		oxu->qtd_used[i] = 1;
 599	}
 600
 601	spin_unlock(&oxu->mem_lock);
 602
 603	return qtd;
 604}
 605
 606static void oxu_qh_free(struct oxu_hcd *oxu, struct ehci_qh *qh)
 607{
 608	int index;
 609
 610	spin_lock(&oxu->mem_lock);
 611
 612	index = qh - &oxu->mem->qh_pool[0];
 613	oxu->qh_used[index] = 0;
 614
 615	spin_unlock(&oxu->mem_lock);
 616}
 617
 618static void qh_destroy(struct kref *kref)
 619{
 620	struct ehci_qh *qh = container_of(kref, struct ehci_qh, kref);
 621	struct oxu_hcd *oxu = qh->oxu;
 622
 623	/* clean qtds first, and know this is not linked */
 624	if (!list_empty(&qh->qtd_list) || qh->qh_next.ptr) {
 625		oxu_dbg(oxu, "unused qh not empty!\n");
 626		BUG();
 627	}
 628	if (qh->dummy)
 629		oxu_qtd_free(oxu, qh->dummy);
 630	oxu_qh_free(oxu, qh);
 631}
 632
 633static struct ehci_qh *oxu_qh_alloc(struct oxu_hcd *oxu)
 634{
 635	int i;
 636	struct ehci_qh *qh = NULL;
 637
 638	spin_lock(&oxu->mem_lock);
 639
 640	for (i = 0; i < QHEAD_NUM; i++)
 641		if (!oxu->qh_used[i])
 642			break;
 643
 644	if (i < QHEAD_NUM) {
 645		qh = (struct ehci_qh *) &oxu->mem->qh_pool[i];
 646		memset(qh, 0, sizeof *qh);
 647
 648		kref_init(&qh->kref);
 649		qh->oxu = oxu;
 650		qh->qh_dma = virt_to_phys(qh);
 651		INIT_LIST_HEAD(&qh->qtd_list);
 652
 653		/* dummy td enables safe urb queuing */
 654		qh->dummy = ehci_qtd_alloc(oxu);
 655		if (qh->dummy == NULL) {
 656			oxu_dbg(oxu, "no dummy td\n");
 657			oxu->qh_used[i] = 0;
 658			qh = NULL;
 659			goto unlock;
 660		}
 661
 662		oxu->qh_used[i] = 1;
 663	}
 664unlock:
 665	spin_unlock(&oxu->mem_lock);
 666
 667	return qh;
 668}
 669
 670/* to share a qh (cpu threads, or hc) */
 671static inline struct ehci_qh *qh_get(struct ehci_qh *qh)
 672{
 673	kref_get(&qh->kref);
 674	return qh;
 675}
 676
 677static inline void qh_put(struct ehci_qh *qh)
 678{
 679	kref_put(&qh->kref, qh_destroy);
 680}
 681
 682static void oxu_murb_free(struct oxu_hcd *oxu, struct oxu_murb *murb)
 683{
 684	int index;
 685
 686	spin_lock(&oxu->mem_lock);
 687
 688	index = murb - &oxu->murb_pool[0];
 689	oxu->murb_used[index] = 0;
 690
 691	spin_unlock(&oxu->mem_lock);
 692}
 693
 694static struct oxu_murb *oxu_murb_alloc(struct oxu_hcd *oxu)
 695
 696{
 697	int i;
 698	struct oxu_murb *murb = NULL;
 699
 700	spin_lock(&oxu->mem_lock);
 701
 702	for (i = 0; i < MURB_NUM; i++)
 703		if (!oxu->murb_used[i])
 704			break;
 705
 706	if (i < MURB_NUM) {
 707		murb = &(oxu->murb_pool)[i];
 708
 709		oxu->murb_used[i] = 1;
 710	}
 711
 712	spin_unlock(&oxu->mem_lock);
 713
 714	return murb;
 715}
 716
 717/* The queue heads and transfer descriptors are managed from pools tied
 718 * to each of the "per device" structures.
 719 * This is the initialisation and cleanup code.
 720 */
 721static void ehci_mem_cleanup(struct oxu_hcd *oxu)
 722{
 723	kfree(oxu->murb_pool);
 724	oxu->murb_pool = NULL;
 725
 726	if (oxu->async)
 727		qh_put(oxu->async);
 728	oxu->async = NULL;
 729
 730	del_timer(&oxu->urb_timer);
 731
 732	oxu->periodic = NULL;
 733
 734	/* shadow periodic table */
 735	kfree(oxu->pshadow);
 736	oxu->pshadow = NULL;
 737}
 738
 739/* Remember to add cleanup code (above) if you add anything here.
 740 */
 741static int ehci_mem_init(struct oxu_hcd *oxu, gfp_t flags)
 742{
 743	int i;
 744
 745	for (i = 0; i < oxu->periodic_size; i++)
 746		oxu->mem->frame_list[i] = EHCI_LIST_END;
 747	for (i = 0; i < QHEAD_NUM; i++)
 748		oxu->qh_used[i] = 0;
 749	for (i = 0; i < QTD_NUM; i++)
 750		oxu->qtd_used[i] = 0;
 751
 752	oxu->murb_pool = kcalloc(MURB_NUM, sizeof(struct oxu_murb), flags);
 753	if (!oxu->murb_pool)
 754		goto fail;
 755
 756	for (i = 0; i < MURB_NUM; i++)
 757		oxu->murb_used[i] = 0;
 758
 759	oxu->async = oxu_qh_alloc(oxu);
 760	if (!oxu->async)
 761		goto fail;
 762
 763	oxu->periodic = (__le32 *) &oxu->mem->frame_list;
 764	oxu->periodic_dma = virt_to_phys(oxu->periodic);
 765
 766	for (i = 0; i < oxu->periodic_size; i++)
 767		oxu->periodic[i] = EHCI_LIST_END;
 768
 769	/* software shadow of hardware table */
 770	oxu->pshadow = kcalloc(oxu->periodic_size, sizeof(void *), flags);
 771	if (oxu->pshadow != NULL)
 772		return 0;
 773
 774fail:
 775	oxu_dbg(oxu, "couldn't init memory\n");
 776	ehci_mem_cleanup(oxu);
 777	return -ENOMEM;
 778}
 779
 780/* Fill a qtd, returning how much of the buffer we were able to queue up.
 781 */
 782static int qtd_fill(struct ehci_qtd *qtd, dma_addr_t buf, size_t len,
 783				int token, int maxpacket)
 784{
 785	int i, count;
 786	u64 addr = buf;
 787
 788	/* one buffer entry per 4K ... first might be short or unaligned */
 789	qtd->hw_buf[0] = cpu_to_le32((u32)addr);
 790	qtd->hw_buf_hi[0] = cpu_to_le32((u32)(addr >> 32));
 791	count = 0x1000 - (buf & 0x0fff);	/* rest of that page */
 792	if (likely(len < count))		/* ... iff needed */
 793		count = len;
 794	else {
 795		buf +=  0x1000;
 796		buf &= ~0x0fff;
 797
 798		/* per-qtd limit: from 16K to 20K (best alignment) */
 799		for (i = 1; count < len && i < 5; i++) {
 800			addr = buf;
 801			qtd->hw_buf[i] = cpu_to_le32((u32)addr);
 802			qtd->hw_buf_hi[i] = cpu_to_le32((u32)(addr >> 32));
 803			buf += 0x1000;
 804			if ((count + 0x1000) < len)
 805				count += 0x1000;
 806			else
 807				count = len;
 808		}
 809
 810		/* short packets may only terminate transfers */
 811		if (count != len)
 812			count -= (count % maxpacket);
 813	}
 814	qtd->hw_token = cpu_to_le32((count << 16) | token);
 815	qtd->length = count;
 816
 817	return count;
 818}
 819
 820static inline void qh_update(struct oxu_hcd *oxu,
 821				struct ehci_qh *qh, struct ehci_qtd *qtd)
 822{
 823	/* writes to an active overlay are unsafe */
 824	BUG_ON(qh->qh_state != QH_STATE_IDLE);
 825
 826	qh->hw_qtd_next = QTD_NEXT(qtd->qtd_dma);
 827	qh->hw_alt_next = EHCI_LIST_END;
 828
 829	/* Except for control endpoints, we make hardware maintain data
 830	 * toggle (like OHCI) ... here (re)initialize the toggle in the QH,
 831	 * and set the pseudo-toggle in udev. Only usb_clear_halt() will
 832	 * ever clear it.
 833	 */
 834	if (!(qh->hw_info1 & cpu_to_le32(1 << 14))) {
 835		unsigned	is_out, epnum;
 836
 837		is_out = !(qtd->hw_token & cpu_to_le32(1 << 8));
 838		epnum = (le32_to_cpup(&qh->hw_info1) >> 8) & 0x0f;
 839		if (unlikely(!usb_gettoggle(qh->dev, epnum, is_out))) {
 840			qh->hw_token &= ~cpu_to_le32(QTD_TOGGLE);
 841			usb_settoggle(qh->dev, epnum, is_out, 1);
 842		}
 843	}
 844
 845	/* HC must see latest qtd and qh data before we clear ACTIVE+HALT */
 846	wmb();
 847	qh->hw_token &= cpu_to_le32(QTD_TOGGLE | QTD_STS_PING);
 848}
 849
 850/* If it weren't for a common silicon quirk (writing the dummy into the qh
 851 * overlay, so qh->hw_token wrongly becomes inactive/halted), only fault
 852 * recovery (including urb dequeue) would need software changes to a QH...
 853 */
 854static void qh_refresh(struct oxu_hcd *oxu, struct ehci_qh *qh)
 855{
 856	struct ehci_qtd *qtd;
 857
 858	if (list_empty(&qh->qtd_list))
 859		qtd = qh->dummy;
 860	else {
 861		qtd = list_entry(qh->qtd_list.next,
 862				struct ehci_qtd, qtd_list);
 863		/* first qtd may already be partially processed */
 864		if (cpu_to_le32(qtd->qtd_dma) == qh->hw_current)
 865			qtd = NULL;
 866	}
 867
 868	if (qtd)
 869		qh_update(oxu, qh, qtd);
 870}
 871
 872static void qtd_copy_status(struct oxu_hcd *oxu, struct urb *urb,
 873				size_t length, u32 token)
 874{
 875	/* count IN/OUT bytes, not SETUP (even short packets) */
 876	if (likely(QTD_PID(token) != 2))
 877		urb->actual_length += length - QTD_LENGTH(token);
 878
 879	/* don't modify error codes */
 880	if (unlikely(urb->status != -EINPROGRESS))
 881		return;
 882
 883	/* force cleanup after short read; not always an error */
 884	if (unlikely(IS_SHORT_READ(token)))
 885		urb->status = -EREMOTEIO;
 886
 887	/* serious "can't proceed" faults reported by the hardware */
 888	if (token & QTD_STS_HALT) {
 889		if (token & QTD_STS_BABBLE) {
 890			/* FIXME "must" disable babbling device's port too */
 891			urb->status = -EOVERFLOW;
 892		} else if (token & QTD_STS_MMF) {
 893			/* fs/ls interrupt xfer missed the complete-split */
 894			urb->status = -EPROTO;
 895		} else if (token & QTD_STS_DBE) {
 896			urb->status = (QTD_PID(token) == 1) /* IN ? */
 897				? -ENOSR  /* hc couldn't read data */
 898				: -ECOMM; /* hc couldn't write data */
 899		} else if (token & QTD_STS_XACT) {
 900			/* timeout, bad crc, wrong PID, etc; retried */
 901			if (QTD_CERR(token))
 902				urb->status = -EPIPE;
 903			else {
 904				oxu_dbg(oxu, "devpath %s ep%d%s 3strikes\n",
 905					urb->dev->devpath,
 906					usb_pipeendpoint(urb->pipe),
 907					usb_pipein(urb->pipe) ? "in" : "out");
 908				urb->status = -EPROTO;
 909			}
 910		/* CERR nonzero + no errors + halt --> stall */
 911		} else if (QTD_CERR(token))
 912			urb->status = -EPIPE;
 913		else	/* unknown */
 914			urb->status = -EPROTO;
 915
 916		oxu_vdbg(oxu, "dev%d ep%d%s qtd token %08x --> status %d\n",
 917			usb_pipedevice(urb->pipe),
 918			usb_pipeendpoint(urb->pipe),
 919			usb_pipein(urb->pipe) ? "in" : "out",
 920			token, urb->status);
 921	}
 922}
 923
 924static void ehci_urb_done(struct oxu_hcd *oxu, struct urb *urb)
 925__releases(oxu->lock)
 926__acquires(oxu->lock)
 927{
 928	if (likely(urb->hcpriv != NULL)) {
 929		struct ehci_qh	*qh = (struct ehci_qh *) urb->hcpriv;
 930
 931		/* S-mask in a QH means it's an interrupt urb */
 932		if ((qh->hw_info2 & cpu_to_le32(QH_SMASK)) != 0) {
 933
 934			/* ... update hc-wide periodic stats (for usbfs) */
 935			oxu_to_hcd(oxu)->self.bandwidth_int_reqs--;
 936		}
 937		qh_put(qh);
 938	}
 939
 940	urb->hcpriv = NULL;
 941	switch (urb->status) {
 942	case -EINPROGRESS:		/* success */
 943		urb->status = 0;
 944	default:			/* fault */
 945		break;
 946	case -EREMOTEIO:		/* fault or normal */
 947		if (!(urb->transfer_flags & URB_SHORT_NOT_OK))
 948			urb->status = 0;
 949		break;
 950	case -ECONNRESET:		/* canceled */
 951	case -ENOENT:
 952		break;
 953	}
 954
 955#ifdef OXU_URB_TRACE
 956	oxu_dbg(oxu, "%s %s urb %p ep%d%s status %d len %d/%d\n",
 957		__func__, urb->dev->devpath, urb,
 958		usb_pipeendpoint(urb->pipe),
 959		usb_pipein(urb->pipe) ? "in" : "out",
 960		urb->status,
 961		urb->actual_length, urb->transfer_buffer_length);
 962#endif
 963
 964	/* complete() can reenter this HCD */
 965	spin_unlock(&oxu->lock);
 966	usb_hcd_giveback_urb(oxu_to_hcd(oxu), urb, urb->status);
 967	spin_lock(&oxu->lock);
 968}
 969
 970static void start_unlink_async(struct oxu_hcd *oxu, struct ehci_qh *qh);
 971static void unlink_async(struct oxu_hcd *oxu, struct ehci_qh *qh);
 972
 973static void intr_deschedule(struct oxu_hcd *oxu, struct ehci_qh *qh);
 974static int qh_schedule(struct oxu_hcd *oxu, struct ehci_qh *qh);
 975
 976#define HALT_BIT cpu_to_le32(QTD_STS_HALT)
 977
 978/* Process and free completed qtds for a qh, returning URBs to drivers.
 979 * Chases up to qh->hw_current.  Returns number of completions called,
 980 * indicating how much "real" work we did.
 981 */
 982static unsigned qh_completions(struct oxu_hcd *oxu, struct ehci_qh *qh)
 983{
 984	struct ehci_qtd *last = NULL, *end = qh->dummy;
 985	struct list_head *entry, *tmp;
 986	int stopped;
 987	unsigned count = 0;
 988	int do_status = 0;
 989	u8 state;
 990	struct oxu_murb *murb = NULL;
 991
 992	if (unlikely(list_empty(&qh->qtd_list)))
 993		return count;
 994
 995	/* completions (or tasks on other cpus) must never clobber HALT
 996	 * till we've gone through and cleaned everything up, even when
 997	 * they add urbs to this qh's queue or mark them for unlinking.
 998	 *
 999	 * NOTE:  unlinking expects to be done in queue order.
1000	 */
1001	state = qh->qh_state;
1002	qh->qh_state = QH_STATE_COMPLETING;
1003	stopped = (state == QH_STATE_IDLE);
1004
1005	/* remove de-activated QTDs from front of queue.
1006	 * after faults (including short reads), cleanup this urb
1007	 * then let the queue advance.
1008	 * if queue is stopped, handles unlinks.
1009	 */
1010	list_for_each_safe(entry, tmp, &qh->qtd_list) {
1011		struct ehci_qtd	*qtd;
1012		struct urb *urb;
1013		u32 token = 0;
1014
1015		qtd = list_entry(entry, struct ehci_qtd, qtd_list);
1016		urb = qtd->urb;
1017
1018		/* Clean up any state from previous QTD ...*/
1019		if (last) {
1020			if (likely(last->urb != urb)) {
1021				if (last->urb->complete == NULL) {
1022					murb = (struct oxu_murb *) last->urb;
1023					last->urb = murb->main;
1024					if (murb->last) {
1025						ehci_urb_done(oxu, last->urb);
1026						count++;
1027					}
1028					oxu_murb_free(oxu, murb);
1029				} else {
1030					ehci_urb_done(oxu, last->urb);
1031					count++;
1032				}
1033			}
1034			oxu_qtd_free(oxu, last);
1035			last = NULL;
1036		}
1037
1038		/* ignore urbs submitted during completions we reported */
1039		if (qtd == end)
1040			break;
1041
1042		/* hardware copies qtd out of qh overlay */
1043		rmb();
1044		token = le32_to_cpu(qtd->hw_token);
1045
1046		/* always clean up qtds the hc de-activated */
1047		if ((token & QTD_STS_ACTIVE) == 0) {
1048
1049			if ((token & QTD_STS_HALT) != 0) {
1050				stopped = 1;
1051
1052			/* magic dummy for some short reads; qh won't advance.
1053			 * that silicon quirk can kick in with this dummy too.
1054			 */
1055			} else if (IS_SHORT_READ(token) &&
1056					!(qtd->hw_alt_next & EHCI_LIST_END)) {
1057				stopped = 1;
1058				goto halt;
1059			}
1060
1061		/* stop scanning when we reach qtds the hc is using */
1062		} else if (likely(!stopped &&
1063				HC_IS_RUNNING(oxu_to_hcd(oxu)->state))) {
1064			break;
1065
1066		} else {
1067			stopped = 1;
1068
1069			if (unlikely(!HC_IS_RUNNING(oxu_to_hcd(oxu)->state)))
1070				urb->status = -ESHUTDOWN;
1071
1072			/* ignore active urbs unless some previous qtd
1073			 * for the urb faulted (including short read) or
1074			 * its urb was canceled.  we may patch qh or qtds.
1075			 */
1076			if (likely(urb->status == -EINPROGRESS))
1077				continue;
1078
1079			/* issue status after short control reads */
1080			if (unlikely(do_status != 0)
1081					&& QTD_PID(token) == 0 /* OUT */) {
1082				do_status = 0;
1083				continue;
1084			}
1085
1086			/* token in overlay may be most current */
1087			if (state == QH_STATE_IDLE
1088					&& cpu_to_le32(qtd->qtd_dma)
1089						== qh->hw_current)
1090				token = le32_to_cpu(qh->hw_token);
1091
1092			/* force halt for unlinked or blocked qh, so we'll
1093			 * patch the qh later and so that completions can't
1094			 * activate it while we "know" it's stopped.
1095			 */
1096			if ((HALT_BIT & qh->hw_token) == 0) {
1097halt:
1098				qh->hw_token |= HALT_BIT;
1099				wmb();
1100			}
1101		}
1102
1103		/* Remove it from the queue */
1104		qtd_copy_status(oxu, urb->complete ?
1105					urb : ((struct oxu_murb *) urb)->main,
1106				qtd->length, token);
1107		if ((usb_pipein(qtd->urb->pipe)) &&
1108				(NULL != qtd->transfer_buffer))
1109			memcpy(qtd->transfer_buffer, qtd->buffer, qtd->length);
1110		do_status = (urb->status == -EREMOTEIO)
1111				&& usb_pipecontrol(urb->pipe);
1112
1113		if (stopped && qtd->qtd_list.prev != &qh->qtd_list) {
1114			last = list_entry(qtd->qtd_list.prev,
1115					struct ehci_qtd, qtd_list);
1116			last->hw_next = qtd->hw_next;
1117		}
1118		list_del(&qtd->qtd_list);
1119		last = qtd;
1120	}
1121
1122	/* last urb's completion might still need calling */
1123	if (likely(last != NULL)) {
1124		if (last->urb->complete == NULL) {
1125			murb = (struct oxu_murb *) last->urb;
1126			last->urb = murb->main;
1127			if (murb->last) {
1128				ehci_urb_done(oxu, last->urb);
1129				count++;
1130			}
1131			oxu_murb_free(oxu, murb);
1132		} else {
1133			ehci_urb_done(oxu, last->urb);
1134			count++;
1135		}
1136		oxu_qtd_free(oxu, last);
1137	}
1138
1139	/* restore original state; caller must unlink or relink */
1140	qh->qh_state = state;
1141
1142	/* be sure the hardware's done with the qh before refreshing
1143	 * it after fault cleanup, or recovering from silicon wrongly
1144	 * overlaying the dummy qtd (which reduces DMA chatter).
1145	 */
1146	if (stopped != 0 || qh->hw_qtd_next == EHCI_LIST_END) {
1147		switch (state) {
1148		case QH_STATE_IDLE:
1149			qh_refresh(oxu, qh);
1150			break;
1151		case QH_STATE_LINKED:
1152			/* should be rare for periodic transfers,
1153			 * except maybe high bandwidth ...
1154			 */
1155			if ((cpu_to_le32(QH_SMASK)
1156					& qh->hw_info2) != 0) {
1157				intr_deschedule(oxu, qh);
1158				(void) qh_schedule(oxu, qh);
1159			} else
1160				unlink_async(oxu, qh);
1161			break;
1162		/* otherwise, unlink already started */
1163		}
1164	}
1165
1166	return count;
1167}
1168
1169/* High bandwidth multiplier, as encoded in highspeed endpoint descriptors */
1170#define hb_mult(wMaxPacketSize)		(1 + (((wMaxPacketSize) >> 11) & 0x03))
1171/* ... and packet size, for any kind of endpoint descriptor */
1172#define max_packet(wMaxPacketSize)	((wMaxPacketSize) & 0x07ff)
1173
1174/* Reverse of qh_urb_transaction: free a list of TDs.
1175 * used for cleanup after errors, before HC sees an URB's TDs.
1176 */
1177static void qtd_list_free(struct oxu_hcd *oxu,
1178				struct urb *urb, struct list_head *qtd_list)
1179{
1180	struct list_head *entry, *temp;
1181
1182	list_for_each_safe(entry, temp, qtd_list) {
1183		struct ehci_qtd	*qtd;
1184
1185		qtd = list_entry(entry, struct ehci_qtd, qtd_list);
1186		list_del(&qtd->qtd_list);
1187		oxu_qtd_free(oxu, qtd);
1188	}
1189}
1190
1191/* Create a list of filled qtds for this URB; won't link into qh.
1192 */
1193static struct list_head *qh_urb_transaction(struct oxu_hcd *oxu,
1194						struct urb *urb,
1195						struct list_head *head,
1196						gfp_t flags)
1197{
1198	struct ehci_qtd	*qtd, *qtd_prev;
1199	dma_addr_t buf;
1200	int len, maxpacket;
1201	int is_input;
1202	u32 token;
1203	void *transfer_buf = NULL;
1204	int ret;
1205
1206	/*
1207	 * URBs map to sequences of QTDs: one logical transaction
1208	 */
1209	qtd = ehci_qtd_alloc(oxu);
1210	if (unlikely(!qtd))
1211		return NULL;
1212	list_add_tail(&qtd->qtd_list, head);
1213	qtd->urb = urb;
1214
1215	token = QTD_STS_ACTIVE;
1216	token |= (EHCI_TUNE_CERR << 10);
1217	/* for split transactions, SplitXState initialized to zero */
1218
1219	len = urb->transfer_buffer_length;
1220	is_input = usb_pipein(urb->pipe);
1221	if (!urb->transfer_buffer && urb->transfer_buffer_length && is_input)
1222		urb->transfer_buffer = phys_to_virt(urb->transfer_dma);
1223
1224	if (usb_pipecontrol(urb->pipe)) {
1225		/* SETUP pid */
1226		ret = oxu_buf_alloc(oxu, qtd, sizeof(struct usb_ctrlrequest));
1227		if (ret)
1228			goto cleanup;
1229
1230		qtd_fill(qtd, qtd->buffer_dma, sizeof(struct usb_ctrlrequest),
1231				token | (2 /* "setup" */ << 8), 8);
1232		memcpy(qtd->buffer, qtd->urb->setup_packet,
1233				sizeof(struct usb_ctrlrequest));
1234
1235		/* ... and always at least one more pid */
1236		token ^= QTD_TOGGLE;
1237		qtd_prev = qtd;
1238		qtd = ehci_qtd_alloc(oxu);
1239		if (unlikely(!qtd))
1240			goto cleanup;
1241		qtd->urb = urb;
1242		qtd_prev->hw_next = QTD_NEXT(qtd->qtd_dma);
1243		list_add_tail(&qtd->qtd_list, head);
1244
1245		/* for zero length DATA stages, STATUS is always IN */
1246		if (len == 0)
1247			token |= (1 /* "in" */ << 8);
1248	}
1249
1250	/*
1251	 * Data transfer stage: buffer setup
1252	 */
1253
1254	ret = oxu_buf_alloc(oxu, qtd, len);
1255	if (ret)
1256		goto cleanup;
1257
1258	buf = qtd->buffer_dma;
1259	transfer_buf = urb->transfer_buffer;
1260
1261	if (!is_input)
1262		memcpy(qtd->buffer, qtd->urb->transfer_buffer, len);
1263
1264	if (is_input)
1265		token |= (1 /* "in" */ << 8);
1266	/* else it's already initted to "out" pid (0 << 8) */
1267
1268	maxpacket = max_packet(usb_maxpacket(urb->dev, urb->pipe, !is_input));
1269
1270	/*
1271	 * buffer gets wrapped in one or more qtds;
1272	 * last one may be "short" (including zero len)
1273	 * and may serve as a control status ack
1274	 */
1275	for (;;) {
1276		int this_qtd_len;
1277
1278		this_qtd_len = qtd_fill(qtd, buf, len, token, maxpacket);
1279		qtd->transfer_buffer = transfer_buf;
1280		len -= this_qtd_len;
1281		buf += this_qtd_len;
1282		transfer_buf += this_qtd_len;
1283		if (is_input)
1284			qtd->hw_alt_next = oxu->async->hw_alt_next;
1285
1286		/* qh makes control packets use qtd toggle; maybe switch it */
1287		if ((maxpacket & (this_qtd_len + (maxpacket - 1))) == 0)
1288			token ^= QTD_TOGGLE;
1289
1290		if (likely(len <= 0))
1291			break;
1292
1293		qtd_prev = qtd;
1294		qtd = ehci_qtd_alloc(oxu);
1295		if (unlikely(!qtd))
1296			goto cleanup;
1297		if (likely(len > 0)) {
1298			ret = oxu_buf_alloc(oxu, qtd, len);
1299			if (ret)
1300				goto cleanup;
1301		}
1302		qtd->urb = urb;
1303		qtd_prev->hw_next = QTD_NEXT(qtd->qtd_dma);
1304		list_add_tail(&qtd->qtd_list, head);
1305	}
1306
1307	/* unless the bulk/interrupt caller wants a chance to clean
1308	 * up after short reads, hc should advance qh past this urb
1309	 */
1310	if (likely((urb->transfer_flags & URB_SHORT_NOT_OK) == 0
1311				|| usb_pipecontrol(urb->pipe)))
1312		qtd->hw_alt_next = EHCI_LIST_END;
1313
1314	/*
1315	 * control requests may need a terminating data "status" ack;
1316	 * bulk ones may need a terminating short packet (zero length).
1317	 */
1318	if (likely(urb->transfer_buffer_length != 0)) {
1319		int	one_more = 0;
1320
1321		if (usb_pipecontrol(urb->pipe)) {
1322			one_more = 1;
1323			token ^= 0x0100;	/* "in" <--> "out"  */
1324			token |= QTD_TOGGLE;	/* force DATA1 */
1325		} else if (usb_pipebulk(urb->pipe)
1326				&& (urb->transfer_flags & URB_ZERO_PACKET)
1327				&& !(urb->transfer_buffer_length % maxpacket)) {
1328			one_more = 1;
1329		}
1330		if (one_more) {
1331			qtd_prev = qtd;
1332			qtd = ehci_qtd_alloc(oxu);
1333			if (unlikely(!qtd))
1334				goto cleanup;
1335			qtd->urb = urb;
1336			qtd_prev->hw_next = QTD_NEXT(qtd->qtd_dma);
1337			list_add_tail(&qtd->qtd_list, head);
1338
1339			/* never any data in such packets */
1340			qtd_fill(qtd, 0, 0, token, 0);
1341		}
1342	}
1343
1344	/* by default, enable interrupt on urb completion */
1345		qtd->hw_token |= cpu_to_le32(QTD_IOC);
1346	return head;
1347
1348cleanup:
1349	qtd_list_free(oxu, urb, head);
1350	return NULL;
1351}
1352
1353/* Each QH holds a qtd list; a QH is used for everything except iso.
1354 *
1355 * For interrupt urbs, the scheduler must set the microframe scheduling
1356 * mask(s) each time the QH gets scheduled.  For highspeed, that's
1357 * just one microframe in the s-mask.  For split interrupt transactions
1358 * there are additional complications: c-mask, maybe FSTNs.
1359 */
1360static struct ehci_qh *qh_make(struct oxu_hcd *oxu,
1361				struct urb *urb, gfp_t flags)
1362{
1363	struct ehci_qh *qh = oxu_qh_alloc(oxu);
1364	u32 info1 = 0, info2 = 0;
1365	int is_input, type;
1366	int maxp = 0;
1367
1368	if (!qh)
1369		return qh;
1370
1371	/*
1372	 * init endpoint/device data for this QH
1373	 */
1374	info1 |= usb_pipeendpoint(urb->pipe) << 8;
1375	info1 |= usb_pipedevice(urb->pipe) << 0;
1376
1377	is_input = usb_pipein(urb->pipe);
1378	type = usb_pipetype(urb->pipe);
1379	maxp = usb_maxpacket(urb->dev, urb->pipe, !is_input);
1380
1381	/* Compute interrupt scheduling parameters just once, and save.
1382	 * - allowing for high bandwidth, how many nsec/uframe are used?
1383	 * - split transactions need a second CSPLIT uframe; same question
1384	 * - splits also need a schedule gap (for full/low speed I/O)
1385	 * - qh has a polling interval
1386	 *
1387	 * For control/bulk requests, the HC or TT handles these.
1388	 */
1389	if (type == PIPE_INTERRUPT) {
1390		qh->usecs = NS_TO_US(usb_calc_bus_time(USB_SPEED_HIGH,
1391								is_input, 0,
1392				hb_mult(maxp) * max_packet(maxp)));
1393		qh->start = NO_FRAME;
1394
1395		if (urb->dev->speed == USB_SPEED_HIGH) {
1396			qh->c_usecs = 0;
1397			qh->gap_uf = 0;
1398
1399			qh->period = urb->interval >> 3;
1400			if (qh->period == 0 && urb->interval != 1) {
1401				/* NOTE interval 2 or 4 uframes could work.
1402				 * But interval 1 scheduling is simpler, and
1403				 * includes high bandwidth.
1404				 */
1405				oxu_dbg(oxu, "intr period %d uframes, NYET!\n",
1406					urb->interval);
1407				goto done;
1408			}
1409		} else {
1410			struct usb_tt	*tt = urb->dev->tt;
1411			int		think_time;
1412
1413			/* gap is f(FS/LS transfer times) */
1414			qh->gap_uf = 1 + usb_calc_bus_time(urb->dev->speed,
1415					is_input, 0, maxp) / (125 * 1000);
1416
1417			/* FIXME this just approximates SPLIT/CSPLIT times */
1418			if (is_input) {		/* SPLIT, gap, CSPLIT+DATA */
1419				qh->c_usecs = qh->usecs + HS_USECS(0);
1420				qh->usecs = HS_USECS(1);
1421			} else {		/* SPLIT+DATA, gap, CSPLIT */
1422				qh->usecs += HS_USECS(1);
1423				qh->c_usecs = HS_USECS(0);
1424			}
1425
1426			think_time = tt ? tt->think_time : 0;
1427			qh->tt_usecs = NS_TO_US(think_time +
1428					usb_calc_bus_time(urb->dev->speed,
1429					is_input, 0, max_packet(maxp)));
1430			qh->period = urb->interval;
1431		}
1432	}
1433
1434	/* support for tt scheduling, and access to toggles */
1435	qh->dev = urb->dev;
1436
1437	/* using TT? */
1438	switch (urb->dev->speed) {
1439	case USB_SPEED_LOW:
1440		info1 |= (1 << 12);	/* EPS "low" */
1441		/* FALL THROUGH */
1442
1443	case USB_SPEED_FULL:
1444		/* EPS 0 means "full" */
1445		if (type != PIPE_INTERRUPT)
1446			info1 |= (EHCI_TUNE_RL_TT << 28);
1447		if (type == PIPE_CONTROL) {
1448			info1 |= (1 << 27);	/* for TT */
1449			info1 |= 1 << 14;	/* toggle from qtd */
1450		}
1451		info1 |= maxp << 16;
1452
1453		info2 |= (EHCI_TUNE_MULT_TT << 30);
1454		info2 |= urb->dev->ttport << 23;
1455
1456		/* NOTE:  if (PIPE_INTERRUPT) { scheduler sets c-mask } */
1457
1458		break;
1459
1460	case USB_SPEED_HIGH:		/* no TT involved */
1461		info1 |= (2 << 12);	/* EPS "high" */
1462		if (type == PIPE_CONTROL) {
1463			info1 |= (EHCI_TUNE_RL_HS << 28);
1464			info1 |= 64 << 16;	/* usb2 fixed maxpacket */
1465			info1 |= 1 << 14;	/* toggle from qtd */
1466			info2 |= (EHCI_TUNE_MULT_HS << 30);
1467		} else if (type == PIPE_BULK) {
1468			info1 |= (EHCI_TUNE_RL_HS << 28);
1469			info1 |= 512 << 16;	/* usb2 fixed maxpacket */
1470			info2 |= (EHCI_TUNE_MULT_HS << 30);
1471		} else {		/* PIPE_INTERRUPT */
1472			info1 |= max_packet(maxp) << 16;
1473			info2 |= hb_mult(maxp) << 30;
1474		}
1475		break;
1476	default:
1477		oxu_dbg(oxu, "bogus dev %p speed %d\n", urb->dev, urb->dev->speed);
1478done:
1479		qh_put(qh);
1480		return NULL;
1481	}
1482
1483	/* NOTE:  if (PIPE_INTERRUPT) { scheduler sets s-mask } */
1484
1485	/* init as live, toggle clear, advance to dummy */
1486	qh->qh_state = QH_STATE_IDLE;
1487	qh->hw_info1 = cpu_to_le32(info1);
1488	qh->hw_info2 = cpu_to_le32(info2);
1489	usb_settoggle(urb->dev, usb_pipeendpoint(urb->pipe), !is_input, 1);
1490	qh_refresh(oxu, qh);
1491	return qh;
1492}
1493
1494/* Move qh (and its qtds) onto async queue; maybe enable queue.
1495 */
1496static void qh_link_async(struct oxu_hcd *oxu, struct ehci_qh *qh)
1497{
1498	__le32 dma = QH_NEXT(qh->qh_dma);
1499	struct ehci_qh *head;
1500
1501	/* (re)start the async schedule? */
1502	head = oxu->async;
1503	timer_action_done(oxu, TIMER_ASYNC_OFF);
1504	if (!head->qh_next.qh) {
1505		u32	cmd = readl(&oxu->regs->command);
1506
1507		if (!(cmd & CMD_ASE)) {
1508			/* in case a clear of CMD_ASE didn't take yet */
1509			(void)handshake(oxu, &oxu->regs->status,
1510					STS_ASS, 0, 150);
1511			cmd |= CMD_ASE | CMD_RUN;
1512			writel(cmd, &oxu->regs->command);
1513			oxu_to_hcd(oxu)->state = HC_STATE_RUNNING;
1514			/* posted write need not be known to HC yet ... */
1515		}
1516	}
1517
1518	/* clear halt and/or toggle; and maybe recover from silicon quirk */
1519	if (qh->qh_state == QH_STATE_IDLE)
1520		qh_refresh(oxu, qh);
1521
1522	/* splice right after start */
1523	qh->qh_next = head->qh_next;
1524	qh->hw_next = head->hw_next;
1525	wmb();
1526
1527	head->qh_next.qh = qh;
1528	head->hw_next = dma;
1529
1530	qh->qh_state = QH_STATE_LINKED;
1531	/* qtd completions reported later by interrupt */
1532}
1533
1534#define	QH_ADDR_MASK	cpu_to_le32(0x7f)
1535
1536/*
1537 * For control/bulk/interrupt, return QH with these TDs appended.
1538 * Allocates and initializes the QH if necessary.
1539 * Returns null if it can't allocate a QH it needs to.
1540 * If the QH has TDs (urbs) already, that's great.
1541 */
1542static struct ehci_qh *qh_append_tds(struct oxu_hcd *oxu,
1543				struct urb *urb, struct list_head *qtd_list,
1544				int epnum, void	**ptr)
1545{
1546	struct ehci_qh *qh = NULL;
1547
1548	qh = (struct ehci_qh *) *ptr;
1549	if (unlikely(qh == NULL)) {
1550		/* can't sleep here, we have oxu->lock... */
1551		qh = qh_make(oxu, urb, GFP_ATOMIC);
1552		*ptr = qh;
1553	}
1554	if (likely(qh != NULL)) {
1555		struct ehci_qtd	*qtd;
1556
1557		if (unlikely(list_empty(qtd_list)))
1558			qtd = NULL;
1559		else
1560			qtd = list_entry(qtd_list->next, struct ehci_qtd,
1561					qtd_list);
1562
1563		/* control qh may need patching ... */
1564		if (unlikely(epnum == 0)) {
1565
1566			/* usb_reset_device() briefly reverts to address 0 */
1567			if (usb_pipedevice(urb->pipe) == 0)
1568				qh->hw_info1 &= ~QH_ADDR_MASK;
1569		}
1570
1571		/* just one way to queue requests: swap with the dummy qtd.
1572		 * only hc or qh_refresh() ever modify the overlay.
1573		 */
1574		if (likely(qtd != NULL)) {
1575			struct ehci_qtd	*dummy;
1576			dma_addr_t dma;
1577			__le32 token;
1578
1579			/* to avoid racing the HC, use the dummy td instead of
1580			 * the first td of our list (becomes new dummy).  both
1581			 * tds stay deactivated until we're done, when the
1582			 * HC is allowed to fetch the old dummy (4.10.2).
1583			 */
1584			token = qtd->hw_token;
1585			qtd->hw_token = HALT_BIT;
1586			wmb();
1587			dummy = qh->dummy;
1588
1589			dma = dummy->qtd_dma;
1590			*dummy = *qtd;
1591			dummy->qtd_dma = dma;
1592
1593			list_del(&qtd->qtd_list);
1594			list_add(&dummy->qtd_list, qtd_list);
1595			list_splice(qtd_list, qh->qtd_list.prev);
1596
1597			ehci_qtd_init(qtd, qtd->qtd_dma);
1598			qh->dummy = qtd;
1599
1600			/* hc must see the new dummy at list end */
1601			dma = qtd->qtd_dma;
1602			qtd = list_entry(qh->qtd_list.prev,
1603					struct ehci_qtd, qtd_list);
1604			qtd->hw_next = QTD_NEXT(dma);
1605
1606			/* let the hc process these next qtds */
1607			dummy->hw_token = (token & ~(0x80));
1608			wmb();
1609			dummy->hw_token = token;
1610
1611			urb->hcpriv = qh_get(qh);
1612		}
1613	}
1614	return qh;
1615}
1616
1617static int submit_async(struct oxu_hcd	*oxu, struct urb *urb,
1618			struct list_head *qtd_list, gfp_t mem_flags)
1619{
1620	struct ehci_qtd	*qtd;
1621	int epnum;
1622	unsigned long flags;
1623	struct ehci_qh *qh = NULL;
1624	int rc = 0;
1625
1626	qtd = list_entry(qtd_list->next, struct ehci_qtd, qtd_list);
1627	epnum = urb->ep->desc.bEndpointAddress;
1628
1629#ifdef OXU_URB_TRACE
1630	oxu_dbg(oxu, "%s %s urb %p ep%d%s len %d, qtd %p [qh %p]\n",
1631		__func__, urb->dev->devpath, urb,
1632		epnum & 0x0f, (epnum & USB_DIR_IN) ? "in" : "out",
1633		urb->transfer_buffer_length,
1634		qtd, urb->ep->hcpriv);
1635#endif
1636
1637	spin_lock_irqsave(&oxu->lock, flags);
1638	if (unlikely(!HCD_HW_ACCESSIBLE(oxu_to_hcd(oxu)))) {
1639		rc = -ESHUTDOWN;
1640		goto done;
1641	}
1642
1643	qh = qh_append_tds(oxu, urb, qtd_list, epnum, &urb->ep->hcpriv);
1644	if (unlikely(qh == NULL)) {
1645		rc = -ENOMEM;
1646		goto done;
1647	}
1648
1649	/* Control/bulk operations through TTs don't need scheduling,
1650	 * the HC and TT handle it when the TT has a buffer ready.
1651	 */
1652	if (likely(qh->qh_state == QH_STATE_IDLE))
1653		qh_link_async(oxu, qh_get(qh));
1654done:
1655	spin_unlock_irqrestore(&oxu->lock, flags);
1656	if (unlikely(qh == NULL))
1657		qtd_list_free(oxu, urb, qtd_list);
1658	return rc;
1659}
1660
1661/* The async qh for the qtds being reclaimed are now unlinked from the HC */
1662
1663static void end_unlink_async(struct oxu_hcd *oxu)
1664{
1665	struct ehci_qh *qh = oxu->reclaim;
1666	struct ehci_qh *next;
1667
1668	timer_action_done(oxu, TIMER_IAA_WATCHDOG);
1669
1670	qh->qh_state = QH_STATE_IDLE;
1671	qh->qh_next.qh = NULL;
1672	qh_put(qh);			/* refcount from reclaim */
1673
1674	/* other unlink(s) may be pending (in QH_STATE_UNLINK_WAIT) */
1675	next = qh->reclaim;
1676	oxu->reclaim = next;
1677	oxu->reclaim_ready = 0;
1678	qh->reclaim = NULL;
1679
1680	qh_completions(oxu, qh);
1681
1682	if (!list_empty(&qh->qtd_list)
1683			&& HC_IS_RUNNING(oxu_to_hcd(oxu)->state))
1684		qh_link_async(oxu, qh);
1685	else {
1686		qh_put(qh);		/* refcount from async list */
1687
1688		/* it's not free to turn the async schedule on/off; leave it
1689		 * active but idle for a while once it empties.
1690		 */
1691		if (HC_IS_RUNNING(oxu_to_hcd(oxu)->state)
1692				&& oxu->async->qh_next.qh == NULL)
1693			timer_action(oxu, TIMER_ASYNC_OFF);
1694	}
1695
1696	if (next) {
1697		oxu->reclaim = NULL;
1698		start_unlink_async(oxu, next);
1699	}
1700}
1701
1702/* makes sure the async qh will become idle */
1703/* caller must own oxu->lock */
1704
1705static void start_unlink_async(struct oxu_hcd *oxu, struct ehci_qh *qh)
1706{
1707	int cmd = readl(&oxu->regs->command);
1708	struct ehci_qh *prev;
1709
1710#ifdef DEBUG
1711	assert_spin_locked(&oxu->lock);
1712	if (oxu->reclaim || (qh->qh_state != QH_STATE_LINKED
1713				&& qh->qh_state != QH_STATE_UNLINK_WAIT))
1714		BUG();
1715#endif
1716
1717	/* stop async schedule right now? */
1718	if (unlikely(qh == oxu->async)) {
1719		/* can't get here without STS_ASS set */
1720		if (oxu_to_hcd(oxu)->state != HC_STATE_HALT
1721				&& !oxu->reclaim) {
1722			/* ... and CMD_IAAD clear */
1723			writel(cmd & ~CMD_ASE, &oxu->regs->command);
1724			wmb();
1725			/* handshake later, if we need to */
1726			timer_action_done(oxu, TIMER_ASYNC_OFF);
1727		}
1728		return;
1729	}
1730
1731	qh->qh_state = QH_STATE_UNLINK;
1732	oxu->reclaim = qh = qh_get(qh);
1733
1734	prev = oxu->async;
1735	while (prev->qh_next.qh != qh)
1736		prev = prev->qh_next.qh;
1737
1738	prev->hw_next = qh->hw_next;
1739	prev->qh_next = qh->qh_next;
1740	wmb();
1741
1742	if (unlikely(oxu_to_hcd(oxu)->state == HC_STATE_HALT)) {
1743		/* if (unlikely(qh->reclaim != 0))
1744		 *	this will recurse, probably not much
1745		 */
1746		end_unlink_async(oxu);
1747		return;
1748	}
1749
1750	oxu->reclaim_ready = 0;
1751	cmd |= CMD_IAAD;
1752	writel(cmd, &oxu->regs->command);
1753	(void) readl(&oxu->regs->command);
1754	timer_action(oxu, TIMER_IAA_WATCHDOG);
1755}
1756
1757static void scan_async(struct oxu_hcd *oxu)
1758{
1759	struct ehci_qh *qh;
1760	enum ehci_timer_action action = TIMER_IO_WATCHDOG;
1761
1762	if (!++(oxu->stamp))
1763		oxu->stamp++;
1764	timer_action_done(oxu, TIMER_ASYNC_SHRINK);
1765rescan:
1766	qh = oxu->async->qh_next.qh;
1767	if (likely(qh != NULL)) {
1768		do {
1769			/* clean any finished work for this qh */
1770			if (!list_empty(&qh->qtd_list)
1771					&& qh->stamp != oxu->stamp) {
1772				int temp;
1773
1774				/* unlinks could happen here; completion
1775				 * reporting drops the lock.  rescan using
1776				 * the latest schedule, but don't rescan
1777				 * qhs we already finished (no looping).
1778				 */
1779				qh = qh_get(qh);
1780				qh->stamp = oxu->stamp;
1781				temp = qh_completions(oxu, qh);
1782				qh_put(qh);
1783				if (temp != 0)
1784					goto rescan;
1785			}
1786
1787			/* unlink idle entries, reducing HC PCI usage as well
1788			 * as HCD schedule-scanning costs.  delay for any qh
1789			 * we just scanned, there's a not-unusual case that it
1790			 * doesn't stay idle for long.
1791			 * (plus, avoids some kind of re-activation race.)
1792			 */
1793			if (list_empty(&qh->qtd_list)) {
1794				if (qh->stamp == oxu->stamp)
1795					action = TIMER_ASYNC_SHRINK;
1796				else if (!oxu->reclaim
1797					    && qh->qh_state == QH_STATE_LINKED)
1798					start_unlink_async(oxu, qh);
1799			}
1800
1801			qh = qh->qh_next.qh;
1802		} while (qh);
1803	}
1804	if (action == TIMER_ASYNC_SHRINK)
1805		timer_action(oxu, TIMER_ASYNC_SHRINK);
1806}
1807
1808/*
1809 * periodic_next_shadow - return "next" pointer on shadow list
1810 * @periodic: host pointer to qh/itd/sitd
1811 * @tag: hardware tag for type of this record
1812 */
1813static union ehci_shadow *periodic_next_shadow(union ehci_shadow *periodic,
1814						__le32 tag)
1815{
1816	switch (tag) {
1817	default:
1818	case Q_TYPE_QH:
1819		return &periodic->qh->qh_next;
1820	}
1821}
1822
1823/* caller must hold oxu->lock */
1824static void periodic_unlink(struct oxu_hcd *oxu, unsigned frame, void *ptr)
1825{
1826	union ehci_shadow *prev_p = &oxu->pshadow[frame];
1827	__le32 *hw_p = &oxu->periodic[frame];
1828	union ehci_shadow here = *prev_p;
1829
1830	/* find predecessor of "ptr"; hw and shadow lists are in sync */
1831	while (here.ptr && here.ptr != ptr) {
1832		prev_p = periodic_next_shadow(prev_p, Q_NEXT_TYPE(*hw_p));
1833		hw_p = here.hw_next;
1834		here = *prev_p;
1835	}
1836	/* an interrupt entry (at list end) could have been shared */
1837	if (!here.ptr)
1838		return;
1839
1840	/* update shadow and hardware lists ... the old "next" pointers
1841	 * from ptr may still be in use, the caller updates them.
1842	 */
1843	*prev_p = *periodic_next_shadow(&here, Q_NEXT_TYPE(*hw_p));
1844	*hw_p = *here.hw_next;
1845}
1846
1847/* how many of the uframe's 125 usecs are allocated? */
1848static unsigned short periodic_usecs(struct oxu_hcd *oxu,
1849					unsigned frame, unsigned uframe)
1850{
1851	__le32 *hw_p = &oxu->periodic[frame];
1852	union ehci_shadow *q = &oxu->pshadow[frame];
1853	unsigned usecs = 0;
1854
1855	while (q->ptr) {
1856		switch (Q_NEXT_TYPE(*hw_p)) {
1857		case Q_TYPE_QH:
1858		default:
1859			/* is it in the S-mask? */
1860			if (q->qh->hw_info2 & cpu_to_le32(1 << uframe))
1861				usecs += q->qh->usecs;
1862			/* ... or C-mask? */
1863			if (q->qh->hw_info2 & cpu_to_le32(1 << (8 + uframe)))
1864				usecs += q->qh->c_usecs;
1865			hw_p = &q->qh->hw_next;
1866			q = &q->qh->qh_next;
1867			break;
1868		}
1869	}
1870#ifdef DEBUG
1871	if (usecs > 100)
1872		oxu_err(oxu, "uframe %d sched overrun: %d usecs\n",
1873						frame * 8 + uframe, usecs);
1874#endif
1875	return usecs;
1876}
1877
1878static int enable_periodic(struct oxu_hcd *oxu)
1879{
1880	u32 cmd;
1881	int status;
1882
1883	/* did clearing PSE did take effect yet?
1884	 * takes effect only at frame boundaries...
1885	 */
1886	status = handshake(oxu, &oxu->regs->status, STS_PSS, 0, 9 * 125);
1887	if (status != 0) {
1888		oxu_to_hcd(oxu)->state = HC_STATE_HALT;
1889		usb_hc_died(oxu_to_hcd(oxu));
1890		return status;
1891	}
1892
1893	cmd = readl(&oxu->regs->command) | CMD_PSE;
1894	writel(cmd, &oxu->regs->command);
1895	/* posted write ... PSS happens later */
1896	oxu_to_hcd(oxu)->state = HC_STATE_RUNNING;
1897
1898	/* make sure ehci_work scans these */
1899	oxu->next_uframe = readl(&oxu->regs->frame_index)
1900		% (oxu->periodic_size << 3);
1901	return 0;
1902}
1903
1904static int disable_periodic(struct oxu_hcd *oxu)
1905{
1906	u32 cmd;
1907	int status;
1908
1909	/* did setting PSE not take effect yet?
1910	 * takes effect only at frame boundaries...
1911	 */
1912	status = handshake(oxu, &oxu->regs->status, STS_PSS, STS_PSS, 9 * 125);
1913	if (status != 0) {
1914		oxu_to_hcd(oxu)->state = HC_STATE_HALT;
1915		usb_hc_died(oxu_to_hcd(oxu));
1916		return status;
1917	}
1918
1919	cmd = readl(&oxu->regs->command) & ~CMD_PSE;
1920	writel(cmd, &oxu->regs->command);
1921	/* posted write ... */
1922
1923	oxu->next_uframe = -1;
1924	return 0;
1925}
1926
1927/* periodic schedule slots have iso tds (normal or split) first, then a
1928 * sparse tree for active interrupt transfers.
1929 *
1930 * this just links in a qh; caller guarantees uframe masks are set right.
1931 * no FSTN support (yet; oxu 0.96+)
1932 */
1933static int qh_link_periodic(struct oxu_hcd *oxu, struct ehci_qh *qh)
1934{
1935	unsigned i;
1936	unsigned period = qh->period;
1937
1938	dev_dbg(&qh->dev->dev,
1939		"link qh%d-%04x/%p start %d [%d/%d us]\n",
1940		period, le32_to_cpup(&qh->hw_info2) & (QH_CMASK | QH_SMASK),
1941		qh, qh->start, qh->usecs, qh->c_usecs);
1942
1943	/* high bandwidth, or otherwise every microframe */
1944	if (period == 0)
1945		period = 1;
1946
1947	for (i = qh->start; i < oxu->periodic_size; i += period) {
1948		union ehci_shadow	*prev = &oxu->pshadow[i];
1949		__le32			*hw_p = &oxu->periodic[i];
1950		union ehci_shadow	here = *prev;
1951		__le32			type = 0;
1952
1953		/* skip the iso nodes at list head */
1954		while (here.ptr) {
1955			type = Q_NEXT_TYPE(*hw_p);
1956			if (type == Q_TYPE_QH)
1957				break;
1958			prev = periodic_next_shadow(prev, type);
1959			hw_p = &here.qh->hw_next;
1960			here = *prev;
1961		}
1962
1963		/* sorting each branch by period (slow-->fast)
1964		 * enables sharing interior tree nodes
1965		 */
1966		while (here.ptr && qh != here.qh) {
1967			if (qh->period > here.qh->period)
1968				break;
1969			prev = &here.qh->qh_next;
1970			hw_p = &here.qh->hw_next;
1971			here = *prev;
1972		}
1973		/* link in this qh, unless some earlier pass did that */
1974		if (qh != here.qh) {
1975			qh->qh_next = here;
1976			if (here.qh)
1977				qh->hw_next = *hw_p;
1978			wmb();
1979			prev->qh = qh;
1980			*hw_p = QH_NEXT(qh->qh_dma);
1981		}
1982	}
1983	qh->qh_state = QH_STATE_LINKED;
1984	qh_get(qh);
1985
1986	/* update per-qh bandwidth for usbfs */
1987	oxu_to_hcd(oxu)->self.bandwidth_allocated += qh->period
1988		? ((qh->usecs + qh->c_usecs) / qh->period)
1989		: (qh->usecs * 8);
1990
1991	/* maybe enable periodic schedule processing */
1992	if (!oxu->periodic_sched++)
1993		return enable_periodic(oxu);
1994
1995	return 0;
1996}
1997
1998static void qh_unlink_periodic(struct oxu_hcd *oxu, struct ehci_qh *qh)
1999{
2000	unsigned i;
2001	unsigned period;
2002
2003	/* FIXME:
2004	 *   IF this isn't high speed
2005	 *   and this qh is active in the current uframe
2006	 *   (and overlay token SplitXstate is false?)
2007	 * THEN
2008	 *   qh->hw_info1 |= cpu_to_le32(1 << 7 "ignore");
2009	 */
2010
2011	/* high bandwidth, or otherwise part of every microframe */
2012	period = qh->period;
2013	if (period == 0)
2014		period = 1;
2015
2016	for (i = qh->start; i < oxu->periodic_size; i += period)
2017		periodic_unlink(oxu, i, qh);
2018
2019	/* update per-qh bandwidth for usbfs */
2020	oxu_to_hcd(oxu)->self.bandwidth_allocated -= qh->period
2021		? ((qh->usecs + qh->c_usecs) / qh->period)
2022		: (qh->usecs * 8);
2023
2024	dev_dbg(&qh->dev->dev,
2025		"unlink qh%d-%04x/%p start %d [%d/%d us]\n",
2026		qh->period,
2027		le32_to_cpup(&qh->hw_info2) & (QH_CMASK | QH_SMASK),
2028		qh, qh->start, qh->usecs, qh->c_usecs);
2029
2030	/* qh->qh_next still "live" to HC */
2031	qh->qh_state = QH_STATE_UNLINK;
2032	qh->qh_next.ptr = NULL;
2033	qh_put(qh);
2034
2035	/* maybe turn off periodic schedule */
2036	oxu->periodic_sched--;
2037	if (!oxu->periodic_sched)
2038		(void) disable_periodic(oxu);
2039}
2040
2041static void intr_deschedule(struct oxu_hcd *oxu, struct ehci_qh *qh)
2042{
2043	unsigned wait;
2044
2045	qh_unlink_periodic(oxu, qh);
2046
2047	/* simple/paranoid:  always delay, expecting the HC needs to read
2048	 * qh->hw_next or finish a writeback after SPLIT/CSPLIT ... and
2049	 * expect khubd to clean up after any CSPLITs we won't issue.
2050	 * active high speed queues may need bigger delays...
2051	 */
2052	if (list_empty(&qh->qtd_list)
2053		|| (cpu_to_le32(QH_CMASK) & qh->hw_info2) != 0)
2054		wait = 2;
2055	else
2056		wait = 55;	/* worst case: 3 * 1024 */
2057
2058	udelay(wait);
2059	qh->qh_state = QH_STATE_IDLE;
2060	qh->hw_next = EHCI_LIST_END;
2061	wmb();
2062}
2063
2064static int check_period(struct oxu_hcd *oxu,
2065			unsigned frame, unsigned uframe,
2066			unsigned period, unsigned usecs)
2067{
2068	int claimed;
2069
2070	/* complete split running into next frame?
2071	 * given FSTN support, we could sometimes check...
2072	 */
2073	if (uframe >= 8)
2074		return 0;
2075
2076	/*
2077	 * 80% periodic == 100 usec/uframe available
2078	 * convert "usecs we need" to "max already claimed"
2079	 */
2080	usecs = 100 - usecs;
2081
2082	/* we "know" 2 and 4 uframe intervals were rejected; so
2083	 * for period 0, check _every_ microframe in the schedule.
2084	 */
2085	if (unlikely(period == 0)) {
2086		do {
2087			for (uframe = 0; uframe < 7; uframe++) {
2088				claimed = periodic_usecs(oxu, frame, uframe);
2089				if (claimed > usecs)
2090					return 0;
2091			}
2092		} while ((frame += 1) < oxu->periodic_size);
2093
2094	/* just check the specified uframe, at that period */
2095	} else {
2096		do {
2097			claimed = periodic_usecs(oxu, frame, uframe);
2098			if (claimed > usecs)
2099				return 0;
2100		} while ((frame += period) < oxu->periodic_size);
2101	}
2102
2103	return 1;
2104}
2105
2106static int check_intr_schedule(struct oxu_hcd	*oxu,
2107				unsigned frame, unsigned uframe,
2108				const struct ehci_qh *qh, __le32 *c_maskp)
2109{
2110	int retval = -ENOSPC;
2111
2112	if (qh->c_usecs && uframe >= 6)		/* FSTN territory? */
2113		goto done;
2114
2115	if (!check_period(oxu, frame, uframe, qh->period, qh->usecs))
2116		goto done;
2117	if (!qh->c_usecs) {
2118		retval = 0;
2119		*c_maskp = 0;
2120		goto done;
2121	}
2122
2123done:
2124	return retval;
2125}
2126
2127/* "first fit" scheduling policy used the first time through,
2128 * or when the previous schedule slot can't be re-used.
2129 */
2130static int qh_schedule(struct oxu_hcd *oxu, struct ehci_qh *qh)
2131{
2132	int		status;
2133	unsigned	uframe;
2134	__le32		c_mask;
2135	unsigned	frame;		/* 0..(qh->period - 1), or NO_FRAME */
2136
2137	qh_refresh(oxu, qh);
2138	qh->hw_next = EHCI_LIST_END;
2139	frame = qh->start;
2140
2141	/* reuse the previous schedule slots, if we can */
2142	if (frame < qh->period) {
2143		uframe = ffs(le32_to_cpup(&qh->hw_info2) & QH_SMASK);
2144		status = check_intr_schedule(oxu, frame, --uframe,
2145				qh, &c_mask);
2146	} else {
2147		uframe = 0;
2148		c_mask = 0;
2149		status = -ENOSPC;
2150	}
2151
2152	/* else scan the schedule to find a group of slots such that all
2153	 * uframes have enough periodic bandwidth available.
2154	 */
2155	if (status) {
2156		/* "normal" case, uframing flexible except with splits */
2157		if (qh->period) {
2158			frame = qh->period - 1;
2159			do {
2160				for (uframe = 0; uframe < 8; uframe++) {
2161					status = check_intr_schedule(oxu,
2162							frame, uframe, qh,
2163							&c_mask);
2164					if (status == 0)
2165						break;
2166				}
2167			} while (status && frame--);
2168
2169		/* qh->period == 0 means every uframe */
2170		} else {
2171			frame = 0;
2172			status = check_intr_schedule(oxu, 0, 0, qh, &c_mask);
2173		}
2174		if (status)
2175			goto done;
2176		qh->start = frame;
2177
2178		/* reset S-frame and (maybe) C-frame masks */
2179		qh->hw_info2 &= cpu_to_le32(~(QH_CMASK | QH_SMASK));
2180		qh->hw_info2 |= qh->period
2181			? cpu_to_le32(1 << uframe)
2182			: cpu_to_le32(QH_SMASK);
2183		qh->hw_info2 |= c_mask;
2184	} else
2185		oxu_dbg(oxu, "reused qh %p schedule\n", qh);
2186
2187	/* stuff into the periodic schedule */
2188	status = qh_link_periodic(oxu, qh);
2189done:
2190	return status;
2191}
2192
2193static int intr_submit(struct oxu_hcd *oxu, struct urb *urb,
2194			struct list_head *qtd_list, gfp_t mem_flags)
2195{
2196	unsigned epnum;
2197	unsigned long flags;
2198	struct ehci_qh *qh;
2199	int status = 0;
2200	struct list_head	empty;
2201
2202	/* get endpoint and transfer/schedule data */
2203	epnum = urb->ep->desc.bEndpointAddress;
2204
2205	spin_lock_irqsave(&oxu->lock, flags);
2206
2207	if (unlikely(!HCD_HW_ACCESSIBLE(oxu_to_hcd(oxu)))) {
2208		status = -ESHUTDOWN;
2209		goto done;
2210	}
2211
2212	/* get qh and force any scheduling errors */
2213	INIT_LIST_HEAD(&empty);
2214	qh = qh_append_tds(oxu, urb, &empty, epnum, &urb->ep->hcpriv);
2215	if (qh == NULL) {
2216		status = -ENOMEM;
2217		goto done;
2218	}
2219	if (qh->qh_state == QH_STATE_IDLE) {
2220		status = qh_schedule(oxu, qh);
2221		if (status != 0)
2222			goto done;
2223	}
2224
2225	/* then queue the urb's tds to the qh */
2226	qh = qh_append_tds(oxu, urb, qtd_list, epnum, &urb->ep->hcpriv);
2227	BUG_ON(qh == NULL);
2228
2229	/* ... update usbfs periodic stats */
2230	oxu_to_hcd(oxu)->self.bandwidth_int_reqs++;
2231
2232done:
2233	spin_unlock_irqrestore(&oxu->lock, flags);
2234	if (status)
2235		qtd_list_free(oxu, urb, qtd_list);
2236
2237	return status;
2238}
2239
2240static inline int itd_submit(struct oxu_hcd *oxu, struct urb *urb,
2241						gfp_t mem_flags)
2242{
2243	oxu_dbg(oxu, "iso support is missing!\n");
2244	return -ENOSYS;
2245}
2246
2247static inline int sitd_submit(struct oxu_hcd *oxu, struct urb *urb,
2248						gfp_t mem_flags)
2249{
2250	oxu_dbg(oxu, "split iso support is missing!\n");
2251	return -ENOSYS;
2252}
2253
2254static void scan_periodic(struct oxu_hcd *oxu)
2255{
2256	unsigned frame, clock, now_uframe, mod;
2257	unsigned modified;
2258
2259	mod = oxu->periodic_size << 3;
2260
2261	/*
2262	 * When running, scan from last scan point up to "now"
2263	 * else clean up by scanning everything that's left.
2264	 * Touches as few pages as possible:  cache-friendly.
2265	 */
2266	now_uframe = oxu->next_uframe;
2267	if (HC_IS_RUNNING(oxu_to_hcd(oxu)->state))
2268		clock = readl(&oxu->regs->frame_index);
2269	else
2270		clock = now_uframe + mod - 1;
2271	clock %= mod;
2272
2273	for (;;) {
2274		union ehci_shadow	q, *q_p;
2275		__le32			type, *hw_p;
2276		unsigned		uframes;
2277
2278		/* don't scan past the live uframe */
2279		frame = now_uframe >> 3;
2280		if (frame == (clock >> 3))
2281			uframes = now_uframe & 0x07;
2282		else {
2283			/* safe to scan the whole frame at once */
2284			now_uframe |= 0x07;
2285			uframes = 8;
2286		}
2287
2288restart:
2289		/* scan each element in frame's queue for completions */
2290		q_p = &oxu->pshadow[frame];
2291		hw_p = &oxu->periodic[frame];
2292		q.ptr = q_p->ptr;
2293		type = Q_NEXT_TYPE(*hw_p);
2294		modified = 0;
2295
2296		while (q.ptr != NULL) {
2297			union ehci_shadow temp;
2298			int live;
2299
2300			live = HC_IS_RUNNING(oxu_to_hcd(oxu)->state);
2301			switch (type) {
2302			case Q_TYPE_QH:
2303				/* handle any completions */
2304				temp.qh = qh_get(q.qh);
2305				type = Q_NEXT_TYPE(q.qh->hw_next);
2306				q = q.qh->qh_next;
2307				modified = qh_completions(oxu, temp.qh);
2308				if (unlikely(list_empty(&temp.qh->qtd_list)))
2309					intr_deschedule(oxu, temp.qh);
2310				qh_put(temp.qh);
2311				break;
2312			default:
2313				oxu_dbg(oxu, "corrupt type %d frame %d shadow %p\n",
2314					type, frame, q.ptr);
2315				q.ptr = NULL;
2316			}
2317
2318			/* assume completion callbacks modify the queue */
2319			if (unlikely(modified))
2320				goto restart;
2321		}
2322
2323		/* Stop when we catch up to the HC */
2324
2325		/* FIXME:  this assumes we won't get lapped when
2326		 * latencies climb; that should be rare, but...
2327		 * detect it, and just go all the way around.
2328		 * FLR might help detect this case, so long as latencies
2329		 * don't exceed periodic_size msec (default 1.024 sec).
2330		 */
2331
2332		/* FIXME: likewise assumes HC doesn't halt mid-scan */
2333
2334		if (now_uframe == clock) {
2335			unsigned	now;
2336
2337			if (!HC_IS_RUNNING(oxu_to_hcd(oxu)->state))
2338				break;
2339			oxu->next_uframe = now_uframe;
2340			now = readl(&oxu->regs->frame_index) % mod;
2341			if (now_uframe == now)
2342				break;
2343
2344			/* rescan the rest of this frame, then ... */
2345			clock = now;
2346		} else {
2347			now_uframe++;
2348			now_uframe %= mod;
2349		}
2350	}
2351}
2352
2353/* On some systems, leaving remote wakeup enabled prevents system shutdown.
2354 * The firmware seems to think that powering off is a wakeup event!
2355 * This routine turns off remote wakeup and everything else, on all ports.
2356 */
2357static void ehci_turn_off_all_ports(struct oxu_hcd *oxu)
2358{
2359	int port = HCS_N_PORTS(oxu->hcs_params);
2360
2361	while (port--)
2362		writel(PORT_RWC_BITS, &oxu->regs->port_status[port]);
2363}
2364
2365static void ehci_port_power(struct oxu_hcd *oxu, int is_on)
2366{
2367	unsigned port;
2368
2369	if (!HCS_PPC(oxu->hcs_params))
2370		return;
2371
2372	oxu_dbg(oxu, "...power%s ports...\n", is_on ? "up" : "down");
2373	for (port = HCS_N_PORTS(oxu->hcs_params); port > 0; )
2374		(void) oxu_hub_control(oxu_to_hcd(oxu),
2375				is_on ? SetPortFeature : ClearPortFeature,
2376				USB_PORT_FEAT_POWER,
2377				port--, NULL, 0);
2378	msleep(20);
2379}
2380
2381/* Called from some interrupts, timers, and so on.
2382 * It calls driver completion functions, after dropping oxu->lock.
2383 */
2384static void ehci_work(struct oxu_hcd *oxu)
2385{
2386	timer_action_done(oxu, TIMER_IO_WATCHDOG);
2387	if (oxu->reclaim_ready)
2388		end_unlink_async(oxu);
2389
2390	/* another CPU may drop oxu->lock during a schedule scan while
2391	 * it reports urb completions.  this flag guards against bogus
2392	 * attempts at re-entrant schedule scanning.
2393	 */
2394	if (oxu->scanning)
2395		return;
2396	oxu->scanning = 1;
2397	scan_async(oxu);
2398	if (oxu->next_uframe != -1)
2399		scan_periodic(oxu);
2400	oxu->scanning = 0;
2401
2402	/* the IO watchdog guards against hardware or driver bugs that
2403	 * misplace IRQs, and should let us run completely without IRQs.
2404	 * such lossage has been observed on both VT6202 and VT8235.
2405	 */
2406	if (HC_IS_RUNNING(oxu_to_hcd(oxu)->state) &&
2407			(oxu->async->qh_next.ptr != NULL ||
2408			 oxu->periodic_sched != 0))
2409		timer_action(oxu, TIMER_IO_WATCHDOG);
2410}
2411
2412static void unlink_async(struct oxu_hcd *oxu, struct ehci_qh *qh)
2413{
2414	/* if we need to use IAA and it's busy, defer */
2415	if (qh->qh_state == QH_STATE_LINKED
2416			&& oxu->reclaim
2417			&& HC_IS_RUNNING(oxu_to_hcd(oxu)->state)) {
2418		struct ehci_qh		*last;
2419
2420		for (last = oxu->reclaim;
2421				last->reclaim;
2422				last = last->reclaim)
2423			continue;
2424		qh->qh_state = QH_STATE_UNLINK_WAIT;
2425		last->reclaim = qh;
2426
2427	/* bypass IAA if the hc can't care */
2428	} else if (!HC_IS_RUNNING(oxu_to_hcd(oxu)->state) && oxu->reclaim)
2429		end_unlink_async(oxu);
2430
2431	/* something else might have unlinked the qh by now */
2432	if (qh->qh_state == QH_STATE_LINKED)
2433		start_unlink_async(oxu, qh);
2434}
2435
2436/*
2437 * USB host controller methods
2438 */
2439
2440static irqreturn_t oxu210_hcd_irq(struct usb_hcd *hcd)
2441{
2442	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2443	u32 status, pcd_status = 0;
2444	int bh;
2445
2446	spin_lock(&oxu->lock);
2447
2448	status = readl(&oxu->regs->status);
2449
2450	/* e.g. cardbus physical eject */
2451	if (status == ~(u32) 0) {
2452		oxu_dbg(oxu, "device removed\n");
2453		goto dead;
2454	}
2455
2456	/* Shared IRQ? */
2457	status &= INTR_MASK;
2458	if (!status || unlikely(hcd->state == HC_STATE_HALT)) {
2459		spin_unlock(&oxu->lock);
2460		return IRQ_NONE;
2461	}
2462
2463	/* clear (just) interrupts */
2464	writel(status, &oxu->regs->status);
2465	readl(&oxu->regs->command);	/* unblock posted write */
2466	bh = 0;
2467
2468#ifdef OXU_VERBOSE_DEBUG
2469	/* unrequested/ignored: Frame List Rollover */
2470	dbg_status(oxu, "irq", status);
2471#endif
2472
2473	/* INT, ERR, and IAA interrupt rates can be throttled */
2474
2475	/* normal [4.15.1.2] or error [4.15.1.1] completion */
2476	if (likely((status & (STS_INT|STS_ERR)) != 0))
2477		bh = 1;
2478
2479	/* complete the unlinking of some qh [4.15.2.3] */
2480	if (status & STS_IAA) {
2481		oxu->reclaim_ready = 1;
2482		bh = 1;
2483	}
2484
2485	/* remote wakeup [4.3.1] */
2486	if (status & STS_PCD) {
2487		unsigned i = HCS_N_PORTS(oxu->hcs_params);
2488		pcd_status = status;
2489
2490		/* resume root hub? */
2491		if (!(readl(&oxu->regs->command) & CMD_RUN))
2492			usb_hcd_resume_root_hub(hcd);
2493
2494		while (i--) {
2495			int pstatus = readl(&oxu->regs->port_status[i]);
2496
2497			if (pstatus & PORT_OWNER)
2498				continue;
2499			if (!(pstatus & PORT_RESUME)
2500					|| oxu->reset_done[i] != 0)
2501				continue;
2502
2503			/* start 20 msec resume signaling from this port,
2504			 * and make khubd collect PORT_STAT_C_SUSPEND to
2505			 * stop that signaling.
2506			 */
2507			oxu->reset_done[i] = jiffies + msecs_to_jiffies(20);
2508			oxu_dbg(oxu, "port %d remote wakeup\n", i + 1);
2509			mod_timer(&hcd->rh_timer, oxu->reset_done[i]);
2510		}
2511	}
2512
2513	/* PCI errors [4.15.2.4] */
2514	if (unlikely((status & STS_FATAL) != 0)) {
2515		/* bogus "fatal" IRQs appear on some chips... why?  */
2516		status = readl(&oxu->regs->status);
2517		dbg_cmd(oxu, "fatal", readl(&oxu->regs->command));
2518		dbg_status(oxu, "fatal", status);
2519		if (status & STS_HALT) {
2520			oxu_err(oxu, "fatal error\n");
2521dead:
2522			ehci_reset(oxu);
2523			writel(0, &oxu->regs->configured_flag);
2524			usb_hc_died(hcd);
2525			/* generic layer kills/unlinks all urbs, then
2526			 * uses oxu_stop to clean up the rest
2527			 */
2528			bh = 1;
2529		}
2530	}
2531
2532	if (bh)
2533		ehci_work(oxu);
2534	spin_unlock(&oxu->lock);
2535	if (pcd_status & STS_PCD)
2536		usb_hcd_poll_rh_status(hcd);
2537	return IRQ_HANDLED;
2538}
2539
2540static irqreturn_t oxu_irq(struct usb_hcd *hcd)
2541{
2542	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2543	int ret = IRQ_HANDLED;
2544
2545	u32 status = oxu_readl(hcd->regs, OXU_CHIPIRQSTATUS);
2546	u32 enable = oxu_readl(hcd->regs, OXU_CHIPIRQEN_SET);
2547
2548	/* Disable all interrupt */
2549	oxu_writel(hcd->regs, OXU_CHIPIRQEN_CLR, enable);
2550
2551	if ((oxu->is_otg && (status & OXU_USBOTGI)) ||
2552		(!oxu->is_otg && (status & OXU_USBSPHI)))
2553		oxu210_hcd_irq(hcd);
2554	else
2555		ret = IRQ_NONE;
2556
2557	/* Enable all interrupt back */
2558	oxu_writel(hcd->regs, OXU_CHIPIRQEN_SET, enable);
2559
2560	return ret;
2561}
2562
2563static void oxu_watchdog(unsigned long param)
2564{
2565	struct oxu_hcd	*oxu = (struct oxu_hcd *) param;
2566	unsigned long flags;
2567
2568	spin_lock_irqsave(&oxu->lock, flags);
2569
2570	/* lost IAA irqs wedge things badly; seen with a vt8235 */
2571	if (oxu->reclaim) {
2572		u32 status = readl(&oxu->regs->status);
2573		if (status & STS_IAA) {
2574			oxu_vdbg(oxu, "lost IAA\n");
2575			writel(STS_IAA, &oxu->regs->status);
2576			oxu->reclaim_ready = 1;
2577		}
2578	}
2579
2580	/* stop async processing after it's idled a bit */
2581	if (test_bit(TIMER_ASYNC_OFF, &oxu->actions))
2582		start_unlink_async(oxu, oxu->async);
2583
2584	/* oxu could run by timer, without IRQs ... */
2585	ehci_work(oxu);
2586
2587	spin_unlock_irqrestore(&oxu->lock, flags);
2588}
2589
2590/* One-time init, only for memory state.
2591 */
2592static int oxu_hcd_init(struct usb_hcd *hcd)
2593{
2594	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2595	u32 temp;
2596	int retval;
2597	u32 hcc_params;
2598
2599	spin_lock_init(&oxu->lock);
2600
2601	init_timer(&oxu->watchdog);
2602	oxu->watchdog.function = oxu_watchdog;
2603	oxu->watchdog.data = (unsigned long) oxu;
2604
2605	/*
2606	 * hw default: 1K periodic list heads, one per frame.
2607	 * periodic_size can shrink by USBCMD update if hcc_params allows.
2608	 */
2609	oxu->periodic_size = DEFAULT_I_TDPS;
2610	retval = ehci_mem_init(oxu, GFP_KERNEL);
2611	if (retval < 0)
2612		return retval;
2613
2614	/* controllers may cache some of the periodic schedule ... */
2615	hcc_params = readl(&oxu->caps->hcc_params);
2616	if (HCC_ISOC_CACHE(hcc_params))		/* full frame cache */
2617		oxu->i_thresh = 8;
2618	else					/* N microframes cached */
2619		oxu->i_thresh = 2 + HCC_ISOC_THRES(hcc_params);
2620
2621	oxu->reclaim = NULL;
2622	oxu->reclaim_ready = 0;
2623	oxu->next_uframe = -1;
2624
2625	/*
2626	 * dedicate a qh for the async ring head, since we couldn't unlink
2627	 * a 'real' qh without stopping the async schedule [4.8].  use it
2628	 * as the 'reclamation list head' too.
2629	 * its dummy is used in hw_alt_next of many tds, to prevent the qh
2630	 * from automatically advancing to the next td after short reads.
2631	 */
2632	oxu->async->qh_next.qh = NULL;
2633	oxu->async->hw_next = QH_NEXT(oxu->async->qh_dma);
2634	oxu->async->hw_info1 = cpu_to_le32(QH_HEAD);
2635	oxu->async->hw_token = cpu_to_le32(QTD_STS_HALT);
2636	oxu->async->hw_qtd_next = EHCI_LIST_END;
2637	oxu->async->qh_state = QH_STATE_LINKED;
2638	oxu->async->hw_alt_next = QTD_NEXT(oxu->async->dummy->qtd_dma);
2639
2640	/* clear interrupt enables, set irq latency */
2641	if (log2_irq_thresh < 0 || log2_irq_thresh > 6)
2642		log2_irq_thresh = 0;
2643	temp = 1 << (16 + log2_irq_thresh);
2644	if (HCC_CANPARK(hcc_params)) {
2645		/* HW default park == 3, on hardware that supports it (like
2646		 * NVidia and ALI silicon), maximizes throughput on the async
2647		 * schedule by avoiding QH fetches between transfers.
2648		 *
2649		 * With fast usb storage devices and NForce2, "park" seems to
2650		 * make problems:  throughput reduction (!), data errors...
2651		 */
2652		if (park) {
2653			park = min(park, (unsigned) 3);
2654			temp |= CMD_PARK;
2655			temp |= park << 8;
2656		}
2657		oxu_dbg(oxu, "park %d\n", park);
2658	}
2659	if (HCC_PGM_FRAMELISTLEN(hcc_params)) {
2660		/* periodic schedule size can be smaller than default */
2661		temp &= ~(3 << 2);
2662		temp |= (EHCI_TUNE_FLS << 2);
2663	}
2664	oxu->command = temp;
2665
2666	return 0;
2667}
2668
2669/* Called during probe() after chip reset completes.
2670 */
2671static int oxu_reset(struct usb_hcd *hcd)
2672{
2673	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2674	int ret;
2675
2676	spin_lock_init(&oxu->mem_lock);
2677	INIT_LIST_HEAD(&oxu->urb_list);
2678	oxu->urb_len = 0;
2679
2680	/* FIMXE */
2681	hcd->self.controller->dma_mask = NULL;
2682
2683	if (oxu->is_otg) {
2684		oxu->caps = hcd->regs + OXU_OTG_CAP_OFFSET;
2685		oxu->regs = hcd->regs + OXU_OTG_CAP_OFFSET + \
2686			HC_LENGTH(readl(&oxu->caps->hc_capbase));
2687
2688		oxu->mem = hcd->regs + OXU_SPH_MEM;
2689	} else {
2690		oxu->caps = hcd->regs + OXU_SPH_CAP_OFFSET;
2691		oxu->regs = hcd->regs + OXU_SPH_CAP_OFFSET + \
2692			HC_LENGTH(readl(&oxu->caps->hc_capbase));
2693
2694		oxu->mem = hcd->regs + OXU_OTG_MEM;
2695	}
2696
2697	oxu->hcs_params = readl(&oxu->caps->hcs_params);
2698	oxu->sbrn = 0x20;
2699
2700	ret = oxu_hcd_init(hcd);
2701	if (ret)
2702		return ret;
2703
2704	return 0;
2705}
2706
2707static int oxu_run(struct usb_hcd *hcd)
2708{
2709	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2710	int retval;
2711	u32 temp, hcc_params;
2712
2713	hcd->uses_new_polling = 1;
2714
2715	/* EHCI spec section 4.1 */
2716	retval = ehci_reset(oxu);
2717	if (retval != 0) {
2718		ehci_mem_cleanup(oxu);
2719		return retval;
2720	}
2721	writel(oxu->periodic_dma, &oxu->regs->frame_list);
2722	writel((u32) oxu->async->qh_dma, &oxu->regs->async_next);
2723
2724	/* hcc_params controls whether oxu->regs->segment must (!!!)
2725	 * be used; it constrains QH/ITD/SITD and QTD locations.
2726	 * pci_pool consistent memory always uses segment zero.
2727	 * streaming mappings for I/O buffers, like pci_map_single(),
2728	 * can return segments above 4GB, if the device allows.
2729	 *
2730	 * NOTE:  the dma mask is visible through dma_supported(), so
2731	 * drivers can pass this info along ... like NETIF_F_HIGHDMA,
2732	 * Scsi_Host.highmem_io, and so forth.  It's readonly to all
2733	 * host side drivers though.
2734	 */
2735	hcc_params = readl(&oxu->caps->hcc_params);
2736	if (HCC_64BIT_ADDR(hcc_params))
2737		writel(0, &oxu->regs->segment);
2738
2739	oxu->command &= ~(CMD_LRESET | CMD_IAAD | CMD_PSE |
2740				CMD_ASE | CMD_RESET);
2741	oxu->command |= CMD_RUN;
2742	writel(oxu->command, &oxu->regs->command);
2743	dbg_cmd(oxu, "init", oxu->command);
2744
2745	/*
2746	 * Start, enabling full USB 2.0 functionality ... usb 1.1 devices
2747	 * are explicitly handed to companion controller(s), so no TT is
2748	 * involved with the root hub.  (Except where one is integrated,
2749	 * and there's no companion controller unless maybe for USB OTG.)
2750	 */
2751	hcd->state = HC_STATE_RUNNING;
2752	writel(FLAG_CF, &oxu->regs->configured_flag);
2753	readl(&oxu->regs->command);	/* unblock posted writes */
2754
2755	temp = HC_VERSION(readl(&oxu->caps->hc_capbase));
2756	oxu_info(oxu, "USB %x.%x started, quasi-EHCI %x.%02x, driver %s%s\n",
2757		((oxu->sbrn & 0xf0)>>4), (oxu->sbrn & 0x0f),
2758		temp >> 8, temp & 0xff, DRIVER_VERSION,
2759		ignore_oc ? ", overcurrent ignored" : "");
2760
2761	writel(INTR_MASK, &oxu->regs->intr_enable); /* Turn On Interrupts */
2762
2763	return 0;
2764}
2765
2766static void oxu_stop(struct usb_hcd *hcd)
2767{
2768	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2769
2770	/* Turn off port power on all root hub ports. */
2771	ehci_port_power(oxu, 0);
2772
2773	/* no more interrupts ... */
2774	del_timer_sync(&oxu->watchdog);
2775
2776	spin_lock_irq(&oxu->lock);
2777	if (HC_IS_RUNNING(hcd->state))
2778		ehci_quiesce(oxu);
2779
2780	ehci_reset(oxu);
2781	writel(0, &oxu->regs->intr_enable);
2782	spin_unlock_irq(&oxu->lock);
2783
2784	/* let companion controllers work when we aren't */
2785	writel(0, &oxu->regs->configured_flag);
2786
2787	/* root hub is shut down separately (first, when possible) */
2788	spin_lock_irq(&oxu->lock);
2789	if (oxu->async)
2790		ehci_work(oxu);
2791	spin_unlock_irq(&oxu->lock);
2792	ehci_mem_cleanup(oxu);
2793
2794	dbg_status(oxu, "oxu_stop completed", readl(&oxu->regs->status));
2795}
2796
2797/* Kick in for silicon on any bus (not just pci, etc).
2798 * This forcibly disables dma and IRQs, helping kexec and other cases
2799 * where the next system software may expect clean state.
2800 */
2801static void oxu_shutdown(struct usb_hcd *hcd)
2802{
2803	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2804
2805	(void) ehci_halt(oxu);
2806	ehci_turn_off_all_ports(oxu);
2807
2808	/* make BIOS/etc use companion controller during reboot */
2809	writel(0, &oxu->regs->configured_flag);
2810
2811	/* unblock posted writes */
2812	readl(&oxu->regs->configured_flag);
2813}
2814
2815/* Non-error returns are a promise to giveback() the urb later
2816 * we drop ownership so next owner (or urb unlink) can get it
2817 *
2818 * urb + dev is in hcd.self.controller.urb_list
2819 * we're queueing TDs onto software and hardware lists
2820 *
2821 * hcd-specific init for hcpriv hasn't been done yet
2822 *
2823 * NOTE:  control, bulk, and interrupt share the same code to append TDs
2824 * to a (possibly active) QH, and the same QH scanning code.
2825 */
2826static int __oxu_urb_enqueue(struct usb_hcd *hcd, struct urb *urb,
2827				gfp_t mem_flags)
2828{
2829	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2830	struct list_head qtd_list;
2831
2832	INIT_LIST_HEAD(&qtd_list);
2833
2834	switch (usb_pipetype(urb->pipe)) {
2835	case PIPE_CONTROL:
2836	case PIPE_BULK:
2837	default:
2838		if (!qh_urb_transaction(oxu, urb, &qtd_list, mem_flags))
2839			return -ENOMEM;
2840		return submit_async(oxu, urb, &qtd_list, mem_flags);
2841
2842	case PIPE_INTERRUPT:
2843		if (!qh_urb_transaction(oxu, urb, &qtd_list, mem_flags))
2844			return -ENOMEM;
2845		return intr_submit(oxu, urb, &qtd_list, mem_flags);
2846
2847	case PIPE_ISOCHRONOUS:
2848		if (urb->dev->speed == USB_SPEED_HIGH)
2849			return itd_submit(oxu, urb, mem_flags);
2850		else
2851			return sitd_submit(oxu, urb, mem_flags);
2852	}
2853}
2854
2855/* This function is responsible for breaking URBs with big data size
2856 * into smaller size and processing small urbs in sequence.
2857 */
2858static int oxu_urb_enqueue(struct usb_hcd *hcd, struct urb *urb,
2859				gfp_t mem_flags)
2860{
2861	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2862	int num, rem;
2863	int transfer_buffer_length;
2864	void *transfer_buffer;
2865	struct urb *murb;
2866	int i, ret;
2867
2868	/* If not bulk pipe just enqueue the URB */
2869	if (!usb_pipebulk(urb->pipe))
2870		return __oxu_urb_enqueue(hcd, urb, mem_flags);
2871
2872	/* Otherwise we should verify the USB transfer buffer size! */
2873	transfer_buffer = urb->transfer_buffer;
2874	transfer_buffer_length = urb->transfer_buffer_length;
2875
2876	num = urb->transfer_buffer_length / 4096;
2877	rem = urb->transfer_buffer_length % 4096;
2878	if (rem != 0)
2879		num++;
2880
2881	/* If URB is smaller than 4096 bytes just enqueue it! */
2882	if (num == 1)
2883		return __oxu_urb_enqueue(hcd, urb, mem_flags);
2884
2885	/* Ok, we have more job to do! :) */
2886
2887	for (i = 0; i < num - 1; i++) {
2888		/* Get free micro URB poll till a free urb is received */
2889
2890		do {
2891			murb = (struct urb *) oxu_murb_alloc(oxu);
2892			if (!murb)
2893				schedule();
2894		} while (!murb);
2895
2896		/* Coping the urb */
2897		memcpy(murb, urb, sizeof(struct urb));
2898
2899		murb->transfer_buffer_length = 4096;
2900		murb->transfer_buffer = transfer_buffer + i * 4096;
2901
2902		/* Null pointer for the encodes that this is a micro urb */
2903		murb->complete = NULL;
2904
2905		((struct oxu_murb *) murb)->main = urb;
2906		((struct oxu_murb *) murb)->last = 0;
2907
2908		/* This loop is to guarantee urb to be processed when there's
2909		 * not enough resources at a particular time by retrying.
2910		 */
2911		do {
2912			ret  = __oxu_urb_enqueue(hcd, murb, mem_flags);
2913			if (ret)
2914				schedule();
2915		} while (ret);
2916	}
2917
2918	/* Last urb requires special handling  */
2919
2920	/* Get free micro URB poll till a free urb is received */
2921	do {
2922		murb = (struct urb *) oxu_murb_alloc(oxu);
2923		if (!murb)
2924			schedule();
2925	} while (!murb);
2926
2927	/* Coping the urb */
2928	memcpy(murb, urb, sizeof(struct urb));
2929
2930	murb->transfer_buffer_length = rem > 0 ? rem : 4096;
2931	murb->transfer_buffer = transfer_buffer + (num - 1) * 4096;
2932
2933	/* Null pointer for the encodes that this is a micro urb */
2934	murb->complete = NULL;
2935
2936	((struct oxu_murb *) murb)->main = urb;
2937	((struct oxu_murb *) murb)->last = 1;
2938
2939	do {
2940		ret = __oxu_urb_enqueue(hcd, murb, mem_flags);
2941		if (ret)
2942			schedule();
2943	} while (ret);
2944
2945	return ret;
2946}
2947
2948/* Remove from hardware lists.
2949 * Completions normally happen asynchronously
2950 */
2951static int oxu_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
2952{
2953	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
2954	struct ehci_qh *qh;
2955	unsigned long flags;
2956
2957	spin_lock_irqsave(&oxu->lock, flags);
2958	switch (usb_pipetype(urb->pipe)) {
2959	case PIPE_CONTROL:
2960	case PIPE_BULK:
2961	default:
2962		qh = (struct ehci_qh *) urb->hcpriv;
2963		if (!qh)
2964			break;
2965		unlink_async(oxu, qh);
2966		break;
2967
2968	case PIPE_INTERRUPT:
2969		qh = (struct ehci_qh *) urb->hcpriv;
2970		if (!qh)
2971			break;
2972		switch (qh->qh_state) {
2973		case QH_STATE_LINKED:
2974			intr_deschedule(oxu, qh);
2975			/* FALL THROUGH */
2976		case QH_STATE_IDLE:
2977			qh_completions(oxu, qh);
2978			break;
2979		default:
2980			oxu_dbg(oxu, "bogus qh %p state %d\n",
2981					qh, qh->qh_state);
2982			goto done;
2983		}
2984
2985		/* reschedule QH iff another request is queued */
2986		if (!list_empty(&qh->qtd_list)
2987				&& HC_IS_RUNNING(hcd->state)) {
2988			int status;
2989
2990			status = qh_schedule(oxu, qh);
2991			spin_unlock_irqrestore(&oxu->lock, flags);
2992
2993			if (status != 0) {
2994				/* shouldn't happen often, but ...
2995				 * FIXME kill those tds' urbs
2996				 */
2997				dev_err(hcd->self.controller,
2998					"can't reschedule qh %p, err %d\n", qh,
2999					status);
3000			}
3001			return status;
3002		}
3003		break;
3004	}
3005done:
3006	spin_unlock_irqrestore(&oxu->lock, flags);
3007	return 0;
3008}
3009
3010/* Bulk qh holds the data toggle */
3011static void oxu_endpoint_disable(struct usb_hcd *hcd,
3012					struct usb_host_endpoint *ep)
3013{
3014	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3015	unsigned long		flags;
3016	struct ehci_qh		*qh, *tmp;
3017
3018	/* ASSERT:  any requests/urbs are being unlinked */
3019	/* ASSERT:  nobody can be submitting urbs for this any more */
3020
3021rescan:
3022	spin_lock_irqsave(&oxu->lock, flags);
3023	qh = ep->hcpriv;
3024	if (!qh)
3025		goto done;
3026
3027	/* endpoints can be iso streams.  for now, we don't
3028	 * accelerate iso completions ... so spin a while.
3029	 */
3030	if (qh->hw_info1 == 0) {
3031		oxu_vdbg(oxu, "iso delay\n");
3032		goto idle_timeout;
3033	}
3034
3035	if (!HC_IS_RUNNING(hcd->state))
3036		qh->qh_state = QH_STATE_IDLE;
3037	switch (qh->qh_state) {
3038	case QH_STATE_LINKED:
3039		for (tmp = oxu->async->qh_next.qh;
3040				tmp && tmp != qh;
3041				tmp = tmp->qh_next.qh)
3042			continue;
3043		/* periodic qh self-unlinks on empty */
3044		if (!tmp)
3045			goto nogood;
3046		unlink_async(oxu, qh);
3047		/* FALL THROUGH */
3048	case QH_STATE_UNLINK:		/* wait for hw to finish? */
3049idle_timeout:
3050		spin_unlock_irqrestore(&oxu->lock, flags);
3051		schedule_timeout_uninterruptible(1);
3052		goto rescan;
3053	case QH_STATE_IDLE:		/* fully unlinked */
3054		if (list_empty(&qh->qtd_list)) {
3055			qh_put(qh);
3056			break;
3057		}
3058		/* else FALL THROUGH */
3059	default:
3060nogood:
3061		/* caller was supposed to have unlinked any requests;
3062		 * that's not our job.  just leak this memory.
3063		 */
3064		oxu_err(oxu, "qh %p (#%02x) state %d%s\n",
3065			qh, ep->desc.bEndpointAddress, qh->qh_state,
3066			list_empty(&qh->qtd_list) ? "" : "(has tds)");
3067		break;
3068	}
3069	ep->hcpriv = NULL;
3070done:
3071	spin_unlock_irqrestore(&oxu->lock, flags);
3072}
3073
3074static int oxu_get_frame(struct usb_hcd *hcd)
3075{
3076	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3077
3078	return (readl(&oxu->regs->frame_index) >> 3) %
3079		oxu->periodic_size;
3080}
3081
3082/* Build "status change" packet (one or two bytes) from HC registers */
3083static int oxu_hub_status_data(struct usb_hcd *hcd, char *buf)
3084{
3085	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3086	u32 temp, mask, status = 0;
3087	int ports, i, retval = 1;
3088	unsigned long flags;
3089
3090	/* if !PM_RUNTIME, root hub timers won't get shut down ... */
3091	if (!HC_IS_RUNNING(hcd->state))
3092		return 0;
3093
3094	/* init status to no-changes */
3095	buf[0] = 0;
3096	ports = HCS_N_PORTS(oxu->hcs_params);
3097	if (ports > 7) {
3098		buf[1] = 0;
3099		retval++;
3100	}
3101
3102	/* Some boards (mostly VIA?) report bogus overcurrent indications,
3103	 * causing massive log spam unless we completely ignore them.  It
3104	 * may be relevant that VIA VT8235 controllers, where PORT_POWER is
3105	 * always set, seem to clear PORT_OCC and PORT_CSC when writing to
3106	 * PORT_POWER; that's surprising, but maybe within-spec.
3107	 */
3108	if (!ignore_oc)
3109		mask = PORT_CSC | PORT_PEC | PORT_OCC;
3110	else
3111		mask = PORT_CSC | PORT_PEC;
3112
3113	/* no hub change reports (bit 0) for now (power, ...) */
3114
3115	/* port N changes (bit N)? */
3116	spin_lock_irqsave(&oxu->lock, flags);
3117	for (i = 0; i < ports; i++) {
3118		temp = readl(&oxu->regs->port_status[i]);
3119
3120		/*
3121		 * Return status information even for ports with OWNER set.
3122		 * Otherwise khubd wouldn't see the disconnect event when a
3123		 * high-speed device is switched over to the companion
3124		 * controller by the user.
3125		 */
3126
3127		if (!(temp & PORT_CONNECT))
3128			oxu->reset_done[i] = 0;
3129		if ((temp & mask) != 0 || ((temp & PORT_RESUME) != 0 &&
3130				time_after_eq(jiffies, oxu->reset_done[i]))) {
3131			if (i < 7)
3132				buf[0] |= 1 << (i + 1);
3133			else
3134				buf[1] |= 1 << (i - 7);
3135			status = STS_PCD;
3136		}
3137	}
3138	/* FIXME autosuspend idle root hubs */
3139	spin_unlock_irqrestore(&oxu->lock, flags);
3140	return status ? retval : 0;
3141}
3142
3143/* Returns the speed of a device attached to a port on the root hub. */
3144static inline unsigned int oxu_port_speed(struct oxu_hcd *oxu,
3145						unsigned int portsc)
3146{
3147	switch ((portsc >> 26) & 3) {
3148	case 0:
3149		return 0;
3150	case 1:
3151		return USB_PORT_STAT_LOW_SPEED;
3152	case 2:
3153	default:
3154		return USB_PORT_STAT_HIGH_SPEED;
3155	}
3156}
3157
3158#define	PORT_WAKE_BITS	(PORT_WKOC_E|PORT_WKDISC_E|PORT_WKCONN_E)
3159static int oxu_hub_control(struct usb_hcd *hcd, u16 typeReq,
3160				u16 wValue, u16 wIndex, char *buf, u16 wLength)
3161{
3162	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3163	int ports = HCS_N_PORTS(oxu->hcs_params);
3164	u32 __iomem *status_reg = &oxu->regs->port_status[wIndex - 1];
3165	u32 temp, status;
3166	unsigned long	flags;
3167	int retval = 0;
3168	unsigned selector;
3169
3170	/*
3171	 * FIXME:  support SetPortFeatures USB_PORT_FEAT_INDICATOR.
3172	 * HCS_INDICATOR may say we can change LEDs to off/amber/green.
3173	 * (track current state ourselves) ... blink for diagnostics,
3174	 * power, "this is the one", etc.  EHCI spec supports this.
3175	 */
3176
3177	spin_lock_irqsave(&oxu->lock, flags);
3178	switch (typeReq) {
3179	case ClearHubFeature:
3180		switch (wValue) {
3181		case C_HUB_LOCAL_POWER:
3182		case C_HUB_OVER_CURRENT:
3183			/* no hub-wide feature/status flags */
3184			break;
3185		default:
3186			goto error;
3187		}
3188		break;
3189	case ClearPortFeature:
3190		if (!wIndex || wIndex > ports)
3191			goto error;
3192		wIndex--;
3193		temp = readl(status_reg);
3194
3195		/*
3196		 * Even if OWNER is set, so the port is owned by the
3197		 * companion controller, khubd needs to be able to clear
3198		 * the port-change status bits (especially
3199		 * USB_PORT_STAT_C_CONNECTION).
3200		 */
3201
3202		switch (wValue) {
3203		case USB_PORT_FEAT_ENABLE:
3204			writel(temp & ~PORT_PE, status_reg);
3205			break;
3206		case USB_PORT_FEAT_C_ENABLE:
3207			writel((temp & ~PORT_RWC_BITS) | PORT_PEC, status_reg);
3208			break;
3209		case USB_PORT_FEAT_SUSPEND:
3210			if (temp & PORT_RESET)
3211				goto error;
3212			if (temp & PORT_SUSPEND) {
3213				if ((temp & PORT_PE) == 0)
3214					goto error;
3215				/* resume signaling for 20 msec */
3216				temp &= ~(PORT_RWC_BITS | PORT_WAKE_BITS);
3217				writel(temp | PORT_RESUME, status_reg);
3218				oxu->reset_done[wIndex] = jiffies
3219						+ msecs_to_jiffies(20);
3220			}
3221			break;
3222		case USB_PORT_FEAT_C_SUSPEND:
3223			/* we auto-clear this feature */
3224			break;
3225		case USB_PORT_FEAT_POWER:
3226			if (HCS_PPC(oxu->hcs_params))
3227				writel(temp & ~(PORT_RWC_BITS | PORT_POWER),
3228					  status_reg);
3229			break;
3230		case USB_PORT_FEAT_C_CONNECTION:
3231			writel((temp & ~PORT_RWC_BITS) | PORT_CSC, status_reg);
3232			break;
3233		case USB_PORT_FEAT_C_OVER_CURRENT:
3234			writel((temp & ~PORT_RWC_BITS) | PORT_OCC, status_reg);
3235			break;
3236		case USB_PORT_FEAT_C_RESET:
3237			/* GetPortStatus clears reset */
3238			break;
3239		default:
3240			goto error;
3241		}
3242		readl(&oxu->regs->command);	/* unblock posted write */
3243		break;
3244	case GetHubDescriptor:
3245		ehci_hub_descriptor(oxu, (struct usb_hub_descriptor *)
3246			buf);
3247		break;
3248	case GetHubStatus:
3249		/* no hub-wide feature/status flags */
3250		memset(buf, 0, 4);
3251		break;
3252	case GetPortStatus:
3253		if (!wIndex || wIndex > ports)
3254			goto error;
3255		wIndex--;
3256		status = 0;
3257		temp = readl(status_reg);
3258
3259		/* wPortChange bits */
3260		if (temp & PORT_CSC)
3261			status |= USB_PORT_STAT_C_CONNECTION << 16;
3262		if (temp & PORT_PEC)
3263			status |= USB_PORT_STAT_C_ENABLE << 16;
3264		if ((temp & PORT_OCC) && !ignore_oc)
3265			status |= USB_PORT_STAT_C_OVERCURRENT << 16;
3266
3267		/* whoever resumes must GetPortStatus to complete it!! */
3268		if (temp & PORT_RESUME) {
3269
3270			/* Remote Wakeup received? */
3271			if (!oxu->reset_done[wIndex]) {
3272				/* resume signaling for 20 msec */
3273				oxu->reset_done[wIndex] = jiffies
3274						+ msecs_to_jiffies(20);
3275				/* check the port again */
3276				mod_timer(&oxu_to_hcd(oxu)->rh_timer,
3277						oxu->reset_done[wIndex]);
3278			}
3279
3280			/* resume completed? */
3281			else if (time_after_eq(jiffies,
3282					oxu->reset_done[wIndex])) {
3283				status |= USB_PORT_STAT_C_SUSPEND << 16;
3284				oxu->reset_done[wIndex] = 0;
3285
3286				/* stop resume signaling */
3287				temp = readl(status_reg);
3288				writel(temp & ~(PORT_RWC_BITS | PORT_RESUME),
3289					status_reg);
3290				retval = handshake(oxu, status_reg,
3291					   PORT_RESUME, 0, 2000 /* 2msec */);
3292				if (retval != 0) {
3293					oxu_err(oxu,
3294						"port %d resume error %d\n",
3295						wIndex + 1, retval);
3296					goto error;
3297				}
3298				temp &= ~(PORT_SUSPEND|PORT_RESUME|(3<<10));
3299			}
3300		}
3301
3302		/* whoever resets must GetPortStatus to complete it!! */
3303		if ((temp & PORT_RESET)
3304				&& time_after_eq(jiffies,
3305					oxu->reset_done[wIndex])) {
3306			status |= USB_PORT_STAT_C_RESET << 16;
3307			oxu->reset_done[wIndex] = 0;
3308
3309			/* force reset to complete */
3310			writel(temp & ~(PORT_RWC_BITS | PORT_RESET),
3311					status_reg);
3312			/* REVISIT:  some hardware needs 550+ usec to clear
3313			 * this bit; seems too long to spin routinely...
3314			 */
3315			retval = handshake(oxu, status_reg,
3316					PORT_RESET, 0, 750);
3317			if (retval != 0) {
3318				oxu_err(oxu, "port %d reset error %d\n",
3319					wIndex + 1, retval);
3320				goto error;
3321			}
3322
3323			/* see what we found out */
3324			temp = check_reset_complete(oxu, wIndex, status_reg,
3325					readl(status_reg));
3326		}
3327
3328		/* transfer dedicated ports to the companion hc */
3329		if ((temp & PORT_CONNECT) &&
3330				test_bit(wIndex, &oxu->companion_ports)) {
3331			temp &= ~PORT_RWC_BITS;
3332			temp |= PORT_OWNER;
3333			writel(temp, status_reg);
3334			oxu_dbg(oxu, "port %d --> companion\n", wIndex + 1);
3335			temp = readl(status_reg);
3336		}
3337
3338		/*
3339		 * Even if OWNER is set, there's no harm letting khubd
3340		 * see the wPortStatus values (they should all be 0 except
3341		 * for PORT_POWER anyway).
3342		 */
3343
3344		if (temp & PORT_CONNECT) {
3345			status |= USB_PORT_STAT_CONNECTION;
3346			/* status may be from integrated TT */
3347			status |= oxu_port_speed(oxu, temp);
3348		}
3349		if (temp & PORT_PE)
3350			status |= USB_PORT_STAT_ENABLE;
3351		if (temp & (PORT_SUSPEND|PORT_RESUME))
3352			status |= USB_PORT_STAT_SUSPEND;
3353		if (temp & PORT_OC)
3354			status |= USB_PORT_STAT_OVERCURRENT;
3355		if (temp & PORT_RESET)
3356			status |= USB_PORT_STAT_RESET;
3357		if (temp & PORT_POWER)
3358			status |= USB_PORT_STAT_POWER;
3359
3360#ifndef	OXU_VERBOSE_DEBUG
3361	if (status & ~0xffff)	/* only if wPortChange is interesting */
3362#endif
3363		dbg_port(oxu, "GetStatus", wIndex + 1, temp);
3364		put_unaligned(cpu_to_le32(status), (__le32 *) buf);
3365		break;
3366	case SetHubFeature:
3367		switch (wValue) {
3368		case C_HUB_LOCAL_POWER:
3369		case C_HUB_OVER_CURRENT:
3370			/* no hub-wide feature/status flags */
3371			break;
3372		default:
3373			goto error;
3374		}
3375		break;
3376	case SetPortFeature:
3377		selector = wIndex >> 8;
3378		wIndex &= 0xff;
3379		if (!wIndex || wIndex > ports)
3380			goto error;
3381		wIndex--;
3382		temp = readl(status_reg);
3383		if (temp & PORT_OWNER)
3384			break;
3385
3386		temp &= ~PORT_RWC_BITS;
3387		switch (wValue) {
3388		case USB_PORT_FEAT_SUSPEND:
3389			if ((temp & PORT_PE) == 0
3390					|| (temp & PORT_RESET) != 0)
3391				goto error;
3392			if (device_may_wakeup(&hcd->self.root_hub->dev))
3393				temp |= PORT_WAKE_BITS;
3394			writel(temp | PORT_SUSPEND, status_reg);
3395			break;
3396		case USB_PORT_FEAT_POWER:
3397			if (HCS_PPC(oxu->hcs_params))
3398				writel(temp | PORT_POWER, status_reg);
3399			break;
3400		case USB_PORT_FEAT_RESET:
3401			if (temp & PORT_RESUME)
3402				goto error;
3403			/* line status bits may report this as low speed,
3404			 * which can be fine if this root hub has a
3405			 * transaction translator built in.
3406			 */
3407			oxu_vdbg(oxu, "port %d reset\n", wIndex + 1);
3408			temp |= PORT_RESET;
3409			temp &= ~PORT_PE;
3410
3411			/*
3412			 * caller must wait, then call GetPortStatus
3413			 * usb 2.0 spec says 50 ms resets on root
3414			 */
3415			oxu->reset_done[wIndex] = jiffies
3416					+ msecs_to_jiffies(50);
3417			writel(temp, status_reg);
3418			break;
3419
3420		/* For downstream facing ports (these):  one hub port is put
3421		 * into test mode according to USB2 11.24.2.13, then the hub
3422		 * must be reset (which for root hub now means rmmod+modprobe,
3423		 * or else system reboot).  See EHCI 2.3.9 and 4.14 for info
3424		 * about the EHCI-specific stuff.
3425		 */
3426		case USB_PORT_FEAT_TEST:
3427			if (!selector || selector > 5)
3428				goto error;
3429			ehci_quiesce(oxu);
3430			ehci_halt(oxu);
3431			temp |= selector << 16;
3432			writel(temp, status_reg);
3433			break;
3434
3435		default:
3436			goto error;
3437		}
3438		readl(&oxu->regs->command);	/* unblock posted writes */
3439		break;
3440
3441	default:
3442error:
3443		/* "stall" on error */
3444		retval = -EPIPE;
3445	}
3446	spin_unlock_irqrestore(&oxu->lock, flags);
3447	return retval;
3448}
3449
3450#ifdef CONFIG_PM
3451
3452static int oxu_bus_suspend(struct usb_hcd *hcd)
3453{
3454	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3455	int port;
3456	int mask;
3457
3458	oxu_dbg(oxu, "suspend root hub\n");
3459
3460	if (time_before(jiffies, oxu->next_statechange))
3461		msleep(5);
3462
3463	port = HCS_N_PORTS(oxu->hcs_params);
3464	spin_lock_irq(&oxu->lock);
3465
3466	/* stop schedules, clean any completed work */
3467	if (HC_IS_RUNNING(hcd->state)) {
3468		ehci_quiesce(oxu);
3469		hcd->state = HC_STATE_QUIESCING;
3470	}
3471	oxu->command = readl(&oxu->regs->command);
3472	if (oxu->reclaim)
3473		oxu->reclaim_ready = 1;
3474	ehci_work(oxu);
3475
3476	/* Unlike other USB host controller types, EHCI doesn't have
3477	 * any notion of "global" or bus-wide suspend.  The driver has
3478	 * to manually suspend all the active unsuspended ports, and
3479	 * then manually resume them in the bus_resume() routine.
3480	 */
3481	oxu->bus_suspended = 0;
3482	while (port--) {
3483		u32 __iomem *reg = &oxu->regs->port_status[port];
3484		u32 t1 = readl(reg) & ~PORT_RWC_BITS;
3485		u32 t2 = t1;
3486
3487		/* keep track of which ports we suspend */
3488		if ((t1 & PORT_PE) && !(t1 & PORT_OWNER) &&
3489				!(t1 & PORT_SUSPEND)) {
3490			t2 |= PORT_SUSPEND;
3491			set_bit(port, &oxu->bus_suspended);
3492		}
3493
3494		/* enable remote wakeup on all ports */
3495		if (device_may_wakeup(&hcd->self.root_hub->dev))
3496			t2 |= PORT_WKOC_E|PORT_WKDISC_E|PORT_WKCONN_E;
3497		else
3498			t2 &= ~(PORT_WKOC_E|PORT_WKDISC_E|PORT_WKCONN_E);
3499
3500		if (t1 != t2) {
3501			oxu_vdbg(oxu, "port %d, %08x -> %08x\n",
3502				port + 1, t1, t2);
3503			writel(t2, reg);
3504		}
3505	}
3506
3507	/* turn off now-idle HC */
3508	del_timer_sync(&oxu->watchdog);
3509	ehci_halt(oxu);
3510	hcd->state = HC_STATE_SUSPENDED;
3511
3512	/* allow remote wakeup */
3513	mask = INTR_MASK;
3514	if (!device_may_wakeup(&hcd->self.root_hub->dev))
3515		mask &= ~STS_PCD;
3516	writel(mask, &oxu->regs->intr_enable);
3517	readl(&oxu->regs->intr_enable);
3518
3519	oxu->next_statechange = jiffies + msecs_to_jiffies(10);
3520	spin_unlock_irq(&oxu->lock);
3521	return 0;
3522}
3523
3524/* Caller has locked the root hub, and should reset/reinit on error */
3525static int oxu_bus_resume(struct usb_hcd *hcd)
3526{
3527	struct oxu_hcd *oxu = hcd_to_oxu(hcd);
3528	u32 temp;
3529	int i;
3530
3531	if (time_before(jiffies, oxu->next_statechange))
3532		msleep(5);
3533	spin_lock_irq(&oxu->lock);
3534
3535	/* Ideally and we've got a real resume here, and no port's power
3536	 * was lost.  (For PCI, that means Vaux was maintained.)  But we
3537	 * could instead be restoring a swsusp snapshot -- so that BIOS was
3538	 * the last user of the controller, not reset/pm hardware keeping
3539	 * state we gave to it.
3540	 */
3541	temp = readl(&oxu->regs->intr_enable);
3542	oxu_dbg(oxu, "resume root hub%s\n", temp ? "" : " after power loss");
3543
3544	/* at least some APM implementations will try to deliver
3545	 * IRQs right away, so delay them until we're ready.
3546	 */
3547	writel(0, &oxu->regs->intr_enable);
3548
3549	/* re-init operational registers */
3550	writel(0, &oxu->regs->segment);
3551	writel(oxu->periodic_dma, &oxu->regs->frame_list);
3552	writel((u32) oxu->async->qh_dma, &oxu->regs->async_next);
3553
3554	/* restore CMD_RUN, framelist size, and irq threshold */
3555	writel(oxu->command, &oxu->regs->command);
3556
3557	/* Some controller/firmware combinations need a delay during which
3558	 * they set up the port statuses.  See Bugzilla #8190. */
3559	mdelay(8);
3560
3561	/* manually resume the ports we suspended during bus_suspend() */
3562	i = HCS_N_PORTS(oxu->hcs_params);
3563	while (i--) {
3564		temp = readl(&oxu->regs->port_status[i]);
3565		temp &= ~(PORT_RWC_BITS
3566			| PORT_WKOC_E | PORT_WKDISC_E | PORT_WKCONN_E);
3567		if (test_bit(i, &oxu->bus_suspended) && (temp & PORT_SUSPEND)) {
3568			oxu->reset_done[i] = jiffies + msecs_to_jiffies(20);
3569			temp |= PORT_RESUME;
3570		}
3571		writel(temp, &oxu->regs->port_status[i]);
3572	}
3573	i = HCS_N_PORTS(oxu->hcs_params);
3574	mdelay(20);
3575	while (i--) {
3576		temp = readl(&oxu->regs->port_status[i]);
3577		if (test_bit(i, &oxu->bus_suspended) && (temp & PORT_SUSPEND)) {
3578			temp &= ~(PORT_RWC_BITS | PORT_RESUME);
3579			writel(temp, &oxu->regs->port_status[i]);
3580			oxu_vdbg(oxu, "resumed port %d\n", i + 1);
3581		}
3582	}
3583	(void) readl(&oxu->regs->command);
3584
3585	/* maybe re-activate the schedule(s) */
3586	temp = 0;
3587	if (oxu->async->qh_next.qh)
3588		temp |= CMD_ASE;
3589	if (oxu->periodic_sched)
3590		temp |= CMD_PSE;
3591	if (temp) {
3592		oxu->command |= temp;
3593		writel(oxu->command, &oxu->regs->command);
3594	}
3595
3596	oxu->next_statechange = jiffies + msecs_to_jiffies(5);
3597	hcd->state = HC_STATE_RUNNING;
3598
3599	/* Now we can safely re-enable irqs */
3600	writel(INTR_MASK, &oxu->regs->intr_enable);
3601
3602	spin_unlock_irq(&oxu->lock);
3603	return 0;
3604}
3605
3606#else
3607
3608static int oxu_bus_suspend(struct usb_hcd *hcd)
3609{
3610	return 0;
3611}
3612
3613static int oxu_bus_resume(struct usb_hcd *hcd)
3614{
3615	return 0;
3616}
3617
3618#endif	/* CONFIG_PM */
3619
3620static const struct hc_driver oxu_hc_driver = {
3621	.description =		"oxu210hp_hcd",
3622	.product_desc =		"oxu210hp HCD",
3623	.hcd_priv_size =	sizeof(struct oxu_hcd),
3624
3625	/*
3626	 * Generic hardware linkage
3627	 */
3628	.irq =			oxu_irq,
3629	.flags =		HCD_MEMORY | HCD_USB2,
3630
3631	/*
3632	 * Basic lifecycle operations
3633	 */
3634	.reset =		oxu_reset,
3635	.start =		oxu_run,
3636	.stop =			oxu_stop,
3637	.shutdown =		oxu_shutdown,
3638
3639	/*
3640	 * Managing i/o requests and associated device resources
3641	 */
3642	.urb_enqueue =		oxu_urb_enqueue,
3643	.urb_dequeue =		oxu_urb_dequeue,
3644	.endpoint_disable =	oxu_endpoint_disable,
3645
3646	/*
3647	 * Scheduling support
3648	 */
3649	.get_frame_number =	oxu_get_frame,
3650
3651	/*
3652	 * Root hub support
3653	 */
3654	.hub_status_data =	oxu_hub_status_data,
3655	.hub_control =		oxu_hub_control,
3656	.bus_suspend =		oxu_bus_suspend,
3657	.bus_resume =		oxu_bus_resume,
3658};
3659
3660/*
3661 * Module stuff
3662 */
3663
3664static void oxu_configuration(struct platform_device *pdev, void *base)
3665{
3666	u32 tmp;
3667
3668	/* Initialize top level registers.
3669	 * First write ever
3670	 */
3671	oxu_writel(base, OXU_HOSTIFCONFIG, 0x0000037D);
3672	oxu_writel(base, OXU_SOFTRESET, OXU_SRESET);
3673	oxu_writel(base, OXU_HOSTIFCONFIG, 0x0000037D);
3674
3675	tmp = oxu_readl(base, OXU_PIOBURSTREADCTRL);
3676	oxu_writel(base, OXU_PIOBURSTREADCTRL, tmp | 0x0040);
3677
3678	oxu_writel(base, OXU_ASO, OXU_SPHPOEN | OXU_OVRCCURPUPDEN |
3679					OXU_COMPARATOR | OXU_ASO_OP);
3680
3681	tmp = oxu_readl(base, OXU_CLKCTRL_SET);
3682	oxu_writel(base, OXU_CLKCTRL_SET, tmp | OXU_SYSCLKEN | OXU_USBOTGCLKEN);
3683
3684	/* Clear all top interrupt enable */
3685	oxu_writel(base, OXU_CHIPIRQEN_CLR, 0xff);
3686
3687	/* Clear all top interrupt status */
3688	oxu_writel(base, OXU_CHIPIRQSTATUS, 0xff);
3689
3690	/* Enable all needed top interrupt except OTG SPH core */
3691	oxu_writel(base, OXU_CHIPIRQEN_SET, OXU_USBSPHLPWUI | OXU_USBOTGLPWUI);
3692}
3693
3694static int oxu_verify_id(struct platform_device *pdev, void *base)
3695{
3696	u32 id;
3697	static const char * const bo[] = {
3698		"reserved",
3699		"128-pin LQFP",
3700		"84-pin TFBGA",
3701		"reserved",
3702	};
3703
3704	/* Read controller signature register to find a match */
3705	id = oxu_readl(base, OXU_DEVICEID);
3706	dev_info(&pdev->dev, "device ID %x\n", id);
3707	if ((id & OXU_REV_MASK) != (OXU_REV_2100 << OXU_REV_SHIFT))
3708		return -1;
3709
3710	dev_info(&pdev->dev, "found device %x %s (%04x:%04x)\n",
3711		id >> OXU_REV_SHIFT,
3712		bo[(id & OXU_BO_MASK) >> OXU_BO_SHIFT],
3713		(id & OXU_MAJ_REV_MASK) >> OXU_MAJ_REV_SHIFT,
3714		(id & OXU_MIN_REV_MASK) >> OXU_MIN_REV_SHIFT);
3715
3716	return 0;
3717}
3718
3719static const struct hc_driver oxu_hc_driver;
3720static struct usb_hcd *oxu_create(struct platform_device *pdev,
3721				unsigned long memstart, unsigned long memlen,
3722				void *base, int irq, int otg)
3723{
3724	struct device *dev = &pdev->dev;
3725
3726	struct usb_hcd *hcd;
3727	struct oxu_hcd *oxu;
3728	int ret;
3729
3730	/* Set endian mode and host mode */
3731	oxu_writel(base + (otg ? OXU_OTG_CORE_OFFSET : OXU_SPH_CORE_OFFSET),
3732				OXU_USBMODE,
3733				OXU_CM_HOST_ONLY | OXU_ES_LITTLE | OXU_VBPS);
3734
3735	hcd = usb_create_hcd(&oxu_hc_driver, dev,
3736				otg ? "oxu210hp_otg" : "oxu210hp_sph");
3737	if (!hcd)
3738		return ERR_PTR(-ENOMEM);
3739
3740	hcd->rsrc_start = memstart;
3741	hcd->rsrc_len = memlen;
3742	hcd->regs = base;
3743	hcd->irq = irq;
3744	hcd->state = HC_STATE_HALT;
3745
3746	oxu = hcd_to_oxu(hcd);
3747	oxu->is_otg = otg;
3748
3749	ret = usb_add_hcd(hcd, irq, IRQF_SHARED);
3750	if (ret < 0)
3751		return ERR_PTR(ret);
3752
3753	device_wakeup_enable(hcd->self.controller);
3754	return hcd;
3755}
3756
3757static int oxu_init(struct platform_device *pdev,
3758				unsigned long memstart, unsigned long memlen,
3759				void *base, int irq)
3760{
3761	struct oxu_info *info = platform_get_drvdata(pdev);
3762	struct usb_hcd *hcd;
3763	int ret;
3764
3765	/* First time configuration at start up */
3766	oxu_configuration(pdev, base);
3767
3768	ret = oxu_verify_id(pdev, base);
3769	if (ret) {
3770		dev_err(&pdev->dev, "no devices found!\n");
3771		return -ENODEV;
3772	}
3773
3774	/* Create the OTG controller */
3775	hcd = oxu_create(pdev, memstart, memlen, base, irq, 1);
3776	if (IS_ERR(hcd)) {
3777		dev_err(&pdev->dev, "cannot create OTG controller!\n");
3778		ret = PTR_ERR(hcd);
3779		goto error_create_otg;
3780	}
3781	info->hcd[0] = hcd;
3782
3783	/* Create the SPH host controller */
3784	hcd = oxu_create(pdev, memstart, memlen, base, irq, 0);
3785	if (IS_ERR(hcd)) {
3786		dev_err(&pdev->dev, "cannot create SPH controller!\n");
3787		ret = PTR_ERR(hcd);
3788		goto error_create_sph;
3789	}
3790	info->hcd[1] = hcd;
3791
3792	oxu_writel(base, OXU_CHIPIRQEN_SET,
3793		oxu_readl(base, OXU_CHIPIRQEN_SET) | 3);
3794
3795	return 0;
3796
3797error_create_sph:
3798	usb_remove_hcd(info->hcd[0]);
3799	usb_put_hcd(info->hcd[0]);
3800
3801error_create_otg:
3802	return ret;
3803}
3804
3805static int oxu_drv_probe(struct platform_device *pdev)
3806{
3807	struct resource *res;
3808	void *base;
3809	unsigned long memstart, memlen;
3810	int irq, ret;
3811	struct oxu_info *info;
3812
3813	if (usb_disabled())
3814		return -ENODEV;
3815
3816	/*
3817	 * Get the platform resources
3818	 */
3819	res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
3820	if (!res) {
3821		dev_err(&pdev->dev,
3822			"no IRQ! Check %s setup!\n", dev_name(&pdev->dev));
3823		return -ENODEV;
3824	}
3825	irq = res->start;
3826	dev_dbg(&pdev->dev, "IRQ resource %d\n", irq);
3827
3828	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
3829	if (!res) {
3830		dev_err(&pdev->dev, "no registers address! Check %s setup!\n",
3831			dev_name(&pdev->dev));
3832		return -ENODEV;
3833	}
3834	memstart = res->start;
3835	memlen = resource_size(res);
3836	dev_dbg(&pdev->dev, "MEM resource %lx-%lx\n", memstart, memlen);
3837	if (!request_mem_region(memstart, memlen,
3838				oxu_hc_driver.description)) {
3839		dev_dbg(&pdev->dev, "memory area already in use\n");
3840		return -EBUSY;
3841	}
3842
3843	ret = irq_set_irq_type(irq, IRQF_TRIGGER_FALLING);
3844	if (ret) {
3845		dev_err(&pdev->dev, "error setting irq type\n");
3846		ret = -EFAULT;
3847		goto error_set_irq_type;
3848	}
3849
3850	base = ioremap(memstart, memlen);
3851	if (!base) {
3852		dev_dbg(&pdev->dev, "error mapping memory\n");
3853		ret = -EFAULT;
3854		goto error_ioremap;
3855	}
3856
3857	/* Allocate a driver data struct to hold useful info for both
3858	 * SPH & OTG devices
3859	 */
3860	info = kzalloc(sizeof(struct oxu_info), GFP_KERNEL);
3861	if (!info) {
3862		dev_dbg(&pdev->dev, "error allocating memory\n");
3863		ret = -EFAULT;
3864		goto error_alloc;
3865	}
3866	platform_set_drvdata(pdev, info);
3867
3868	ret = oxu_init(pdev, memstart, memlen, base, irq);
3869	if (ret < 0) {
3870		dev_dbg(&pdev->dev, "cannot init USB devices\n");
3871		goto error_init;
3872	}
3873
3874	dev_info(&pdev->dev, "devices enabled and running\n");
3875	platform_set_drvdata(pdev, info);
3876
3877	return 0;
3878
3879error_init:
3880	kfree(info);
 
3881
3882error_alloc:
3883	iounmap(base);
3884
3885error_set_irq_type:
3886error_ioremap:
3887	release_mem_region(memstart, memlen);
3888
3889	dev_err(&pdev->dev, "init %s fail, %d\n", dev_name(&pdev->dev), ret);
3890	return ret;
3891}
3892
3893static void oxu_remove(struct platform_device *pdev, struct usb_hcd *hcd)
3894{
3895	usb_remove_hcd(hcd);
3896	usb_put_hcd(hcd);
3897}
3898
3899static int oxu_drv_remove(struct platform_device *pdev)
3900{
3901	struct oxu_info *info = platform_get_drvdata(pdev);
3902	unsigned long memstart = info->hcd[0]->rsrc_start,
3903			memlen = info->hcd[0]->rsrc_len;
3904	void *base = info->hcd[0]->regs;
3905
3906	oxu_remove(pdev, info->hcd[0]);
3907	oxu_remove(pdev, info->hcd[1]);
3908
3909	iounmap(base);
3910	release_mem_region(memstart, memlen);
3911
3912	kfree(info);
 
3913
3914	return 0;
3915}
3916
3917static void oxu_drv_shutdown(struct platform_device *pdev)
3918{
3919	oxu_drv_remove(pdev);
3920}
3921
3922#if 0
3923/* FIXME: TODO */
3924static int oxu_drv_suspend(struct device *dev)
3925{
3926	struct platform_device *pdev = to_platform_device(dev);
3927	struct usb_hcd *hcd = dev_get_drvdata(dev);
3928
3929	return 0;
3930}
3931
3932static int oxu_drv_resume(struct device *dev)
3933{
3934	struct platform_device *pdev = to_platform_device(dev);
3935	struct usb_hcd *hcd = dev_get_drvdata(dev);
3936
3937	return 0;
3938}
3939#else
3940#define oxu_drv_suspend	NULL
3941#define oxu_drv_resume	NULL
3942#endif
3943
3944static struct platform_driver oxu_driver = {
3945	.probe		= oxu_drv_probe,
3946	.remove		= oxu_drv_remove,
3947	.shutdown	= oxu_drv_shutdown,
3948	.suspend	= oxu_drv_suspend,
3949	.resume		= oxu_drv_resume,
3950	.driver = {
3951		.name = "oxu210hp-hcd",
3952		.bus = &platform_bus_type
3953	}
3954};
3955
3956module_platform_driver(oxu_driver);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3957
3958MODULE_DESCRIPTION("Oxford OXU210HP HCD driver - ver. " DRIVER_VERSION);
3959MODULE_AUTHOR("Rodolfo Giometti <giometti@linux.it>");
3960MODULE_LICENSE("GPL");