Merge git://git.denx.de/u-boot-usb
[platform/kernel/u-boot.git] / drivers / usb / host / xhci.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * USB HOST XHCI Controller stack
4  *
5  * Based on xHCI host controller driver in linux-kernel
6  * by Sarah Sharp.
7  *
8  * Copyright (C) 2008 Intel Corp.
9  * Author: Sarah Sharp
10  *
11  * Copyright (C) 2013 Samsung Electronics Co.Ltd
12  * Authors: Vivek Gautam <gautam.vivek@samsung.com>
13  *          Vikas Sajjan <vikas.sajjan@samsung.com>
14  */
15
16 /**
17  * This file gives the xhci stack for usb3.0 looking into
18  * xhci specification Rev1.0 (5/21/10).
19  * The quirk devices support hasn't been given yet.
20  */
21
22 #include <common.h>
23 #include <cpu_func.h>
24 #include <dm.h>
25 #include <asm/byteorder.h>
26 #include <usb.h>
27 #include <malloc.h>
28 #include <watchdog.h>
29 #include <asm/cache.h>
30 #include <asm/unaligned.h>
31 #include <linux/errno.h>
32 #include <usb/xhci.h>
33
34 #ifndef CONFIG_USB_MAX_CONTROLLER_COUNT
35 #define CONFIG_USB_MAX_CONTROLLER_COUNT 1
36 #endif
37
38 static struct descriptor {
39         struct usb_hub_descriptor hub;
40         struct usb_device_descriptor device;
41         struct usb_config_descriptor config;
42         struct usb_interface_descriptor interface;
43         struct usb_endpoint_descriptor endpoint;
44         struct usb_ss_ep_comp_descriptor ep_companion;
45 } __attribute__ ((packed)) descriptor = {
46         {
47                 0xc,            /* bDescLength */
48                 0x2a,           /* bDescriptorType: hub descriptor */
49                 2,              /* bNrPorts -- runtime modified */
50                 cpu_to_le16(0x8), /* wHubCharacteristics */
51                 10,             /* bPwrOn2PwrGood */
52                 0,              /* bHubCntrCurrent */
53                 {               /* Device removable */
54                 }               /* at most 7 ports! XXX */
55         },
56         {
57                 0x12,           /* bLength */
58                 1,              /* bDescriptorType: UDESC_DEVICE */
59                 cpu_to_le16(0x0300), /* bcdUSB: v3.0 */
60                 9,              /* bDeviceClass: UDCLASS_HUB */
61                 0,              /* bDeviceSubClass: UDSUBCLASS_HUB */
62                 3,              /* bDeviceProtocol: UDPROTO_SSHUBSTT */
63                 9,              /* bMaxPacketSize: 512 bytes  2^9 */
64                 0x0000,         /* idVendor */
65                 0x0000,         /* idProduct */
66                 cpu_to_le16(0x0100), /* bcdDevice */
67                 1,              /* iManufacturer */
68                 2,              /* iProduct */
69                 0,              /* iSerialNumber */
70                 1               /* bNumConfigurations: 1 */
71         },
72         {
73                 0x9,
74                 2,              /* bDescriptorType: UDESC_CONFIG */
75                 cpu_to_le16(0x1f), /* includes SS endpoint descriptor */
76                 1,              /* bNumInterface */
77                 1,              /* bConfigurationValue */
78                 0,              /* iConfiguration */
79                 0x40,           /* bmAttributes: UC_SELF_POWER */
80                 0               /* bMaxPower */
81         },
82         {
83                 0x9,            /* bLength */
84                 4,              /* bDescriptorType: UDESC_INTERFACE */
85                 0,              /* bInterfaceNumber */
86                 0,              /* bAlternateSetting */
87                 1,              /* bNumEndpoints */
88                 9,              /* bInterfaceClass: UICLASS_HUB */
89                 0,              /* bInterfaceSubClass: UISUBCLASS_HUB */
90                 0,              /* bInterfaceProtocol: UIPROTO_HSHUBSTT */
91                 0               /* iInterface */
92         },
93         {
94                 0x7,            /* bLength */
95                 5,              /* bDescriptorType: UDESC_ENDPOINT */
96                 0x81,           /* bEndpointAddress: IN endpoint 1 */
97                 3,              /* bmAttributes: UE_INTERRUPT */
98                 8,              /* wMaxPacketSize */
99                 255             /* bInterval */
100         },
101         {
102                 0x06,           /* ss_bLength */
103                 0x30,           /* ss_bDescriptorType: SS EP Companion */
104                 0x00,           /* ss_bMaxBurst: allows 1 TX between ACKs */
105                 /* ss_bmAttributes: 1 packet per service interval */
106                 0x00,
107                 /* ss_wBytesPerInterval: 15 bits for max 15 ports */
108                 cpu_to_le16(0x02),
109         },
110 };
111
112 #if !CONFIG_IS_ENABLED(DM_USB)
113 static struct xhci_ctrl xhcic[CONFIG_USB_MAX_CONTROLLER_COUNT];
114 #endif
115
116 struct xhci_ctrl *xhci_get_ctrl(struct usb_device *udev)
117 {
118 #if CONFIG_IS_ENABLED(DM_USB)
119         struct udevice *dev;
120
121         /* Find the USB controller */
122         for (dev = udev->dev;
123              device_get_uclass_id(dev) != UCLASS_USB;
124              dev = dev->parent)
125                 ;
126         return dev_get_priv(dev);
127 #else
128         return udev->controller;
129 #endif
130 }
131
132 /**
133  * Waits for as per specified amount of time
134  * for the "result" to match with "done"
135  *
136  * @param ptr   pointer to the register to be read
137  * @param mask  mask for the value read
138  * @param done  value to be campared with result
139  * @param usec  time to wait till
140  * @return 0 if handshake is success else < 0 on failure
141  */
142 static int handshake(uint32_t volatile *ptr, uint32_t mask,
143                                         uint32_t done, int usec)
144 {
145         uint32_t result;
146
147         do {
148                 result = xhci_readl(ptr);
149                 if (result == ~(uint32_t)0)
150                         return -ENODEV;
151                 result &= mask;
152                 if (result == done)
153                         return 0;
154                 usec--;
155                 udelay(1);
156         } while (usec > 0);
157
158         return -ETIMEDOUT;
159 }
160
161 /**
162  * Set the run bit and wait for the host to be running.
163  *
164  * @param hcor  pointer to host controller operation registers
165  * @return status of the Handshake
166  */
167 static int xhci_start(struct xhci_hcor *hcor)
168 {
169         u32 temp;
170         int ret;
171
172         puts("Starting the controller\n");
173         temp = xhci_readl(&hcor->or_usbcmd);
174         temp |= (CMD_RUN);
175         xhci_writel(&hcor->or_usbcmd, temp);
176
177         /*
178          * Wait for the HCHalted Status bit to be 0 to indicate the host is
179          * running.
180          */
181         ret = handshake(&hcor->or_usbsts, STS_HALT, 0, XHCI_MAX_HALT_USEC);
182         if (ret)
183                 debug("Host took too long to start, "
184                                 "waited %u microseconds.\n",
185                                 XHCI_MAX_HALT_USEC);
186         return ret;
187 }
188
189 /**
190  * Resets the XHCI Controller
191  *
192  * @param hcor  pointer to host controller operation registers
193  * @return -EBUSY if XHCI Controller is not halted else status of handshake
194  */
195 static int xhci_reset(struct xhci_hcor *hcor)
196 {
197         u32 cmd;
198         u32 state;
199         int ret;
200
201         /* Halting the Host first */
202         debug("// Halt the HC: %p\n", hcor);
203         state = xhci_readl(&hcor->or_usbsts) & STS_HALT;
204         if (!state) {
205                 cmd = xhci_readl(&hcor->or_usbcmd);
206                 cmd &= ~CMD_RUN;
207                 xhci_writel(&hcor->or_usbcmd, cmd);
208         }
209
210         ret = handshake(&hcor->or_usbsts,
211                         STS_HALT, STS_HALT, XHCI_MAX_HALT_USEC);
212         if (ret) {
213                 printf("Host not halted after %u microseconds.\n",
214                                 XHCI_MAX_HALT_USEC);
215                 return -EBUSY;
216         }
217
218         debug("// Reset the HC\n");
219         cmd = xhci_readl(&hcor->or_usbcmd);
220         cmd |= CMD_RESET;
221         xhci_writel(&hcor->or_usbcmd, cmd);
222
223         ret = handshake(&hcor->or_usbcmd, CMD_RESET, 0, XHCI_MAX_RESET_USEC);
224         if (ret)
225                 return ret;
226
227         /*
228          * xHCI cannot write to any doorbells or operational registers other
229          * than status until the "Controller Not Ready" flag is cleared.
230          */
231         return handshake(&hcor->or_usbsts, STS_CNR, 0, XHCI_MAX_RESET_USEC);
232 }
233
234 /**
235  * Used for passing endpoint bitmasks between the core and HCDs.
236  * Find the index for an endpoint given its descriptor.
237  * Use the return value to right shift 1 for the bitmask.
238  *
239  * Index  = (epnum * 2) + direction - 1,
240  * where direction = 0 for OUT, 1 for IN.
241  * For control endpoints, the IN index is used (OUT index is unused), so
242  * index = (epnum * 2) + direction - 1 = (epnum * 2) + 1 - 1 = (epnum * 2)
243  *
244  * @param desc  USB enpdoint Descriptor
245  * @return index of the Endpoint
246  */
247 static unsigned int xhci_get_ep_index(struct usb_endpoint_descriptor *desc)
248 {
249         unsigned int index;
250
251         if (usb_endpoint_xfer_control(desc))
252                 index = (unsigned int)(usb_endpoint_num(desc) * 2);
253         else
254                 index = (unsigned int)((usb_endpoint_num(desc) * 2) -
255                                 (usb_endpoint_dir_in(desc) ? 0 : 1));
256
257         return index;
258 }
259
260 /*
261  * Convert bInterval expressed in microframes (in 1-255 range) to exponent of
262  * microframes, rounded down to nearest power of 2.
263  */
264 static unsigned int xhci_microframes_to_exponent(unsigned int desc_interval,
265                                                  unsigned int min_exponent,
266                                                  unsigned int max_exponent)
267 {
268         unsigned int interval;
269
270         interval = fls(desc_interval) - 1;
271         interval = clamp_val(interval, min_exponent, max_exponent);
272         if ((1 << interval) != desc_interval)
273                 debug("rounding interval to %d microframes, "\
274                       "ep desc says %d microframes\n",
275                       1 << interval, desc_interval);
276
277         return interval;
278 }
279
280 static unsigned int xhci_parse_microframe_interval(struct usb_device *udev,
281         struct usb_endpoint_descriptor *endpt_desc)
282 {
283         if (endpt_desc->bInterval == 0)
284                 return 0;
285
286         return xhci_microframes_to_exponent(endpt_desc->bInterval, 0, 15);
287 }
288
289 static unsigned int xhci_parse_frame_interval(struct usb_device *udev,
290         struct usb_endpoint_descriptor *endpt_desc)
291 {
292         return xhci_microframes_to_exponent(endpt_desc->bInterval * 8, 3, 10);
293 }
294
295 /*
296  * Convert interval expressed as 2^(bInterval - 1) == interval into
297  * straight exponent value 2^n == interval.
298  */
299 static unsigned int xhci_parse_exponent_interval(struct usb_device *udev,
300         struct usb_endpoint_descriptor *endpt_desc)
301 {
302         unsigned int interval;
303
304         interval = clamp_val(endpt_desc->bInterval, 1, 16) - 1;
305         if (interval != endpt_desc->bInterval - 1)
306                 debug("ep %#x - rounding interval to %d %sframes\n",
307                       endpt_desc->bEndpointAddress, 1 << interval,
308                       udev->speed == USB_SPEED_FULL ? "" : "micro");
309
310         if (udev->speed == USB_SPEED_FULL) {
311                 /*
312                  * Full speed isoc endpoints specify interval in frames,
313                  * not microframes. We are using microframes everywhere,
314                  * so adjust accordingly.
315                  */
316                 interval += 3;  /* 1 frame = 2^3 uframes */
317         }
318
319         return interval;
320 }
321
322 /*
323  * Return the polling or NAK interval.
324  *
325  * The polling interval is expressed in "microframes". If xHCI's Interval field
326  * is set to N, it will service the endpoint every 2^(Interval)*125us.
327  *
328  * The NAK interval is one NAK per 1 to 255 microframes, or no NAKs if interval
329  * is set to 0.
330  */
331 static unsigned int xhci_get_endpoint_interval(struct usb_device *udev,
332         struct usb_endpoint_descriptor *endpt_desc)
333 {
334         unsigned int interval = 0;
335
336         switch (udev->speed) {
337         case USB_SPEED_HIGH:
338                 /* Max NAK rate */
339                 if (usb_endpoint_xfer_control(endpt_desc) ||
340                     usb_endpoint_xfer_bulk(endpt_desc)) {
341                         interval = xhci_parse_microframe_interval(udev,
342                                                                   endpt_desc);
343                         break;
344                 }
345                 /* Fall through - SS and HS isoc/int have same decoding */
346
347         case USB_SPEED_SUPER:
348                 if (usb_endpoint_xfer_int(endpt_desc) ||
349                     usb_endpoint_xfer_isoc(endpt_desc)) {
350                         interval = xhci_parse_exponent_interval(udev,
351                                                                 endpt_desc);
352                 }
353                 break;
354
355         case USB_SPEED_FULL:
356                 if (usb_endpoint_xfer_isoc(endpt_desc)) {
357                         interval = xhci_parse_exponent_interval(udev,
358                                                                 endpt_desc);
359                         break;
360                 }
361                 /*
362                  * Fall through for interrupt endpoint interval decoding
363                  * since it uses the same rules as low speed interrupt
364                  * endpoints.
365                  */
366
367         case USB_SPEED_LOW:
368                 if (usb_endpoint_xfer_int(endpt_desc) ||
369                     usb_endpoint_xfer_isoc(endpt_desc)) {
370                         interval = xhci_parse_frame_interval(udev, endpt_desc);
371                 }
372                 break;
373
374         default:
375                 BUG();
376         }
377
378         return interval;
379 }
380
381 /*
382  * The "Mult" field in the endpoint context is only set for SuperSpeed isoc eps.
383  * High speed endpoint descriptors can define "the number of additional
384  * transaction opportunities per microframe", but that goes in the Max Burst
385  * endpoint context field.
386  */
387 static u32 xhci_get_endpoint_mult(struct usb_device *udev,
388         struct usb_endpoint_descriptor *endpt_desc,
389         struct usb_ss_ep_comp_descriptor *ss_ep_comp_desc)
390 {
391         if (udev->speed < USB_SPEED_SUPER ||
392             !usb_endpoint_xfer_isoc(endpt_desc))
393                 return 0;
394
395         return ss_ep_comp_desc->bmAttributes;
396 }
397
398 static u32 xhci_get_endpoint_max_burst(struct usb_device *udev,
399         struct usb_endpoint_descriptor *endpt_desc,
400         struct usb_ss_ep_comp_descriptor *ss_ep_comp_desc)
401 {
402         /* Super speed and Plus have max burst in ep companion desc */
403         if (udev->speed >= USB_SPEED_SUPER)
404                 return ss_ep_comp_desc->bMaxBurst;
405
406         if (udev->speed == USB_SPEED_HIGH &&
407             (usb_endpoint_xfer_isoc(endpt_desc) ||
408              usb_endpoint_xfer_int(endpt_desc)))
409                 return usb_endpoint_maxp_mult(endpt_desc) - 1;
410
411         return 0;
412 }
413
414 /*
415  * Return the maximum endpoint service interval time (ESIT) payload.
416  * Basically, this is the maxpacket size, multiplied by the burst size
417  * and mult size.
418  */
419 static u32 xhci_get_max_esit_payload(struct usb_device *udev,
420         struct usb_endpoint_descriptor *endpt_desc,
421         struct usb_ss_ep_comp_descriptor *ss_ep_comp_desc)
422 {
423         int max_burst;
424         int max_packet;
425
426         /* Only applies for interrupt or isochronous endpoints */
427         if (usb_endpoint_xfer_control(endpt_desc) ||
428             usb_endpoint_xfer_bulk(endpt_desc))
429                 return 0;
430
431         /* SuperSpeed Isoc ep with less than 48k per esit */
432         if (udev->speed >= USB_SPEED_SUPER)
433                 return le16_to_cpu(ss_ep_comp_desc->wBytesPerInterval);
434
435         max_packet = usb_endpoint_maxp(endpt_desc);
436         max_burst = usb_endpoint_maxp_mult(endpt_desc);
437
438         /* A 0 in max burst means 1 transfer per ESIT */
439         return max_packet * max_burst;
440 }
441
442 /**
443  * Issue a configure endpoint command or evaluate context command
444  * and wait for it to finish.
445  *
446  * @param udev  pointer to the Device Data Structure
447  * @param ctx_change    flag to indicate the Context has changed or NOT
448  * @return 0 on success, -1 on failure
449  */
450 static int xhci_configure_endpoints(struct usb_device *udev, bool ctx_change)
451 {
452         struct xhci_container_ctx *in_ctx;
453         struct xhci_virt_device *virt_dev;
454         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
455         union xhci_trb *event;
456
457         virt_dev = ctrl->devs[udev->slot_id];
458         in_ctx = virt_dev->in_ctx;
459
460         xhci_flush_cache((uintptr_t)in_ctx->bytes, in_ctx->size);
461         xhci_queue_command(ctrl, in_ctx->bytes, udev->slot_id, 0,
462                            ctx_change ? TRB_EVAL_CONTEXT : TRB_CONFIG_EP);
463         event = xhci_wait_for_event(ctrl, TRB_COMPLETION);
464         BUG_ON(TRB_TO_SLOT_ID(le32_to_cpu(event->event_cmd.flags))
465                 != udev->slot_id);
466
467         switch (GET_COMP_CODE(le32_to_cpu(event->event_cmd.status))) {
468         case COMP_SUCCESS:
469                 debug("Successful %s command\n",
470                         ctx_change ? "Evaluate Context" : "Configure Endpoint");
471                 break;
472         default:
473                 printf("ERROR: %s command returned completion code %d.\n",
474                         ctx_change ? "Evaluate Context" : "Configure Endpoint",
475                         GET_COMP_CODE(le32_to_cpu(event->event_cmd.status)));
476                 return -EINVAL;
477         }
478
479         xhci_acknowledge_event(ctrl);
480
481         return 0;
482 }
483
484 /**
485  * Configure the endpoint, programming the device contexts.
486  *
487  * @param udev  pointer to the USB device structure
488  * @return returns the status of the xhci_configure_endpoints
489  */
490 static int xhci_set_configuration(struct usb_device *udev)
491 {
492         struct xhci_container_ctx *in_ctx;
493         struct xhci_container_ctx *out_ctx;
494         struct xhci_input_control_ctx *ctrl_ctx;
495         struct xhci_slot_ctx *slot_ctx;
496         struct xhci_ep_ctx *ep_ctx[MAX_EP_CTX_NUM];
497         int cur_ep;
498         int max_ep_flag = 0;
499         int ep_index;
500         unsigned int dir;
501         unsigned int ep_type;
502         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
503         int num_of_ep;
504         int ep_flag = 0;
505         u64 trb_64 = 0;
506         int slot_id = udev->slot_id;
507         struct xhci_virt_device *virt_dev = ctrl->devs[slot_id];
508         struct usb_interface *ifdesc;
509         u32 max_esit_payload;
510         unsigned int interval;
511         unsigned int mult;
512         unsigned int max_burst;
513         unsigned int avg_trb_len;
514         unsigned int err_count = 0;
515
516         out_ctx = virt_dev->out_ctx;
517         in_ctx = virt_dev->in_ctx;
518
519         num_of_ep = udev->config.if_desc[0].no_of_ep;
520         ifdesc = &udev->config.if_desc[0];
521
522         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
523         /* Initialize the input context control */
524         ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
525         ctrl_ctx->drop_flags = 0;
526
527         /* EP_FLAG gives values 1 & 4 for EP1OUT and EP2IN */
528         for (cur_ep = 0; cur_ep < num_of_ep; cur_ep++) {
529                 ep_flag = xhci_get_ep_index(&ifdesc->ep_desc[cur_ep]);
530                 ctrl_ctx->add_flags |= cpu_to_le32(1 << (ep_flag + 1));
531                 if (max_ep_flag < ep_flag)
532                         max_ep_flag = ep_flag;
533         }
534
535         xhci_inval_cache((uintptr_t)out_ctx->bytes, out_ctx->size);
536
537         /* slot context */
538         xhci_slot_copy(ctrl, in_ctx, out_ctx);
539         slot_ctx = xhci_get_slot_ctx(ctrl, in_ctx);
540         slot_ctx->dev_info &= ~(cpu_to_le32(LAST_CTX_MASK));
541         slot_ctx->dev_info |= cpu_to_le32(LAST_CTX(max_ep_flag + 1) | 0);
542
543         xhci_endpoint_copy(ctrl, in_ctx, out_ctx, 0);
544
545         /* filling up ep contexts */
546         for (cur_ep = 0; cur_ep < num_of_ep; cur_ep++) {
547                 struct usb_endpoint_descriptor *endpt_desc = NULL;
548                 struct usb_ss_ep_comp_descriptor *ss_ep_comp_desc = NULL;
549
550                 endpt_desc = &ifdesc->ep_desc[cur_ep];
551                 ss_ep_comp_desc = &ifdesc->ss_ep_comp_desc[cur_ep];
552                 trb_64 = 0;
553
554                 /*
555                  * Get values to fill the endpoint context, mostly from ep
556                  * descriptor. The average TRB buffer lengt for bulk endpoints
557                  * is unclear as we have no clue on scatter gather list entry
558                  * size. For Isoc and Int, set it to max available.
559                  * See xHCI 1.1 spec 4.14.1.1 for details.
560                  */
561                 max_esit_payload = xhci_get_max_esit_payload(udev, endpt_desc,
562                                                              ss_ep_comp_desc);
563                 interval = xhci_get_endpoint_interval(udev, endpt_desc);
564                 mult = xhci_get_endpoint_mult(udev, endpt_desc,
565                                               ss_ep_comp_desc);
566                 max_burst = xhci_get_endpoint_max_burst(udev, endpt_desc,
567                                                         ss_ep_comp_desc);
568                 avg_trb_len = max_esit_payload;
569
570                 ep_index = xhci_get_ep_index(endpt_desc);
571                 ep_ctx[ep_index] = xhci_get_ep_ctx(ctrl, in_ctx, ep_index);
572
573                 /* Allocate the ep rings */
574                 virt_dev->eps[ep_index].ring = xhci_ring_alloc(1, true);
575                 if (!virt_dev->eps[ep_index].ring)
576                         return -ENOMEM;
577
578                 /*NOTE: ep_desc[0] actually represents EP1 and so on */
579                 dir = (((endpt_desc->bEndpointAddress) & (0x80)) >> 7);
580                 ep_type = (((endpt_desc->bmAttributes) & (0x3)) | (dir << 2));
581
582                 ep_ctx[ep_index]->ep_info =
583                         cpu_to_le32(EP_MAX_ESIT_PAYLOAD_HI(max_esit_payload) |
584                         EP_INTERVAL(interval) | EP_MULT(mult));
585
586                 ep_ctx[ep_index]->ep_info2 =
587                         cpu_to_le32(ep_type << EP_TYPE_SHIFT);
588                 ep_ctx[ep_index]->ep_info2 |=
589                         cpu_to_le32(MAX_PACKET
590                         (get_unaligned(&endpt_desc->wMaxPacketSize)));
591
592                 /* Allow 3 retries for everything but isoc, set CErr = 3 */
593                 if (!usb_endpoint_xfer_isoc(endpt_desc))
594                         err_count = 3;
595                 ep_ctx[ep_index]->ep_info2 |=
596                         cpu_to_le32(MAX_BURST(max_burst) |
597                         ERROR_COUNT(err_count));
598
599                 trb_64 = (uintptr_t)
600                                 virt_dev->eps[ep_index].ring->enqueue;
601                 ep_ctx[ep_index]->deq = cpu_to_le64(trb_64 |
602                                 virt_dev->eps[ep_index].ring->cycle_state);
603
604                 /*
605                  * xHCI spec 6.2.3:
606                  * 'Average TRB Length' should be 8 for control endpoints.
607                  */
608                 if (usb_endpoint_xfer_control(endpt_desc))
609                         avg_trb_len = 8;
610                 ep_ctx[ep_index]->tx_info =
611                         cpu_to_le32(EP_MAX_ESIT_PAYLOAD_LO(max_esit_payload) |
612                         EP_AVG_TRB_LENGTH(avg_trb_len));
613
614                 /*
615                  * The MediaTek xHCI defines some extra SW parameters which
616                  * are put into reserved DWs in Slot and Endpoint Contexts
617                  * for synchronous endpoints.
618                  */
619                 if (IS_ENABLED(CONFIG_USB_XHCI_MTK)) {
620                         ep_ctx[ep_index]->reserved[0] =
621                                 cpu_to_le32(EP_BPKTS(1) | EP_BBM(1));
622                 }
623         }
624
625         return xhci_configure_endpoints(udev, false);
626 }
627
628 /**
629  * Issue an Address Device command (which will issue a SetAddress request to
630  * the device).
631  *
632  * @param udev pointer to the Device Data Structure
633  * @return 0 if successful else error code on failure
634  */
635 static int xhci_address_device(struct usb_device *udev, int root_portnr)
636 {
637         int ret = 0;
638         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
639         struct xhci_slot_ctx *slot_ctx;
640         struct xhci_input_control_ctx *ctrl_ctx;
641         struct xhci_virt_device *virt_dev;
642         int slot_id = udev->slot_id;
643         union xhci_trb *event;
644
645         virt_dev = ctrl->devs[slot_id];
646
647         /*
648          * This is the first Set Address since device plug-in
649          * so setting up the slot context.
650          */
651         debug("Setting up addressable devices %p\n", ctrl->dcbaa);
652         xhci_setup_addressable_virt_dev(ctrl, udev, root_portnr);
653
654         ctrl_ctx = xhci_get_input_control_ctx(virt_dev->in_ctx);
655         ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG | EP0_FLAG);
656         ctrl_ctx->drop_flags = 0;
657
658         xhci_queue_command(ctrl, (void *)ctrl_ctx, slot_id, 0, TRB_ADDR_DEV);
659         event = xhci_wait_for_event(ctrl, TRB_COMPLETION);
660         BUG_ON(TRB_TO_SLOT_ID(le32_to_cpu(event->event_cmd.flags)) != slot_id);
661
662         switch (GET_COMP_CODE(le32_to_cpu(event->event_cmd.status))) {
663         case COMP_CTX_STATE:
664         case COMP_EBADSLT:
665                 printf("Setup ERROR: address device command for slot %d.\n",
666                                                                 slot_id);
667                 ret = -EINVAL;
668                 break;
669         case COMP_TX_ERR:
670                 puts("Device not responding to set address.\n");
671                 ret = -EPROTO;
672                 break;
673         case COMP_DEV_ERR:
674                 puts("ERROR: Incompatible device"
675                                         "for address device command.\n");
676                 ret = -ENODEV;
677                 break;
678         case COMP_SUCCESS:
679                 debug("Successful Address Device command\n");
680                 udev->status = 0;
681                 break;
682         default:
683                 printf("ERROR: unexpected command completion code 0x%x.\n",
684                         GET_COMP_CODE(le32_to_cpu(event->event_cmd.status)));
685                 ret = -EINVAL;
686                 break;
687         }
688
689         xhci_acknowledge_event(ctrl);
690
691         if (ret < 0)
692                 /*
693                  * TODO: Unsuccessful Address Device command shall leave the
694                  * slot in default state. So, issue Disable Slot command now.
695                  */
696                 return ret;
697
698         xhci_inval_cache((uintptr_t)virt_dev->out_ctx->bytes,
699                          virt_dev->out_ctx->size);
700         slot_ctx = xhci_get_slot_ctx(ctrl, virt_dev->out_ctx);
701
702         debug("xHC internal address is: %d\n",
703                 le32_to_cpu(slot_ctx->dev_state) & DEV_ADDR_MASK);
704
705         return 0;
706 }
707
708 /**
709  * Issue Enable slot command to the controller to allocate
710  * device slot and assign the slot id. It fails if the xHC
711  * ran out of device slots, the Enable Slot command timed out,
712  * or allocating memory failed.
713  *
714  * @param udev  pointer to the Device Data Structure
715  * @return Returns 0 on succes else return error code on failure
716  */
717 static int _xhci_alloc_device(struct usb_device *udev)
718 {
719         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
720         union xhci_trb *event;
721         int ret;
722
723         /*
724          * Root hub will be first device to be initailized.
725          * If this device is root-hub, don't do any xHC related
726          * stuff.
727          */
728         if (ctrl->rootdev == 0) {
729                 udev->speed = USB_SPEED_SUPER;
730                 return 0;
731         }
732
733         xhci_queue_command(ctrl, NULL, 0, 0, TRB_ENABLE_SLOT);
734         event = xhci_wait_for_event(ctrl, TRB_COMPLETION);
735         BUG_ON(GET_COMP_CODE(le32_to_cpu(event->event_cmd.status))
736                 != COMP_SUCCESS);
737
738         udev->slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->event_cmd.flags));
739
740         xhci_acknowledge_event(ctrl);
741
742         ret = xhci_alloc_virt_device(ctrl, udev->slot_id);
743         if (ret < 0) {
744                 /*
745                  * TODO: Unsuccessful Address Device command shall leave
746                  * the slot in default. So, issue Disable Slot command now.
747                  */
748                 puts("Could not allocate xHCI USB device data structures\n");
749                 return ret;
750         }
751
752         return 0;
753 }
754
755 #if !CONFIG_IS_ENABLED(DM_USB)
756 int usb_alloc_device(struct usb_device *udev)
757 {
758         return _xhci_alloc_device(udev);
759 }
760 #endif
761
762 /*
763  * Full speed devices may have a max packet size greater than 8 bytes, but the
764  * USB core doesn't know that until it reads the first 8 bytes of the
765  * descriptor.  If the usb_device's max packet size changes after that point,
766  * we need to issue an evaluate context command and wait on it.
767  *
768  * @param udev  pointer to the Device Data Structure
769  * @return returns the status of the xhci_configure_endpoints
770  */
771 int xhci_check_maxpacket(struct usb_device *udev)
772 {
773         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
774         unsigned int slot_id = udev->slot_id;
775         int ep_index = 0;       /* control endpoint */
776         struct xhci_container_ctx *in_ctx;
777         struct xhci_container_ctx *out_ctx;
778         struct xhci_input_control_ctx *ctrl_ctx;
779         struct xhci_ep_ctx *ep_ctx;
780         int max_packet_size;
781         int hw_max_packet_size;
782         int ret = 0;
783
784         out_ctx = ctrl->devs[slot_id]->out_ctx;
785         xhci_inval_cache((uintptr_t)out_ctx->bytes, out_ctx->size);
786
787         ep_ctx = xhci_get_ep_ctx(ctrl, out_ctx, ep_index);
788         hw_max_packet_size = MAX_PACKET_DECODED(le32_to_cpu(ep_ctx->ep_info2));
789         max_packet_size = udev->epmaxpacketin[0];
790         if (hw_max_packet_size != max_packet_size) {
791                 debug("Max Packet Size for ep 0 changed.\n");
792                 debug("Max packet size in usb_device = %d\n", max_packet_size);
793                 debug("Max packet size in xHCI HW = %d\n", hw_max_packet_size);
794                 debug("Issuing evaluate context command.\n");
795
796                 /* Set up the modified control endpoint 0 */
797                 xhci_endpoint_copy(ctrl, ctrl->devs[slot_id]->in_ctx,
798                                 ctrl->devs[slot_id]->out_ctx, ep_index);
799                 in_ctx = ctrl->devs[slot_id]->in_ctx;
800                 ep_ctx = xhci_get_ep_ctx(ctrl, in_ctx, ep_index);
801                 ep_ctx->ep_info2 &= cpu_to_le32(~((0xffff & MAX_PACKET_MASK)
802                                                 << MAX_PACKET_SHIFT));
803                 ep_ctx->ep_info2 |= cpu_to_le32(MAX_PACKET(max_packet_size));
804
805                 /*
806                  * Set up the input context flags for the command
807                  * FIXME: This won't work if a non-default control endpoint
808                  * changes max packet sizes.
809                  */
810                 ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
811                 ctrl_ctx->add_flags = cpu_to_le32(EP0_FLAG);
812                 ctrl_ctx->drop_flags = 0;
813
814                 ret = xhci_configure_endpoints(udev, true);
815         }
816         return ret;
817 }
818
819 /**
820  * Clears the Change bits of the Port Status Register
821  *
822  * @param wValue        request value
823  * @param wIndex        request index
824  * @param addr          address of posrt status register
825  * @param port_status   state of port status register
826  * @return none
827  */
828 static void xhci_clear_port_change_bit(u16 wValue,
829                 u16 wIndex, volatile uint32_t *addr, u32 port_status)
830 {
831         char *port_change_bit;
832         u32 status;
833
834         switch (wValue) {
835         case USB_PORT_FEAT_C_RESET:
836                 status = PORT_RC;
837                 port_change_bit = "reset";
838                 break;
839         case USB_PORT_FEAT_C_CONNECTION:
840                 status = PORT_CSC;
841                 port_change_bit = "connect";
842                 break;
843         case USB_PORT_FEAT_C_OVER_CURRENT:
844                 status = PORT_OCC;
845                 port_change_bit = "over-current";
846                 break;
847         case USB_PORT_FEAT_C_ENABLE:
848                 status = PORT_PEC;
849                 port_change_bit = "enable/disable";
850                 break;
851         case USB_PORT_FEAT_C_SUSPEND:
852                 status = PORT_PLC;
853                 port_change_bit = "suspend/resume";
854                 break;
855         default:
856                 /* Should never happen */
857                 return;
858         }
859
860         /* Change bits are all write 1 to clear */
861         xhci_writel(addr, port_status | status);
862
863         port_status = xhci_readl(addr);
864         debug("clear port %s change, actual port %d status  = 0x%x\n",
865                         port_change_bit, wIndex, port_status);
866 }
867
868 /**
869  * Save Read Only (RO) bits and save read/write bits where
870  * writing a 0 clears the bit and writing a 1 sets the bit (RWS).
871  * For all other types (RW1S, RW1CS, RW, and RZ), writing a '0' has no effect.
872  *
873  * @param state state of the Port Status and Control Regsiter
874  * @return a value that would result in the port being in the
875  *         same state, if the value was written to the port
876  *         status control register.
877  */
878 static u32 xhci_port_state_to_neutral(u32 state)
879 {
880         /* Save read-only status and port state */
881         return (state & XHCI_PORT_RO) | (state & XHCI_PORT_RWS);
882 }
883
884 /**
885  * Submits the Requests to the XHCI Host Controller
886  *
887  * @param udev pointer to the USB device structure
888  * @param pipe contains the DIR_IN or OUT , devnum
889  * @param buffer buffer to be read/written based on the request
890  * @return returns 0 if successful else -1 on failure
891  */
892 static int xhci_submit_root(struct usb_device *udev, unsigned long pipe,
893                         void *buffer, struct devrequest *req)
894 {
895         uint8_t tmpbuf[4];
896         u16 typeReq;
897         void *srcptr = NULL;
898         int len, srclen;
899         uint32_t reg;
900         volatile uint32_t *status_reg;
901         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
902         struct xhci_hccr *hccr = ctrl->hccr;
903         struct xhci_hcor *hcor = ctrl->hcor;
904         int max_ports = HCS_MAX_PORTS(xhci_readl(&hccr->cr_hcsparams1));
905
906         if ((req->requesttype & USB_RT_PORT) &&
907             le16_to_cpu(req->index) > max_ports) {
908                 printf("The request port(%d) exceeds maximum port number\n",
909                        le16_to_cpu(req->index) - 1);
910                 return -EINVAL;
911         }
912
913         status_reg = (volatile uint32_t *)
914                      (&hcor->portregs[le16_to_cpu(req->index) - 1].or_portsc);
915         srclen = 0;
916
917         typeReq = req->request | req->requesttype << 8;
918
919         switch (typeReq) {
920         case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
921                 switch (le16_to_cpu(req->value) >> 8) {
922                 case USB_DT_DEVICE:
923                         debug("USB_DT_DEVICE request\n");
924                         srcptr = &descriptor.device;
925                         srclen = 0x12;
926                         break;
927                 case USB_DT_CONFIG:
928                         debug("USB_DT_CONFIG config\n");
929                         srcptr = &descriptor.config;
930                         srclen = 0x19;
931                         break;
932                 case USB_DT_STRING:
933                         debug("USB_DT_STRING config\n");
934                         switch (le16_to_cpu(req->value) & 0xff) {
935                         case 0: /* Language */
936                                 srcptr = "\4\3\11\4";
937                                 srclen = 4;
938                                 break;
939                         case 1: /* Vendor String  */
940                                 srcptr = "\16\3U\0-\0B\0o\0o\0t\0";
941                                 srclen = 14;
942                                 break;
943                         case 2: /* Product Name */
944                                 srcptr = "\52\3X\0H\0C\0I\0 "
945                                          "\0H\0o\0s\0t\0 "
946                                          "\0C\0o\0n\0t\0r\0o\0l\0l\0e\0r\0";
947                                 srclen = 42;
948                                 break;
949                         default:
950                                 printf("unknown value DT_STRING %x\n",
951                                         le16_to_cpu(req->value));
952                                 goto unknown;
953                         }
954                         break;
955                 default:
956                         printf("unknown value %x\n", le16_to_cpu(req->value));
957                         goto unknown;
958                 }
959                 break;
960         case USB_REQ_GET_DESCRIPTOR | ((USB_DIR_IN | USB_RT_HUB) << 8):
961                 switch (le16_to_cpu(req->value) >> 8) {
962                 case USB_DT_HUB:
963                 case USB_DT_SS_HUB:
964                         debug("USB_DT_HUB config\n");
965                         srcptr = &descriptor.hub;
966                         srclen = 0x8;
967                         break;
968                 default:
969                         printf("unknown value %x\n", le16_to_cpu(req->value));
970                         goto unknown;
971                 }
972                 break;
973         case USB_REQ_SET_ADDRESS | (USB_RECIP_DEVICE << 8):
974                 debug("USB_REQ_SET_ADDRESS\n");
975                 ctrl->rootdev = le16_to_cpu(req->value);
976                 break;
977         case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
978                 /* Do nothing */
979                 break;
980         case USB_REQ_GET_STATUS | ((USB_DIR_IN | USB_RT_HUB) << 8):
981                 tmpbuf[0] = 1;  /* USB_STATUS_SELFPOWERED */
982                 tmpbuf[1] = 0;
983                 srcptr = tmpbuf;
984                 srclen = 2;
985                 break;
986         case USB_REQ_GET_STATUS | ((USB_RT_PORT | USB_DIR_IN) << 8):
987                 memset(tmpbuf, 0, 4);
988                 reg = xhci_readl(status_reg);
989                 if (reg & PORT_CONNECT) {
990                         tmpbuf[0] |= USB_PORT_STAT_CONNECTION;
991                         switch (reg & DEV_SPEED_MASK) {
992                         case XDEV_FS:
993                                 debug("SPEED = FULLSPEED\n");
994                                 break;
995                         case XDEV_LS:
996                                 debug("SPEED = LOWSPEED\n");
997                                 tmpbuf[1] |= USB_PORT_STAT_LOW_SPEED >> 8;
998                                 break;
999                         case XDEV_HS:
1000                                 debug("SPEED = HIGHSPEED\n");
1001                                 tmpbuf[1] |= USB_PORT_STAT_HIGH_SPEED >> 8;
1002                                 break;
1003                         case XDEV_SS:
1004                                 debug("SPEED = SUPERSPEED\n");
1005                                 tmpbuf[1] |= USB_PORT_STAT_SUPER_SPEED >> 8;
1006                                 break;
1007                         }
1008                 }
1009                 if (reg & PORT_PE)
1010                         tmpbuf[0] |= USB_PORT_STAT_ENABLE;
1011                 if ((reg & PORT_PLS_MASK) == XDEV_U3)
1012                         tmpbuf[0] |= USB_PORT_STAT_SUSPEND;
1013                 if (reg & PORT_OC)
1014                         tmpbuf[0] |= USB_PORT_STAT_OVERCURRENT;
1015                 if (reg & PORT_RESET)
1016                         tmpbuf[0] |= USB_PORT_STAT_RESET;
1017                 if (reg & PORT_POWER)
1018                         /*
1019                          * XXX: This Port power bit (for USB 3.0 hub)
1020                          * we are faking in USB 2.0 hub port status;
1021                          * since there's a change in bit positions in
1022                          * two:
1023                          * USB 2.0 port status PP is at position[8]
1024                          * USB 3.0 port status PP is at position[9]
1025                          * So, we are still keeping it at position [8]
1026                          */
1027                         tmpbuf[1] |= USB_PORT_STAT_POWER >> 8;
1028                 if (reg & PORT_CSC)
1029                         tmpbuf[2] |= USB_PORT_STAT_C_CONNECTION;
1030                 if (reg & PORT_PEC)
1031                         tmpbuf[2] |= USB_PORT_STAT_C_ENABLE;
1032                 if (reg & PORT_OCC)
1033                         tmpbuf[2] |= USB_PORT_STAT_C_OVERCURRENT;
1034                 if (reg & PORT_RC)
1035                         tmpbuf[2] |= USB_PORT_STAT_C_RESET;
1036
1037                 srcptr = tmpbuf;
1038                 srclen = 4;
1039                 break;
1040         case USB_REQ_SET_FEATURE | ((USB_DIR_OUT | USB_RT_PORT) << 8):
1041                 reg = xhci_readl(status_reg);
1042                 reg = xhci_port_state_to_neutral(reg);
1043                 switch (le16_to_cpu(req->value)) {
1044                 case USB_PORT_FEAT_ENABLE:
1045                         reg |= PORT_PE;
1046                         xhci_writel(status_reg, reg);
1047                         break;
1048                 case USB_PORT_FEAT_POWER:
1049                         reg |= PORT_POWER;
1050                         xhci_writel(status_reg, reg);
1051                         break;
1052                 case USB_PORT_FEAT_RESET:
1053                         reg |= PORT_RESET;
1054                         xhci_writel(status_reg, reg);
1055                         break;
1056                 default:
1057                         printf("unknown feature %x\n", le16_to_cpu(req->value));
1058                         goto unknown;
1059                 }
1060                 break;
1061         case USB_REQ_CLEAR_FEATURE | ((USB_DIR_OUT | USB_RT_PORT) << 8):
1062                 reg = xhci_readl(status_reg);
1063                 reg = xhci_port_state_to_neutral(reg);
1064                 switch (le16_to_cpu(req->value)) {
1065                 case USB_PORT_FEAT_ENABLE:
1066                         reg &= ~PORT_PE;
1067                         break;
1068                 case USB_PORT_FEAT_POWER:
1069                         reg &= ~PORT_POWER;
1070                         break;
1071                 case USB_PORT_FEAT_C_RESET:
1072                 case USB_PORT_FEAT_C_CONNECTION:
1073                 case USB_PORT_FEAT_C_OVER_CURRENT:
1074                 case USB_PORT_FEAT_C_ENABLE:
1075                         xhci_clear_port_change_bit((le16_to_cpu(req->value)),
1076                                                         le16_to_cpu(req->index),
1077                                                         status_reg, reg);
1078                         break;
1079                 default:
1080                         printf("unknown feature %x\n", le16_to_cpu(req->value));
1081                         goto unknown;
1082                 }
1083                 xhci_writel(status_reg, reg);
1084                 break;
1085         default:
1086                 puts("Unknown request\n");
1087                 goto unknown;
1088         }
1089
1090         debug("scrlen = %d\n req->length = %d\n",
1091                 srclen, le16_to_cpu(req->length));
1092
1093         len = min(srclen, (int)le16_to_cpu(req->length));
1094
1095         if (srcptr != NULL && len > 0)
1096                 memcpy(buffer, srcptr, len);
1097         else
1098                 debug("Len is 0\n");
1099
1100         udev->act_len = len;
1101         udev->status = 0;
1102
1103         return 0;
1104
1105 unknown:
1106         udev->act_len = 0;
1107         udev->status = USB_ST_STALLED;
1108
1109         return -ENODEV;
1110 }
1111
1112 /**
1113  * Submits the INT request to XHCI Host cotroller
1114  *
1115  * @param udev  pointer to the USB device
1116  * @param pipe          contains the DIR_IN or OUT , devnum
1117  * @param buffer        buffer to be read/written based on the request
1118  * @param length        length of the buffer
1119  * @param interval      interval of the interrupt
1120  * @return 0
1121  */
1122 static int _xhci_submit_int_msg(struct usb_device *udev, unsigned long pipe,
1123                                 void *buffer, int length, int interval,
1124                                 bool nonblock)
1125 {
1126         if (usb_pipetype(pipe) != PIPE_INTERRUPT) {
1127                 printf("non-interrupt pipe (type=%lu)", usb_pipetype(pipe));
1128                 return -EINVAL;
1129         }
1130
1131         /*
1132          * xHCI uses normal TRBs for both bulk and interrupt. When the
1133          * interrupt endpoint is to be serviced, the xHC will consume
1134          * (at most) one TD. A TD (comprised of sg list entries) can
1135          * take several service intervals to transmit.
1136          */
1137         return xhci_bulk_tx(udev, pipe, length, buffer);
1138 }
1139
1140 /**
1141  * submit the BULK type of request to the USB Device
1142  *
1143  * @param udev  pointer to the USB device
1144  * @param pipe          contains the DIR_IN or OUT , devnum
1145  * @param buffer        buffer to be read/written based on the request
1146  * @param length        length of the buffer
1147  * @return returns 0 if successful else -1 on failure
1148  */
1149 static int _xhci_submit_bulk_msg(struct usb_device *udev, unsigned long pipe,
1150                                  void *buffer, int length)
1151 {
1152         if (usb_pipetype(pipe) != PIPE_BULK) {
1153                 printf("non-bulk pipe (type=%lu)", usb_pipetype(pipe));
1154                 return -EINVAL;
1155         }
1156
1157         return xhci_bulk_tx(udev, pipe, length, buffer);
1158 }
1159
1160 /**
1161  * submit the control type of request to the Root hub/Device based on the devnum
1162  *
1163  * @param udev  pointer to the USB device
1164  * @param pipe          contains the DIR_IN or OUT , devnum
1165  * @param buffer        buffer to be read/written based on the request
1166  * @param length        length of the buffer
1167  * @param setup         Request type
1168  * @param root_portnr   Root port number that this device is on
1169  * @return returns 0 if successful else -1 on failure
1170  */
1171 static int _xhci_submit_control_msg(struct usb_device *udev, unsigned long pipe,
1172                                     void *buffer, int length,
1173                                     struct devrequest *setup, int root_portnr)
1174 {
1175         struct xhci_ctrl *ctrl = xhci_get_ctrl(udev);
1176         int ret = 0;
1177
1178         if (usb_pipetype(pipe) != PIPE_CONTROL) {
1179                 printf("non-control pipe (type=%lu)", usb_pipetype(pipe));
1180                 return -EINVAL;
1181         }
1182
1183         if (usb_pipedevice(pipe) == ctrl->rootdev)
1184                 return xhci_submit_root(udev, pipe, buffer, setup);
1185
1186         if (setup->request == USB_REQ_SET_ADDRESS &&
1187            (setup->requesttype & USB_TYPE_MASK) == USB_TYPE_STANDARD)
1188                 return xhci_address_device(udev, root_portnr);
1189
1190         if (setup->request == USB_REQ_SET_CONFIGURATION &&
1191            (setup->requesttype & USB_TYPE_MASK) == USB_TYPE_STANDARD) {
1192                 ret = xhci_set_configuration(udev);
1193                 if (ret) {
1194                         puts("Failed to configure xHCI endpoint\n");
1195                         return ret;
1196                 }
1197         }
1198
1199         return xhci_ctrl_tx(udev, pipe, setup, length, buffer);
1200 }
1201
1202 static int xhci_lowlevel_init(struct xhci_ctrl *ctrl)
1203 {
1204         struct xhci_hccr *hccr;
1205         struct xhci_hcor *hcor;
1206         uint32_t val;
1207         uint32_t val2;
1208         uint32_t reg;
1209
1210         hccr = ctrl->hccr;
1211         hcor = ctrl->hcor;
1212         /*
1213          * Program the Number of Device Slots Enabled field in the CONFIG
1214          * register with the max value of slots the HC can handle.
1215          */
1216         val = (xhci_readl(&hccr->cr_hcsparams1) & HCS_SLOTS_MASK);
1217         val2 = xhci_readl(&hcor->or_config);
1218         val |= (val2 & ~HCS_SLOTS_MASK);
1219         xhci_writel(&hcor->or_config, val);
1220
1221         /* initializing xhci data structures */
1222         if (xhci_mem_init(ctrl, hccr, hcor) < 0)
1223                 return -ENOMEM;
1224
1225         reg = xhci_readl(&hccr->cr_hcsparams1);
1226         descriptor.hub.bNbrPorts = ((reg & HCS_MAX_PORTS_MASK) >>
1227                                                 HCS_MAX_PORTS_SHIFT);
1228         printf("Register %x NbrPorts %d\n", reg, descriptor.hub.bNbrPorts);
1229
1230         /* Port Indicators */
1231         reg = xhci_readl(&hccr->cr_hccparams);
1232         if (HCS_INDICATOR(reg))
1233                 put_unaligned(get_unaligned(&descriptor.hub.wHubCharacteristics)
1234                                 | 0x80, &descriptor.hub.wHubCharacteristics);
1235
1236         /* Port Power Control */
1237         if (HCC_PPC(reg))
1238                 put_unaligned(get_unaligned(&descriptor.hub.wHubCharacteristics)
1239                                 | 0x01, &descriptor.hub.wHubCharacteristics);
1240
1241         if (xhci_start(hcor)) {
1242                 xhci_reset(hcor);
1243                 return -ENODEV;
1244         }
1245
1246         /* Zero'ing IRQ control register and IRQ pending register */
1247         xhci_writel(&ctrl->ir_set->irq_control, 0x0);
1248         xhci_writel(&ctrl->ir_set->irq_pending, 0x0);
1249
1250         reg = HC_VERSION(xhci_readl(&hccr->cr_capbase));
1251         printf("USB XHCI %x.%02x\n", reg >> 8, reg & 0xff);
1252
1253         return 0;
1254 }
1255
1256 static int xhci_lowlevel_stop(struct xhci_ctrl *ctrl)
1257 {
1258         u32 temp;
1259
1260         xhci_reset(ctrl->hcor);
1261
1262         debug("// Disabling event ring interrupts\n");
1263         temp = xhci_readl(&ctrl->hcor->or_usbsts);
1264         xhci_writel(&ctrl->hcor->or_usbsts, temp & ~STS_EINT);
1265         temp = xhci_readl(&ctrl->ir_set->irq_pending);
1266         xhci_writel(&ctrl->ir_set->irq_pending, ER_IRQ_DISABLE(temp));
1267
1268         return 0;
1269 }
1270
1271 #if !CONFIG_IS_ENABLED(DM_USB)
1272 int submit_control_msg(struct usb_device *udev, unsigned long pipe,
1273                        void *buffer, int length, struct devrequest *setup)
1274 {
1275         struct usb_device *hop = udev;
1276
1277         if (hop->parent)
1278                 while (hop->parent->parent)
1279                         hop = hop->parent;
1280
1281         return _xhci_submit_control_msg(udev, pipe, buffer, length, setup,
1282                                         hop->portnr);
1283 }
1284
1285 int submit_bulk_msg(struct usb_device *udev, unsigned long pipe, void *buffer,
1286                     int length)
1287 {
1288         return _xhci_submit_bulk_msg(udev, pipe, buffer, length);
1289 }
1290
1291 int submit_int_msg(struct usb_device *udev, unsigned long pipe, void *buffer,
1292                    int length, int interval, bool nonblock)
1293 {
1294         return _xhci_submit_int_msg(udev, pipe, buffer, length, interval,
1295                                     nonblock);
1296 }
1297
1298 /**
1299  * Intialises the XHCI host controller
1300  * and allocates the necessary data structures
1301  *
1302  * @param index index to the host controller data structure
1303  * @return pointer to the intialised controller
1304  */
1305 int usb_lowlevel_init(int index, enum usb_init_type init, void **controller)
1306 {
1307         struct xhci_hccr *hccr;
1308         struct xhci_hcor *hcor;
1309         struct xhci_ctrl *ctrl;
1310         int ret;
1311
1312         *controller = NULL;
1313
1314         if (xhci_hcd_init(index, &hccr, (struct xhci_hcor **)&hcor) != 0)
1315                 return -ENODEV;
1316
1317         if (xhci_reset(hcor) != 0)
1318                 return -ENODEV;
1319
1320         ctrl = &xhcic[index];
1321
1322         ctrl->hccr = hccr;
1323         ctrl->hcor = hcor;
1324
1325         ret = xhci_lowlevel_init(ctrl);
1326
1327         if (ret) {
1328                 ctrl->hccr = NULL;
1329                 ctrl->hcor = NULL;
1330         } else {
1331                 *controller = &xhcic[index];
1332         }
1333
1334         return ret;
1335 }
1336
1337 /**
1338  * Stops the XHCI host controller
1339  * and cleans up all the related data structures
1340  *
1341  * @param index index to the host controller data structure
1342  * @return none
1343  */
1344 int usb_lowlevel_stop(int index)
1345 {
1346         struct xhci_ctrl *ctrl = (xhcic + index);
1347
1348         if (ctrl->hcor) {
1349                 xhci_lowlevel_stop(ctrl);
1350                 xhci_hcd_stop(index);
1351                 xhci_cleanup(ctrl);
1352         }
1353
1354         return 0;
1355 }
1356 #endif /* CONFIG_IS_ENABLED(DM_USB) */
1357
1358 #if CONFIG_IS_ENABLED(DM_USB)
1359
1360 static int xhci_submit_control_msg(struct udevice *dev, struct usb_device *udev,
1361                                    unsigned long pipe, void *buffer, int length,
1362                                    struct devrequest *setup)
1363 {
1364         struct usb_device *uhop;
1365         struct udevice *hub;
1366         int root_portnr = 0;
1367
1368         debug("%s: dev='%s', udev=%p, udev->dev='%s', portnr=%d\n", __func__,
1369               dev->name, udev, udev->dev->name, udev->portnr);
1370         hub = udev->dev;
1371         if (device_get_uclass_id(hub) == UCLASS_USB_HUB) {
1372                 /* Figure out our port number on the root hub */
1373                 if (usb_hub_is_root_hub(hub)) {
1374                         root_portnr = udev->portnr;
1375                 } else {
1376                         while (!usb_hub_is_root_hub(hub->parent))
1377                                 hub = hub->parent;
1378                         uhop = dev_get_parent_priv(hub);
1379                         root_portnr = uhop->portnr;
1380                 }
1381         }
1382 /*
1383         struct usb_device *hop = udev;
1384
1385         if (hop->parent)
1386                 while (hop->parent->parent)
1387                         hop = hop->parent;
1388 */
1389         return _xhci_submit_control_msg(udev, pipe, buffer, length, setup,
1390                                         root_portnr);
1391 }
1392
1393 static int xhci_submit_bulk_msg(struct udevice *dev, struct usb_device *udev,
1394                                 unsigned long pipe, void *buffer, int length)
1395 {
1396         debug("%s: dev='%s', udev=%p\n", __func__, dev->name, udev);
1397         return _xhci_submit_bulk_msg(udev, pipe, buffer, length);
1398 }
1399
1400 static int xhci_submit_int_msg(struct udevice *dev, struct usb_device *udev,
1401                                unsigned long pipe, void *buffer, int length,
1402                                int interval, bool nonblock)
1403 {
1404         debug("%s: dev='%s', udev=%p\n", __func__, dev->name, udev);
1405         return _xhci_submit_int_msg(udev, pipe, buffer, length, interval,
1406                                     nonblock);
1407 }
1408
1409 static int xhci_alloc_device(struct udevice *dev, struct usb_device *udev)
1410 {
1411         debug("%s: dev='%s', udev=%p\n", __func__, dev->name, udev);
1412         return _xhci_alloc_device(udev);
1413 }
1414
1415 static int xhci_update_hub_device(struct udevice *dev, struct usb_device *udev)
1416 {
1417         struct xhci_ctrl *ctrl = dev_get_priv(dev);
1418         struct usb_hub_device *hub = dev_get_uclass_priv(udev->dev);
1419         struct xhci_virt_device *virt_dev;
1420         struct xhci_input_control_ctx *ctrl_ctx;
1421         struct xhci_container_ctx *out_ctx;
1422         struct xhci_container_ctx *in_ctx;
1423         struct xhci_slot_ctx *slot_ctx;
1424         int slot_id = udev->slot_id;
1425         unsigned think_time;
1426
1427         debug("%s: dev='%s', udev=%p\n", __func__, dev->name, udev);
1428
1429         /* Ignore root hubs */
1430         if (usb_hub_is_root_hub(udev->dev))
1431                 return 0;
1432
1433         virt_dev = ctrl->devs[slot_id];
1434         BUG_ON(!virt_dev);
1435
1436         out_ctx = virt_dev->out_ctx;
1437         in_ctx = virt_dev->in_ctx;
1438
1439         ctrl_ctx = xhci_get_input_control_ctx(in_ctx);
1440         /* Initialize the input context control */
1441         ctrl_ctx->add_flags = cpu_to_le32(SLOT_FLAG);
1442         ctrl_ctx->drop_flags = 0;
1443
1444         xhci_inval_cache((uintptr_t)out_ctx->bytes, out_ctx->size);
1445
1446         /* slot context */
1447         xhci_slot_copy(ctrl, in_ctx, out_ctx);
1448         slot_ctx = xhci_get_slot_ctx(ctrl, in_ctx);
1449
1450         /* Update hub related fields */
1451         slot_ctx->dev_info |= cpu_to_le32(DEV_HUB);
1452         /*
1453          * refer to section 6.2.2: MTT should be 0 for full speed hub,
1454          * but it may be already set to 1 when setup an xHCI virtual
1455          * device, so clear it anyway.
1456          */
1457         if (hub->tt.multi)
1458                 slot_ctx->dev_info |= cpu_to_le32(DEV_MTT);
1459         else if (udev->speed == USB_SPEED_FULL)
1460                 slot_ctx->dev_info &= cpu_to_le32(~DEV_MTT);
1461         slot_ctx->dev_info2 |= cpu_to_le32(XHCI_MAX_PORTS(udev->maxchild));
1462         /*
1463          * Set TT think time - convert from ns to FS bit times.
1464          * Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns
1465          *
1466          * 0 =  8 FS bit times, 1 = 16 FS bit times,
1467          * 2 = 24 FS bit times, 3 = 32 FS bit times.
1468          *
1469          * This field shall be 0 if the device is not a high-spped hub.
1470          */
1471         think_time = hub->tt.think_time;
1472         if (think_time != 0)
1473                 think_time = (think_time / 666) - 1;
1474         if (udev->speed == USB_SPEED_HIGH)
1475                 slot_ctx->tt_info |= cpu_to_le32(TT_THINK_TIME(think_time));
1476         slot_ctx->dev_state = 0;
1477
1478         return xhci_configure_endpoints(udev, false);
1479 }
1480
1481 static int xhci_get_max_xfer_size(struct udevice *dev, size_t *size)
1482 {
1483         /*
1484          * xHCD allocates one segment which includes 64 TRBs for each endpoint
1485          * and the last TRB in this segment is configured as a link TRB to form
1486          * a TRB ring. Each TRB can transfer up to 64K bytes, however data
1487          * buffers referenced by transfer TRBs shall not span 64KB boundaries.
1488          * Hence the maximum number of TRBs we can use in one transfer is 62.
1489          */
1490         *size = (TRBS_PER_SEGMENT - 2) * TRB_MAX_BUFF_SIZE;
1491
1492         return 0;
1493 }
1494
1495 int xhci_register(struct udevice *dev, struct xhci_hccr *hccr,
1496                   struct xhci_hcor *hcor)
1497 {
1498         struct xhci_ctrl *ctrl = dev_get_priv(dev);
1499         struct usb_bus_priv *priv = dev_get_uclass_priv(dev);
1500         int ret;
1501
1502         debug("%s: dev='%s', ctrl=%p, hccr=%p, hcor=%p\n", __func__, dev->name,
1503               ctrl, hccr, hcor);
1504
1505         ctrl->dev = dev;
1506
1507         /*
1508          * XHCI needs to issue a Address device command to setup
1509          * proper device context structures, before it can interact
1510          * with the device. So a get_descriptor will fail before any
1511          * of that is done for XHCI unlike EHCI.
1512          */
1513         priv->desc_before_addr = false;
1514
1515         ret = xhci_reset(hcor);
1516         if (ret)
1517                 goto err;
1518
1519         ctrl->hccr = hccr;
1520         ctrl->hcor = hcor;
1521         ret = xhci_lowlevel_init(ctrl);
1522         if (ret)
1523                 goto err;
1524
1525         return 0;
1526 err:
1527         free(ctrl);
1528         debug("%s: failed, ret=%d\n", __func__, ret);
1529         return ret;
1530 }
1531
1532 int xhci_deregister(struct udevice *dev)
1533 {
1534         struct xhci_ctrl *ctrl = dev_get_priv(dev);
1535
1536         xhci_lowlevel_stop(ctrl);
1537         xhci_cleanup(ctrl);
1538
1539         return 0;
1540 }
1541
1542 struct dm_usb_ops xhci_usb_ops = {
1543         .control = xhci_submit_control_msg,
1544         .bulk = xhci_submit_bulk_msg,
1545         .interrupt = xhci_submit_int_msg,
1546         .alloc_device = xhci_alloc_device,
1547         .update_hub_device = xhci_update_hub_device,
1548         .get_max_xfer_size  = xhci_get_max_xfer_size,
1549 };
1550
1551 #endif