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