]> git.sur5r.net Git - u-boot/blob - drivers/usb/host/xhci.c
62f422b8d5a65ba738fc6b028035a5bc3bf0a5e2
[u-boot] / drivers / usb / host / xhci.c
1 /*
2  * USB HOST XHCI Controller stack
3  *
4  * Based on xHCI host controller driver in linux-kernel
5  * by Sarah Sharp.
6  *
7  * Copyright (C) 2008 Intel Corp.
8  * Author: Sarah Sharp
9  *
10  * Copyright (C) 2013 Samsung Electronics Co.Ltd
11  * Authors: Vivek Gautam <gautam.vivek@samsung.com>
12  *          Vikas Sajjan <vikas.sajjan@samsung.com>
13  *
14  * SPDX-License-Identifier:     GPL-2.0+
15  */
16
17 /**
18  * This file gives the xhci stack for usb3.0 looking into
19  * xhci specification Rev1.0 (5/21/10).
20  * The quirk devices support hasn't been given yet.
21  */
22
23 #include <common.h>
24 #include <asm/byteorder.h>
25 #include <usb.h>
26 #include <malloc.h>
27 #include <watchdog.h>
28 #include <asm/cache.h>
29 #include <asm/unaligned.h>
30 #include <asm-generic/errno.h>
31 #include "xhci.h"
32
33 #ifndef CONFIG_USB_MAX_CONTROLLER_COUNT
34 #define CONFIG_USB_MAX_CONTROLLER_COUNT 1
35 #endif
36
37 static struct descriptor {
38         struct usb_hub_descriptor hub;
39         struct usb_device_descriptor device;
40         struct usb_config_descriptor config;
41         struct usb_interface_descriptor interface;
42         struct usb_endpoint_descriptor endpoint;
43         struct usb_ss_ep_comp_descriptor ep_companion;
44 } __attribute__ ((packed)) descriptor = {
45         {
46                 0xc,            /* bDescLength */
47                 0x2a,           /* bDescriptorType: hub descriptor */
48                 2,              /* bNrPorts -- runtime modified */
49                 cpu_to_le16(0x8), /* wHubCharacteristics */
50                 10,             /* bPwrOn2PwrGood */
51                 0,              /* bHubCntrCurrent */
52                 {},             /* Device removable */
53                 {}              /* at most 7 ports! XXX */
54         },
55         {
56                 0x12,           /* bLength */
57                 1,              /* bDescriptorType: UDESC_DEVICE */
58                 cpu_to_le16(0x0300), /* bcdUSB: v3.0 */
59                 9,              /* bDeviceClass: UDCLASS_HUB */
60                 0,              /* bDeviceSubClass: UDSUBCLASS_HUB */
61                 3,              /* bDeviceProtocol: UDPROTO_SSHUBSTT */
62                 9,              /* bMaxPacketSize: 512 bytes  2^9 */
63                 0x0000,         /* idVendor */
64                 0x0000,         /* idProduct */
65                 cpu_to_le16(0x0100), /* bcdDevice */
66                 1,              /* iManufacturer */
67                 2,              /* iProduct */
68                 0,              /* iSerialNumber */
69                 1               /* bNumConfigurations: 1 */
70         },
71         {
72                 0x9,
73                 2,              /* bDescriptorType: UDESC_CONFIG */
74                 cpu_to_le16(0x1f), /* includes SS endpoint descriptor */
75                 1,              /* bNumInterface */
76                 1,              /* bConfigurationValue */
77                 0,              /* iConfiguration */
78                 0x40,           /* bmAttributes: UC_SELF_POWER */
79                 0               /* bMaxPower */
80         },
81         {
82                 0x9,            /* bLength */
83                 4,              /* bDescriptorType: UDESC_INTERFACE */
84                 0,              /* bInterfaceNumber */
85                 0,              /* bAlternateSetting */
86                 1,              /* bNumEndpoints */
87                 9,              /* bInterfaceClass: UICLASS_HUB */
88                 0,              /* bInterfaceSubClass: UISUBCLASS_HUB */
89                 0,              /* bInterfaceProtocol: UIPROTO_HSHUBSTT */
90                 0               /* iInterface */
91         },
92         {
93                 0x7,            /* bLength */
94                 5,              /* bDescriptorType: UDESC_ENDPOINT */
95                 0x81,           /* bEndpointAddress: IN endpoint 1 */
96                 3,              /* bmAttributes: UE_INTERRUPT */
97                 8,              /* wMaxPacketSize */
98                 255             /* bInterval */
99         },
100         {
101                 0x06,           /* ss_bLength */
102                 0x30,           /* ss_bDescriptorType: SS EP Companion */
103                 0x00,           /* ss_bMaxBurst: allows 1 TX between ACKs */
104                 /* ss_bmAttributes: 1 packet per service interval */
105                 0x00,
106                 /* ss_wBytesPerInterval: 15 bits for max 15 ports */
107                 cpu_to_le16(0x02),
108         },
109 };
110
111 static struct xhci_ctrl xhcic[CONFIG_USB_MAX_CONTROLLER_COUNT];
112
113 struct xhci_ctrl *xhci_get_ctrl(struct usb_device *udev)
114 {
115         return udev->controller;
116 }
117
118 /**
119  * Waits for as per specified amount of time
120  * for the "result" to match with "done"
121  *
122  * @param ptr   pointer to the register to be read
123  * @param mask  mask for the value read
124  * @param done  value to be campared with result
125  * @param usec  time to wait till
126  * @return 0 if handshake is success else < 0 on failure
127  */
128 static int handshake(uint32_t volatile *ptr, uint32_t mask,
129                                         uint32_t done, int usec)
130 {
131         uint32_t result;
132
133         do {
134                 result = xhci_readl(ptr);
135                 if (result == ~(uint32_t)0)
136                         return -ENODEV;
137                 result &= mask;
138                 if (result == done)
139                         return 0;
140                 usec--;
141                 udelay(1);
142         } while (usec > 0);
143
144         return -ETIMEDOUT;
145 }
146
147 /**
148  * Set the run bit and wait for the host to be running.
149  *
150  * @param hcor  pointer to host controller operation registers
151  * @return status of the Handshake
152  */
153 static int xhci_start(struct xhci_hcor *hcor)
154 {
155         u32 temp;
156         int ret;
157
158         puts("Starting the controller\n");
159         temp = xhci_readl(&hcor->or_usbcmd);
160         temp |= (CMD_RUN);
161         xhci_writel(&hcor->or_usbcmd, temp);
162
163         /*
164          * Wait for the HCHalted Status bit to be 0 to indicate the host is
165          * running.
166          */
167         ret = handshake(&hcor->or_usbsts, STS_HALT, 0, XHCI_MAX_HALT_USEC);
168         if (ret)
169                 debug("Host took too long to start, "
170                                 "waited %u microseconds.\n",
171                                 XHCI_MAX_HALT_USEC);
172         return ret;
173 }
174
175 /**
176  * Resets the XHCI Controller
177  *
178  * @param hcor  pointer to host controller operation registers
179  * @return -EBUSY if XHCI Controller is not halted else status of handshake
180  */
181 int xhci_reset(struct xhci_hcor *hcor)
182 {
183         u32 cmd;
184         u32 state;
185         int ret;
186
187         /* Halting the Host first */
188         debug("// Halt the HC\n");
189         state = xhci_readl(&hcor->or_usbsts) & STS_HALT;
190         if (!state) {
191                 cmd = xhci_readl(&hcor->or_usbcmd);
192                 cmd &= ~CMD_RUN;
193                 xhci_writel(&hcor->or_usbcmd, cmd);
194         }
195
196         ret = handshake(&hcor->or_usbsts,
197                         STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
198         if (ret) {
199                 printf("Host not halted after %u microseconds.\n",
200                                 XHCI_MAX_HALT_USEC);
201                 return -EBUSY;
202         }
203
204         debug("// Reset the HC\n");
205         cmd = xhci_readl(&hcor->or_usbcmd);
206         cmd |= CMD_RESET;
207         xhci_writel(&hcor->or_usbcmd, cmd);
208
209         ret = handshake(&hcor->or_usbcmd, CMD_RESET, 0, XHCI_MAX_RESET_USEC);
210         if (ret)
211                 return ret;
212
213         /*
214          * xHCI cannot write to any doorbells or operational registers other
215          * than status until the "Controller Not Ready" flag is cleared.
216          */
217         return handshake(&hcor->or_usbsts, STS_CNR, 0, XHCI_MAX_RESET_USEC);
218 }
219
220 /**
221  * Used for passing endpoint bitmasks between the core and HCDs.
222  * Find the index for an endpoint given its descriptor.
223  * Use the return value to right shift 1 for the bitmask.
224  *
225  * Index  = (epnum * 2) + direction - 1,
226  * where direction = 0 for OUT, 1 for IN.
227  * For control endpoints, the IN index is used (OUT index is unused), so
228  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
229  *
230  * @param desc  USB enpdoint Descriptor
231  * @return index of the Endpoint
232  */
233 static unsigned int xhci_get_ep_index(struct usb_endpoint_descriptor *desc)
234 {
235         unsigned int index;
236
237         if (usb_endpoint_xfer_control(desc))
238                 index = (unsigned int)(usb_endpoint_num(desc) * 2);
239         else
240                 index = (unsigned int)((usb_endpoint_num(desc) * 2) -
241                                 (usb_endpoint_dir_in(desc) ? 0 : 1));
242
243         return index;
244 }
245
246 /**
247  * Issue a configure endpoint command or evaluate context command
248  * and wait for it to finish.
249  *
250  * @param udev  pointer to the Device Data Structure
251  * @param ctx_change    flag to indicate the Context has changed or NOT
252  * @return 0 on success, -1 on failure
253  */
254 static int xhci_configure_endpoints(struct usb_device *udev, bool ctx_change)
255 {
256         struct xhci_container_ctx *in_ctx;
257         struct xhci_virt_device *virt_dev;
258         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
259         union xhci_trb *event;
260
261         virt_dev = ctrl->devs[udev->slot_id];
262         in_ctx = virt_dev->in_ctx;
263
264         xhci_flush_cache((uintptr_t)in_ctx->bytes, in_ctx->size);
265         xhci_queue_command(ctrl, in_ctx->bytes, udev->slot_id, 0,
266                            ctx_change ? TRB_EVAL_CONTEXT : TRB_CONFIG_EP);
267         event = xhci_wait_for_event(ctrl, TRB_COMPLETION);
268         BUG_ON(TRB_TO_SLOT_ID(le32_to_cpu(event->event_cmd.flags))
269                 != udev->slot_id);
270
271         switch (GET_COMP_CODE(le32_to_cpu(event->event_cmd.status))) {
272         case COMP_SUCCESS:
273                 debug("Successful %s command\n",
274                         ctx_change ? "Evaluate Context" : "Configure Endpoint");
275                 break;
276         default:
277                 printf("ERROR: %s command returned completion code %d.\n",
278                         ctx_change ? "Evaluate Context" : "Configure Endpoint",
279                         GET_COMP_CODE(le32_to_cpu(event->event_cmd.status)));
280                 return -EINVAL;
281         }
282
283         xhci_acknowledge_event(ctrl);
284
285         return 0;
286 }
287
288 /**
289  * Configure the endpoint, programming the device contexts.
290  *
291  * @param udev  pointer to the USB device structure
292  * @return returns the status of the xhci_configure_endpoints
293  */
294 static int xhci_set_configuration(struct usb_device *udev)
295 {
296         struct xhci_container_ctx *in_ctx;
297         struct xhci_container_ctx *out_ctx;
298         struct xhci_input_control_ctx *ctrl_ctx;
299         struct xhci_slot_ctx *slot_ctx;
300         struct xhci_ep_ctx *ep_ctx[MAX_EP_CTX_NUM];
301         int cur_ep;
302         int max_ep_flag = 0;
303         int ep_index;
304         unsigned int dir;
305         unsigned int ep_type;
306         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
307         int num_of_ep;
308         int ep_flag = 0;
309         u64 trb_64 = 0;
310         int slot_id = udev->slot_id;
311         struct xhci_virt_device *virt_dev = ctrl->devs[slot_id];
312         struct usb_interface *ifdesc;
313
314         out_ctx = virt_dev->out_ctx;
315         in_ctx = virt_dev->in_ctx;
316
317         num_of_ep = udev->config.if_desc[0].no_of_ep;
318         ifdesc = &udev->config.if_desc[0];
319
320         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
321         /* Zero the input context control */
322         ctrl_ctx->add_flags = 0;
323         ctrl_ctx->drop_flags = 0;
324
325         /* EP_FLAG gives values 1 & 4 for EP1OUT and EP2IN */
326         for (cur_ep = 0; cur_ep < num_of_ep; cur_ep++) {
327                 ep_flag = xhci_get_ep_index(&ifdesc->ep_desc[cur_ep]);
328                 ctrl_ctx->add_flags |= cpu_to_le32(1 << (ep_flag + 1));
329                 if (max_ep_flag < ep_flag)
330                         max_ep_flag = ep_flag;
331         }
332
333         xhci_inval_cache((uintptr_t)out_ctx->bytes, out_ctx->size);
334
335         /* slot context */
336         xhci_slot_copy(ctrl, in_ctx, out_ctx);
337         slot_ctx = xhci_get_slot_ctx(ctrl, in_ctx);
338         slot_ctx->dev_info &= ~(LAST_CTX_MASK);
339         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(max_ep_flag + 1) | 0);
340
341         xhci_endpoint_copy(ctrl, in_ctx, out_ctx, 0);
342
343         /* filling up ep contexts */
344         for (cur_ep = 0; cur_ep < num_of_ep; cur_ep++) {
345                 struct usb_endpoint_descriptor *endpt_desc = NULL;
346
347                 endpt_desc = &ifdesc->ep_desc[cur_ep];
348                 trb_64 = 0;
349
350                 ep_index = xhci_get_ep_index(endpt_desc);
351                 ep_ctx[ep_index] = xhci_get_ep_ctx(ctrl, in_ctx, ep_index);
352
353                 /* Allocate the ep rings */
354                 virt_dev->eps[ep_index].ring = xhci_ring_alloc(1, true);
355                 if (!virt_dev->eps[ep_index].ring)
356                         return -ENOMEM;
357
358                 /*NOTE: ep_desc[0] actually represents EP1 and so on */
359                 dir = (((endpt_desc->bEndpointAddress) & (0x80)) >> 7);
360                 ep_type = (((endpt_desc->bmAttributes) & (0x3)) | (dir << 2));
361                 ep_ctx[ep_index]->ep_info2 =
362                         cpu_to_le32(ep_type << EP_TYPE_SHIFT);
363                 ep_ctx[ep_index]->ep_info2 |=
364                         cpu_to_le32(MAX_PACKET
365                         (get_unaligned(&endpt_desc->wMaxPacketSize)));
366
367                 ep_ctx[ep_index]->ep_info2 |=
368                         cpu_to_le32(((0 & MAX_BURST_MASK) << MAX_BURST_SHIFT) |
369                         ((3 & ERROR_COUNT_MASK) << ERROR_COUNT_SHIFT));
370
371                 trb_64 = (uintptr_t)
372                                 virt_dev->eps[ep_index].ring->enqueue;
373                 ep_ctx[ep_index]->deq = cpu_to_le64(trb_64 |
374                                 virt_dev->eps[ep_index].ring->cycle_state);
375         }
376
377         return xhci_configure_endpoints(udev, false);
378 }
379
380 /**
381  * Issue an Address Device command (which will issue a SetAddress request to
382  * the device).
383  *
384  * @param udev pointer to the Device Data Structure
385  * @return 0 if successful else error code on failure
386  */
387 static int xhci_address_device(struct usb_device *udev, int root_portnr)
388 {
389         int ret = 0;
390         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
391         struct xhci_slot_ctx *slot_ctx;
392         struct xhci_input_control_ctx *ctrl_ctx;
393         struct xhci_virt_device *virt_dev;
394         int slot_id = udev->slot_id;
395         union xhci_trb *event;
396
397         virt_dev = ctrl->devs[slot_id];
398
399         /*
400          * This is the first Set Address since device plug-in
401          * so setting up the slot context.
402          */
403         debug("Setting up addressable devices %p\n", ctrl->dcbaa);
404         xhci_setup_addressable_virt_dev(ctrl, udev->slot_id, udev->speed,
405                                         root_portnr);
406
407         ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
408         ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
409         ctrl_ctx->drop_flags = 0;
410
411         xhci_queue_command(ctrl, (void *)ctrl_ctx, slot_id, 0, TRB_ADDR_DEV);
412         event = xhci_wait_for_event(ctrl, TRB_COMPLETION);
413         BUG_ON(TRB_TO_SLOT_ID(le32_to_cpu(event->event_cmd.flags)) != slot_id);
414
415         switch (GET_COMP_CODE(le32_to_cpu(event->event_cmd.status))) {
416         case COMP_CTX_STATE:
417         case COMP_EBADSLT:
418                 printf("Setup ERROR: address device command for slot %d.\n",
419                                                                 slot_id);
420                 ret = -EINVAL;
421                 break;
422         case COMP_TX_ERR:
423                 puts("Device not responding to set address.\n");
424                 ret = -EPROTO;
425                 break;
426         case COMP_DEV_ERR:
427                 puts("ERROR: Incompatible device"
428                                         "for address device command.\n");
429                 ret = -ENODEV;
430                 break;
431         case COMP_SUCCESS:
432                 debug("Successful Address Device command\n");
433                 udev->status = 0;
434                 break;
435         default:
436                 printf("ERROR: unexpected command completion code 0x%x.\n",
437                         GET_COMP_CODE(le32_to_cpu(event->event_cmd.status)));
438                 ret = -EINVAL;
439                 break;
440         }
441
442         xhci_acknowledge_event(ctrl);
443
444         if (ret < 0)
445                 /*
446                  * TODO: Unsuccessful Address Device command shall leave the
447                  * slot in default state. So, issue Disable Slot command now.
448                  */
449                 return ret;
450
451         xhci_inval_cache((uintptr_t)virt_dev->out_ctx->bytes,
452                          virt_dev->out_ctx->size);
453         slot_ctx = xhci_get_slot_ctx(ctrl, virt_dev->out_ctx);
454
455         debug("xHC internal address is: %d\n",
456                 le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
457
458         return 0;
459 }
460
461 /**
462  * Issue Enable slot command to the controller to allocate
463  * device slot and assign the slot id. It fails if the xHC
464  * ran out of device slots, the Enable Slot command timed out,
465  * or allocating memory failed.
466  *
467  * @param udev  pointer to the Device Data Structure
468  * @return Returns 0 on succes else return error code on failure
469  */
470 int usb_alloc_device(struct usb_device *udev)
471 {
472         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
473         union xhci_trb *event;
474         int ret;
475
476         /*
477          * Root hub will be first device to be initailized.
478          * If this device is root-hub, don't do any xHC related
479          * stuff.
480          */
481         if (ctrl->rootdev == 0) {
482                 udev->speed = USB_SPEED_SUPER;
483                 return 0;
484         }
485
486         xhci_queue_command(ctrl, NULL, 0, 0, TRB_ENABLE_SLOT);
487         event = xhci_wait_for_event(ctrl, TRB_COMPLETION);
488         BUG_ON(GET_COMP_CODE(le32_to_cpu(event->event_cmd.status))
489                 != COMP_SUCCESS);
490
491         udev->slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->event_cmd.flags));
492
493         xhci_acknowledge_event(ctrl);
494
495         ret = xhci_alloc_virt_device(ctrl, udev->slot_id);
496         if (ret < 0) {
497                 /*
498                  * TODO: Unsuccessful Address Device command shall leave
499                  * the slot in default. So, issue Disable Slot command now.
500                  */
501                 puts("Could not allocate xHCI USB device data structures\n");
502                 return ret;
503         }
504
505         return 0;
506 }
507
508 /*
509  * Full speed devices may have a max packet size greater than 8 bytes, but the
510  * USB core doesn't know that until it reads the first 8 bytes of the
511  * descriptor.  If the usb_device's max packet size changes after that point,
512  * we need to issue an evaluate context command and wait on it.
513  *
514  * @param udev  pointer to the Device Data Structure
515  * @return returns the status of the xhci_configure_endpoints
516  */
517 int xhci_check_maxpacket(struct usb_device *udev)
518 {
519         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
520         unsigned int slot_id = udev->slot_id;
521         int ep_index = 0;       /* control endpoint */
522         struct xhci_container_ctx *in_ctx;
523         struct xhci_container_ctx *out_ctx;
524         struct xhci_input_control_ctx *ctrl_ctx;
525         struct xhci_ep_ctx *ep_ctx;
526         int max_packet_size;
527         int hw_max_packet_size;
528         int ret = 0;
529         struct usb_interface *ifdesc;
530
531         ifdesc = &udev->config.if_desc[0];
532
533         out_ctx = ctrl->devs[slot_id]->out_ctx;
534         xhci_inval_cache((uintptr_t)out_ctx->bytes, out_ctx->size);
535
536         ep_ctx = xhci_get_ep_ctx(ctrl, out_ctx, ep_index);
537         hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
538         max_packet_size = usb_endpoint_maxp(&ifdesc->ep_desc[0]);
539         if (hw_max_packet_size != max_packet_size) {
540                 debug("Max Packet Size for ep 0 changed.\n");
541                 debug("Max packet size in usb_device = %d\n", max_packet_size);
542                 debug("Max packet size in xHCI HW = %d\n", hw_max_packet_size);
543                 debug("Issuing evaluate context command.\n");
544
545                 /* Set up the modified control endpoint 0 */
546                 xhci_endpoint_copy(ctrl, ctrl->devs[slot_id]->in_ctx,
547                                 ctrl->devs[slot_id]->out_ctx, ep_index);
548                 in_ctx = ctrl->devs[slot_id]->in_ctx;
549                 ep_ctx = xhci_get_ep_ctx(ctrl, in_ctx, ep_index);
550                 ep_ctx->ep_info2 &= cpu_to_le32(~MAX_PACKET_MASK);
551                 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
552
553                 /*
554                  * Set up the input context flags for the command
555                  * FIXME: This won't work if a non-default control endpoint
556                  * changes max packet sizes.
557                  */
558                 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
559                 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
560                 ctrl_ctx->drop_flags = 0;
561
562                 ret = xhci_configure_endpoints(udev, true);
563         }
564         return ret;
565 }
566
567 /**
568  * Clears the Change bits of the Port Status Register
569  *
570  * @param wValue        request value
571  * @param wIndex        request index
572  * @param addr          address of posrt status register
573  * @param port_status   state of port status register
574  * @return none
575  */
576 static void xhci_clear_port_change_bit(u16 wValue,
577                 u16 wIndex, volatile uint32_t *addr, u32 port_status)
578 {
579         char *port_change_bit;
580         u32 status;
581
582         switch (wValue) {
583         case USB_PORT_FEAT_C_RESET:
584                 status = PORT_RC;
585                 port_change_bit = "reset";
586                 break;
587         case USB_PORT_FEAT_C_CONNECTION:
588                 status = PORT_CSC;
589                 port_change_bit = "connect";
590                 break;
591         case USB_PORT_FEAT_C_OVER_CURRENT:
592                 status = PORT_OCC;
593                 port_change_bit = "over-current";
594                 break;
595         case USB_PORT_FEAT_C_ENABLE:
596                 status = PORT_PEC;
597                 port_change_bit = "enable/disable";
598                 break;
599         case USB_PORT_FEAT_C_SUSPEND:
600                 status = PORT_PLC;
601                 port_change_bit = "suspend/resume";
602                 break;
603         default:
604                 /* Should never happen */
605                 return;
606         }
607
608         /* Change bits are all write 1 to clear */
609         xhci_writel(addr, port_status | status);
610
611         port_status = xhci_readl(addr);
612         debug("clear port %s change, actual port %d status  = 0x%x\n",
613                         port_change_bit, wIndex, port_status);
614 }
615
616 /**
617  * Save Read Only (RO) bits and save read/write bits where
618  * writing a 0 clears the bit and writing a 1 sets the bit (RWS).
619  * For all other types (RW1S, RW1CS, RW, and RZ), writing a '0' has no effect.
620  *
621  * @param state state of the Port Status and Control Regsiter
622  * @return a value that would result in the port being in the
623  *         same state, if the value was written to the port
624  *         status control register.
625  */
626 static u32 xhci_port_state_to_neutral(u32 state)
627 {
628         /* Save read-only status and port state */
629         return (state & XHCI_PORT_RO) | (state & XHCI_PORT_RWS);
630 }
631
632 /**
633  * Submits the Requests to the XHCI Host Controller
634  *
635  * @param udev pointer to the USB device structure
636  * @param pipe contains the DIR_IN or OUT , devnum
637  * @param buffer buffer to be read/written based on the request
638  * @return returns 0 if successful else -1 on failure
639  */
640 static int xhci_submit_root(struct usb_device *udev, unsigned long pipe,
641                         void *buffer, struct devrequest *req)
642 {
643         uint8_t tmpbuf[4];
644         u16 typeReq;
645         void *srcptr = NULL;
646         int len, srclen;
647         uint32_t reg;
648         volatile uint32_t *status_reg;
649         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
650         struct xhci_hcor *hcor = ctrl->hcor;
651
652         if ((req->requesttype & USB_RT_PORT) &&
653             le16_to_cpu(req->index) > CONFIG_SYS_USB_XHCI_MAX_ROOT_PORTS) {
654                 printf("The request port(%d) is not configured\n",
655                         le16_to_cpu(req->index) - 1);
656                 return -EINVAL;
657         }
658
659         status_reg = (volatile uint32_t *)
660                      (&hcor->portregs[le16_to_cpu(req->index) - 1].or_portsc);
661         srclen = 0;
662
663         typeReq = req->request | req->requesttype << 8;
664
665         switch (typeReq) {
666         case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
667                 switch (le16_to_cpu(req->value) >> 8) {
668                 case USB_DT_DEVICE:
669                         debug("USB_DT_DEVICE request\n");
670                         srcptr = &descriptor.device;
671                         srclen = 0x12;
672                         break;
673                 case USB_DT_CONFIG:
674                         debug("USB_DT_CONFIG config\n");
675                         srcptr = &descriptor.config;
676                         srclen = 0x19;
677                         break;
678                 case USB_DT_STRING:
679                         debug("USB_DT_STRING config\n");
680                         switch (le16_to_cpu(req->value) & 0xff) {
681                         case 0: /* Language */
682                                 srcptr = "\4\3\11\4";
683                                 srclen = 4;
684                                 break;
685                         case 1: /* Vendor String  */
686                                 srcptr = "\16\3u\0-\0b\0o\0o\0t\0";
687                                 srclen = 14;
688                                 break;
689                         case 2: /* Product Name */
690                                 srcptr = "\52\3X\0H\0C\0I\0 "
691                                          "\0H\0o\0s\0t\0 "
692                                          "\0C\0o\0n\0t\0r\0o\0l\0l\0e\0r\0";
693                                 srclen = 42;
694                                 break;
695                         default:
696                                 printf("unknown value DT_STRING %x\n",
697                                         le16_to_cpu(req->value));
698                                 goto unknown;
699                         }
700                         break;
701                 default:
702                         printf("unknown value %x\n", le16_to_cpu(req->value));
703                         goto unknown;
704                 }
705                 break;
706         case USB_REQ_GET_DESCRIPTOR | ((USB_DIR_IN | USB_RT_HUB) << 8):
707                 switch (le16_to_cpu(req->value) >> 8) {
708                 case USB_DT_HUB:
709                         debug("USB_DT_HUB config\n");
710                         srcptr = &descriptor.hub;
711                         srclen = 0x8;
712                         break;
713                 default:
714                         printf("unknown value %x\n", le16_to_cpu(req->value));
715                         goto unknown;
716                 }
717                 break;
718         case USB_REQ_SET_ADDRESS | (USB_RECIP_DEVICE << 8):
719                 debug("USB_REQ_SET_ADDRESS\n");
720                 ctrl->rootdev = le16_to_cpu(req->value);
721                 break;
722         case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
723                 /* Do nothing */
724                 break;
725         case USB_REQ_GET_STATUS | ((USB_DIR_IN | USB_RT_HUB) << 8):
726                 tmpbuf[0] = 1;  /* USB_STATUS_SELFPOWERED */
727                 tmpbuf[1] = 0;
728                 srcptr = tmpbuf;
729                 srclen = 2;
730                 break;
731         case USB_REQ_GET_STATUS | ((USB_RT_PORT | USB_DIR_IN) << 8):
732                 memset(tmpbuf, 0, 4);
733                 reg = xhci_readl(status_reg);
734                 if (reg & PORT_CONNECT) {
735                         tmpbuf[0] |= USB_PORT_STAT_CONNECTION;
736                         switch (reg & DEV_SPEED_MASK) {
737                         case XDEV_FS:
738                                 debug("SPEED = FULLSPEED\n");
739                                 break;
740                         case XDEV_LS:
741                                 debug("SPEED = LOWSPEED\n");
742                                 tmpbuf[1] |= USB_PORT_STAT_LOW_SPEED >> 8;
743                                 break;
744                         case XDEV_HS:
745                                 debug("SPEED = HIGHSPEED\n");
746                                 tmpbuf[1] |= USB_PORT_STAT_HIGH_SPEED >> 8;
747                                 break;
748                         case XDEV_SS:
749                                 debug("SPEED = SUPERSPEED\n");
750                                 tmpbuf[1] |= USB_PORT_STAT_SUPER_SPEED >> 8;
751                                 break;
752                         }
753                 }
754                 if (reg & PORT_PE)
755                         tmpbuf[0] |= USB_PORT_STAT_ENABLE;
756                 if ((reg & PORT_PLS_MASK) == XDEV_U3)
757                         tmpbuf[0] |= USB_PORT_STAT_SUSPEND;
758                 if (reg & PORT_OC)
759                         tmpbuf[0] |= USB_PORT_STAT_OVERCURRENT;
760                 if (reg & PORT_RESET)
761                         tmpbuf[0] |= USB_PORT_STAT_RESET;
762                 if (reg & PORT_POWER)
763                         /*
764                          * XXX: This Port power bit (for USB 3.0 hub)
765                          * we are faking in USB 2.0 hub port status;
766                          * since there's a change in bit positions in
767                          * two:
768                          * USB 2.0 port status PP is at position[8]
769                          * USB 3.0 port status PP is at position[9]
770                          * So, we are still keeping it at position [8]
771                          */
772                         tmpbuf[1] |= USB_PORT_STAT_POWER >> 8;
773                 if (reg & PORT_CSC)
774                         tmpbuf[2] |= USB_PORT_STAT_C_CONNECTION;
775                 if (reg & PORT_PEC)
776                         tmpbuf[2] |= USB_PORT_STAT_C_ENABLE;
777                 if (reg & PORT_OCC)
778                         tmpbuf[2] |= USB_PORT_STAT_C_OVERCURRENT;
779                 if (reg & PORT_RC)
780                         tmpbuf[2] |= USB_PORT_STAT_C_RESET;
781
782                 srcptr = tmpbuf;
783                 srclen = 4;
784                 break;
785         case USB_REQ_SET_FEATURE | ((USB_DIR_OUT | USB_RT_PORT) << 8):
786                 reg = xhci_readl(status_reg);
787                 reg = xhci_port_state_to_neutral(reg);
788                 switch (le16_to_cpu(req->value)) {
789                 case USB_PORT_FEAT_ENABLE:
790                         reg |= PORT_PE;
791                         xhci_writel(status_reg, reg);
792                         break;
793                 case USB_PORT_FEAT_POWER:
794                         reg |= PORT_POWER;
795                         xhci_writel(status_reg, reg);
796                         break;
797                 case USB_PORT_FEAT_RESET:
798                         reg |= PORT_RESET;
799                         xhci_writel(status_reg, reg);
800                         break;
801                 default:
802                         printf("unknown feature %x\n", le16_to_cpu(req->value));
803                         goto unknown;
804                 }
805                 break;
806         case USB_REQ_CLEAR_FEATURE | ((USB_DIR_OUT | USB_RT_PORT) << 8):
807                 reg = xhci_readl(status_reg);
808                 reg = xhci_port_state_to_neutral(reg);
809                 switch (le16_to_cpu(req->value)) {
810                 case USB_PORT_FEAT_ENABLE:
811                         reg &= ~PORT_PE;
812                         break;
813                 case USB_PORT_FEAT_POWER:
814                         reg &= ~PORT_POWER;
815                         break;
816                 case USB_PORT_FEAT_C_RESET:
817                 case USB_PORT_FEAT_C_CONNECTION:
818                 case USB_PORT_FEAT_C_OVER_CURRENT:
819                 case USB_PORT_FEAT_C_ENABLE:
820                         xhci_clear_port_change_bit((le16_to_cpu(req->value)),
821                                                         le16_to_cpu(req->index),
822                                                         status_reg, reg);
823                         break;
824                 default:
825                         printf("unknown feature %x\n", le16_to_cpu(req->value));
826                         goto unknown;
827                 }
828                 xhci_writel(status_reg, reg);
829                 break;
830         default:
831                 puts("Unknown request\n");
832                 goto unknown;
833         }
834
835         debug("scrlen = %d\n req->length = %d\n",
836                 srclen, le16_to_cpu(req->length));
837
838         len = min(srclen, (int)le16_to_cpu(req->length));
839
840         if (srcptr != NULL && len > 0)
841                 memcpy(buffer, srcptr, len);
842         else
843                 debug("Len is 0\n");
844
845         udev->act_len = len;
846         udev->status = 0;
847
848         return 0;
849
850 unknown:
851         udev->act_len = 0;
852         udev->status = USB_ST_STALLED;
853
854         return -ENODEV;
855 }
856
857 /**
858  * Submits the INT request to XHCI Host cotroller
859  *
860  * @param udev  pointer to the USB device
861  * @param pipe          contains the DIR_IN or OUT , devnum
862  * @param buffer        buffer to be read/written based on the request
863  * @param length        length of the buffer
864  * @param interval      interval of the interrupt
865  * @return 0
866  */
867 int
868 submit_int_msg(struct usb_device *udev, unsigned long pipe, void *buffer,
869                                                 int length, int interval)
870 {
871         /*
872          * TODO: Not addressing any interrupt type transfer requests
873          * Add support for it later.
874          */
875         return -EINVAL;
876 }
877
878 /**
879  * submit the BULK type of request to the USB Device
880  *
881  * @param udev  pointer to the USB device
882  * @param pipe          contains the DIR_IN or OUT , devnum
883  * @param buffer        buffer to be read/written based on the request
884  * @param length        length of the buffer
885  * @return returns 0 if successful else -1 on failure
886  */
887 int
888 submit_bulk_msg(struct usb_device *udev, unsigned long pipe, void *buffer,
889                                                                 int length)
890 {
891         if (usb_pipetype(pipe) != PIPE_BULK) {
892                 printf("non-bulk pipe (type=%lu)", usb_pipetype(pipe));
893                 return -EINVAL;
894         }
895
896         return xhci_bulk_tx(udev, pipe, length, buffer);
897 }
898
899 /**
900  * submit the control type of request to the Root hub/Device based on the devnum
901  *
902  * @param udev  pointer to the USB device
903  * @param pipe          contains the DIR_IN or OUT , devnum
904  * @param buffer        buffer to be read/written based on the request
905  * @param length        length of the buffer
906  * @param setup         Request type
907  * @param root_portnr   Root port number that this device is on
908  * @return returns 0 if successful else -1 on failure
909  */
910 static int _xhci_submit_control_msg(struct usb_device *udev, unsigned long pipe,
911                                     void *buffer, int length,
912                                     struct devrequest *setup, int root_portnr)
913 {
914         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
915         int ret = 0;
916
917         if (usb_pipetype(pipe) != PIPE_CONTROL) {
918                 printf("non-control pipe (type=%lu)", usb_pipetype(pipe));
919                 return -EINVAL;
920         }
921
922         if (usb_pipedevice(pipe) == ctrl->rootdev)
923                 return xhci_submit_root(udev, pipe, buffer, setup);
924
925         if (setup->request == USB_REQ_SET_ADDRESS)
926                 return xhci_address_device(udev, root_portnr);
927
928         if (setup->request == USB_REQ_SET_CONFIGURATION) {
929                 ret = xhci_set_configuration(udev);
930                 if (ret) {
931                         puts("Failed to configure xHCI endpoint\n");
932                         return ret;
933                 }
934         }
935
936         return xhci_ctrl_tx(udev, pipe, setup, length, buffer);
937 }
938
939 /**
940  * Intialises the XHCI host controller
941  * and allocates the necessary data structures
942  *
943  * @param index index to the host controller data structure
944  * @return pointer to the intialised controller
945  */
946 int usb_lowlevel_init(int index, enum usb_init_type init, void **controller)
947 {
948         uint32_t val;
949         uint32_t val2;
950         uint32_t reg;
951         struct xhci_hccr *hccr;
952         struct xhci_hcor *hcor;
953         struct xhci_ctrl *ctrl;
954
955         if (xhci_hcd_init(index, &hccr, (struct xhci_hcor **)&hcor) != 0)
956                 return -ENODEV;
957
958         if (xhci_reset(hcor) != 0)
959                 return -ENODEV;
960
961         ctrl = &xhcic[index];
962
963         ctrl->hccr = hccr;
964         ctrl->hcor = hcor;
965
966         /*
967          * Program the Number of Device Slots Enabled field in the CONFIG
968          * register with the max value of slots the HC can handle.
969          */
970         val = (xhci_readl(&hccr->cr_hcsparams1) & HCS_SLOTS_MASK);
971         val2 = xhci_readl(&hcor->or_config);
972         val |= (val2 & ~HCS_SLOTS_MASK);
973         xhci_writel(&hcor->or_config, val);
974
975         /* initializing xhci data structures */
976         if (xhci_mem_init(ctrl, hccr, hcor) < 0)
977                 return -ENOMEM;
978
979         reg = xhci_readl(&hccr->cr_hcsparams1);
980         descriptor.hub.bNbrPorts = ((reg & HCS_MAX_PORTS_MASK) >>
981                                                 HCS_MAX_PORTS_SHIFT);
982         printf("Register %x NbrPorts %d\n", reg, descriptor.hub.bNbrPorts);
983
984         /* Port Indicators */
985         reg = xhci_readl(&hccr->cr_hccparams);
986         if (HCS_INDICATOR(reg))
987                 put_unaligned(get_unaligned(&descriptor.hub.wHubCharacteristics)
988                                 | 0x80, &descriptor.hub.wHubCharacteristics);
989
990         /* Port Power Control */
991         if (HCC_PPC(reg))
992                 put_unaligned(get_unaligned(&descriptor.hub.wHubCharacteristics)
993                                 | 0x01, &descriptor.hub.wHubCharacteristics);
994
995         if (xhci_start(hcor)) {
996                 xhci_reset(hcor);
997                 return -ENODEV;
998         }
999
1000         /* Zero'ing IRQ control register and IRQ pending register */
1001         xhci_writel(&ctrl->ir_set->irq_control, 0x0);
1002         xhci_writel(&ctrl->ir_set->irq_pending, 0x0);
1003
1004         reg = HC_VERSION(xhci_readl(&hccr->cr_capbase));
1005         printf("USB XHCI %x.%02x\n", reg >> 8, reg & 0xff);
1006
1007         *controller = &xhcic[index];
1008
1009         return 0;
1010 }
1011
1012 int submit_control_msg(struct usb_device *udev, unsigned long pipe,
1013                        void *buffer, int length, struct devrequest *setup)
1014 {
1015         struct usb_device *hop = udev;
1016
1017         if (hop->parent)
1018                 while (hop->parent->parent)
1019                         hop = hop->parent;
1020
1021         return _xhci_submit_control_msg(udev, pipe, buffer, length, setup,
1022                                         hop->portnr);
1023 }
1024
1025 /**
1026  * Stops the XHCI host controller
1027  * and cleans up all the related data structures
1028  *
1029  * @param index index to the host controller data structure
1030  * @return none
1031  */
1032 int usb_lowlevel_stop(int index)
1033 {
1034         struct xhci_ctrl *ctrl = (xhcic + index);
1035         u32 temp;
1036
1037         xhci_reset(ctrl->hcor);
1038
1039         debug("// Disabling event ring interrupts\n");
1040         temp = xhci_readl(&ctrl->hcor->or_usbsts);
1041         xhci_writel(&ctrl->hcor->or_usbsts, temp & ~STS_EINT);
1042         temp = xhci_readl(&ctrl->ir_set->irq_pending);
1043         xhci_writel(&ctrl->ir_set->irq_pending, ER_IRQ_DISABLE(temp));
1044
1045         xhci_hcd_stop(index);
1046
1047         xhci_cleanup(ctrl);
1048
1049         return 0;
1050 }