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