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