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