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