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