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