1 /*
2  * USB hub driver.
3  *
4  * (C) Copyright 1999 Linus Torvalds
5  * (C) Copyright 1999 Johannes Erdfelt
6  * (C) Copyright 1999 Gregory P. Smith
7  * (C) Copyright 2001 Brad Hards (bhards@bigpond.net.au)
8  *
9  */
10 
11 #include <linux/config.h>
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/completion.h>
15 #include <linux/sched.h>
16 #include <linux/list.h>
17 #include <linux/slab.h>
18 #include <linux/smp_lock.h>
19 #ifdef CONFIG_USB_DEBUG
20 	#define DEBUG
21 #else
22 	#undef DEBUG
23 #endif
24 #include <linux/usb.h>
25 #include <linux/usbdevice_fs.h>
26 
27 #include <asm/semaphore.h>
28 #include <asm/uaccess.h>
29 #include <asm/byteorder.h>
30 
31 #include "hub.h"
32 
33 /* Wakes up khubd */
34 static spinlock_t hub_event_lock = SPIN_LOCK_UNLOCKED;
35 static DECLARE_MUTEX(usb_address0_sem);
36 
37 static LIST_HEAD(hub_event_list);	/* List of hubs needing servicing */
38 static LIST_HEAD(hub_list);		/* List containing all of the hubs (for cleanup) */
39 
40 static DECLARE_WAIT_QUEUE_HEAD(khubd_wait);
41 static pid_t khubd_pid = 0;			/* PID of khubd */
42 static DECLARE_COMPLETION(khubd_exited);
43 
44 #ifdef	DEBUG
portspeed(int portstatus)45 static inline char *portspeed (int portstatus)
46 {
47 	if (portstatus & (1 << USB_PORT_FEAT_HIGHSPEED))
48     		return "480 Mb/s";
49 	else if (portstatus & (1 << USB_PORT_FEAT_LOWSPEED))
50 		return "1.5 Mb/s";
51 	else
52 		return "12 Mb/s";
53 }
54 #endif
55 
56 /* USB 2.0 spec Section 11.24.4.5 */
usb_get_hub_descriptor(struct usb_device * dev,void * data,int size)57 static int usb_get_hub_descriptor(struct usb_device *dev, void *data, int size)
58 {
59 	return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
60 		USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
61 		USB_DT_HUB << 8, 0, data, size, HZ);
62 }
63 
64 /*
65  * USB 2.0 spec Section 11.24.2.1
66  */
usb_clear_hub_feature(struct usb_device * dev,int feature)67 static int usb_clear_hub_feature(struct usb_device *dev, int feature)
68 {
69 	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
70 		USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, HZ);
71 }
72 
73 /*
74  * USB 2.0 spec Section 11.24.2.2
75  * BUG: doesn't handle port indicator selector in high byte of wIndex
76  */
usb_clear_port_feature(struct usb_device * dev,int port,int feature)77 static int usb_clear_port_feature(struct usb_device *dev, int port, int feature)
78 {
79 	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
80 		USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port, NULL, 0, HZ);
81 }
82 
83 /*
84  * USB 2.0 spec Section 11.24.2.13
85  * BUG: doesn't handle port indicator selector in high byte of wIndex
86  */
usb_set_port_feature(struct usb_device * dev,int port,int feature)87 static int usb_set_port_feature(struct usb_device *dev, int port, int feature)
88 {
89 	return usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
90 		USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port, NULL, 0, HZ);
91 }
92 
93 /*
94  * USB 2.0 spec Section 11.24.2.6
95  */
usb_get_hub_status(struct usb_device * dev,void * data)96 static int usb_get_hub_status(struct usb_device *dev, void *data)
97 {
98 	return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
99 		USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
100 		data, sizeof(struct usb_hub_status), HZ);
101 }
102 
103 /*
104  * USB 2.0 spec Section 11.24.2.7
105  */
usb_get_port_status(struct usb_device * dev,int port,void * data)106 static int usb_get_port_status(struct usb_device *dev, int port, void *data)
107 {
108 	return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
109 		USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port,
110 		data, sizeof(struct usb_hub_status), HZ);
111 }
112 
hub_irq(struct urb * urb)113 static void hub_irq(struct urb *urb)
114 {
115 	struct usb_hub *hub = (struct usb_hub *)urb->context;
116 	unsigned long flags;
117 
118 	/* Cause a hub reset after 10 consecutive errors */
119 	if (urb->status) {
120 		if (urb->status == -ENOENT)
121 			return;
122 
123 		dbg("nonzero status in irq %d", urb->status);
124 
125 		if ((++hub->nerrors < 10) || hub->error)
126 			return;
127 
128 		hub->error = urb->status;
129 	}
130 
131 	hub->nerrors = 0;
132 
133 	/* Something happened, let khubd figure it out */
134 	spin_lock_irqsave(&hub_event_lock, flags);
135 	if (list_empty(&hub->event_list)) {
136 		list_add(&hub->event_list, &hub_event_list);
137 		wake_up(&khubd_wait);
138 	}
139 	spin_unlock_irqrestore(&hub_event_lock, flags);
140 }
141 
usb_hub_power_on(struct usb_hub * hub)142 static void usb_hub_power_on(struct usb_hub *hub)
143 {
144 	int i;
145 
146 	/* Enable power to the ports */
147 	dbg("enabling power on all ports");
148 	for (i = 0; i < hub->descriptor->bNbrPorts; i++)
149 		usb_set_port_feature(hub->dev, i + 1, USB_PORT_FEAT_POWER);
150 
151 	/* Wait for power to be enabled */
152 	wait_ms(hub->descriptor->bPwrOn2PwrGood * 2);
153 }
154 
usb_hub_configure(struct usb_hub * hub,struct usb_endpoint_descriptor * endpoint)155 static int usb_hub_configure(struct usb_hub *hub, struct usb_endpoint_descriptor *endpoint)
156 {
157 	struct usb_device *dev = hub->dev;
158 	struct usb_hub_status *hubstatus;
159 	char portstr[USB_MAXCHILDREN + 1];
160 	unsigned int pipe;
161 	int i, maxp, ret;
162 
163 	hub->descriptor = kmalloc(sizeof(*hub->descriptor), GFP_KERNEL);
164 	if (!hub->descriptor) {
165 		err("Unable to kmalloc %Zd bytes for hub descriptor", sizeof(*hub->descriptor));
166 		return -1;
167 	}
168 
169 	/* Request the entire hub descriptor. */
170 	ret = usb_get_hub_descriptor(dev, hub->descriptor, sizeof(*hub->descriptor));
171 		/* <hub->descriptor> is large enough for a hub with 127 ports;
172 		 * the hub can/will return fewer bytes here. */
173 	if (ret < 0) {
174 		err("Unable to get hub descriptor (err = %d)", ret);
175 		kfree(hub->descriptor);
176 		return -1;
177 	}
178 
179 	dev->maxchild = hub->descriptor->bNbrPorts;
180 	info("%d port%s detected", hub->descriptor->bNbrPorts, (hub->descriptor->bNbrPorts == 1) ? "" : "s");
181 
182 	le16_to_cpus(&hub->descriptor->wHubCharacteristics);
183 
184 	if (hub->descriptor->wHubCharacteristics & HUB_CHAR_COMPOUND)
185 		dbg("part of a compound device");
186 	else
187 		dbg("standalone hub");
188 
189 	switch (hub->descriptor->wHubCharacteristics & HUB_CHAR_LPSM) {
190 		case 0x00:
191 			dbg("ganged power switching");
192 			break;
193 		case 0x01:
194 			dbg("individual port power switching");
195 			break;
196 		case 0x02:
197 		case 0x03:
198 			dbg("unknown reserved power switching mode");
199 			break;
200 	}
201 
202 	switch (hub->descriptor->wHubCharacteristics & HUB_CHAR_OCPM) {
203 		case 0x00:
204 			dbg("global over-current protection");
205 			break;
206 		case 0x08:
207 			dbg("individual port over-current protection");
208 			break;
209 		case 0x10:
210 		case 0x18:
211 			dbg("no over-current protection");
212                         break;
213 	}
214 
215 	switch (dev->descriptor.bDeviceProtocol) {
216 		case 0:
217 			break;
218 		case 1:
219 			dbg("Single TT");
220 			hub->tt.hub = dev;
221 			break;
222 		case 2:
223 			dbg("TT per port");
224 			hub->tt.hub = dev;
225 			hub->tt.multi = 1;
226 			break;
227 		default:
228 			dbg("Unrecognized hub protocol %d",
229 				dev->descriptor.bDeviceProtocol);
230 			break;
231 	}
232 
233 	switch (hub->descriptor->wHubCharacteristics & HUB_CHAR_TTTT) {
234 		case 0x00:
235 			if (dev->descriptor.bDeviceProtocol != 0)
236 				dbg("TT requires at most 8 FS bit times");
237 			break;
238 		case 0x20:
239 			dbg("TT requires at most 16 FS bit times");
240 			break;
241 		case 0x40:
242 			dbg("TT requires at most 24 FS bit times");
243 			break;
244 		case 0x60:
245 			dbg("TT requires at most 32 FS bit times");
246 			break;
247 	}
248 
249 	dbg("Port indicators are %s supported",
250 	    (hub->descriptor->wHubCharacteristics & HUB_CHAR_PORTIND) ? "" : "not");
251 
252 	dbg("power on to power good time: %dms", hub->descriptor->bPwrOn2PwrGood * 2);
253 	dbg("hub controller current requirement: %dmA", hub->descriptor->bHubContrCurrent);
254 
255 	for (i = 0; i < dev->maxchild; i++)
256 		portstr[i] = hub->descriptor->DeviceRemovable[((i + 1) / 8)] & (1 << ((i + 1) % 8)) ? 'F' : 'R';
257 	portstr[dev->maxchild] = 0;
258 
259 	dbg("port removable status: %s", portstr);
260 
261 	hubstatus = kmalloc(sizeof *hubstatus, GFP_KERNEL);
262 	if (!hubstatus) {
263 		err("Unable to allocate hubstatus");
264 		kfree(hub->descriptor);
265 		return -1;
266 	}
267 	ret = usb_get_hub_status(dev, hubstatus);
268 	if (ret < 0) {
269 		err("Unable to get hub status (err = %d)", ret);
270 		kfree(hubstatus);
271 		kfree(hub->descriptor);
272 		return -1;
273 	}
274 
275 	le16_to_cpus(&hubstatus->wHubStatus);
276 
277 	dbg("local power source is %s",
278 		(hubstatus->wHubStatus & HUB_STATUS_LOCAL_POWER) ? "lost (inactive)" : "good");
279 
280 	dbg("%sover-current condition exists",
281 		(hubstatus->wHubStatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
282 
283 	kfree(hubstatus);
284 
285 	/* Start the interrupt endpoint */
286 	pipe = usb_rcvintpipe(dev, endpoint->bEndpointAddress);
287 	maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe));
288 
289 	if (maxp > sizeof(hub->buffer))
290 		maxp = sizeof(hub->buffer);
291 
292 	hub->urb = usb_alloc_urb(0);
293 	if (!hub->urb) {
294 		err("couldn't allocate interrupt urb");
295 		kfree(hub->descriptor);
296 		return -1;
297 	}
298 
299 	FILL_INT_URB(hub->urb, dev, pipe, hub->buffer, maxp, hub_irq, hub,
300 		/* NOTE:  in 2.5 fill_int_urb() converts the encoding */
301 		(dev->speed == USB_SPEED_HIGH)
302 			? 1 << (endpoint->bInterval - 1)
303 			: endpoint->bInterval);
304 	ret = usb_submit_urb(hub->urb);
305 	if (ret) {
306 		err("usb_submit_urb failed (%d)", ret);
307 		kfree(hub->descriptor);
308 		return -1;
309 	}
310 
311 	/* Wake up khubd */
312 	wake_up(&khubd_wait);
313 
314 	usb_hub_power_on(hub);
315 
316 	return 0;
317 }
318 
hub_probe(struct usb_device * dev,unsigned int i,const struct usb_device_id * id)319 static void *hub_probe(struct usb_device *dev, unsigned int i,
320 		       const struct usb_device_id *id)
321 {
322 	struct usb_interface_descriptor *interface;
323 	struct usb_endpoint_descriptor *endpoint;
324 	struct usb_hub *hub;
325 	unsigned long flags;
326 
327 	interface = &dev->actconfig->interface[i].altsetting[0];
328 
329 	/* Some hubs have a subclass of 1, which AFAICT according to the */
330 	/*  specs is not defined, but it works */
331 	if ((interface->bInterfaceSubClass != 0) &&
332 	    (interface->bInterfaceSubClass != 1)) {
333 		err("invalid subclass (%d) for USB hub device #%d",
334 			interface->bInterfaceSubClass, dev->devnum);
335 		return NULL;
336 	}
337 
338 	/* Multiple endpoints? What kind of mutant ninja-hub is this? */
339 	if (interface->bNumEndpoints != 1) {
340 		err("invalid bNumEndpoints (%d) for USB hub device #%d",
341 			interface->bNumEndpoints, dev->devnum);
342 		return NULL;
343 	}
344 
345 	endpoint = &interface->endpoint[0];
346 
347 	/* Output endpoint? Curiousier and curiousier.. */
348 	if (!(endpoint->bEndpointAddress & USB_DIR_IN)) {
349 		err("Device #%d is hub class, but has output endpoint?",
350 			dev->devnum);
351 		return NULL;
352 	}
353 
354 	/* If it's not an interrupt endpoint, we'd better punt! */
355 	if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) != USB_ENDPOINT_XFER_INT) {
356 		err("Device #%d is hub class, but has endpoint other than interrupt?",
357 			dev->devnum);
358 		return NULL;
359 	}
360 
361 	/* We found a hub */
362 	info("USB hub found");
363 
364 	hub = kmalloc(sizeof(*hub), GFP_KERNEL);
365 	if (!hub) {
366 		err("couldn't kmalloc hub struct");
367 		return NULL;
368 	}
369 
370 	memset(hub, 0, sizeof(*hub));
371 
372 	INIT_LIST_HEAD(&hub->event_list);
373 	hub->dev = dev;
374 	init_MUTEX(&hub->khubd_sem);
375 
376 	/* Record the new hub's existence */
377 	spin_lock_irqsave(&hub_event_lock, flags);
378 	INIT_LIST_HEAD(&hub->hub_list);
379 	list_add(&hub->hub_list, &hub_list);
380 	spin_unlock_irqrestore(&hub_event_lock, flags);
381 
382 	if (usb_hub_configure(hub, endpoint) >= 0)
383 		return hub;
384 
385 	err("hub configuration failed for device #%d", dev->devnum);
386 
387 	/* free hub, but first clean up its list. */
388 	spin_lock_irqsave(&hub_event_lock, flags);
389 
390 	/* Delete it and then reset it */
391 	list_del(&hub->event_list);
392 	INIT_LIST_HEAD(&hub->event_list);
393 	list_del(&hub->hub_list);
394 	INIT_LIST_HEAD(&hub->hub_list);
395 
396 	spin_unlock_irqrestore(&hub_event_lock, flags);
397 
398 	kfree(hub);
399 
400 	return NULL;
401 }
402 
hub_disconnect(struct usb_device * dev,void * ptr)403 static void hub_disconnect(struct usb_device *dev, void *ptr)
404 {
405 	struct usb_hub *hub = (struct usb_hub *)ptr;
406 	unsigned long flags;
407 
408 	spin_lock_irqsave(&hub_event_lock, flags);
409 
410 	/* Delete it and then reset it */
411 	list_del(&hub->event_list);
412 	INIT_LIST_HEAD(&hub->event_list);
413 	list_del(&hub->hub_list);
414 	INIT_LIST_HEAD(&hub->hub_list);
415 
416 	spin_unlock_irqrestore(&hub_event_lock, flags);
417 
418 	down(&hub->khubd_sem); /* Wait for khubd to leave this hub alone. */
419 	up(&hub->khubd_sem);
420 
421 	if (hub->urb) {
422 		usb_unlink_urb(hub->urb);
423 		usb_free_urb(hub->urb);
424 		hub->urb = NULL;
425 	}
426 
427 	if (hub->descriptor) {
428 		kfree(hub->descriptor);
429 		hub->descriptor = NULL;
430 	}
431 
432 	/* Free the memory */
433 	kfree(hub);
434 }
435 
hub_ioctl(struct usb_device * hub,unsigned int code,void * user_data)436 static int hub_ioctl(struct usb_device *hub, unsigned int code, void *user_data)
437 {
438 	/* assert ifno == 0 (part of hub spec) */
439 	switch (code) {
440 	case USBDEVFS_HUB_PORTINFO: {
441 		struct usbdevfs_hub_portinfo *info = user_data;
442 		unsigned long flags;
443 		int i;
444 
445 		spin_lock_irqsave(&hub_event_lock, flags);
446 		if (hub->devnum <= 0)
447 			info->nports = 0;
448 		else {
449 			info->nports = hub->maxchild;
450 			for (i = 0; i < info->nports; i++) {
451 				if (hub->children[i] == NULL)
452 					info->port[i] = 0;
453 				else
454 					info->port[i] = hub->children[i]->devnum;
455 			}
456 		}
457 		spin_unlock_irqrestore(&hub_event_lock, flags);
458 
459 		return info->nports + 1;
460 		}
461 
462 	default:
463 		return -ENOSYS;
464 	}
465 }
466 
usb_hub_reset(struct usb_hub * hub)467 static int usb_hub_reset(struct usb_hub *hub)
468 {
469 	struct usb_device *dev = hub->dev;
470 	int i;
471 
472 	/* Disconnect any attached devices */
473 	for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
474 		if (dev->children[i])
475 			usb_disconnect(&dev->children[i]);
476 	}
477 
478 	/* Attempt to reset the hub */
479 	if (hub->urb)
480 		usb_unlink_urb(hub->urb);
481 	else
482 		return -1;
483 
484 	if (usb_reset_device(dev))
485 		return -1;
486 
487 	hub->urb->dev = dev;
488 	if (usb_submit_urb(hub->urb))
489 		return -1;
490 
491 	usb_hub_power_on(hub);
492 
493 	return 0;
494 }
495 
usb_hub_disconnect(struct usb_device * dev)496 static void usb_hub_disconnect(struct usb_device *dev)
497 {
498 	struct usb_device *parent = dev->parent;
499 	int i;
500 
501 	/* Find the device pointer to disconnect */
502 	if (parent) {
503 		for (i = 0; i < parent->maxchild; i++) {
504 			if (parent->children[i] == dev) {
505 				usb_disconnect(&parent->children[i]);
506 				return;
507 			}
508 		}
509 	}
510 
511 	err("cannot disconnect hub %d", dev->devnum);
512 }
513 
usb_hub_port_status(struct usb_device * hub,int port,u16 * status,u16 * change)514 static int usb_hub_port_status(struct usb_device *hub, int port,
515 			       u16 *status, u16 *change)
516 {
517 	struct usb_port_status *portsts;
518 	int ret = -ENOMEM;
519 
520 	portsts = kmalloc(sizeof(*portsts), GFP_KERNEL);
521 	if (portsts) {
522 		ret = usb_get_port_status(hub, port + 1, portsts);
523 		if (ret < 0)
524 			err("%s (%d) failed (err = %d)", __FUNCTION__, hub->devnum, ret);
525 		else {
526 			*status = le16_to_cpu(portsts->wPortStatus);
527 			*change = le16_to_cpu(portsts->wPortChange);
528 			dbg("port %d, portstatus %x, change %x, %s", port + 1,
529 				*status, *change, portspeed(*status));
530 			ret = 0;
531 		}
532 		kfree(portsts);
533 	}
534 	return ret;
535 }
536 
537 #define HUB_RESET_TRIES		5
538 #define HUB_PROBE_TRIES		2
539 #define HUB_SHORT_RESET_TIME	10
540 #define HUB_LONG_RESET_TIME	200
541 #define HUB_RESET_TIMEOUT	500
542 
543 /* return: -1 on error, 0 on success, 1 on disconnect.  */
usb_hub_port_wait_reset(struct usb_device * hub,int port,struct usb_device * dev,unsigned int delay)544 static int usb_hub_port_wait_reset(struct usb_device *hub, int port,
545 				struct usb_device *dev, unsigned int delay)
546 {
547 	int delay_time, ret;
548 	u16 portstatus;
549 	u16 portchange;
550 
551 	for (delay_time = 0; delay_time < HUB_RESET_TIMEOUT; delay_time += delay) {
552 		/* wait to give the device a chance to reset */
553 		wait_ms(delay);
554 
555 		/* read and decode port status */
556 		ret = usb_hub_port_status(hub, port, &portstatus, &portchange);
557 		if (ret < 0) {
558 			return -1;
559 		}
560 
561 		/* Device went away? */
562 		if (!(portstatus & USB_PORT_STAT_CONNECTION))
563 			return 1;
564 
565 		/* bomb out completely if something weird happened */
566 		if ((portchange & USB_PORT_STAT_C_CONNECTION))
567 			return -1;
568 
569 		/* if we`ve finished resetting, then break out of the loop */
570 		if (!(portstatus & USB_PORT_STAT_RESET) &&
571 		    (portstatus & USB_PORT_STAT_ENABLE)) {
572 			if (portstatus & USB_PORT_STAT_HIGH_SPEED)
573 				dev->speed = USB_SPEED_HIGH;
574 			else if (portstatus & USB_PORT_STAT_LOW_SPEED)
575 				dev->speed = USB_SPEED_LOW;
576 			else
577 				dev->speed = USB_SPEED_FULL;
578 			return 0;
579 		}
580 
581 		/* switch to the long delay after two short delay failures */
582 		if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
583 			delay = HUB_LONG_RESET_TIME;
584 
585 		dbg("port %d of hub %d not reset yet, waiting %dms", port + 1,
586 			hub->devnum, delay);
587 	}
588 
589 	return -1;
590 }
591 
592 /* return: -1 on error, 0 on success, 1 on disconnect.  */
usb_hub_port_reset(struct usb_device * hub,int port,struct usb_device * dev,unsigned int delay)593 static int usb_hub_port_reset(struct usb_device *hub, int port,
594 				struct usb_device *dev, unsigned int delay)
595 {
596 	int i, status;
597 
598 	/* Reset the port */
599 	for (i = 0; i < HUB_RESET_TRIES; i++) {
600 		usb_set_port_feature(hub, port + 1, USB_PORT_FEAT_RESET);
601 
602 		/* return on disconnect or reset */
603 		status = usb_hub_port_wait_reset(hub, port, dev, delay);
604 		if (status != -1) {
605 			usb_clear_port_feature(hub, port + 1, USB_PORT_FEAT_C_RESET);
606 			return status;
607 		}
608 
609 		dbg("port %d of hub %d not enabled, trying reset again...",
610 			port + 1, hub->devnum);
611 		delay = HUB_LONG_RESET_TIME;
612 	}
613 
614 	err("Cannot enable port %i of hub %d, disabling port.",
615 		port + 1, hub->devnum);
616 	err("Maybe the USB cable is bad?");
617 
618 	return -1;
619 }
620 
usb_hub_port_disable(struct usb_device * hub,int port)621 void usb_hub_port_disable(struct usb_device *hub, int port)
622 {
623 	int ret;
624 
625 	ret = usb_clear_port_feature(hub, port + 1, USB_PORT_FEAT_ENABLE);
626 	if (ret)
627 		err("cannot disable port %d of hub %d (err = %d)",
628 			port + 1, hub->devnum, ret);
629 }
630 
631 /* USB 2.0 spec, 7.1.7.3 / fig 7-29:
632  *
633  * Between connect detection and reset signaling there must be a delay
634  * of 100ms at least for debounce and power-settling. The corresponding
635  * timer shall restart whenever the downstream port detects a disconnect.
636  *
637  * Apparently there are some bluetooth and irda-dongles and a number
638  * of low-speed devices which require longer delays of about 200-400ms.
639  * Not covered by the spec - but easy to deal with.
640  *
641  * This implementation uses 400ms minimum debounce timeout and checks
642  * every 100ms for transient disconnects to restart the delay.
643  */
644 
645 #define HUB_DEBOUNCE_TIMEOUT	400
646 #define HUB_DEBOUNCE_STEP	100
647 
648 /* return: -1 on error, 0 on success, 1 on disconnect.  */
usb_hub_port_debounce(struct usb_device * hub,int port)649 static int usb_hub_port_debounce(struct usb_device *hub, int port)
650 {
651 	int ret;
652 	unsigned delay_time;
653 	u16 portchange, portstatus;
654 
655 	for (delay_time = 0; delay_time < HUB_DEBOUNCE_TIMEOUT; /* empty */ ) {
656 
657 		/* wait debounce step increment */
658 		wait_ms(HUB_DEBOUNCE_STEP);
659 
660 		ret = usb_hub_port_status(hub, port, &portstatus, &portchange);
661 		if (ret < 0)
662 			return -1;
663 
664 		if ((portchange & USB_PORT_STAT_C_CONNECTION)) {
665 			usb_clear_port_feature(hub, port+1, USB_PORT_FEAT_C_CONNECTION);
666 			delay_time = 0;
667 		}
668 		else
669 			delay_time += HUB_DEBOUNCE_STEP;
670 	}
671 	return ((portstatus&USB_PORT_STAT_CONNECTION)) ? 0 : 1;
672 }
673 
usb_hub_port_connect_change(struct usb_hub * hubstate,int port,u16 portstatus,u16 portchange)674 static void usb_hub_port_connect_change(struct usb_hub *hubstate, int port,
675 					u16 portstatus, u16 portchange)
676 {
677 	struct usb_device *hub = hubstate->dev;
678 	struct usb_device *dev;
679 	unsigned int delay = HUB_SHORT_RESET_TIME;
680 	int i;
681 
682 	dbg("port %d, portstatus %x, change %x, %s",
683 		port + 1, portstatus, portchange, portspeed (portstatus));
684 
685 	/* Clear the connection change status */
686 	usb_clear_port_feature(hub, port + 1, USB_PORT_FEAT_C_CONNECTION);
687 
688 	/* Disconnect any existing devices under this port */
689 	if (hub->children[port])
690 		usb_disconnect(&hub->children[port]);
691 
692 	/* Return now if nothing is connected */
693 	if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
694 		if (portstatus & USB_PORT_STAT_ENABLE)
695 			usb_hub_port_disable(hub, port);
696 
697 		return;
698 	}
699 
700 	if (usb_hub_port_debounce(hub, port)) {
701 		err("connect-debounce failed, port %d disabled", port+1);
702 		usb_hub_port_disable(hub, port);
703 		return;
704 	}
705 
706 	down(&usb_address0_sem);
707 
708 	for (i = 0; i < HUB_PROBE_TRIES; i++) {
709 		struct usb_device *pdev;
710 		int len;
711 
712 		/* Allocate a new device struct */
713 		dev = usb_alloc_dev(hub, hub->bus);
714 		if (!dev) {
715 			err("couldn't allocate usb_device");
716 			break;
717 		}
718 
719 		/* Reset the device */
720 		if (usb_hub_port_reset(hub, port, dev, delay)) {
721 			usb_free_dev(dev);
722 			break;
723 		}
724 
725 		/* Find a new device ID for it */
726 		usb_connect(dev);
727 
728 		/* Set up TT records, if needed  */
729 		if (hub->tt) {
730 			dev->tt = hub->tt;
731 			dev->ttport = hub->ttport;
732 		} else if (dev->speed != USB_SPEED_HIGH
733 				&& hub->speed == USB_SPEED_HIGH) {
734 			dev->tt = &hubstate->tt;
735 			dev->ttport = port + 1;
736 		}
737 
738 		/* Save readable and stable topology id, distinguishing
739 		 * devices by location for diagnostics, tools, etc.  The
740 		 * string is a path along hub ports, from the root.  Each
741 		 * device's id will be stable until USB is re-cabled, and
742 		 * hubs are often labeled with these port numbers.
743 		 *
744 		 * Initial size: ".NN" times five hubs + NUL = 16 bytes max
745 		 * (quite rare, since most hubs have 4-6 ports).
746 		 */
747 		pdev = dev->parent;
748 		if (pdev->devpath [0] != '0')	/* parent not root? */
749 			len = snprintf (dev->devpath, sizeof dev->devpath,
750 				"%s.%d", pdev->devpath, port + 1);
751 		/* root == "0", root port 2 == "2", port 3 that hub "2.3" */
752 		else
753 			len = snprintf (dev->devpath, sizeof dev->devpath,
754 				"%d", port + 1);
755 		if (len == sizeof dev->devpath)
756 			warn ("devpath size! usb/%03d/%03d path %s",
757 				dev->bus->busnum, dev->devnum, dev->devpath);
758 		info("new USB device %s-%s, assigned address %d",
759 			dev->bus->bus_name, dev->devpath, dev->devnum);
760 
761 		/* Run it through the hoops (find a driver, etc) */
762 		if (!usb_new_device(dev)) {
763 			hub->children[port] = dev;
764 			goto done;
765 		}
766 
767 		/* Free the configuration if there was an error */
768 		usb_free_dev(dev);
769 
770 		/* Switch to a long reset time */
771 		delay = HUB_LONG_RESET_TIME;
772 	}
773 
774 	usb_hub_port_disable(hub, port);
775 done:
776 	up(&usb_address0_sem);
777 }
778 
usb_hub_events(void)779 static void usb_hub_events(void)
780 {
781 	unsigned long flags;
782 	struct list_head *tmp;
783 	struct usb_device *dev;
784 	struct usb_hub *hub;
785 	struct usb_hub_status *hubsts;
786 	u16 hubstatus;
787 	u16 hubchange;
788 	u16 portstatus;
789 	u16 portchange;
790 	int i, ret;
791 
792 	/*
793 	 *  We restart the list everytime to avoid a deadlock with
794 	 * deleting hubs downstream from this one. This should be
795 	 * safe since we delete the hub from the event list.
796 	 * Not the most efficient, but avoids deadlocks.
797 	 */
798 	while (1) {
799 		spin_lock_irqsave(&hub_event_lock, flags);
800 
801 		if (list_empty(&hub_event_list))
802 			break;
803 
804 		/* Grab the next entry from the beginning of the list */
805 		tmp = hub_event_list.next;
806 
807 		hub = list_entry(tmp, struct usb_hub, event_list);
808 		dev = hub->dev;
809 
810 		list_del(tmp);
811 		INIT_LIST_HEAD(tmp);
812 
813 		down(&hub->khubd_sem); /* never blocks, we were on list */
814 		spin_unlock_irqrestore(&hub_event_lock, flags);
815 
816 		if (hub->error) {
817 			dbg("resetting hub %d for error %d", dev->devnum, hub->error);
818 
819 			if (usb_hub_reset(hub)) {
820 				err("error resetting hub %d - disconnecting", dev->devnum);
821 				up(&hub->khubd_sem);
822 				usb_hub_disconnect(dev);
823 				continue;
824 			}
825 
826 			hub->nerrors = 0;
827 			hub->error = 0;
828 		}
829 
830 		for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
831 			ret = usb_hub_port_status(dev, i, &portstatus, &portchange);
832 			if (ret < 0) {
833 				continue;
834 			}
835 
836 			if (portchange & USB_PORT_STAT_C_CONNECTION) {
837 				dbg("port %d connection change", i + 1);
838 
839 				usb_hub_port_connect_change(hub, i, portstatus, portchange);
840 			} else if (portchange & USB_PORT_STAT_C_ENABLE) {
841 				dbg("port %d enable change, status %x", i + 1, portstatus);
842 				usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_ENABLE);
843 
844 				/*
845 				 * EM interference sometimes causes bad shielded USB devices to
846 				 * be shutdown by the hub, this hack enables them again.
847 				 * Works at least with mouse driver.
848 				 */
849 				if (!(portstatus & USB_PORT_STAT_ENABLE) &&
850 				    (portstatus & USB_PORT_STAT_CONNECTION) && (dev->children[i])) {
851 					err("already running port %i disabled by hub (EMI?), re-enabling...",
852 						i + 1);
853 					usb_hub_port_connect_change(hub, i, portstatus, portchange);
854 				}
855 			}
856 
857 			if (portchange & USB_PORT_STAT_C_SUSPEND) {
858 				dbg("port %d suspend change", i + 1);
859 				usb_clear_port_feature(dev, i + 1,  USB_PORT_FEAT_C_SUSPEND);
860 			}
861 
862 			if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
863 				err("port %d over-current change", i + 1);
864 				usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_OVER_CURRENT);
865 				usb_hub_power_on(hub);
866 			}
867 
868 			if (portchange & USB_PORT_STAT_C_RESET) {
869 				dbg("port %d reset change", i + 1);
870 				usb_clear_port_feature(dev, i + 1, USB_PORT_FEAT_C_RESET);
871 			}
872 		} /* end for i */
873 
874 		/* deal with hub status changes */
875 		hubsts = kmalloc(sizeof *hubsts, GFP_KERNEL);
876 		if (!hubsts) {
877 			err("couldn't allocate hubsts");
878 		} else {
879 			if (usb_get_hub_status(dev, hubsts) < 0)
880 				err("get_hub_status failed");
881 			else {
882 				hubstatus = le16_to_cpup(&hubsts->wHubStatus);
883 				hubchange = le16_to_cpup(&hubsts->wHubChange);
884 				if (hubchange & HUB_CHANGE_LOCAL_POWER) {
885 					dbg("hub power change");
886 					usb_clear_hub_feature(dev, C_HUB_LOCAL_POWER);
887 				}
888 				if (hubchange & HUB_CHANGE_OVERCURRENT) {
889 					dbg("hub overcurrent change");
890 					wait_ms(500);	/* Cool down */
891 					usb_clear_hub_feature(dev, C_HUB_OVER_CURRENT);
892 					usb_hub_power_on(hub);
893 				}
894 			}
895 			kfree(hubsts);
896 		}
897 		up(&hub->khubd_sem);
898         } /* end while (1) */
899 
900 	spin_unlock_irqrestore(&hub_event_lock, flags);
901 }
902 
usb_hub_thread(void * __hub)903 static int usb_hub_thread(void *__hub)
904 {
905 	lock_kernel();
906 
907 	/*
908 	 * This thread doesn't need any user-level access,
909 	 * so get rid of all our resources
910 	 */
911 
912 	daemonize();
913 	reparent_to_init();
914 
915 	/* Setup a nice name */
916 	strcpy(current->comm, "khubd");
917 
918 	/* Send me a signal to get me die (for debugging) */
919 	do {
920 		usb_hub_events();
921 		wait_event_interruptible(khubd_wait, !list_empty(&hub_event_list));
922 	} while (!signal_pending(current));
923 
924 	dbg("usb_hub_thread exiting");
925 
926 	unlock_kernel();
927 	complete_and_exit(&khubd_exited, 0);
928 }
929 
930 static struct usb_device_id hub_id_table [] = {
931     { match_flags: USB_DEVICE_ID_MATCH_INT_CLASS,
932       bInterfaceClass: USB_CLASS_HUB},
933     { }						/* Terminating entry */
934 };
935 
936 MODULE_DEVICE_TABLE (usb, hub_id_table);
937 
938 static struct usb_driver hub_driver = {
939 	name:		"hub",
940 	probe:		hub_probe,
941 	ioctl:		hub_ioctl,
942 	disconnect:	hub_disconnect,
943 	id_table:	hub_id_table,
944 };
945 
946 /*
947  * This should be a separate module.
948  */
usb_hub_init(void)949 int usb_hub_init(void)
950 {
951 	pid_t pid;
952 
953 	if (usb_register(&hub_driver) < 0) {
954 		err("Unable to register USB hub driver");
955 		return -1;
956 	}
957 
958 	pid = kernel_thread(usb_hub_thread, NULL,
959 		CLONE_FS | CLONE_FILES | CLONE_SIGHAND);
960 	if (pid >= 0) {
961 		khubd_pid = pid;
962 
963 		return 0;
964 	}
965 
966 	/* Fall through if kernel_thread failed */
967 	usb_deregister(&hub_driver);
968 	err("failed to start usb_hub_thread");
969 
970 	return -1;
971 }
972 
usb_hub_cleanup(void)973 void usb_hub_cleanup(void)
974 {
975 	int ret;
976 
977 	/* Kill the thread */
978 	ret = kill_proc(khubd_pid, SIGTERM, 1);
979 
980 	wait_for_completion(&khubd_exited);
981 
982 	/*
983 	 * Hub resources are freed for us by usb_deregister. It calls
984 	 * usb_driver_purge on every device which in turn calls that
985 	 * devices disconnect function if it is using this driver.
986 	 * The hub_disconnect function takes care of releasing the
987 	 * individual hub resources. -greg
988 	 */
989 	usb_deregister(&hub_driver);
990 } /* usb_hub_cleanup() */
991 
992 /*
993  * WARNING - If a driver calls usb_reset_device, you should simulate a
994  * disconnect() and probe() for other interfaces you doesn't claim. This
995  * is left up to the driver writer right now. This insures other drivers
996  * have a chance to re-setup their interface.
997  *
998  * Take a look at proc_resetdevice in devio.c for some sample code to
999  * do this.
1000  */
usb_reset_device(struct usb_device * dev)1001 int usb_reset_device(struct usb_device *dev)
1002 {
1003 	struct usb_device *parent = dev->parent;
1004 	struct usb_device_descriptor *descriptor;
1005 	int i, ret, port = -1;
1006 
1007 	if (!parent) {
1008 		err("attempting to reset root hub!");
1009 		return -EINVAL;
1010 	}
1011 
1012 	for (i = 0; i < parent->maxchild; i++)
1013 		if (parent->children[i] == dev) {
1014 			port = i;
1015 			break;
1016 		}
1017 
1018 	if (port < 0)
1019 		return -ENOENT;
1020 
1021 	down(&usb_address0_sem);
1022 
1023 	/* Send a reset to the device */
1024 	if (usb_hub_port_reset(parent, port, dev, HUB_SHORT_RESET_TIME)) {
1025 		usb_hub_port_disable(parent, port);
1026 		up(&usb_address0_sem);
1027 		return(-ENODEV);
1028 	}
1029 
1030 	/* Reprogram the Address */
1031 	ret = usb_set_address(dev);
1032 	if (ret < 0) {
1033 		err("USB device not accepting new address (error=%d)", ret);
1034 		usb_hub_port_disable(parent, port);
1035 		up(&usb_address0_sem);
1036 		return ret;
1037 	}
1038 
1039 	/* Let the SET_ADDRESS settle */
1040 	wait_ms(10);
1041 
1042 	up(&usb_address0_sem);
1043 
1044 	/*
1045 	 * Now we fetch the configuration descriptors for the device and
1046 	 * see if anything has changed. If it has, we dump the current
1047 	 * parsed descriptors and reparse from scratch. Then we leave
1048 	 * the device alone for the caller to finish setting up.
1049 	 *
1050 	 * If nothing changed, we reprogram the configuration and then
1051 	 * the alternate settings.
1052 	 */
1053 	descriptor = kmalloc(sizeof *descriptor, GFP_NOIO);
1054 	if (!descriptor) {
1055 		return -ENOMEM;
1056 	}
1057 	ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, descriptor,
1058 			sizeof(*descriptor));
1059 	if (ret < 0) {
1060 		kfree(descriptor);
1061 		return ret;
1062 	}
1063 
1064 	le16_to_cpus(&descriptor->bcdUSB);
1065 	le16_to_cpus(&descriptor->idVendor);
1066 	le16_to_cpus(&descriptor->idProduct);
1067 	le16_to_cpus(&descriptor->bcdDevice);
1068 
1069 	if (memcmp(&dev->descriptor, descriptor, sizeof(*descriptor))) {
1070 		kfree(descriptor);
1071 		usb_destroy_configuration(dev);
1072 
1073 		ret = usb_get_device_descriptor(dev);
1074 		if (ret < sizeof(dev->descriptor)) {
1075 			if (ret < 0)
1076 				err("unable to get device descriptor (error=%d)", ret);
1077 			else
1078 				err("USB device descriptor short read (expected %Zi, got %i)", sizeof(dev->descriptor), ret);
1079 
1080 			clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1081 			dev->devnum = -1;
1082 			return -EIO;
1083 		}
1084 
1085 		ret = usb_get_configuration(dev);
1086 		if (ret < 0) {
1087 			err("unable to get configuration (error=%d)", ret);
1088 			usb_destroy_configuration(dev);
1089 			clear_bit(dev->devnum, &dev->bus->devmap.devicemap);
1090 			dev->devnum = -1;
1091 			return 1;
1092 		}
1093 
1094 		dev->actconfig = dev->config;
1095 		usb_set_maxpacket(dev);
1096 
1097 		return 1;
1098 	}
1099 
1100 	kfree(descriptor);
1101 
1102 	ret = usb_set_configuration(dev, dev->actconfig->bConfigurationValue);
1103 	if (ret < 0) {
1104 		err("failed to set active configuration (error=%d)", ret);
1105 		return ret;
1106 	}
1107 
1108 	for (i = 0; i < dev->actconfig->bNumInterfaces; i++) {
1109 		struct usb_interface *intf = &dev->actconfig->interface[i];
1110 		struct usb_interface_descriptor *as = &intf->altsetting[intf->act_altsetting];
1111 
1112 		ret = usb_set_interface(dev, as->bInterfaceNumber, as->bAlternateSetting);
1113 		if (ret < 0) {
1114 			err("failed to set active alternate setting for interface %d (error=%d)", i, ret);
1115 			return ret;
1116 		}
1117 	}
1118 
1119 	return 0;
1120 }
1121 
1122