1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Most of this source has been derived from the Linux USB
4  * project:
5  * (C) Copyright Linus Torvalds 1999
6  * (C) Copyright Johannes Erdfelt 1999-2001
7  * (C) Copyright Andreas Gal 1999
8  * (C) Copyright Gregory P. Smith 1999
9  * (C) Copyright Deti Fliegl 1999 (new USB architecture)
10  * (C) Copyright Randy Dunlap 2000
11  * (C) Copyright David Brownell 2000 (kernel hotplug, usb_device_id)
12  * (C) Copyright Yggdrasil Computing, Inc. 2000
13  *     (usb_device_id matching changes by Adam J. Richter)
14  *
15  * Adapted for U-Boot:
16  * (C) Copyright 2001 Denis Peter, MPL AG Switzerland
17  */
18 
19 /****************************************************************************
20  * HUB "Driver"
21  * Probes device for being a hub and configurate it
22  */
23 
24 #include <command.h>
25 #include <dm.h>
26 #include <env.h>
27 #include <errno.h>
28 #include <log.h>
29 #include <malloc.h>
30 #include <memalign.h>
31 #include <time.h>
32 #include <asm/processor.h>
33 #include <asm/unaligned.h>
34 #include <linux/ctype.h>
35 #include <linux/delay.h>
36 #include <linux/list.h>
37 #include <asm/byteorder.h>
38 #ifdef CONFIG_SANDBOX
39 #include <asm/state.h>
40 #endif
41 #include <asm/unaligned.h>
42 
43 #include <usb.h>
44 
45 #define USB_BUFSIZ	512
46 
47 #define HUB_SHORT_RESET_TIME	20
48 #define HUB_LONG_RESET_TIME	200
49 
50 #define HUB_DEBOUNCE_TIMEOUT	CONFIG_USB_HUB_DEBOUNCE_TIMEOUT
51 
52 #define PORT_OVERCURRENT_MAX_SCAN_COUNT		3
53 
54 struct usb_device_scan {
55 	struct usb_device *dev;		/* USB hub device to scan */
56 	struct usb_hub_device *hub;	/* USB hub struct */
57 	int port;			/* USB port to scan */
58 	struct list_head list;
59 };
60 
61 static LIST_HEAD(usb_scan_list);
62 
usb_hub_reset_devices(struct usb_hub_device * hub,int port)63 __weak void usb_hub_reset_devices(struct usb_hub_device *hub, int port)
64 {
65 	return;
66 }
67 
usb_hub_is_superspeed(struct usb_device * hdev)68 static inline bool usb_hub_is_superspeed(struct usb_device *hdev)
69 {
70 	return hdev->descriptor.bDeviceProtocol == 3;
71 }
72 
73 #if CONFIG_IS_ENABLED(DM_USB)
usb_hub_is_root_hub(struct udevice * hub)74 bool usb_hub_is_root_hub(struct udevice *hub)
75 {
76 	if (device_get_uclass_id(hub->parent) != UCLASS_USB_HUB)
77 		return true;
78 
79 	return false;
80 }
81 
usb_set_hub_depth(struct usb_device * dev,int depth)82 static int usb_set_hub_depth(struct usb_device *dev, int depth)
83 {
84 	if (depth < 0 || depth > 4)
85 		return -EINVAL;
86 
87 	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
88 		USB_REQ_SET_HUB_DEPTH, USB_DIR_OUT | USB_RT_HUB,
89 		depth, 0, NULL, 0, USB_CNTL_TIMEOUT);
90 }
91 #endif
92 
usb_get_hub_descriptor(struct usb_device * dev,void * data,int size)93 static int usb_get_hub_descriptor(struct usb_device *dev, void *data, int size)
94 {
95 	unsigned short dtype = USB_DT_HUB;
96 
97 	if (usb_hub_is_superspeed(dev))
98 		dtype = USB_DT_SS_HUB;
99 
100 	return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
101 		USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
102 		dtype << 8, 0, data, size, USB_CNTL_TIMEOUT);
103 }
104 
usb_clear_port_feature(struct usb_device * dev,int port,int feature)105 static int usb_clear_port_feature(struct usb_device *dev, int port, int feature)
106 {
107 	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
108 				USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature,
109 				port, NULL, 0, USB_CNTL_TIMEOUT);
110 }
111 
usb_set_port_feature(struct usb_device * dev,int port,int feature)112 static int usb_set_port_feature(struct usb_device *dev, int port, int feature)
113 {
114 	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
115 				USB_REQ_SET_FEATURE, USB_RT_PORT, feature,
116 				port, NULL, 0, USB_CNTL_TIMEOUT);
117 }
118 
usb_get_hub_status(struct usb_device * dev,void * data)119 static int usb_get_hub_status(struct usb_device *dev, void *data)
120 {
121 	return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
122 			USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
123 			data, sizeof(struct usb_hub_status), USB_CNTL_TIMEOUT);
124 }
125 
usb_get_port_status(struct usb_device * dev,int port,void * data)126 int usb_get_port_status(struct usb_device *dev, int port, void *data)
127 {
128 	int ret;
129 
130 	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
131 			USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port,
132 			data, sizeof(struct usb_port_status), USB_CNTL_TIMEOUT);
133 
134 #if CONFIG_IS_ENABLED(DM_USB)
135 	if (ret < 0)
136 		return ret;
137 
138 	/*
139 	 * Translate the USB 3.0 hub port status field into the old version
140 	 * that U-Boot understands. Do this only when the hub is not root hub.
141 	 * For root hub, the port status field has already been translated
142 	 * in the host controller driver (see xhci_submit_root() in xhci.c).
143 	 *
144 	 * Note: this only supports driver model.
145 	 */
146 
147 	if (!usb_hub_is_root_hub(dev->dev) && usb_hub_is_superspeed(dev)) {
148 		struct usb_port_status *status = (struct usb_port_status *)data;
149 		u16 tmp = le16_to_cpu(status->wPortStatus) &
150 			USB_SS_PORT_STAT_MASK;
151 
152 		if (status->wPortStatus & USB_SS_PORT_STAT_POWER)
153 			tmp |= USB_PORT_STAT_POWER;
154 		if ((status->wPortStatus & USB_SS_PORT_STAT_SPEED) ==
155 		    USB_SS_PORT_STAT_SPEED_5GBPS)
156 			tmp |= USB_PORT_STAT_SUPER_SPEED;
157 
158 		status->wPortStatus = cpu_to_le16(tmp);
159 	}
160 #endif
161 
162 	return ret;
163 }
164 
usb_hub_power_on(struct usb_hub_device * hub)165 static void usb_hub_power_on(struct usb_hub_device *hub)
166 {
167 	int i;
168 	struct usb_device *dev;
169 	unsigned pgood_delay = hub->desc.bPwrOn2PwrGood * 2;
170 	const char __maybe_unused *env;
171 
172 	dev = hub->pusb_dev;
173 
174 	debug("enabling power on all ports\n");
175 	for (i = 0; i < dev->maxchild; i++) {
176 		if (usb_hub_is_superspeed(dev)) {
177 			usb_set_port_feature(dev, i + 1, USB_PORT_FEAT_RESET);
178 			debug("Reset : port %d returns %lX\n", i + 1, dev->status);
179 		}
180 		usb_set_port_feature(dev, i + 1, USB_PORT_FEAT_POWER);
181 		debug("PowerOn : port %d returns %lX\n", i + 1, dev->status);
182 	}
183 
184 #ifdef CONFIG_SANDBOX
185 	/*
186 	 * Don't set timeout / delay values here. This results
187 	 * in these values still being reset to 0.
188 	 */
189 	if (state_get_skip_delays())
190 		return;
191 #endif
192 
193 	/*
194 	 * Wait for power to become stable,
195 	 * plus spec-defined max time for device to connect
196 	 * but allow this time to be increased via env variable as some
197 	 * devices break the spec and require longer warm-up times
198 	 */
199 #if CONFIG_IS_ENABLED(ENV_SUPPORT)
200 	env = env_get("usb_pgood_delay");
201 	if (env)
202 		pgood_delay = max(pgood_delay,
203 			          (unsigned)simple_strtol(env, NULL, 0));
204 #endif
205 	debug("pgood_delay=%dms\n", pgood_delay);
206 
207 	/*
208 	 * Do a minimum delay of the larger value of 100ms or pgood_delay
209 	 * so that the power can stablize before the devices are queried
210 	 */
211 	hub->query_delay = get_timer(0) + max(100, (int)pgood_delay);
212 
213 	/*
214 	 * Record the power-on timeout here. The max. delay (timeout)
215 	 * will be done based on this value in the USB port loop in
216 	 * usb_hub_configure() later.
217 	 */
218 	hub->connect_timeout = hub->query_delay + HUB_DEBOUNCE_TIMEOUT;
219 	debug("devnum=%d poweron: query_delay=%d connect_timeout=%d\n",
220 	      dev->devnum, max(100, (int)pgood_delay),
221 	      max(100, (int)pgood_delay) + HUB_DEBOUNCE_TIMEOUT);
222 }
223 
224 #if !CONFIG_IS_ENABLED(DM_USB)
225 static struct usb_hub_device hub_dev[USB_MAX_HUB];
226 static int usb_hub_index;
227 
usb_hub_reset(void)228 void usb_hub_reset(void)
229 {
230 	usb_hub_index = 0;
231 
232 	/* Zero out global hub_dev in case its re-used again */
233 	memset(hub_dev, 0, sizeof(hub_dev));
234 }
235 
usb_hub_allocate(void)236 static struct usb_hub_device *usb_hub_allocate(void)
237 {
238 	if (usb_hub_index < USB_MAX_HUB)
239 		return &hub_dev[usb_hub_index++];
240 
241 	printf("ERROR: USB_MAX_HUB (%d) reached\n", USB_MAX_HUB);
242 	return NULL;
243 }
244 #endif
245 
246 #define MAX_TRIES 5
247 
portspeed(int portstatus)248 static inline const char *portspeed(int portstatus)
249 {
250 	switch (portstatus & USB_PORT_STAT_SPEED_MASK) {
251 	case USB_PORT_STAT_SUPER_SPEED:
252 		return "5 Gb/s";
253 	case USB_PORT_STAT_HIGH_SPEED:
254 		return "480 Mb/s";
255 	case USB_PORT_STAT_LOW_SPEED:
256 		return "1.5 Mb/s";
257 	default:
258 		return "12 Mb/s";
259 	}
260 }
261 
262 /**
263  * usb_hub_port_reset() - reset a port given its usb_device pointer
264  *
265  * Reset a hub port and see if a device is present on that port, providing
266  * sufficient time for it to show itself. The port status is returned.
267  *
268  * @dev:	USB device to reset
269  * @port:	Port number to reset (note ports are numbered from 0 here)
270  * @portstat:	Returns port status
271  */
usb_hub_port_reset(struct usb_device * dev,int port,unsigned short * portstat)272 static int usb_hub_port_reset(struct usb_device *dev, int port,
273 			      unsigned short *portstat)
274 {
275 	int err, tries;
276 	ALLOC_CACHE_ALIGN_BUFFER(struct usb_port_status, portsts, 1);
277 	unsigned short portstatus, portchange;
278 	int delay = HUB_SHORT_RESET_TIME; /* start with short reset delay */
279 
280 #if CONFIG_IS_ENABLED(DM_USB)
281 	debug("%s: resetting '%s' port %d...\n", __func__, dev->dev->name,
282 	      port + 1);
283 #else
284 	debug("%s: resetting port %d...\n", __func__, port + 1);
285 #endif
286 	for (tries = 0; tries < MAX_TRIES; tries++) {
287 		err = usb_set_port_feature(dev, port + 1, USB_PORT_FEAT_RESET);
288 		if (err < 0)
289 			return err;
290 
291 		mdelay(delay);
292 
293 		if (usb_get_port_status(dev, port + 1, portsts) < 0) {
294 			debug("get_port_status failed status %lX\n",
295 			      dev->status);
296 			return -1;
297 		}
298 		portstatus = le16_to_cpu(portsts->wPortStatus);
299 		portchange = le16_to_cpu(portsts->wPortChange);
300 
301 		debug("portstatus %x, change %x, %s\n", portstatus, portchange,
302 							portspeed(portstatus));
303 
304 		debug("STAT_C_CONNECTION = %d STAT_CONNECTION = %d" \
305 		      "  USB_PORT_STAT_ENABLE %d\n",
306 		      (portchange & USB_PORT_STAT_C_CONNECTION) ? 1 : 0,
307 		      (portstatus & USB_PORT_STAT_CONNECTION) ? 1 : 0,
308 		      (portstatus & USB_PORT_STAT_ENABLE) ? 1 : 0);
309 
310 		/*
311 		 * Perhaps we should check for the following here:
312 		 * - C_CONNECTION hasn't been set.
313 		 * - CONNECTION is still set.
314 		 *
315 		 * Doing so would ensure that the device is still connected
316 		 * to the bus, and hasn't been unplugged or replaced while the
317 		 * USB bus reset was going on.
318 		 *
319 		 * However, if we do that, then (at least) a San Disk Ultra
320 		 * USB 3.0 16GB device fails to reset on (at least) an NVIDIA
321 		 * Tegra Jetson TK1 board. For some reason, the device appears
322 		 * to briefly drop off the bus when this second bus reset is
323 		 * executed, yet if we retry this loop, it'll eventually come
324 		 * back after another reset or two.
325 		 */
326 
327 		if (portstatus & USB_PORT_STAT_ENABLE)
328 			break;
329 
330 		/* Switch to long reset delay for the next round */
331 		delay = HUB_LONG_RESET_TIME;
332 	}
333 
334 	if (tries == MAX_TRIES) {
335 		debug("Cannot enable port %i after %i retries, " \
336 		      "disabling port.\n", port + 1, MAX_TRIES);
337 		debug("Maybe the USB cable is bad?\n");
338 		return -1;
339 	}
340 
341 	usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_RESET);
342 	*portstat = portstatus;
343 	return 0;
344 }
345 
usb_hub_port_connect_change(struct usb_device * dev,int port)346 int usb_hub_port_connect_change(struct usb_device *dev, int port)
347 {
348 	ALLOC_CACHE_ALIGN_BUFFER(struct usb_port_status, portsts, 1);
349 	unsigned short portstatus;
350 	int ret, speed;
351 
352 	/* Check status */
353 	ret = usb_get_port_status(dev, port + 1, portsts);
354 	if (ret < 0) {
355 		debug("get_port_status failed\n");
356 		return ret;
357 	}
358 
359 	portstatus = le16_to_cpu(portsts->wPortStatus);
360 	debug("portstatus %x, change %x, %s\n",
361 	      portstatus,
362 	      le16_to_cpu(portsts->wPortChange),
363 	      portspeed(portstatus));
364 
365 	/* Clear the connection change status */
366 	usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_C_CONNECTION);
367 
368 	/* Disconnect any existing devices under this port */
369 	if (((!(portstatus & USB_PORT_STAT_CONNECTION)) &&
370 	     (!(portstatus & USB_PORT_STAT_ENABLE))) ||
371 	    usb_device_has_child_on_port(dev, port)) {
372 		debug("usb_disconnect(&hub->children[port]);\n");
373 		/* Return now if nothing is connected */
374 		if (!(portstatus & USB_PORT_STAT_CONNECTION))
375 			return -ENOTCONN;
376 	}
377 
378 	/* Reset the port */
379 	ret = usb_hub_port_reset(dev, port, &portstatus);
380 	if (ret < 0) {
381 		if (ret != -ENXIO)
382 			printf("cannot reset port %i!?\n", port + 1);
383 		return ret;
384 	}
385 
386 	switch (portstatus & USB_PORT_STAT_SPEED_MASK) {
387 	case USB_PORT_STAT_SUPER_SPEED:
388 		speed = USB_SPEED_SUPER;
389 		break;
390 	case USB_PORT_STAT_HIGH_SPEED:
391 		speed = USB_SPEED_HIGH;
392 		break;
393 	case USB_PORT_STAT_LOW_SPEED:
394 		speed = USB_SPEED_LOW;
395 		break;
396 	default:
397 		speed = USB_SPEED_FULL;
398 		break;
399 	}
400 
401 	/*
402 	 * USB 2.0 7.1.7.5: devices must be able to accept a SetAddress()
403 	 * request (refer to Section 11.24.2 and Section 9.4 respectively)
404 	 * after the reset recovery time 10 ms
405 	 */
406 	mdelay(10);
407 
408 #if CONFIG_IS_ENABLED(DM_USB)
409 	struct udevice *child;
410 
411 	ret = usb_scan_device(dev->dev, port + 1, speed, &child);
412 #else
413 	struct usb_device *usb;
414 
415 	ret = usb_alloc_new_device(dev->controller, &usb);
416 	if (ret) {
417 		printf("cannot create new device: ret=%d", ret);
418 		return ret;
419 	}
420 
421 	dev->children[port] = usb;
422 	usb->speed = speed;
423 	usb->parent = dev;
424 	usb->portnr = port + 1;
425 	/* Run it through the hoops (find a driver, etc) */
426 	ret = usb_new_device(usb);
427 	if (ret < 0) {
428 		/* Woops, disable the port */
429 		usb_free_device(dev->controller);
430 		dev->children[port] = NULL;
431 	}
432 #endif
433 	if (ret < 0) {
434 		debug("hub: disabling port %d\n", port + 1);
435 		usb_clear_port_feature(dev, port + 1, USB_PORT_FEAT_ENABLE);
436 	}
437 
438 	return ret;
439 }
440 
usb_scan_port(struct usb_device_scan * usb_scan)441 static int usb_scan_port(struct usb_device_scan *usb_scan)
442 {
443 	ALLOC_CACHE_ALIGN_BUFFER(struct usb_port_status, portsts, 1);
444 	unsigned short portstatus;
445 	unsigned short portchange;
446 	struct usb_device *dev;
447 	struct usb_hub_device *hub;
448 	int ret = 0;
449 	int i;
450 
451 	dev = usb_scan->dev;
452 	hub = usb_scan->hub;
453 	i = usb_scan->port;
454 
455 	/*
456 	 * Don't talk to the device before the query delay is expired.
457 	 * This is needed for voltages to stabalize.
458 	 */
459 	if (get_timer(0) < hub->query_delay)
460 		return 0;
461 
462 	ret = usb_get_port_status(dev, i + 1, portsts);
463 	if (ret < 0) {
464 		debug("get_port_status failed\n");
465 		if (get_timer(0) >= hub->connect_timeout) {
466 			debug("devnum=%d port=%d: timeout\n",
467 			      dev->devnum, i + 1);
468 			/* Remove this device from scanning list */
469 			list_del(&usb_scan->list);
470 			free(usb_scan);
471 			return 0;
472 		}
473 		return 0;
474 	}
475 
476 	portstatus = le16_to_cpu(portsts->wPortStatus);
477 	portchange = le16_to_cpu(portsts->wPortChange);
478 	debug("Port %d Status %X Change %X\n", i + 1, portstatus, portchange);
479 
480 	/*
481 	 * No connection change happened, wait a bit more.
482 	 *
483 	 * For some situation, the hub reports no connection change but a
484 	 * device is connected to the port (eg: CCS bit is set but CSC is not
485 	 * in the PORTSC register of a root hub), ignore such case.
486 	 */
487 	if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
488 	    !(portstatus & USB_PORT_STAT_CONNECTION)) {
489 		if (get_timer(0) >= hub->connect_timeout) {
490 			debug("devnum=%d port=%d: timeout\n",
491 			      dev->devnum, i + 1);
492 			/* Remove this device from scanning list */
493 			list_del(&usb_scan->list);
494 			free(usb_scan);
495 			return 0;
496 		}
497 		return 0;
498 	}
499 
500 	if (portchange & USB_PORT_STAT_C_RESET) {
501 		debug("port %d reset change\n", i + 1);
502 		usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_RESET);
503 	}
504 
505 	if ((portchange & USB_SS_PORT_STAT_C_BH_RESET) &&
506 	    usb_hub_is_superspeed(dev)) {
507 		debug("port %d BH reset change\n", i + 1);
508 		usb_clear_port_feature(dev, i + 1, USB_SS_PORT_FEAT_C_BH_RESET);
509 	}
510 
511 	/* A new USB device is ready at this point */
512 	debug("devnum=%d port=%d: USB dev found\n", dev->devnum, i + 1);
513 
514 	usb_hub_port_connect_change(dev, i);
515 
516 	if (portchange & USB_PORT_STAT_C_ENABLE) {
517 		debug("port %d enable change, status %x\n", i + 1, portstatus);
518 		usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_ENABLE);
519 		/*
520 		 * EM interference sometimes causes bad shielded USB
521 		 * devices to be shutdown by the hub, this hack enables
522 		 * them again. Works at least with mouse driver
523 		 */
524 		if (!(portstatus & USB_PORT_STAT_ENABLE) &&
525 		    (portstatus & USB_PORT_STAT_CONNECTION) &&
526 		    usb_device_has_child_on_port(dev, i)) {
527 			debug("already running port %i disabled by hub (EMI?), re-enabling...\n",
528 			      i + 1);
529 			usb_hub_port_connect_change(dev, i);
530 		}
531 	}
532 
533 	if (portstatus & USB_PORT_STAT_SUSPEND) {
534 		debug("port %d suspend change\n", i + 1);
535 		usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_SUSPEND);
536 	}
537 
538 	if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
539 		debug("port %d over-current change\n", i + 1);
540 		usb_clear_port_feature(dev, i + 1,
541 				       USB_PORT_FEAT_C_OVER_CURRENT);
542 		/* Only power-on this one port */
543 		usb_set_port_feature(dev, i + 1, USB_PORT_FEAT_POWER);
544 		hub->overcurrent_count[i]++;
545 
546 		/*
547 		 * If the max-scan-count is not reached, return without removing
548 		 * the device from scan-list. This will re-issue a new scan.
549 		 */
550 		if (hub->overcurrent_count[i] <=
551 		    PORT_OVERCURRENT_MAX_SCAN_COUNT)
552 			return 0;
553 
554 		/* Otherwise the device will get removed */
555 		printf("Port %d over-current occurred %d times\n", i + 1,
556 		       hub->overcurrent_count[i]);
557 	}
558 
559 	/*
560 	 * We're done with this device, so let's remove this device from
561 	 * scanning list
562 	 */
563 	list_del(&usb_scan->list);
564 	free(usb_scan);
565 
566 	return 0;
567 }
568 
usb_device_list_scan(void)569 static int usb_device_list_scan(void)
570 {
571 	struct usb_device_scan *usb_scan;
572 	struct usb_device_scan *tmp;
573 	static int running;
574 	int ret = 0;
575 
576 	/* Only run this loop once for each controller */
577 	if (running)
578 		return 0;
579 
580 	running = 1;
581 
582 	while (1) {
583 		/* We're done, once the list is empty again */
584 		if (list_empty(&usb_scan_list))
585 			goto out;
586 
587 		list_for_each_entry_safe(usb_scan, tmp, &usb_scan_list, list) {
588 			int ret;
589 
590 			/* Scan this port */
591 			ret = usb_scan_port(usb_scan);
592 			if (ret)
593 				goto out;
594 		}
595 	}
596 
597 out:
598 	/*
599 	 * This USB controller has finished scanning all its connected
600 	 * USB devices. Set "running" back to 0, so that other USB controllers
601 	 * will scan their devices too.
602 	 */
603 	running = 0;
604 
605 	return ret;
606 }
607 
usb_get_hub_device(struct usb_device * dev)608 static struct usb_hub_device *usb_get_hub_device(struct usb_device *dev)
609 {
610 	struct usb_hub_device *hub;
611 
612 #if !CONFIG_IS_ENABLED(DM_USB)
613 	/* "allocate" Hub device */
614 	hub = usb_hub_allocate();
615 #else
616 	hub = dev_get_uclass_priv(dev->dev);
617 #endif
618 
619 	return hub;
620 }
621 
usb_hub_configure(struct usb_device * dev)622 static int usb_hub_configure(struct usb_device *dev)
623 {
624 	int i, length;
625 	ALLOC_CACHE_ALIGN_BUFFER(unsigned char, buffer, USB_BUFSIZ);
626 	unsigned char *bitmap;
627 	short hubCharacteristics;
628 	struct usb_hub_descriptor *descriptor;
629 	struct usb_hub_device *hub;
630 	struct usb_hub_status *hubsts;
631 	int ret;
632 
633 	hub = usb_get_hub_device(dev);
634 	if (hub == NULL)
635 		return -ENOMEM;
636 	hub->pusb_dev = dev;
637 
638 	/* Get the the hub descriptor */
639 	ret = usb_get_hub_descriptor(dev, buffer, 4);
640 	if (ret < 0) {
641 		debug("usb_hub_configure: failed to get hub " \
642 		      "descriptor, giving up %lX\n", dev->status);
643 		return ret;
644 	}
645 	descriptor = (struct usb_hub_descriptor *)buffer;
646 
647 	length = min_t(int, descriptor->bLength,
648 		       sizeof(struct usb_hub_descriptor));
649 
650 	ret = usb_get_hub_descriptor(dev, buffer, length);
651 	if (ret < 0) {
652 		debug("usb_hub_configure: failed to get hub " \
653 		      "descriptor 2nd giving up %lX\n", dev->status);
654 		return ret;
655 	}
656 	memcpy((unsigned char *)&hub->desc, buffer, length);
657 	/* adjust 16bit values */
658 	put_unaligned(le16_to_cpu(get_unaligned(
659 			&descriptor->wHubCharacteristics)),
660 			&hub->desc.wHubCharacteristics);
661 	/* set the bitmap */
662 	bitmap = (unsigned char *)&hub->desc.u.hs.DeviceRemovable[0];
663 	/* devices not removable by default */
664 	memset(bitmap, 0xff, (USB_MAXCHILDREN+1+7)/8);
665 	bitmap = (unsigned char *)&hub->desc.u.hs.PortPowerCtrlMask[0];
666 	memset(bitmap, 0xff, (USB_MAXCHILDREN+1+7)/8); /* PowerMask = 1B */
667 
668 	for (i = 0; i < ((hub->desc.bNbrPorts + 1 + 7)/8); i++)
669 		hub->desc.u.hs.DeviceRemovable[i] =
670 			descriptor->u.hs.DeviceRemovable[i];
671 
672 	for (i = 0; i < ((hub->desc.bNbrPorts + 1 + 7)/8); i++)
673 		hub->desc.u.hs.PortPowerCtrlMask[i] =
674 			descriptor->u.hs.PortPowerCtrlMask[i];
675 
676 	dev->maxchild = descriptor->bNbrPorts;
677 	debug("%d ports detected\n", dev->maxchild);
678 
679 	hubCharacteristics = get_unaligned(&hub->desc.wHubCharacteristics);
680 	switch (hubCharacteristics & HUB_CHAR_LPSM) {
681 	case 0x00:
682 		debug("ganged power switching\n");
683 		break;
684 	case 0x01:
685 		debug("individual port power switching\n");
686 		break;
687 	case 0x02:
688 	case 0x03:
689 		debug("unknown reserved power switching mode\n");
690 		break;
691 	}
692 
693 	if (hubCharacteristics & HUB_CHAR_COMPOUND)
694 		debug("part of a compound device\n");
695 	else
696 		debug("standalone hub\n");
697 
698 	switch (hubCharacteristics & HUB_CHAR_OCPM) {
699 	case 0x00:
700 		debug("global over-current protection\n");
701 		break;
702 	case 0x08:
703 		debug("individual port over-current protection\n");
704 		break;
705 	case 0x10:
706 	case 0x18:
707 		debug("no over-current protection\n");
708 		break;
709 	}
710 
711 	switch (dev->descriptor.bDeviceProtocol) {
712 	case USB_HUB_PR_FS:
713 		break;
714 	case USB_HUB_PR_HS_SINGLE_TT:
715 		debug("Single TT\n");
716 		break;
717 	case USB_HUB_PR_HS_MULTI_TT:
718 		ret = usb_set_interface(dev, 0, 1);
719 		if (ret == 0) {
720 			debug("TT per port\n");
721 			hub->tt.multi = true;
722 		} else {
723 			debug("Using single TT (err %d)\n", ret);
724 		}
725 		break;
726 	case USB_HUB_PR_SS:
727 		/* USB 3.0 hubs don't have a TT */
728 		break;
729 	default:
730 		debug("Unrecognized hub protocol %d\n",
731 		      dev->descriptor.bDeviceProtocol);
732 		break;
733 	}
734 
735 	/* Note 8 FS bit times == (8 bits / 12000000 bps) ~= 666ns */
736 	switch (hubCharacteristics & HUB_CHAR_TTTT) {
737 	case HUB_TTTT_8_BITS:
738 		if (dev->descriptor.bDeviceProtocol != 0) {
739 			hub->tt.think_time = 666;
740 			debug("TT requires at most %d FS bit times (%d ns)\n",
741 			      8, hub->tt.think_time);
742 		}
743 		break;
744 	case HUB_TTTT_16_BITS:
745 		hub->tt.think_time = 666 * 2;
746 		debug("TT requires at most %d FS bit times (%d ns)\n",
747 		      16, hub->tt.think_time);
748 		break;
749 	case HUB_TTTT_24_BITS:
750 		hub->tt.think_time = 666 * 3;
751 		debug("TT requires at most %d FS bit times (%d ns)\n",
752 		      24, hub->tt.think_time);
753 		break;
754 	case HUB_TTTT_32_BITS:
755 		hub->tt.think_time = 666 * 4;
756 		debug("TT requires at most %d FS bit times (%d ns)\n",
757 		      32, hub->tt.think_time);
758 		break;
759 	}
760 
761 	debug("power on to power good time: %dms\n",
762 	      descriptor->bPwrOn2PwrGood * 2);
763 	debug("hub controller current requirement: %dmA\n",
764 	      descriptor->bHubContrCurrent);
765 
766 	for (i = 0; i < dev->maxchild; i++)
767 		debug("port %d is%s removable\n", i + 1,
768 		      hub->desc.u.hs.DeviceRemovable[(i + 1) / 8] & \
769 		      (1 << ((i + 1) % 8)) ? " not" : "");
770 
771 	if (sizeof(struct usb_hub_status) > USB_BUFSIZ) {
772 		debug("usb_hub_configure: failed to get Status - " \
773 		      "too long: %d\n", descriptor->bLength);
774 		return -EFBIG;
775 	}
776 
777 	ret = usb_get_hub_status(dev, buffer);
778 	if (ret < 0) {
779 		debug("usb_hub_configure: failed to get Status %lX\n",
780 		      dev->status);
781 		return ret;
782 	}
783 
784 	hubsts = (struct usb_hub_status *)buffer;
785 
786 	debug("get_hub_status returned status %X, change %X\n",
787 	      le16_to_cpu(hubsts->wHubStatus),
788 	      le16_to_cpu(hubsts->wHubChange));
789 	debug("local power source is %s\n",
790 	      (le16_to_cpu(hubsts->wHubStatus) & HUB_STATUS_LOCAL_POWER) ? \
791 	      "lost (inactive)" : "good");
792 	debug("%sover-current condition exists\n",
793 	      (le16_to_cpu(hubsts->wHubStatus) & HUB_STATUS_OVERCURRENT) ? \
794 	      "" : "no ");
795 
796 #if CONFIG_IS_ENABLED(DM_USB)
797 	/*
798 	 * Update USB host controller's internal representation of this hub
799 	 * after the hub descriptor is fetched.
800 	 */
801 	ret = usb_update_hub_device(dev);
802 	if (ret < 0 && ret != -ENOSYS) {
803 		debug("%s: failed to update hub device for HCD (%x)\n",
804 		      __func__, ret);
805 		return ret;
806 	}
807 
808 	/*
809 	 * A maximum of seven tiers are allowed in a USB topology, and the
810 	 * root hub occupies the first tier. The last tier ends with a normal
811 	 * USB device. USB 3.0 hubs use a 20-bit field called 'route string'
812 	 * to route packets to the designated downstream port. The hub uses a
813 	 * hub depth value multiplied by four as an offset into the 'route
814 	 * string' to locate the bits it uses to determine the downstream
815 	 * port number.
816 	 */
817 	if (usb_hub_is_root_hub(dev->dev)) {
818 		hub->hub_depth = -1;
819 	} else {
820 		struct udevice *hdev;
821 		int depth = 0;
822 
823 		hdev = dev->dev->parent;
824 		while (!usb_hub_is_root_hub(hdev)) {
825 			depth++;
826 			hdev = hdev->parent;
827 		}
828 
829 		hub->hub_depth = depth;
830 
831 		if (usb_hub_is_superspeed(dev)) {
832 			debug("set hub (%p) depth to %d\n", dev, depth);
833 			/*
834 			 * This request sets the value that the hub uses to
835 			 * determine the index into the 'route string index'
836 			 * for this hub.
837 			 */
838 			ret = usb_set_hub_depth(dev, depth);
839 			if (ret < 0) {
840 				debug("%s: failed to set hub depth (%lX)\n",
841 				      __func__, dev->status);
842 				return ret;
843 			}
844 		}
845 	}
846 #endif
847 
848 	usb_hub_power_on(hub);
849 
850 	/*
851 	 * Reset any devices that may be in a bad state when applying
852 	 * the power.  This is a __weak function.  Resetting of the devices
853 	 * should occur in the board file of the device.
854 	 */
855 	for (i = 0; i < dev->maxchild; i++)
856 		usb_hub_reset_devices(hub, i + 1);
857 
858 	/*
859 	 * Only add the connected USB devices, including potential hubs,
860 	 * to a scanning list. This list will get scanned and devices that
861 	 * are detected (either via port connected or via port timeout)
862 	 * will get removed from this list. Scanning of the devices on this
863 	 * list will continue until all devices are removed.
864 	 */
865 	for (i = 0; i < dev->maxchild; i++) {
866 		struct usb_device_scan *usb_scan;
867 
868 		usb_scan = calloc(1, sizeof(*usb_scan));
869 		if (!usb_scan) {
870 			printf("Can't allocate memory for USB device!\n");
871 			return -ENOMEM;
872 		}
873 		usb_scan->dev = dev;
874 		usb_scan->hub = hub;
875 		usb_scan->port = i;
876 		list_add_tail(&usb_scan->list, &usb_scan_list);
877 	}
878 
879 	/*
880 	 * And now call the scanning code which loops over the generated list
881 	 */
882 	ret = usb_device_list_scan();
883 
884 	return ret;
885 }
886 
usb_hub_check(struct usb_device * dev,int ifnum)887 static int usb_hub_check(struct usb_device *dev, int ifnum)
888 {
889 	struct usb_interface *iface;
890 	struct usb_endpoint_descriptor *ep = NULL;
891 
892 	iface = &dev->config.if_desc[ifnum];
893 	/* Is it a hub? */
894 	if (iface->desc.bInterfaceClass != USB_CLASS_HUB)
895 		goto err;
896 	/* Some hubs have a subclass of 1, which AFAICT according to the */
897 	/*  specs is not defined, but it works */
898 	if ((iface->desc.bInterfaceSubClass != 0) &&
899 	    (iface->desc.bInterfaceSubClass != 1))
900 		goto err;
901 	/* Multiple endpoints? What kind of mutant ninja-hub is this? */
902 	if (iface->desc.bNumEndpoints != 1)
903 		goto err;
904 	ep = &iface->ep_desc[0];
905 	/* Output endpoint? Curiousier and curiousier.. */
906 	if (!(ep->bEndpointAddress & USB_DIR_IN))
907 		goto err;
908 	/* If it's not an interrupt endpoint, we'd better punt! */
909 	if ((ep->bmAttributes & 3) != 3)
910 		goto err;
911 	/* We found a hub */
912 	debug("USB hub found\n");
913 	return 0;
914 
915 err:
916 	debug("USB hub not found: bInterfaceClass=%d, bInterfaceSubClass=%d, bNumEndpoints=%d\n",
917 	      iface->desc.bInterfaceClass, iface->desc.bInterfaceSubClass,
918 	      iface->desc.bNumEndpoints);
919 	if (ep) {
920 		debug("   bEndpointAddress=%#x, bmAttributes=%d",
921 		      ep->bEndpointAddress, ep->bmAttributes);
922 	}
923 
924 	return -ENOENT;
925 }
926 
usb_hub_probe(struct usb_device * dev,int ifnum)927 int usb_hub_probe(struct usb_device *dev, int ifnum)
928 {
929 	int ret;
930 
931 	ret = usb_hub_check(dev, ifnum);
932 	if (ret)
933 		return 0;
934 	ret = usb_hub_configure(dev);
935 	return ret;
936 }
937 
938 #if CONFIG_IS_ENABLED(DM_USB)
usb_hub_scan(struct udevice * hub)939 int usb_hub_scan(struct udevice *hub)
940 {
941 	struct usb_device *udev = dev_get_parent_priv(hub);
942 
943 	return usb_hub_configure(udev);
944 }
945 
usb_hub_post_probe(struct udevice * dev)946 static int usb_hub_post_probe(struct udevice *dev)
947 {
948 	debug("%s\n", __func__);
949 	return usb_hub_scan(dev);
950 }
951 
952 static const struct udevice_id usb_hub_ids[] = {
953 	{ .compatible = "usb-hub" },
954 	{ }
955 };
956 
957 U_BOOT_DRIVER(usb_generic_hub) = {
958 	.name	= "usb_hub",
959 	.id	= UCLASS_USB_HUB,
960 	.of_match = usb_hub_ids,
961 	.flags	= DM_FLAG_ALLOC_PRIV_DMA,
962 };
963 
964 UCLASS_DRIVER(usb_hub) = {
965 	.id		= UCLASS_USB_HUB,
966 	.name		= "usb_hub",
967 	.post_bind	= dm_scan_fdt_dev,
968 	.post_probe	= usb_hub_post_probe,
969 	.child_pre_probe	= usb_child_pre_probe,
970 	.per_child_auto	= sizeof(struct usb_device),
971 	.per_child_plat_auto	= sizeof(struct usb_dev_plat),
972 	.per_device_auto	= sizeof(struct usb_hub_device),
973 };
974 
975 static const struct usb_device_id hub_id_table[] = {
976 	{
977 		.match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
978 		.bDeviceClass = USB_CLASS_HUB
979 	},
980 	{ }	/* Terminating entry */
981 };
982 
983 U_BOOT_USB_DEVICE(usb_generic_hub, hub_id_table);
984 
985 #endif
986