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