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