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