xref: /rk3399_rockchip-uboot/drivers/usb/host/ehci-hcd.c (revision 25c8ebdfcd9b2fca08ccf6bcc37de9ba388ad458)
1 /*-
2  * Copyright (c) 2007-2008, Juniper Networks, Inc.
3  * Copyright (c) 2008, Excito Elektronik i Skåne AB
4  * Copyright (c) 2008, Michael Trimarchi <trimarchimichael@yahoo.it>
5  *
6  * All rights reserved.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as
10  * published by the Free Software Foundation version 2 of
11  * the License.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License 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
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
21  * MA 02111-1307 USA
22  */
23 #include <common.h>
24 #include <dm.h>
25 #include <errno.h>
26 #include <asm/byteorder.h>
27 #include <asm/unaligned.h>
28 #include <usb.h>
29 #include <asm/io.h>
30 #include <malloc.h>
31 #include <watchdog.h>
32 #include <linux/compiler.h>
33 
34 #include "ehci.h"
35 
36 #ifndef CONFIG_USB_MAX_CONTROLLER_COUNT
37 #define CONFIG_USB_MAX_CONTROLLER_COUNT 1
38 #endif
39 
40 /*
41  * EHCI spec page 20 says that the HC may take up to 16 uFrames (= 4ms) to halt.
42  * Let's time out after 8 to have a little safety margin on top of that.
43  */
44 #define HCHALT_TIMEOUT (8 * 1000)
45 
46 #ifndef CONFIG_DM_USB
47 static struct ehci_ctrl ehcic[CONFIG_USB_MAX_CONTROLLER_COUNT];
48 #endif
49 
50 #define ALIGN_END_ADDR(type, ptr, size)			\
51 	((unsigned long)(ptr) + roundup((size) * sizeof(type), USB_DMA_MINALIGN))
52 
53 static struct descriptor {
54 	struct usb_hub_descriptor hub;
55 	struct usb_device_descriptor device;
56 	struct usb_linux_config_descriptor config;
57 	struct usb_linux_interface_descriptor interface;
58 	struct usb_endpoint_descriptor endpoint;
59 }  __attribute__ ((packed)) descriptor = {
60 	{
61 		0x8,		/* bDescLength */
62 		0x29,		/* bDescriptorType: hub descriptor */
63 		2,		/* bNrPorts -- runtime modified */
64 		0,		/* wHubCharacteristics */
65 		10,		/* bPwrOn2PwrGood */
66 		0,		/* bHubCntrCurrent */
67 		{},		/* Device removable */
68 		{}		/* at most 7 ports! XXX */
69 	},
70 	{
71 		0x12,		/* bLength */
72 		1,		/* bDescriptorType: UDESC_DEVICE */
73 		cpu_to_le16(0x0200), /* bcdUSB: v2.0 */
74 		9,		/* bDeviceClass: UDCLASS_HUB */
75 		0,		/* bDeviceSubClass: UDSUBCLASS_HUB */
76 		1,		/* bDeviceProtocol: UDPROTO_HSHUBSTT */
77 		64,		/* bMaxPacketSize: 64 bytes */
78 		0x0000,		/* idVendor */
79 		0x0000,		/* idProduct */
80 		cpu_to_le16(0x0100), /* bcdDevice */
81 		1,		/* iManufacturer */
82 		2,		/* iProduct */
83 		0,		/* iSerialNumber */
84 		1		/* bNumConfigurations: 1 */
85 	},
86 	{
87 		0x9,
88 		2,		/* bDescriptorType: UDESC_CONFIG */
89 		cpu_to_le16(0x19),
90 		1,		/* bNumInterface */
91 		1,		/* bConfigurationValue */
92 		0,		/* iConfiguration */
93 		0x40,		/* bmAttributes: UC_SELF_POWER */
94 		0		/* bMaxPower */
95 	},
96 	{
97 		0x9,		/* bLength */
98 		4,		/* bDescriptorType: UDESC_INTERFACE */
99 		0,		/* bInterfaceNumber */
100 		0,		/* bAlternateSetting */
101 		1,		/* bNumEndpoints */
102 		9,		/* bInterfaceClass: UICLASS_HUB */
103 		0,		/* bInterfaceSubClass: UISUBCLASS_HUB */
104 		0,		/* bInterfaceProtocol: UIPROTO_HSHUBSTT */
105 		0		/* iInterface */
106 	},
107 	{
108 		0x7,		/* bLength */
109 		5,		/* bDescriptorType: UDESC_ENDPOINT */
110 		0x81,		/* bEndpointAddress:
111 				 * UE_DIR_IN | EHCI_INTR_ENDPT
112 				 */
113 		3,		/* bmAttributes: UE_INTERRUPT */
114 		8,		/* wMaxPacketSize */
115 		255		/* bInterval */
116 	},
117 };
118 
119 #if defined(CONFIG_EHCI_IS_TDI)
120 #define ehci_is_TDI()	(1)
121 #else
122 #define ehci_is_TDI()	(0)
123 #endif
124 
125 static struct ehci_ctrl *ehci_get_ctrl(struct usb_device *udev)
126 {
127 #ifdef CONFIG_DM_USB
128 	return dev_get_priv(usb_get_bus(udev->dev));
129 #else
130 	return udev->controller;
131 #endif
132 }
133 
134 static int ehci_get_port_speed(struct ehci_ctrl *ctrl, uint32_t reg)
135 {
136 	return PORTSC_PSPD(reg);
137 }
138 
139 static void ehci_set_usbmode(struct ehci_ctrl *ctrl)
140 {
141 	uint32_t tmp;
142 	uint32_t *reg_ptr;
143 
144 	reg_ptr = (uint32_t *)((u8 *)&ctrl->hcor->or_usbcmd + USBMODE);
145 	tmp = ehci_readl(reg_ptr);
146 	tmp |= USBMODE_CM_HC;
147 #if defined(CONFIG_EHCI_MMIO_BIG_ENDIAN)
148 	tmp |= USBMODE_BE;
149 #endif
150 	ehci_writel(reg_ptr, tmp);
151 }
152 
153 static void ehci_powerup_fixup(struct ehci_ctrl *ctrl, uint32_t *status_reg,
154 			       uint32_t *reg)
155 {
156 	mdelay(50);
157 }
158 
159 static uint32_t *ehci_get_portsc_register(struct ehci_ctrl *ctrl, int port)
160 {
161 	if (port < 0 || port >= CONFIG_SYS_USB_EHCI_MAX_ROOT_PORTS) {
162 		/* Printing the message would cause a scan failure! */
163 		debug("The request port(%u) is not configured\n", port);
164 		return NULL;
165 	}
166 
167 	return (uint32_t *)&ctrl->hcor->or_portsc[port];
168 }
169 
170 static int handshake(uint32_t *ptr, uint32_t mask, uint32_t done, int usec)
171 {
172 	uint32_t result;
173 	do {
174 		result = ehci_readl(ptr);
175 		udelay(5);
176 		if (result == ~(uint32_t)0)
177 			return -1;
178 		result &= mask;
179 		if (result == done)
180 			return 0;
181 		usec--;
182 	} while (usec > 0);
183 	return -1;
184 }
185 
186 static int ehci_reset(struct ehci_ctrl *ctrl)
187 {
188 	uint32_t cmd;
189 	int ret = 0;
190 
191 	cmd = ehci_readl(&ctrl->hcor->or_usbcmd);
192 	cmd = (cmd & ~CMD_RUN) | CMD_RESET;
193 	ehci_writel(&ctrl->hcor->or_usbcmd, cmd);
194 	ret = handshake((uint32_t *)&ctrl->hcor->or_usbcmd,
195 			CMD_RESET, 0, 250 * 1000);
196 	if (ret < 0) {
197 		printf("EHCI fail to reset\n");
198 		goto out;
199 	}
200 
201 	if (ehci_is_TDI())
202 		ctrl->ops.set_usb_mode(ctrl);
203 
204 #ifdef CONFIG_USB_EHCI_TXFIFO_THRESH
205 	cmd = ehci_readl(&ctrl->hcor->or_txfilltuning);
206 	cmd &= ~TXFIFO_THRESH_MASK;
207 	cmd |= TXFIFO_THRESH(CONFIG_USB_EHCI_TXFIFO_THRESH);
208 	ehci_writel(&ctrl->hcor->or_txfilltuning, cmd);
209 #endif
210 out:
211 	return ret;
212 }
213 
214 static int ehci_shutdown(struct ehci_ctrl *ctrl)
215 {
216 	int i, ret = 0;
217 	uint32_t cmd, reg;
218 
219 	if (!ctrl || !ctrl->hcor)
220 		return -EINVAL;
221 
222 	cmd = ehci_readl(&ctrl->hcor->or_usbcmd);
223 	cmd &= ~(CMD_PSE | CMD_ASE);
224 	ehci_writel(&ctrl->hcor->or_usbcmd, cmd);
225 	ret = handshake(&ctrl->hcor->or_usbsts, STS_ASS | STS_PSS, 0,
226 		100 * 1000);
227 
228 	if (!ret) {
229 		for (i = 0; i < CONFIG_SYS_USB_EHCI_MAX_ROOT_PORTS; i++) {
230 			reg = ehci_readl(&ctrl->hcor->or_portsc[i]);
231 			reg |= EHCI_PS_SUSP;
232 			ehci_writel(&ctrl->hcor->or_portsc[i], reg);
233 		}
234 
235 		cmd &= ~CMD_RUN;
236 		ehci_writel(&ctrl->hcor->or_usbcmd, cmd);
237 		ret = handshake(&ctrl->hcor->or_usbsts, STS_HALT, STS_HALT,
238 			HCHALT_TIMEOUT);
239 	}
240 
241 	if (ret)
242 		puts("EHCI failed to shut down host controller.\n");
243 
244 	return ret;
245 }
246 
247 static int ehci_td_buffer(struct qTD *td, void *buf, size_t sz)
248 {
249 	uint32_t delta, next;
250 	uint32_t addr = (unsigned long)buf;
251 	int idx;
252 
253 	if (addr != ALIGN(addr, ARCH_DMA_MINALIGN))
254 		debug("EHCI-HCD: Misaligned buffer address (%p)\n", buf);
255 
256 	flush_dcache_range(addr, ALIGN(addr + sz, ARCH_DMA_MINALIGN));
257 
258 	idx = 0;
259 	while (idx < QT_BUFFER_CNT) {
260 		td->qt_buffer[idx] = cpu_to_hc32(addr);
261 		td->qt_buffer_hi[idx] = 0;
262 		next = (addr + EHCI_PAGE_SIZE) & ~(EHCI_PAGE_SIZE - 1);
263 		delta = next - addr;
264 		if (delta >= sz)
265 			break;
266 		sz -= delta;
267 		addr = next;
268 		idx++;
269 	}
270 
271 	if (idx == QT_BUFFER_CNT) {
272 		printf("out of buffer pointers (%zu bytes left)\n", sz);
273 		return -1;
274 	}
275 
276 	return 0;
277 }
278 
279 static inline u8 ehci_encode_speed(enum usb_device_speed speed)
280 {
281 	#define QH_HIGH_SPEED	2
282 	#define QH_FULL_SPEED	0
283 	#define QH_LOW_SPEED	1
284 	if (speed == USB_SPEED_HIGH)
285 		return QH_HIGH_SPEED;
286 	if (speed == USB_SPEED_LOW)
287 		return QH_LOW_SPEED;
288 	return QH_FULL_SPEED;
289 }
290 
291 static void ehci_update_endpt2_dev_n_port(struct usb_device *udev,
292 					  struct QH *qh)
293 {
294 	struct usb_device *ttdev;
295 	int parent_devnum;
296 
297 	if (udev->speed != USB_SPEED_LOW && udev->speed != USB_SPEED_FULL)
298 		return;
299 
300 	/*
301 	 * For full / low speed devices we need to get the devnum and portnr of
302 	 * the tt, so of the first upstream usb-2 hub, there may be usb-1 hubs
303 	 * in the tree before that one!
304 	 */
305 #ifdef CONFIG_DM_USB
306 	struct udevice *parent;
307 
308 	for (ttdev = udev; ; ) {
309 		struct udevice *dev = ttdev->dev;
310 
311 		if (dev->parent &&
312 		    device_get_uclass_id(dev->parent) == UCLASS_USB_HUB)
313 			parent = dev->parent;
314 		else
315 			parent = NULL;
316 		if (!parent)
317 			return;
318 		ttdev = dev_get_parentdata(parent);
319 		if (!ttdev->speed != USB_SPEED_HIGH)
320 			break;
321 	}
322 	parent_devnum = ttdev->devnum;
323 #else
324 	ttdev = udev;
325 	while (ttdev->parent && ttdev->parent->speed != USB_SPEED_HIGH)
326 		ttdev = ttdev->parent;
327 	if (!ttdev->parent)
328 		return;
329 	parent_devnum = ttdev->parent->devnum;
330 #endif
331 
332 	qh->qh_endpt2 |= cpu_to_hc32(QH_ENDPT2_PORTNUM(ttdev->portnr) |
333 				     QH_ENDPT2_HUBADDR(parent_devnum));
334 }
335 
336 static int
337 ehci_submit_async(struct usb_device *dev, unsigned long pipe, void *buffer,
338 		   int length, struct devrequest *req)
339 {
340 	ALLOC_ALIGN_BUFFER(struct QH, qh, 1, USB_DMA_MINALIGN);
341 	struct qTD *qtd;
342 	int qtd_count = 0;
343 	int qtd_counter = 0;
344 	volatile struct qTD *vtd;
345 	unsigned long ts;
346 	uint32_t *tdp;
347 	uint32_t endpt, maxpacket, token, usbsts;
348 	uint32_t c, toggle;
349 	uint32_t cmd;
350 	int timeout;
351 	int ret = 0;
352 	struct ehci_ctrl *ctrl = ehci_get_ctrl(dev);
353 
354 	debug("dev=%p, pipe=%lx, buffer=%p, length=%d, req=%p\n", dev, pipe,
355 	      buffer, length, req);
356 	if (req != NULL)
357 		debug("req=%u (%#x), type=%u (%#x), value=%u (%#x), index=%u\n",
358 		      req->request, req->request,
359 		      req->requesttype, req->requesttype,
360 		      le16_to_cpu(req->value), le16_to_cpu(req->value),
361 		      le16_to_cpu(req->index));
362 
363 #define PKT_ALIGN	512
364 	/*
365 	 * The USB transfer is split into qTD transfers. Eeach qTD transfer is
366 	 * described by a transfer descriptor (the qTD). The qTDs form a linked
367 	 * list with a queue head (QH).
368 	 *
369 	 * Each qTD transfer starts with a new USB packet, i.e. a packet cannot
370 	 * have its beginning in a qTD transfer and its end in the following
371 	 * one, so the qTD transfer lengths have to be chosen accordingly.
372 	 *
373 	 * Each qTD transfer uses up to QT_BUFFER_CNT data buffers, mapped to
374 	 * single pages. The first data buffer can start at any offset within a
375 	 * page (not considering the cache-line alignment issues), while the
376 	 * following buffers must be page-aligned. There is no alignment
377 	 * constraint on the size of a qTD transfer.
378 	 */
379 	if (req != NULL)
380 		/* 1 qTD will be needed for SETUP, and 1 for ACK. */
381 		qtd_count += 1 + 1;
382 	if (length > 0 || req == NULL) {
383 		/*
384 		 * Determine the qTD transfer size that will be used for the
385 		 * data payload (not considering the first qTD transfer, which
386 		 * may be longer or shorter, and the final one, which may be
387 		 * shorter).
388 		 *
389 		 * In order to keep each packet within a qTD transfer, the qTD
390 		 * transfer size is aligned to PKT_ALIGN, which is a multiple of
391 		 * wMaxPacketSize (except in some cases for interrupt transfers,
392 		 * see comment in submit_int_msg()).
393 		 *
394 		 * By default, i.e. if the input buffer is aligned to PKT_ALIGN,
395 		 * QT_BUFFER_CNT full pages will be used.
396 		 */
397 		int xfr_sz = QT_BUFFER_CNT;
398 		/*
399 		 * However, if the input buffer is not aligned to PKT_ALIGN, the
400 		 * qTD transfer size will be one page shorter, and the first qTD
401 		 * data buffer of each transfer will be page-unaligned.
402 		 */
403 		if ((unsigned long)buffer & (PKT_ALIGN - 1))
404 			xfr_sz--;
405 		/* Convert the qTD transfer size to bytes. */
406 		xfr_sz *= EHCI_PAGE_SIZE;
407 		/*
408 		 * Approximate by excess the number of qTDs that will be
409 		 * required for the data payload. The exact formula is way more
410 		 * complicated and saves at most 2 qTDs, i.e. a total of 128
411 		 * bytes.
412 		 */
413 		qtd_count += 2 + length / xfr_sz;
414 	}
415 /*
416  * Threshold value based on the worst-case total size of the allocated qTDs for
417  * a mass-storage transfer of 65535 blocks of 512 bytes.
418  */
419 #if CONFIG_SYS_MALLOC_LEN <= 64 + 128 * 1024
420 #warning CONFIG_SYS_MALLOC_LEN may be too small for EHCI
421 #endif
422 	qtd = memalign(USB_DMA_MINALIGN, qtd_count * sizeof(struct qTD));
423 	if (qtd == NULL) {
424 		printf("unable to allocate TDs\n");
425 		return -1;
426 	}
427 
428 	memset(qh, 0, sizeof(struct QH));
429 	memset(qtd, 0, qtd_count * sizeof(*qtd));
430 
431 	toggle = usb_gettoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
432 
433 	/*
434 	 * Setup QH (3.6 in ehci-r10.pdf)
435 	 *
436 	 *   qh_link ................. 03-00 H
437 	 *   qh_endpt1 ............... 07-04 H
438 	 *   qh_endpt2 ............... 0B-08 H
439 	 * - qh_curtd
440 	 *   qh_overlay.qt_next ...... 13-10 H
441 	 * - qh_overlay.qt_altnext
442 	 */
443 	qh->qh_link = cpu_to_hc32((unsigned long)&ctrl->qh_list | QH_LINK_TYPE_QH);
444 	c = (dev->speed != USB_SPEED_HIGH) && !usb_pipeendpoint(pipe);
445 	maxpacket = usb_maxpacket(dev, pipe);
446 	endpt = QH_ENDPT1_RL(8) | QH_ENDPT1_C(c) |
447 		QH_ENDPT1_MAXPKTLEN(maxpacket) | QH_ENDPT1_H(0) |
448 		QH_ENDPT1_DTC(QH_ENDPT1_DTC_DT_FROM_QTD) |
449 		QH_ENDPT1_EPS(ehci_encode_speed(dev->speed)) |
450 		QH_ENDPT1_ENDPT(usb_pipeendpoint(pipe)) | QH_ENDPT1_I(0) |
451 		QH_ENDPT1_DEVADDR(usb_pipedevice(pipe));
452 	qh->qh_endpt1 = cpu_to_hc32(endpt);
453 	endpt = QH_ENDPT2_MULT(1) | QH_ENDPT2_UFCMASK(0) | QH_ENDPT2_UFSMASK(0);
454 	qh->qh_endpt2 = cpu_to_hc32(endpt);
455 	ehci_update_endpt2_dev_n_port(dev, qh);
456 	qh->qh_overlay.qt_next = cpu_to_hc32(QT_NEXT_TERMINATE);
457 	qh->qh_overlay.qt_altnext = cpu_to_hc32(QT_NEXT_TERMINATE);
458 
459 	tdp = &qh->qh_overlay.qt_next;
460 
461 	if (req != NULL) {
462 		/*
463 		 * Setup request qTD (3.5 in ehci-r10.pdf)
464 		 *
465 		 *   qt_next ................ 03-00 H
466 		 *   qt_altnext ............. 07-04 H
467 		 *   qt_token ............... 0B-08 H
468 		 *
469 		 *   [ buffer, buffer_hi ] loaded with "req".
470 		 */
471 		qtd[qtd_counter].qt_next = cpu_to_hc32(QT_NEXT_TERMINATE);
472 		qtd[qtd_counter].qt_altnext = cpu_to_hc32(QT_NEXT_TERMINATE);
473 		token = QT_TOKEN_DT(0) | QT_TOKEN_TOTALBYTES(sizeof(*req)) |
474 			QT_TOKEN_IOC(0) | QT_TOKEN_CPAGE(0) | QT_TOKEN_CERR(3) |
475 			QT_TOKEN_PID(QT_TOKEN_PID_SETUP) |
476 			QT_TOKEN_STATUS(QT_TOKEN_STATUS_ACTIVE);
477 		qtd[qtd_counter].qt_token = cpu_to_hc32(token);
478 		if (ehci_td_buffer(&qtd[qtd_counter], req, sizeof(*req))) {
479 			printf("unable to construct SETUP TD\n");
480 			goto fail;
481 		}
482 		/* Update previous qTD! */
483 		*tdp = cpu_to_hc32((unsigned long)&qtd[qtd_counter]);
484 		tdp = &qtd[qtd_counter++].qt_next;
485 		toggle = 1;
486 	}
487 
488 	if (length > 0 || req == NULL) {
489 		uint8_t *buf_ptr = buffer;
490 		int left_length = length;
491 
492 		do {
493 			/*
494 			 * Determine the size of this qTD transfer. By default,
495 			 * QT_BUFFER_CNT full pages can be used.
496 			 */
497 			int xfr_bytes = QT_BUFFER_CNT * EHCI_PAGE_SIZE;
498 			/*
499 			 * However, if the input buffer is not page-aligned, the
500 			 * portion of the first page before the buffer start
501 			 * offset within that page is unusable.
502 			 */
503 			xfr_bytes -= (unsigned long)buf_ptr & (EHCI_PAGE_SIZE - 1);
504 			/*
505 			 * In order to keep each packet within a qTD transfer,
506 			 * align the qTD transfer size to PKT_ALIGN.
507 			 */
508 			xfr_bytes &= ~(PKT_ALIGN - 1);
509 			/*
510 			 * This transfer may be shorter than the available qTD
511 			 * transfer size that has just been computed.
512 			 */
513 			xfr_bytes = min(xfr_bytes, left_length);
514 
515 			/*
516 			 * Setup request qTD (3.5 in ehci-r10.pdf)
517 			 *
518 			 *   qt_next ................ 03-00 H
519 			 *   qt_altnext ............. 07-04 H
520 			 *   qt_token ............... 0B-08 H
521 			 *
522 			 *   [ buffer, buffer_hi ] loaded with "buffer".
523 			 */
524 			qtd[qtd_counter].qt_next =
525 					cpu_to_hc32(QT_NEXT_TERMINATE);
526 			qtd[qtd_counter].qt_altnext =
527 					cpu_to_hc32(QT_NEXT_TERMINATE);
528 			token = QT_TOKEN_DT(toggle) |
529 				QT_TOKEN_TOTALBYTES(xfr_bytes) |
530 				QT_TOKEN_IOC(req == NULL) | QT_TOKEN_CPAGE(0) |
531 				QT_TOKEN_CERR(3) |
532 				QT_TOKEN_PID(usb_pipein(pipe) ?
533 					QT_TOKEN_PID_IN : QT_TOKEN_PID_OUT) |
534 				QT_TOKEN_STATUS(QT_TOKEN_STATUS_ACTIVE);
535 			qtd[qtd_counter].qt_token = cpu_to_hc32(token);
536 			if (ehci_td_buffer(&qtd[qtd_counter], buf_ptr,
537 						xfr_bytes)) {
538 				printf("unable to construct DATA TD\n");
539 				goto fail;
540 			}
541 			/* Update previous qTD! */
542 			*tdp = cpu_to_hc32((unsigned long)&qtd[qtd_counter]);
543 			tdp = &qtd[qtd_counter++].qt_next;
544 			/*
545 			 * Data toggle has to be adjusted since the qTD transfer
546 			 * size is not always an even multiple of
547 			 * wMaxPacketSize.
548 			 */
549 			if ((xfr_bytes / maxpacket) & 1)
550 				toggle ^= 1;
551 			buf_ptr += xfr_bytes;
552 			left_length -= xfr_bytes;
553 		} while (left_length > 0);
554 	}
555 
556 	if (req != NULL) {
557 		/*
558 		 * Setup request qTD (3.5 in ehci-r10.pdf)
559 		 *
560 		 *   qt_next ................ 03-00 H
561 		 *   qt_altnext ............. 07-04 H
562 		 *   qt_token ............... 0B-08 H
563 		 */
564 		qtd[qtd_counter].qt_next = cpu_to_hc32(QT_NEXT_TERMINATE);
565 		qtd[qtd_counter].qt_altnext = cpu_to_hc32(QT_NEXT_TERMINATE);
566 		token = QT_TOKEN_DT(1) | QT_TOKEN_TOTALBYTES(0) |
567 			QT_TOKEN_IOC(1) | QT_TOKEN_CPAGE(0) | QT_TOKEN_CERR(3) |
568 			QT_TOKEN_PID(usb_pipein(pipe) ?
569 				QT_TOKEN_PID_OUT : QT_TOKEN_PID_IN) |
570 			QT_TOKEN_STATUS(QT_TOKEN_STATUS_ACTIVE);
571 		qtd[qtd_counter].qt_token = cpu_to_hc32(token);
572 		/* Update previous qTD! */
573 		*tdp = cpu_to_hc32((unsigned long)&qtd[qtd_counter]);
574 		tdp = &qtd[qtd_counter++].qt_next;
575 	}
576 
577 	ctrl->qh_list.qh_link = cpu_to_hc32((unsigned long)qh | QH_LINK_TYPE_QH);
578 
579 	/* Flush dcache */
580 	flush_dcache_range((unsigned long)&ctrl->qh_list,
581 		ALIGN_END_ADDR(struct QH, &ctrl->qh_list, 1));
582 	flush_dcache_range((unsigned long)qh, ALIGN_END_ADDR(struct QH, qh, 1));
583 	flush_dcache_range((unsigned long)qtd,
584 			   ALIGN_END_ADDR(struct qTD, qtd, qtd_count));
585 
586 	/* Set async. queue head pointer. */
587 	ehci_writel(&ctrl->hcor->or_asynclistaddr, (unsigned long)&ctrl->qh_list);
588 
589 	usbsts = ehci_readl(&ctrl->hcor->or_usbsts);
590 	ehci_writel(&ctrl->hcor->or_usbsts, (usbsts & 0x3f));
591 
592 	/* Enable async. schedule. */
593 	cmd = ehci_readl(&ctrl->hcor->or_usbcmd);
594 	cmd |= CMD_ASE;
595 	ehci_writel(&ctrl->hcor->or_usbcmd, cmd);
596 
597 	ret = handshake((uint32_t *)&ctrl->hcor->or_usbsts, STS_ASS, STS_ASS,
598 			100 * 1000);
599 	if (ret < 0) {
600 		printf("EHCI fail timeout STS_ASS set\n");
601 		goto fail;
602 	}
603 
604 	/* Wait for TDs to be processed. */
605 	ts = get_timer(0);
606 	vtd = &qtd[qtd_counter - 1];
607 	timeout = USB_TIMEOUT_MS(pipe);
608 	do {
609 		/* Invalidate dcache */
610 		invalidate_dcache_range((unsigned long)&ctrl->qh_list,
611 			ALIGN_END_ADDR(struct QH, &ctrl->qh_list, 1));
612 		invalidate_dcache_range((unsigned long)qh,
613 			ALIGN_END_ADDR(struct QH, qh, 1));
614 		invalidate_dcache_range((unsigned long)qtd,
615 			ALIGN_END_ADDR(struct qTD, qtd, qtd_count));
616 
617 		token = hc32_to_cpu(vtd->qt_token);
618 		if (!(QT_TOKEN_GET_STATUS(token) & QT_TOKEN_STATUS_ACTIVE))
619 			break;
620 		WATCHDOG_RESET();
621 	} while (get_timer(ts) < timeout);
622 
623 	/*
624 	 * Invalidate the memory area occupied by buffer
625 	 * Don't try to fix the buffer alignment, if it isn't properly
626 	 * aligned it's upper layer's fault so let invalidate_dcache_range()
627 	 * vow about it. But we have to fix the length as it's actual
628 	 * transfer length and can be unaligned. This is potentially
629 	 * dangerous operation, it's responsibility of the calling
630 	 * code to make sure enough space is reserved.
631 	 */
632 	invalidate_dcache_range((unsigned long)buffer,
633 		ALIGN((unsigned long)buffer + length, ARCH_DMA_MINALIGN));
634 
635 	/* Check that the TD processing happened */
636 	if (QT_TOKEN_GET_STATUS(token) & QT_TOKEN_STATUS_ACTIVE)
637 		printf("EHCI timed out on TD - token=%#x\n", token);
638 
639 	/* Disable async schedule. */
640 	cmd = ehci_readl(&ctrl->hcor->or_usbcmd);
641 	cmd &= ~CMD_ASE;
642 	ehci_writel(&ctrl->hcor->or_usbcmd, cmd);
643 
644 	ret = handshake((uint32_t *)&ctrl->hcor->or_usbsts, STS_ASS, 0,
645 			100 * 1000);
646 	if (ret < 0) {
647 		printf("EHCI fail timeout STS_ASS reset\n");
648 		goto fail;
649 	}
650 
651 	token = hc32_to_cpu(qh->qh_overlay.qt_token);
652 	if (!(QT_TOKEN_GET_STATUS(token) & QT_TOKEN_STATUS_ACTIVE)) {
653 		debug("TOKEN=%#x\n", token);
654 		switch (QT_TOKEN_GET_STATUS(token) &
655 			~(QT_TOKEN_STATUS_SPLITXSTATE | QT_TOKEN_STATUS_PERR)) {
656 		case 0:
657 			toggle = QT_TOKEN_GET_DT(token);
658 			usb_settoggle(dev, usb_pipeendpoint(pipe),
659 				       usb_pipeout(pipe), toggle);
660 			dev->status = 0;
661 			break;
662 		case QT_TOKEN_STATUS_HALTED:
663 			dev->status = USB_ST_STALLED;
664 			break;
665 		case QT_TOKEN_STATUS_ACTIVE | QT_TOKEN_STATUS_DATBUFERR:
666 		case QT_TOKEN_STATUS_DATBUFERR:
667 			dev->status = USB_ST_BUF_ERR;
668 			break;
669 		case QT_TOKEN_STATUS_HALTED | QT_TOKEN_STATUS_BABBLEDET:
670 		case QT_TOKEN_STATUS_BABBLEDET:
671 			dev->status = USB_ST_BABBLE_DET;
672 			break;
673 		default:
674 			dev->status = USB_ST_CRC_ERR;
675 			if (QT_TOKEN_GET_STATUS(token) & QT_TOKEN_STATUS_HALTED)
676 				dev->status |= USB_ST_STALLED;
677 			break;
678 		}
679 		dev->act_len = length - QT_TOKEN_GET_TOTALBYTES(token);
680 	} else {
681 		dev->act_len = 0;
682 #ifndef CONFIG_USB_EHCI_FARADAY
683 		debug("dev=%u, usbsts=%#x, p[1]=%#x, p[2]=%#x\n",
684 		      dev->devnum, ehci_readl(&ctrl->hcor->or_usbsts),
685 		      ehci_readl(&ctrl->hcor->or_portsc[0]),
686 		      ehci_readl(&ctrl->hcor->or_portsc[1]));
687 #endif
688 	}
689 
690 	free(qtd);
691 	return (dev->status != USB_ST_NOT_PROC) ? 0 : -1;
692 
693 fail:
694 	free(qtd);
695 	return -1;
696 }
697 
698 static int ehci_submit_root(struct usb_device *dev, unsigned long pipe,
699 			    void *buffer, int length, struct devrequest *req)
700 {
701 	uint8_t tmpbuf[4];
702 	u16 typeReq;
703 	void *srcptr = NULL;
704 	int len, srclen;
705 	uint32_t reg;
706 	uint32_t *status_reg;
707 	int port = le16_to_cpu(req->index) & 0xff;
708 	struct ehci_ctrl *ctrl = ehci_get_ctrl(dev);
709 
710 	srclen = 0;
711 
712 	debug("req=%u (%#x), type=%u (%#x), value=%u, index=%u\n",
713 	      req->request, req->request,
714 	      req->requesttype, req->requesttype,
715 	      le16_to_cpu(req->value), le16_to_cpu(req->index));
716 
717 	typeReq = req->request | req->requesttype << 8;
718 
719 	switch (typeReq) {
720 	case USB_REQ_GET_STATUS | ((USB_RT_PORT | USB_DIR_IN) << 8):
721 	case USB_REQ_SET_FEATURE | ((USB_DIR_OUT | USB_RT_PORT) << 8):
722 	case USB_REQ_CLEAR_FEATURE | ((USB_DIR_OUT | USB_RT_PORT) << 8):
723 		status_reg = ctrl->ops.get_portsc_register(ctrl, port - 1);
724 		if (!status_reg)
725 			return -1;
726 		break;
727 	default:
728 		status_reg = NULL;
729 		break;
730 	}
731 
732 	switch (typeReq) {
733 	case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
734 		switch (le16_to_cpu(req->value) >> 8) {
735 		case USB_DT_DEVICE:
736 			debug("USB_DT_DEVICE request\n");
737 			srcptr = &descriptor.device;
738 			srclen = descriptor.device.bLength;
739 			break;
740 		case USB_DT_CONFIG:
741 			debug("USB_DT_CONFIG config\n");
742 			srcptr = &descriptor.config;
743 			srclen = descriptor.config.bLength +
744 					descriptor.interface.bLength +
745 					descriptor.endpoint.bLength;
746 			break;
747 		case USB_DT_STRING:
748 			debug("USB_DT_STRING config\n");
749 			switch (le16_to_cpu(req->value) & 0xff) {
750 			case 0:	/* Language */
751 				srcptr = "\4\3\1\0";
752 				srclen = 4;
753 				break;
754 			case 1:	/* Vendor */
755 				srcptr = "\16\3u\0-\0b\0o\0o\0t\0";
756 				srclen = 14;
757 				break;
758 			case 2:	/* Product */
759 				srcptr = "\52\3E\0H\0C\0I\0 "
760 					 "\0H\0o\0s\0t\0 "
761 					 "\0C\0o\0n\0t\0r\0o\0l\0l\0e\0r\0";
762 				srclen = 42;
763 				break;
764 			default:
765 				debug("unknown value DT_STRING %x\n",
766 					le16_to_cpu(req->value));
767 				goto unknown;
768 			}
769 			break;
770 		default:
771 			debug("unknown value %x\n", le16_to_cpu(req->value));
772 			goto unknown;
773 		}
774 		break;
775 	case USB_REQ_GET_DESCRIPTOR | ((USB_DIR_IN | USB_RT_HUB) << 8):
776 		switch (le16_to_cpu(req->value) >> 8) {
777 		case USB_DT_HUB:
778 			debug("USB_DT_HUB config\n");
779 			srcptr = &descriptor.hub;
780 			srclen = descriptor.hub.bLength;
781 			break;
782 		default:
783 			debug("unknown value %x\n", le16_to_cpu(req->value));
784 			goto unknown;
785 		}
786 		break;
787 	case USB_REQ_SET_ADDRESS | (USB_RECIP_DEVICE << 8):
788 		debug("USB_REQ_SET_ADDRESS\n");
789 		ctrl->rootdev = le16_to_cpu(req->value);
790 		break;
791 	case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
792 		debug("USB_REQ_SET_CONFIGURATION\n");
793 		/* Nothing to do */
794 		break;
795 	case USB_REQ_GET_STATUS | ((USB_DIR_IN | USB_RT_HUB) << 8):
796 		tmpbuf[0] = 1;	/* USB_STATUS_SELFPOWERED */
797 		tmpbuf[1] = 0;
798 		srcptr = tmpbuf;
799 		srclen = 2;
800 		break;
801 	case USB_REQ_GET_STATUS | ((USB_RT_PORT | USB_DIR_IN) << 8):
802 		memset(tmpbuf, 0, 4);
803 		reg = ehci_readl(status_reg);
804 		if (reg & EHCI_PS_CS)
805 			tmpbuf[0] |= USB_PORT_STAT_CONNECTION;
806 		if (reg & EHCI_PS_PE)
807 			tmpbuf[0] |= USB_PORT_STAT_ENABLE;
808 		if (reg & EHCI_PS_SUSP)
809 			tmpbuf[0] |= USB_PORT_STAT_SUSPEND;
810 		if (reg & EHCI_PS_OCA)
811 			tmpbuf[0] |= USB_PORT_STAT_OVERCURRENT;
812 		if (reg & EHCI_PS_PR)
813 			tmpbuf[0] |= USB_PORT_STAT_RESET;
814 		if (reg & EHCI_PS_PP)
815 			tmpbuf[1] |= USB_PORT_STAT_POWER >> 8;
816 
817 		if (ehci_is_TDI()) {
818 			switch (ctrl->ops.get_port_speed(ctrl, reg)) {
819 			case PORTSC_PSPD_FS:
820 				break;
821 			case PORTSC_PSPD_LS:
822 				tmpbuf[1] |= USB_PORT_STAT_LOW_SPEED >> 8;
823 				break;
824 			case PORTSC_PSPD_HS:
825 			default:
826 				tmpbuf[1] |= USB_PORT_STAT_HIGH_SPEED >> 8;
827 				break;
828 			}
829 		} else {
830 			tmpbuf[1] |= USB_PORT_STAT_HIGH_SPEED >> 8;
831 		}
832 
833 		if (reg & EHCI_PS_CSC)
834 			tmpbuf[2] |= USB_PORT_STAT_C_CONNECTION;
835 		if (reg & EHCI_PS_PEC)
836 			tmpbuf[2] |= USB_PORT_STAT_C_ENABLE;
837 		if (reg & EHCI_PS_OCC)
838 			tmpbuf[2] |= USB_PORT_STAT_C_OVERCURRENT;
839 		if (ctrl->portreset & (1 << port))
840 			tmpbuf[2] |= USB_PORT_STAT_C_RESET;
841 
842 		srcptr = tmpbuf;
843 		srclen = 4;
844 		break;
845 	case USB_REQ_SET_FEATURE | ((USB_DIR_OUT | USB_RT_PORT) << 8):
846 		reg = ehci_readl(status_reg);
847 		reg &= ~EHCI_PS_CLEAR;
848 		switch (le16_to_cpu(req->value)) {
849 		case USB_PORT_FEAT_ENABLE:
850 			reg |= EHCI_PS_PE;
851 			ehci_writel(status_reg, reg);
852 			break;
853 		case USB_PORT_FEAT_POWER:
854 			if (HCS_PPC(ehci_readl(&ctrl->hccr->cr_hcsparams))) {
855 				reg |= EHCI_PS_PP;
856 				ehci_writel(status_reg, reg);
857 			}
858 			break;
859 		case USB_PORT_FEAT_RESET:
860 			if ((reg & (EHCI_PS_PE | EHCI_PS_CS)) == EHCI_PS_CS &&
861 			    !ehci_is_TDI() &&
862 			    EHCI_PS_IS_LOWSPEED(reg)) {
863 				/* Low speed device, give up ownership. */
864 				debug("port %d low speed --> companion\n",
865 				      port - 1);
866 				reg |= EHCI_PS_PO;
867 				ehci_writel(status_reg, reg);
868 				break;
869 			} else {
870 				int ret;
871 
872 				reg |= EHCI_PS_PR;
873 				reg &= ~EHCI_PS_PE;
874 				ehci_writel(status_reg, reg);
875 				/*
876 				 * caller must wait, then call GetPortStatus
877 				 * usb 2.0 specification say 50 ms resets on
878 				 * root
879 				 */
880 				ctrl->ops.powerup_fixup(ctrl, status_reg, &reg);
881 
882 				ehci_writel(status_reg, reg & ~EHCI_PS_PR);
883 				/*
884 				 * A host controller must terminate the reset
885 				 * and stabilize the state of the port within
886 				 * 2 milliseconds
887 				 */
888 				ret = handshake(status_reg, EHCI_PS_PR, 0,
889 						2 * 1000);
890 				if (!ret)
891 					ctrl->portreset |= 1 << port;
892 				else
893 					printf("port(%d) reset error\n",
894 					       port - 1);
895 			}
896 			break;
897 		case USB_PORT_FEAT_TEST:
898 			ehci_shutdown(ctrl);
899 			reg &= ~(0xf << 16);
900 			reg |= ((le16_to_cpu(req->index) >> 8) & 0xf) << 16;
901 			ehci_writel(status_reg, reg);
902 			break;
903 		default:
904 			debug("unknown feature %x\n", le16_to_cpu(req->value));
905 			goto unknown;
906 		}
907 		/* unblock posted writes */
908 		(void) ehci_readl(&ctrl->hcor->or_usbcmd);
909 		break;
910 	case USB_REQ_CLEAR_FEATURE | ((USB_DIR_OUT | USB_RT_PORT) << 8):
911 		reg = ehci_readl(status_reg);
912 		reg &= ~EHCI_PS_CLEAR;
913 		switch (le16_to_cpu(req->value)) {
914 		case USB_PORT_FEAT_ENABLE:
915 			reg &= ~EHCI_PS_PE;
916 			break;
917 		case USB_PORT_FEAT_C_ENABLE:
918 			reg |= EHCI_PS_PE;
919 			break;
920 		case USB_PORT_FEAT_POWER:
921 			if (HCS_PPC(ehci_readl(&ctrl->hccr->cr_hcsparams)))
922 				reg &= ~EHCI_PS_PP;
923 			break;
924 		case USB_PORT_FEAT_C_CONNECTION:
925 			reg |= EHCI_PS_CSC;
926 			break;
927 		case USB_PORT_FEAT_OVER_CURRENT:
928 			reg |= EHCI_PS_OCC;
929 			break;
930 		case USB_PORT_FEAT_C_RESET:
931 			ctrl->portreset &= ~(1 << port);
932 			break;
933 		default:
934 			debug("unknown feature %x\n", le16_to_cpu(req->value));
935 			goto unknown;
936 		}
937 		ehci_writel(status_reg, reg);
938 		/* unblock posted write */
939 		(void) ehci_readl(&ctrl->hcor->or_usbcmd);
940 		break;
941 	default:
942 		debug("Unknown request\n");
943 		goto unknown;
944 	}
945 
946 	mdelay(1);
947 	len = min3(srclen, (int)le16_to_cpu(req->length), length);
948 	if (srcptr != NULL && len > 0)
949 		memcpy(buffer, srcptr, len);
950 	else
951 		debug("Len is 0\n");
952 
953 	dev->act_len = len;
954 	dev->status = 0;
955 	return 0;
956 
957 unknown:
958 	debug("requesttype=%x, request=%x, value=%x, index=%x, length=%x\n",
959 	      req->requesttype, req->request, le16_to_cpu(req->value),
960 	      le16_to_cpu(req->index), le16_to_cpu(req->length));
961 
962 	dev->act_len = 0;
963 	dev->status = USB_ST_STALLED;
964 	return -1;
965 }
966 
967 const struct ehci_ops default_ehci_ops = {
968 	.set_usb_mode		= ehci_set_usbmode,
969 	.get_port_speed		= ehci_get_port_speed,
970 	.powerup_fixup		= ehci_powerup_fixup,
971 	.get_portsc_register	= ehci_get_portsc_register,
972 };
973 
974 static void ehci_setup_ops(struct ehci_ctrl *ctrl, const struct ehci_ops *ops)
975 {
976 	if (!ops) {
977 		ctrl->ops = default_ehci_ops;
978 	} else {
979 		ctrl->ops = *ops;
980 		if (!ctrl->ops.set_usb_mode)
981 			ctrl->ops.set_usb_mode = ehci_set_usbmode;
982 		if (!ctrl->ops.get_port_speed)
983 			ctrl->ops.get_port_speed = ehci_get_port_speed;
984 		if (!ctrl->ops.powerup_fixup)
985 			ctrl->ops.powerup_fixup = ehci_powerup_fixup;
986 		if (!ctrl->ops.get_portsc_register)
987 			ctrl->ops.get_portsc_register =
988 					ehci_get_portsc_register;
989 	}
990 }
991 
992 #ifndef CONFIG_DM_USB
993 void ehci_set_controller_priv(int index, void *priv, const struct ehci_ops *ops)
994 {
995 	struct ehci_ctrl *ctrl = &ehcic[index];
996 
997 	ctrl->priv = priv;
998 	ehci_setup_ops(ctrl, ops);
999 }
1000 
1001 void *ehci_get_controller_priv(int index)
1002 {
1003 	return ehcic[index].priv;
1004 }
1005 #endif
1006 
1007 static int ehci_common_init(struct ehci_ctrl *ctrl, uint tweaks)
1008 {
1009 	struct QH *qh_list;
1010 	struct QH *periodic;
1011 	uint32_t reg;
1012 	uint32_t cmd;
1013 	int i;
1014 
1015 	/* Set the high address word (aka segment) for 64-bit controller */
1016 	if (ehci_readl(&ctrl->hccr->cr_hccparams) & 1)
1017 		ehci_writel(&ctrl->hcor->or_ctrldssegment, 0);
1018 
1019 	qh_list = &ctrl->qh_list;
1020 
1021 	/* Set head of reclaim list */
1022 	memset(qh_list, 0, sizeof(*qh_list));
1023 	qh_list->qh_link = cpu_to_hc32((unsigned long)qh_list | QH_LINK_TYPE_QH);
1024 	qh_list->qh_endpt1 = cpu_to_hc32(QH_ENDPT1_H(1) |
1025 						QH_ENDPT1_EPS(USB_SPEED_HIGH));
1026 	qh_list->qh_overlay.qt_next = cpu_to_hc32(QT_NEXT_TERMINATE);
1027 	qh_list->qh_overlay.qt_altnext = cpu_to_hc32(QT_NEXT_TERMINATE);
1028 	qh_list->qh_overlay.qt_token =
1029 			cpu_to_hc32(QT_TOKEN_STATUS(QT_TOKEN_STATUS_HALTED));
1030 
1031 	flush_dcache_range((unsigned long)qh_list,
1032 			   ALIGN_END_ADDR(struct QH, qh_list, 1));
1033 
1034 	/* Set async. queue head pointer. */
1035 	ehci_writel(&ctrl->hcor->or_asynclistaddr, (unsigned long)qh_list);
1036 
1037 	/*
1038 	 * Set up periodic list
1039 	 * Step 1: Parent QH for all periodic transfers.
1040 	 */
1041 	ctrl->periodic_schedules = 0;
1042 	periodic = &ctrl->periodic_queue;
1043 	memset(periodic, 0, sizeof(*periodic));
1044 	periodic->qh_link = cpu_to_hc32(QH_LINK_TERMINATE);
1045 	periodic->qh_overlay.qt_next = cpu_to_hc32(QT_NEXT_TERMINATE);
1046 	periodic->qh_overlay.qt_altnext = cpu_to_hc32(QT_NEXT_TERMINATE);
1047 
1048 	flush_dcache_range((unsigned long)periodic,
1049 			   ALIGN_END_ADDR(struct QH, periodic, 1));
1050 
1051 	/*
1052 	 * Step 2: Setup frame-list: Every microframe, USB tries the same list.
1053 	 *         In particular, device specifications on polling frequency
1054 	 *         are disregarded. Keyboards seem to send NAK/NYet reliably
1055 	 *         when polled with an empty buffer.
1056 	 *
1057 	 *         Split Transactions will be spread across microframes using
1058 	 *         S-mask and C-mask.
1059 	 */
1060 	if (ctrl->periodic_list == NULL)
1061 		ctrl->periodic_list = memalign(4096, 1024 * 4);
1062 
1063 	if (!ctrl->periodic_list)
1064 		return -ENOMEM;
1065 	for (i = 0; i < 1024; i++) {
1066 		ctrl->periodic_list[i] = cpu_to_hc32((unsigned long)periodic
1067 						| QH_LINK_TYPE_QH);
1068 	}
1069 
1070 	flush_dcache_range((unsigned long)ctrl->periodic_list,
1071 			   ALIGN_END_ADDR(uint32_t, ctrl->periodic_list,
1072 					  1024));
1073 
1074 	/* Set periodic list base address */
1075 	ehci_writel(&ctrl->hcor->or_periodiclistbase,
1076 		(unsigned long)ctrl->periodic_list);
1077 
1078 	reg = ehci_readl(&ctrl->hccr->cr_hcsparams);
1079 	descriptor.hub.bNbrPorts = HCS_N_PORTS(reg);
1080 	debug("Register %x NbrPorts %d\n", reg, descriptor.hub.bNbrPorts);
1081 	/* Port Indicators */
1082 	if (HCS_INDICATOR(reg))
1083 		put_unaligned(get_unaligned(&descriptor.hub.wHubCharacteristics)
1084 				| 0x80, &descriptor.hub.wHubCharacteristics);
1085 	/* Port Power Control */
1086 	if (HCS_PPC(reg))
1087 		put_unaligned(get_unaligned(&descriptor.hub.wHubCharacteristics)
1088 				| 0x01, &descriptor.hub.wHubCharacteristics);
1089 
1090 	/* Start the host controller. */
1091 	cmd = ehci_readl(&ctrl->hcor->or_usbcmd);
1092 	/*
1093 	 * Philips, Intel, and maybe others need CMD_RUN before the
1094 	 * root hub will detect new devices (why?); NEC doesn't
1095 	 */
1096 	cmd &= ~(CMD_LRESET|CMD_IAAD|CMD_PSE|CMD_ASE|CMD_RESET);
1097 	cmd |= CMD_RUN;
1098 	ehci_writel(&ctrl->hcor->or_usbcmd, cmd);
1099 
1100 	if (!(tweaks & EHCI_TWEAK_NO_INIT_CF)) {
1101 		/* take control over the ports */
1102 		cmd = ehci_readl(&ctrl->hcor->or_configflag);
1103 		cmd |= FLAG_CF;
1104 		ehci_writel(&ctrl->hcor->or_configflag, cmd);
1105 	}
1106 
1107 	/* unblock posted write */
1108 	cmd = ehci_readl(&ctrl->hcor->or_usbcmd);
1109 	mdelay(5);
1110 	reg = HC_VERSION(ehci_readl(&ctrl->hccr->cr_capbase));
1111 	printf("USB EHCI %x.%02x\n", reg >> 8, reg & 0xff);
1112 
1113 	return 0;
1114 }
1115 
1116 #ifndef CONFIG_DM_USB
1117 int usb_lowlevel_stop(int index)
1118 {
1119 	ehci_shutdown(&ehcic[index]);
1120 	return ehci_hcd_stop(index);
1121 }
1122 
1123 int usb_lowlevel_init(int index, enum usb_init_type init, void **controller)
1124 {
1125 	struct ehci_ctrl *ctrl = &ehcic[index];
1126 	uint tweaks = 0;
1127 	int rc;
1128 
1129 	/**
1130 	 * Set ops to default_ehci_ops, ehci_hcd_init should call
1131 	 * ehci_set_controller_priv to change any of these function pointers.
1132 	 */
1133 	ctrl->ops = default_ehci_ops;
1134 
1135 	rc = ehci_hcd_init(index, init, &ctrl->hccr, &ctrl->hcor);
1136 	if (rc)
1137 		return rc;
1138 	if (init == USB_INIT_DEVICE)
1139 		goto done;
1140 
1141 	/* EHCI spec section 4.1 */
1142 	if (ehci_reset(ctrl))
1143 		return -1;
1144 
1145 #if defined(CONFIG_EHCI_HCD_INIT_AFTER_RESET)
1146 	rc = ehci_hcd_init(index, init, &ctrl->hccr, &ctrl->hcor);
1147 	if (rc)
1148 		return rc;
1149 #endif
1150 #ifdef CONFIG_USB_EHCI_FARADAY
1151 	tweaks |= EHCI_TWEAK_NO_INIT_CF;
1152 #endif
1153 	rc = ehci_common_init(ctrl, tweaks);
1154 	if (rc)
1155 		return rc;
1156 
1157 	ctrl->rootdev = 0;
1158 done:
1159 	*controller = &ehcic[index];
1160 	return 0;
1161 }
1162 #endif
1163 
1164 static int _ehci_submit_bulk_msg(struct usb_device *dev, unsigned long pipe,
1165 				 void *buffer, int length)
1166 {
1167 
1168 	if (usb_pipetype(pipe) != PIPE_BULK) {
1169 		debug("non-bulk pipe (type=%lu)", usb_pipetype(pipe));
1170 		return -1;
1171 	}
1172 	return ehci_submit_async(dev, pipe, buffer, length, NULL);
1173 }
1174 
1175 static int _ehci_submit_control_msg(struct usb_device *dev, unsigned long pipe,
1176 				    void *buffer, int length,
1177 				    struct devrequest *setup)
1178 {
1179 	struct ehci_ctrl *ctrl = ehci_get_ctrl(dev);
1180 
1181 	if (usb_pipetype(pipe) != PIPE_CONTROL) {
1182 		debug("non-control pipe (type=%lu)", usb_pipetype(pipe));
1183 		return -1;
1184 	}
1185 
1186 	if (usb_pipedevice(pipe) == ctrl->rootdev) {
1187 		if (!ctrl->rootdev)
1188 			dev->speed = USB_SPEED_HIGH;
1189 		return ehci_submit_root(dev, pipe, buffer, length, setup);
1190 	}
1191 	return ehci_submit_async(dev, pipe, buffer, length, setup);
1192 }
1193 
1194 struct int_queue {
1195 	int elementsize;
1196 	struct QH *first;
1197 	struct QH *current;
1198 	struct QH *last;
1199 	struct qTD *tds;
1200 };
1201 
1202 #define NEXT_QH(qh) (struct QH *)((unsigned long)hc32_to_cpu((qh)->qh_link) & ~0x1f)
1203 
1204 static int
1205 enable_periodic(struct ehci_ctrl *ctrl)
1206 {
1207 	uint32_t cmd;
1208 	struct ehci_hcor *hcor = ctrl->hcor;
1209 	int ret;
1210 
1211 	cmd = ehci_readl(&hcor->or_usbcmd);
1212 	cmd |= CMD_PSE;
1213 	ehci_writel(&hcor->or_usbcmd, cmd);
1214 
1215 	ret = handshake((uint32_t *)&hcor->or_usbsts,
1216 			STS_PSS, STS_PSS, 100 * 1000);
1217 	if (ret < 0) {
1218 		printf("EHCI failed: timeout when enabling periodic list\n");
1219 		return -ETIMEDOUT;
1220 	}
1221 	udelay(1000);
1222 	return 0;
1223 }
1224 
1225 static int
1226 disable_periodic(struct ehci_ctrl *ctrl)
1227 {
1228 	uint32_t cmd;
1229 	struct ehci_hcor *hcor = ctrl->hcor;
1230 	int ret;
1231 
1232 	cmd = ehci_readl(&hcor->or_usbcmd);
1233 	cmd &= ~CMD_PSE;
1234 	ehci_writel(&hcor->or_usbcmd, cmd);
1235 
1236 	ret = handshake((uint32_t *)&hcor->or_usbsts,
1237 			STS_PSS, 0, 100 * 1000);
1238 	if (ret < 0) {
1239 		printf("EHCI failed: timeout when disabling periodic list\n");
1240 		return -ETIMEDOUT;
1241 	}
1242 	return 0;
1243 }
1244 
1245 struct int_queue *
1246 create_int_queue(struct usb_device *dev, unsigned long pipe, int queuesize,
1247 		 int elementsize, void *buffer, int interval)
1248 {
1249 	struct ehci_ctrl *ctrl = ehci_get_ctrl(dev);
1250 	struct int_queue *result = NULL;
1251 	int i;
1252 
1253 	/*
1254 	 * Interrupt transfers requiring several transactions are not supported
1255 	 * because bInterval is ignored.
1256 	 *
1257 	 * Also, ehci_submit_async() relies on wMaxPacketSize being a power of 2
1258 	 * <= PKT_ALIGN if several qTDs are required, while the USB
1259 	 * specification does not constrain this for interrupt transfers. That
1260 	 * means that ehci_submit_async() would support interrupt transfers
1261 	 * requiring several transactions only as long as the transfer size does
1262 	 * not require more than a single qTD.
1263 	 */
1264 	if (elementsize > usb_maxpacket(dev, pipe)) {
1265 		printf("%s: xfers requiring several transactions are not supported.\n",
1266 		       __func__);
1267 		return NULL;
1268 	}
1269 
1270 	debug("Enter create_int_queue\n");
1271 	if (usb_pipetype(pipe) != PIPE_INTERRUPT) {
1272 		debug("non-interrupt pipe (type=%lu)", usb_pipetype(pipe));
1273 		return NULL;
1274 	}
1275 
1276 	/* limit to 4 full pages worth of data -
1277 	 * we can safely fit them in a single TD,
1278 	 * no matter the alignment
1279 	 */
1280 	if (elementsize >= 16384) {
1281 		debug("too large elements for interrupt transfers\n");
1282 		return NULL;
1283 	}
1284 
1285 	result = malloc(sizeof(*result));
1286 	if (!result) {
1287 		debug("ehci intr queue: out of memory\n");
1288 		goto fail1;
1289 	}
1290 	result->elementsize = elementsize;
1291 	result->first = memalign(USB_DMA_MINALIGN,
1292 				 sizeof(struct QH) * queuesize);
1293 	if (!result->first) {
1294 		debug("ehci intr queue: out of memory\n");
1295 		goto fail2;
1296 	}
1297 	result->current = result->first;
1298 	result->last = result->first + queuesize - 1;
1299 	result->tds = memalign(USB_DMA_MINALIGN,
1300 			       sizeof(struct qTD) * queuesize);
1301 	if (!result->tds) {
1302 		debug("ehci intr queue: out of memory\n");
1303 		goto fail3;
1304 	}
1305 	memset(result->first, 0, sizeof(struct QH) * queuesize);
1306 	memset(result->tds, 0, sizeof(struct qTD) * queuesize);
1307 
1308 	for (i = 0; i < queuesize; i++) {
1309 		struct QH *qh = result->first + i;
1310 		struct qTD *td = result->tds + i;
1311 		void **buf = &qh->buffer;
1312 
1313 		qh->qh_link = cpu_to_hc32((unsigned long)(qh+1) | QH_LINK_TYPE_QH);
1314 		if (i == queuesize - 1)
1315 			qh->qh_link = cpu_to_hc32(QH_LINK_TERMINATE);
1316 
1317 		qh->qh_overlay.qt_next = cpu_to_hc32((unsigned long)td);
1318 		qh->qh_overlay.qt_altnext = cpu_to_hc32(QT_NEXT_TERMINATE);
1319 		qh->qh_endpt1 =
1320 			cpu_to_hc32((0 << 28) | /* No NAK reload (ehci 4.9) */
1321 			(usb_maxpacket(dev, pipe) << 16) | /* MPS */
1322 			(1 << 14) |
1323 			QH_ENDPT1_EPS(ehci_encode_speed(dev->speed)) |
1324 			(usb_pipeendpoint(pipe) << 8) | /* Endpoint Number */
1325 			(usb_pipedevice(pipe) << 0));
1326 		qh->qh_endpt2 = cpu_to_hc32((1 << 30) | /* 1 Tx per mframe */
1327 			(1 << 0)); /* S-mask: microframe 0 */
1328 		if (dev->speed == USB_SPEED_LOW ||
1329 				dev->speed == USB_SPEED_FULL) {
1330 			/* C-mask: microframes 2-4 */
1331 			qh->qh_endpt2 |= cpu_to_hc32((0x1c << 8));
1332 		}
1333 		ehci_update_endpt2_dev_n_port(dev, qh);
1334 
1335 		td->qt_next = cpu_to_hc32(QT_NEXT_TERMINATE);
1336 		td->qt_altnext = cpu_to_hc32(QT_NEXT_TERMINATE);
1337 		debug("communication direction is '%s'\n",
1338 		      usb_pipein(pipe) ? "in" : "out");
1339 		td->qt_token = cpu_to_hc32((elementsize << 16) |
1340 			((usb_pipein(pipe) ? 1 : 0) << 8) | /* IN/OUT token */
1341 			0x80); /* active */
1342 		td->qt_buffer[0] =
1343 		    cpu_to_hc32((unsigned long)buffer + i * elementsize);
1344 		td->qt_buffer[1] =
1345 		    cpu_to_hc32((td->qt_buffer[0] + 0x1000) & ~0xfff);
1346 		td->qt_buffer[2] =
1347 		    cpu_to_hc32((td->qt_buffer[0] + 0x2000) & ~0xfff);
1348 		td->qt_buffer[3] =
1349 		    cpu_to_hc32((td->qt_buffer[0] + 0x3000) & ~0xfff);
1350 		td->qt_buffer[4] =
1351 		    cpu_to_hc32((td->qt_buffer[0] + 0x4000) & ~0xfff);
1352 
1353 		*buf = buffer + i * elementsize;
1354 	}
1355 
1356 	flush_dcache_range((unsigned long)buffer,
1357 			   ALIGN_END_ADDR(char, buffer,
1358 					  queuesize * elementsize));
1359 	flush_dcache_range((unsigned long)result->first,
1360 			   ALIGN_END_ADDR(struct QH, result->first,
1361 					  queuesize));
1362 	flush_dcache_range((unsigned long)result->tds,
1363 			   ALIGN_END_ADDR(struct qTD, result->tds,
1364 					  queuesize));
1365 
1366 	if (ctrl->periodic_schedules > 0) {
1367 		if (disable_periodic(ctrl) < 0) {
1368 			debug("FATAL: periodic should never fail, but did");
1369 			goto fail3;
1370 		}
1371 	}
1372 
1373 	/* hook up to periodic list */
1374 	struct QH *list = &ctrl->periodic_queue;
1375 	result->last->qh_link = list->qh_link;
1376 	list->qh_link = cpu_to_hc32((unsigned long)result->first | QH_LINK_TYPE_QH);
1377 
1378 	flush_dcache_range((unsigned long)result->last,
1379 			   ALIGN_END_ADDR(struct QH, result->last, 1));
1380 	flush_dcache_range((unsigned long)list,
1381 			   ALIGN_END_ADDR(struct QH, list, 1));
1382 
1383 	if (enable_periodic(ctrl) < 0) {
1384 		debug("FATAL: periodic should never fail, but did");
1385 		goto fail3;
1386 	}
1387 	ctrl->periodic_schedules++;
1388 
1389 	debug("Exit create_int_queue\n");
1390 	return result;
1391 fail3:
1392 	if (result->tds)
1393 		free(result->tds);
1394 fail2:
1395 	if (result->first)
1396 		free(result->first);
1397 	if (result)
1398 		free(result);
1399 fail1:
1400 	return NULL;
1401 }
1402 
1403 void *poll_int_queue(struct usb_device *dev, struct int_queue *queue)
1404 {
1405 	struct QH *cur = queue->current;
1406 	struct qTD *cur_td;
1407 
1408 	/* depleted queue */
1409 	if (cur == NULL) {
1410 		debug("Exit poll_int_queue with completed queue\n");
1411 		return NULL;
1412 	}
1413 	/* still active */
1414 	cur_td = &queue->tds[queue->current - queue->first];
1415 	invalidate_dcache_range((unsigned long)cur_td,
1416 				ALIGN_END_ADDR(struct qTD, cur_td, 1));
1417 	if (QT_TOKEN_GET_STATUS(hc32_to_cpu(cur_td->qt_token)) &
1418 			QT_TOKEN_STATUS_ACTIVE) {
1419 		debug("Exit poll_int_queue with no completed intr transfer. token is %x\n",
1420 		      hc32_to_cpu(cur_td->qt_token));
1421 		return NULL;
1422 	}
1423 	if (!(cur->qh_link & QH_LINK_TERMINATE))
1424 		queue->current++;
1425 	else
1426 		queue->current = NULL;
1427 
1428 	invalidate_dcache_range((unsigned long)cur->buffer,
1429 				ALIGN_END_ADDR(char, cur->buffer,
1430 					       queue->elementsize));
1431 
1432 	debug("Exit poll_int_queue with completed intr transfer. token is %x at %p (first at %p)\n",
1433 	      hc32_to_cpu(cur_td->qt_token), cur, queue->first);
1434 	return cur->buffer;
1435 }
1436 
1437 /* Do not free buffers associated with QHs, they're owned by someone else */
1438 int
1439 destroy_int_queue(struct usb_device *dev, struct int_queue *queue)
1440 {
1441 	struct ehci_ctrl *ctrl = ehci_get_ctrl(dev);
1442 	int result = -1;
1443 	unsigned long timeout;
1444 
1445 	if (disable_periodic(ctrl) < 0) {
1446 		debug("FATAL: periodic should never fail, but did");
1447 		goto out;
1448 	}
1449 	ctrl->periodic_schedules--;
1450 
1451 	struct QH *cur = &ctrl->periodic_queue;
1452 	timeout = get_timer(0) + 500; /* abort after 500ms */
1453 	while (!(cur->qh_link & cpu_to_hc32(QH_LINK_TERMINATE))) {
1454 		debug("considering %p, with qh_link %x\n", cur, cur->qh_link);
1455 		if (NEXT_QH(cur) == queue->first) {
1456 			debug("found candidate. removing from chain\n");
1457 			cur->qh_link = queue->last->qh_link;
1458 			flush_dcache_range((unsigned long)cur,
1459 					   ALIGN_END_ADDR(struct QH, cur, 1));
1460 			result = 0;
1461 			break;
1462 		}
1463 		cur = NEXT_QH(cur);
1464 		if (get_timer(0) > timeout) {
1465 			printf("Timeout destroying interrupt endpoint queue\n");
1466 			result = -1;
1467 			goto out;
1468 		}
1469 	}
1470 
1471 	if (ctrl->periodic_schedules > 0) {
1472 		result = enable_periodic(ctrl);
1473 		if (result < 0)
1474 			debug("FATAL: periodic should never fail, but did");
1475 	}
1476 
1477 out:
1478 	free(queue->tds);
1479 	free(queue->first);
1480 	free(queue);
1481 
1482 	return result;
1483 }
1484 
1485 static int _ehci_submit_int_msg(struct usb_device *dev, unsigned long pipe,
1486 				void *buffer, int length, int interval)
1487 {
1488 	void *backbuffer;
1489 	struct int_queue *queue;
1490 	unsigned long timeout;
1491 	int result = 0, ret;
1492 
1493 	debug("dev=%p, pipe=%lu, buffer=%p, length=%d, interval=%d",
1494 	      dev, pipe, buffer, length, interval);
1495 
1496 	queue = create_int_queue(dev, pipe, 1, length, buffer, interval);
1497 	if (!queue)
1498 		return -1;
1499 
1500 	timeout = get_timer(0) + USB_TIMEOUT_MS(pipe);
1501 	while ((backbuffer = poll_int_queue(dev, queue)) == NULL)
1502 		if (get_timer(0) > timeout) {
1503 			printf("Timeout poll on interrupt endpoint\n");
1504 			result = -ETIMEDOUT;
1505 			break;
1506 		}
1507 
1508 	if (backbuffer != buffer) {
1509 		debug("got wrong buffer back (%p instead of %p)\n",
1510 		      backbuffer, buffer);
1511 		return -EINVAL;
1512 	}
1513 
1514 	ret = destroy_int_queue(dev, queue);
1515 	if (ret < 0)
1516 		return ret;
1517 
1518 	/* everything worked out fine */
1519 	return result;
1520 }
1521 
1522 #ifndef CONFIG_DM_USB
1523 int submit_bulk_msg(struct usb_device *dev, unsigned long pipe,
1524 			    void *buffer, int length)
1525 {
1526 	return _ehci_submit_bulk_msg(dev, pipe, buffer, length);
1527 }
1528 
1529 int submit_control_msg(struct usb_device *dev, unsigned long pipe, void *buffer,
1530 		   int length, struct devrequest *setup)
1531 {
1532 	return _ehci_submit_control_msg(dev, pipe, buffer, length, setup);
1533 }
1534 
1535 int submit_int_msg(struct usb_device *dev, unsigned long pipe,
1536 		   void *buffer, int length, int interval)
1537 {
1538 	return _ehci_submit_int_msg(dev, pipe, buffer, length, interval);
1539 }
1540 #endif
1541 
1542 #ifdef CONFIG_DM_USB
1543 static int ehci_submit_control_msg(struct udevice *dev, struct usb_device *udev,
1544 				   unsigned long pipe, void *buffer, int length,
1545 				   struct devrequest *setup)
1546 {
1547 	debug("%s: dev='%s', udev=%p, udev->dev='%s', portnr=%d\n", __func__,
1548 	      dev->name, udev, udev->dev->name, udev->portnr);
1549 
1550 	return _ehci_submit_control_msg(udev, pipe, buffer, length, setup);
1551 }
1552 
1553 static int ehci_submit_bulk_msg(struct udevice *dev, struct usb_device *udev,
1554 				unsigned long pipe, void *buffer, int length)
1555 {
1556 	debug("%s: dev='%s', udev=%p\n", __func__, dev->name, udev);
1557 	return _ehci_submit_bulk_msg(udev, pipe, buffer, length);
1558 }
1559 
1560 static int ehci_submit_int_msg(struct udevice *dev, struct usb_device *udev,
1561 			       unsigned long pipe, void *buffer, int length,
1562 			       int interval)
1563 {
1564 	debug("%s: dev='%s', udev=%p\n", __func__, dev->name, udev);
1565 	return _ehci_submit_int_msg(udev, pipe, buffer, length, interval);
1566 }
1567 
1568 int ehci_register(struct udevice *dev, struct ehci_hccr *hccr,
1569 		  struct ehci_hcor *hcor, const struct ehci_ops *ops,
1570 		  uint tweaks, enum usb_init_type init)
1571 {
1572 	struct ehci_ctrl *ctrl = dev_get_priv(dev);
1573 	int ret;
1574 
1575 	debug("%s: dev='%s', ctrl=%p, hccr=%p, hcor=%p, init=%d\n", __func__,
1576 	      dev->name, ctrl, hccr, hcor, init);
1577 
1578 	ehci_setup_ops(ctrl, ops);
1579 	ctrl->hccr = hccr;
1580 	ctrl->hcor = hcor;
1581 	ctrl->priv = ctrl;
1582 
1583 	if (init == USB_INIT_DEVICE)
1584 		goto done;
1585 	ret = ehci_reset(ctrl);
1586 	if (ret)
1587 		goto err;
1588 
1589 	ret = ehci_common_init(ctrl, tweaks);
1590 	if (ret)
1591 		goto err;
1592 done:
1593 	return 0;
1594 err:
1595 	free(ctrl);
1596 	debug("%s: failed, ret=%d\n", __func__, ret);
1597 	return ret;
1598 }
1599 
1600 int ehci_deregister(struct udevice *dev)
1601 {
1602 	struct ehci_ctrl *ctrl = dev_get_priv(dev);
1603 
1604 	ehci_shutdown(ctrl);
1605 
1606 	return 0;
1607 }
1608 
1609 struct dm_usb_ops ehci_usb_ops = {
1610 	.control = ehci_submit_control_msg,
1611 	.bulk = ehci_submit_bulk_msg,
1612 	.interrupt = ehci_submit_int_msg,
1613 };
1614 
1615 #endif
1616