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