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