• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/usb/core/
1/* Modified by Broadcom Corp. Portions Copyright (c) Broadcom Corp, 2012. */
2/*
3 * (C) Copyright Linus Torvalds 1999
4 * (C) Copyright Johannes Erdfelt 1999-2001
5 * (C) Copyright Andreas Gal 1999
6 * (C) Copyright Gregory P. Smith 1999
7 * (C) Copyright Deti Fliegl 1999
8 * (C) Copyright Randy Dunlap 2000
9 * (C) Copyright David Brownell 2000-2002
10 *
11 * This program is free software; you can redistribute it and/or modify it
12 * under the terms of the GNU General Public License as published by the
13 * Free Software Foundation; either version 2 of the License, or (at your
14 * option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
18 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
19 * for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software Foundation,
23 * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24 */
25
26#include <linux/module.h>
27#include <linux/version.h>
28#include <linux/kernel.h>
29#include <linux/slab.h>
30#include <linux/completion.h>
31#include <linux/utsname.h>
32#include <linux/mm.h>
33#include <asm/io.h>
34#include <linux/device.h>
35#include <linux/dma-mapping.h>
36#include <linux/mutex.h>
37#include <asm/irq.h>
38#include <asm/byteorder.h>
39#include <asm/unaligned.h>
40#include <linux/platform_device.h>
41#include <linux/workqueue.h>
42#include <linux/pm_runtime.h>
43
44#include <linux/usb.h>
45#include <linux/usb/hcd.h>
46
47#include "usb.h"
48
49
50/*-------------------------------------------------------------------------*/
51
52/*
53 * USB Host Controller Driver framework
54 *
55 * Plugs into usbcore (usb_bus) and lets HCDs share code, minimizing
56 * HCD-specific behaviors/bugs.
57 *
58 * This does error checks, tracks devices and urbs, and delegates to a
59 * "hc_driver" only for code (and data) that really needs to know about
60 * hardware differences.  That includes root hub registers, i/o queues,
61 * and so on ... but as little else as possible.
62 *
63 * Shared code includes most of the "root hub" code (these are emulated,
64 * though each HC's hardware works differently) and PCI glue, plus request
65 * tracking overhead.  The HCD code should only block on spinlocks or on
66 * hardware handshaking; blocking on software events (such as other kernel
67 * threads releasing resources, or completing actions) is all generic.
68 *
69 * Happens the USB 2.0 spec says this would be invisible inside the "USBD",
70 * and includes mostly a "HCDI" (HCD Interface) along with some APIs used
71 * only by the hub driver ... and that neither should be seen or used by
72 * usb client device drivers.
73 *
74 * Contributors of ideas or unattributed patches include: David Brownell,
75 * Roman Weissgaerber, Rory Bolt, Greg Kroah-Hartman, ...
76 *
77 * HISTORY:
78 * 2002-02-21	Pull in most of the usb_bus support from usb.c; some
79 *		associated cleanup.  "usb_hcd" still != "usb_bus".
80 * 2001-12-12	Initial patch version for Linux 2.5.1 kernel.
81 */
82
83/*-------------------------------------------------------------------------*/
84
85/* Keep track of which host controller drivers are loaded */
86unsigned long usb_hcds_loaded;
87EXPORT_SYMBOL_GPL(usb_hcds_loaded);
88
89/* host controllers we manage */
90LIST_HEAD (usb_bus_list);
91EXPORT_SYMBOL_GPL (usb_bus_list);
92
93/* used when allocating bus numbers */
94#define USB_MAXBUS		64
95struct usb_busmap {
96	unsigned long busmap [USB_MAXBUS / (8*sizeof (unsigned long))];
97};
98static struct usb_busmap busmap;
99
100/* used when updating list of hcds */
101DEFINE_MUTEX(usb_bus_list_lock);	/* exported only for usbfs */
102EXPORT_SYMBOL_GPL (usb_bus_list_lock);
103
104/* used for controlling access to virtual root hubs */
105static DEFINE_SPINLOCK(hcd_root_hub_lock);
106
107/* used when updating an endpoint's URB list */
108static DEFINE_SPINLOCK(hcd_urb_list_lock);
109
110/* used to protect against unlinking URBs after the device is gone */
111static DEFINE_SPINLOCK(hcd_urb_unlink_lock);
112
113/* wait queue for synchronous unlinks */
114DECLARE_WAIT_QUEUE_HEAD(usb_kill_urb_queue);
115
116static inline int is_root_hub(struct usb_device *udev)
117{
118	return (udev->parent == NULL);
119}
120
121/*-------------------------------------------------------------------------*/
122
123/*
124 * Sharable chunks of root hub code.
125 */
126
127/*-------------------------------------------------------------------------*/
128
129#define KERNEL_REL	((LINUX_VERSION_CODE >> 16) & 0x0ff)
130#define KERNEL_VER	((LINUX_VERSION_CODE >> 8) & 0x0ff)
131
132/* usb 3.0 root hub device descriptor */
133static const u8 usb3_rh_dev_descriptor[18] = {
134	0x12,       /*  __u8  bLength; */
135	0x01,       /*  __u8  bDescriptorType; Device */
136	0x00, 0x03, /*  __le16 bcdUSB; v3.0 */
137
138	0x09,	    /*  __u8  bDeviceClass; HUB_CLASSCODE */
139	0x00,	    /*  __u8  bDeviceSubClass; */
140	0x03,       /*  __u8  bDeviceProtocol; USB 3.0 hub */
141	0x09,       /*  __u8  bMaxPacketSize0; 2^9 = 512 Bytes */
142
143	0x6b, 0x1d, /*  __le16 idVendor; Linux Foundation */
144	0x03, 0x00, /*  __le16 idProduct; device 0x0003 */
145	KERNEL_VER, KERNEL_REL, /*  __le16 bcdDevice */
146
147	0x03,       /*  __u8  iManufacturer; */
148	0x02,       /*  __u8  iProduct; */
149	0x01,       /*  __u8  iSerialNumber; */
150	0x01        /*  __u8  bNumConfigurations; */
151};
152
153/* usb 2.0 root hub device descriptor */
154static const u8 usb2_rh_dev_descriptor [18] = {
155	0x12,       /*  __u8  bLength; */
156	0x01,       /*  __u8  bDescriptorType; Device */
157	0x00, 0x02, /*  __le16 bcdUSB; v2.0 */
158
159	0x09,	    /*  __u8  bDeviceClass; HUB_CLASSCODE */
160	0x00,	    /*  __u8  bDeviceSubClass; */
161	0x00,       /*  __u8  bDeviceProtocol; [ usb 2.0 no TT ] */
162	0x40,       /*  __u8  bMaxPacketSize0; 64 Bytes */
163
164	0x6b, 0x1d, /*  __le16 idVendor; Linux Foundation */
165	0x02, 0x00, /*  __le16 idProduct; device 0x0002 */
166	KERNEL_VER, KERNEL_REL, /*  __le16 bcdDevice */
167
168	0x03,       /*  __u8  iManufacturer; */
169	0x02,       /*  __u8  iProduct; */
170	0x01,       /*  __u8  iSerialNumber; */
171	0x01        /*  __u8  bNumConfigurations; */
172};
173
174/* no usb 2.0 root hub "device qualifier" descriptor: one speed only */
175
176/* usb 1.1 root hub device descriptor */
177static const u8 usb11_rh_dev_descriptor [18] = {
178	0x12,       /*  __u8  bLength; */
179	0x01,       /*  __u8  bDescriptorType; Device */
180	0x10, 0x01, /*  __le16 bcdUSB; v1.1 */
181
182	0x09,	    /*  __u8  bDeviceClass; HUB_CLASSCODE */
183	0x00,	    /*  __u8  bDeviceSubClass; */
184	0x00,       /*  __u8  bDeviceProtocol; [ low/full speeds only ] */
185	0x40,       /*  __u8  bMaxPacketSize0; 64 Bytes */
186
187	0x6b, 0x1d, /*  __le16 idVendor; Linux Foundation */
188	0x01, 0x00, /*  __le16 idProduct; device 0x0001 */
189	KERNEL_VER, KERNEL_REL, /*  __le16 bcdDevice */
190
191	0x03,       /*  __u8  iManufacturer; */
192	0x02,       /*  __u8  iProduct; */
193	0x01,       /*  __u8  iSerialNumber; */
194	0x01        /*  __u8  bNumConfigurations; */
195};
196
197
198/*-------------------------------------------------------------------------*/
199
200/* Configuration descriptors for our root hubs */
201
202static const u8 fs_rh_config_descriptor [] = {
203
204	/* one configuration */
205	0x09,       /*  __u8  bLength; */
206	0x02,       /*  __u8  bDescriptorType; Configuration */
207	0x19, 0x00, /*  __le16 wTotalLength; */
208	0x01,       /*  __u8  bNumInterfaces; (1) */
209	0x01,       /*  __u8  bConfigurationValue; */
210	0x00,       /*  __u8  iConfiguration; */
211	0xc0,       /*  __u8  bmAttributes;
212				 Bit 7: must be set,
213				     6: Self-powered,
214				     5: Remote wakeup,
215				     4..0: resvd */
216	0x00,       /*  __u8  MaxPower; */
217
218	/* USB 1.1:
219	 * USB 2.0, single TT organization (mandatory):
220	 *	one interface, protocol 0
221	 *
222	 * USB 2.0, multiple TT organization (optional):
223	 *	two interfaces, protocols 1 (like single TT)
224	 *	and 2 (multiple TT mode) ... config is
225	 *	sometimes settable
226	 *	NOT IMPLEMENTED
227	 */
228
229	/* one interface */
230	0x09,       /*  __u8  if_bLength; */
231	0x04,       /*  __u8  if_bDescriptorType; Interface */
232	0x00,       /*  __u8  if_bInterfaceNumber; */
233	0x00,       /*  __u8  if_bAlternateSetting; */
234	0x01,       /*  __u8  if_bNumEndpoints; */
235	0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
236	0x00,       /*  __u8  if_bInterfaceSubClass; */
237	0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
238	0x00,       /*  __u8  if_iInterface; */
239
240	/* one endpoint (status change endpoint) */
241	0x07,       /*  __u8  ep_bLength; */
242	0x05,       /*  __u8  ep_bDescriptorType; Endpoint */
243	0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
244 	0x03,       /*  __u8  ep_bmAttributes; Interrupt */
245 	0x02, 0x00, /*  __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
246	0xff        /*  __u8  ep_bInterval; (255ms -- usb 2.0 spec) */
247};
248
249static const u8 hs_rh_config_descriptor [] = {
250
251	/* one configuration */
252	0x09,       /*  __u8  bLength; */
253	0x02,       /*  __u8  bDescriptorType; Configuration */
254	0x19, 0x00, /*  __le16 wTotalLength; */
255	0x01,       /*  __u8  bNumInterfaces; (1) */
256	0x01,       /*  __u8  bConfigurationValue; */
257	0x00,       /*  __u8  iConfiguration; */
258	0xc0,       /*  __u8  bmAttributes;
259				 Bit 7: must be set,
260				     6: Self-powered,
261				     5: Remote wakeup,
262				     4..0: resvd */
263	0x00,       /*  __u8  MaxPower; */
264
265	/* USB 1.1:
266	 * USB 2.0, single TT organization (mandatory):
267	 *	one interface, protocol 0
268	 *
269	 * USB 2.0, multiple TT organization (optional):
270	 *	two interfaces, protocols 1 (like single TT)
271	 *	and 2 (multiple TT mode) ... config is
272	 *	sometimes settable
273	 *	NOT IMPLEMENTED
274	 */
275
276	/* one interface */
277	0x09,       /*  __u8  if_bLength; */
278	0x04,       /*  __u8  if_bDescriptorType; Interface */
279	0x00,       /*  __u8  if_bInterfaceNumber; */
280	0x00,       /*  __u8  if_bAlternateSetting; */
281	0x01,       /*  __u8  if_bNumEndpoints; */
282	0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
283	0x00,       /*  __u8  if_bInterfaceSubClass; */
284	0x00,       /*  __u8  if_bInterfaceProtocol; [usb1.1 or single tt] */
285	0x00,       /*  __u8  if_iInterface; */
286
287	/* one endpoint (status change endpoint) */
288	0x07,       /*  __u8  ep_bLength; */
289	0x05,       /*  __u8  ep_bDescriptorType; Endpoint */
290	0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
291 	0x03,       /*  __u8  ep_bmAttributes; Interrupt */
292		    /* __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8)
293		     * see hub.c:hub_configure() for details. */
294	(USB_MAXCHILDREN + 1 + 7) / 8, 0x00,
295	0x0c        /*  __u8  ep_bInterval; (256ms -- usb 2.0 spec) */
296};
297
298static const u8 ss_rh_config_descriptor[] = {
299	/* one configuration */
300	0x09,       /*  __u8  bLength; */
301	0x02,       /*  __u8  bDescriptorType; Configuration */
302	0x19, 0x00,
303	0x01,       /*  __u8  bNumInterfaces; (1) */
304	0x01,       /*  __u8  bConfigurationValue; */
305	0x00,       /*  __u8  iConfiguration; */
306	0xc0,       /*  __u8  bmAttributes;
307				 Bit 7: must be set,
308				     6: Self-powered,
309				     5: Remote wakeup,
310				     4..0: resvd */
311	0x00,       /*  __u8  MaxPower; */
312
313	/* one interface */
314	0x09,       /*  __u8  if_bLength; */
315	0x04,       /*  __u8  if_bDescriptorType; Interface */
316	0x00,       /*  __u8  if_bInterfaceNumber; */
317	0x00,       /*  __u8  if_bAlternateSetting; */
318	0x01,       /*  __u8  if_bNumEndpoints; */
319	0x09,       /*  __u8  if_bInterfaceClass; HUB_CLASSCODE */
320	0x00,       /*  __u8  if_bInterfaceSubClass; */
321	0x00,       /*  __u8  if_bInterfaceProtocol; */
322	0x00,       /*  __u8  if_iInterface; */
323
324	/* one endpoint (status change endpoint) */
325	0x07,       /*  __u8  ep_bLength; */
326	0x05,       /*  __u8  ep_bDescriptorType; Endpoint */
327	0x81,       /*  __u8  ep_bEndpointAddress; IN Endpoint 1 */
328	0x03,       /*  __u8  ep_bmAttributes; Interrupt */
329		    /* __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8)
330		     * see hub.c:hub_configure() for details. */
331	(USB_MAXCHILDREN + 1 + 7) / 8, 0x00,
332	0x0c        /*  __u8  ep_bInterval; (256ms -- usb 2.0 spec) */
333};
334
335/*-------------------------------------------------------------------------*/
336
337/**
338 * ascii2desc() - Helper routine for producing UTF-16LE string descriptors
339 * @s: Null-terminated ASCII (actually ISO-8859-1) string
340 * @buf: Buffer for USB string descriptor (header + UTF-16LE)
341 * @len: Length (in bytes; may be odd) of descriptor buffer.
342 *
343 * The return value is the number of bytes filled in: 2 + 2*strlen(s) or
344 * buflen, whichever is less.
345 *
346 * USB String descriptors can contain at most 126 characters; input
347 * strings longer than that are truncated.
348 */
349static unsigned
350ascii2desc(char const *s, u8 *buf, unsigned len)
351{
352	unsigned n, t = 2 + 2*strlen(s);
353
354	if (t > 254)
355		t = 254;	/* Longest possible UTF string descriptor */
356	if (len > t)
357		len = t;
358
359	t += USB_DT_STRING << 8;	/* Now t is first 16 bits to store */
360
361	n = len;
362	while (n--) {
363		*buf++ = t;
364		if (!n--)
365			break;
366		*buf++ = t >> 8;
367		t = (unsigned char)*s++;
368	}
369	return len;
370}
371
372/**
373 * rh_string() - provides string descriptors for root hub
374 * @id: the string ID number (0: langids, 1: serial #, 2: product, 3: vendor)
375 * @hcd: the host controller for this root hub
376 * @data: buffer for output packet
377 * @len: length of the provided buffer
378 *
379 * Produces either a manufacturer, product or serial number string for the
380 * virtual root hub device.
381 * Returns the number of bytes filled in: the length of the descriptor or
382 * of the provided buffer, whichever is less.
383 */
384static unsigned
385rh_string(int id, struct usb_hcd const *hcd, u8 *data, unsigned len)
386{
387	char buf[100];
388	char const *s;
389	static char const langids[4] = {4, USB_DT_STRING, 0x09, 0x04};
390
391	// language ids
392	switch (id) {
393	case 0:
394		/* Array of LANGID codes (0x0409 is MSFT-speak for "en-us") */
395		/* See http://www.usb.org/developers/docs/USB_LANGIDs.pdf */
396		if (len > 4)
397			len = 4;
398		memcpy(data, langids, len);
399		return len;
400	case 1:
401		/* Serial number */
402		s = hcd->self.bus_name;
403		break;
404	case 2:
405		/* Product name */
406		s = hcd->product_desc;
407		break;
408	case 3:
409		/* Manufacturer */
410		snprintf (buf, sizeof buf, "%s %s %s", init_utsname()->sysname,
411			init_utsname()->release, hcd->driver->description);
412		s = buf;
413		break;
414	default:
415		/* Can't happen; caller guarantees it */
416		return 0;
417	}
418
419	return ascii2desc(s, data, len);
420}
421
422
423/* Root hub control transfers execute synchronously */
424static int rh_call_control (struct usb_hcd *hcd, struct urb *urb)
425{
426	struct usb_ctrlrequest *cmd;
427 	u16		typeReq, wValue, wIndex, wLength;
428	u8		*ubuf = urb->transfer_buffer;
429	u8		tbuf [sizeof (struct usb_hub_descriptor)]
430		__attribute__((aligned(4)));
431	const u8	*bufp = tbuf;
432	unsigned	len = 0;
433	int		status;
434	u8		patch_wakeup = 0;
435	u8		patch_protocol = 0;
436
437	might_sleep();
438
439	spin_lock_irq(&hcd_root_hub_lock);
440	status = usb_hcd_link_urb_to_ep(hcd, urb);
441	spin_unlock_irq(&hcd_root_hub_lock);
442	if (status)
443		return status;
444	urb->hcpriv = hcd;	/* Indicate it's queued */
445
446	cmd = (struct usb_ctrlrequest *) urb->setup_packet;
447	typeReq  = (cmd->bRequestType << 8) | cmd->bRequest;
448	wValue   = le16_to_cpu (cmd->wValue);
449	wIndex   = le16_to_cpu (cmd->wIndex);
450	wLength  = le16_to_cpu (cmd->wLength);
451
452	if (wLength > urb->transfer_buffer_length)
453		goto error;
454
455	urb->actual_length = 0;
456	switch (typeReq) {
457
458	/* DEVICE REQUESTS */
459
460	/* The root hub's remote wakeup enable bit is implemented using
461	 * driver model wakeup flags.  If this system supports wakeup
462	 * through USB, userspace may change the default "allow wakeup"
463	 * policy through sysfs or these calls.
464	 *
465	 * Most root hubs support wakeup from downstream devices, for
466	 * runtime power management (disabling USB clocks and reducing
467	 * VBUS power usage).  However, not all of them do so; silicon,
468	 * board, and BIOS bugs here are not uncommon, so these can't
469	 * be treated quite like external hubs.
470	 *
471	 * Likewise, not all root hubs will pass wakeup events upstream,
472	 * to wake up the whole system.  So don't assume root hub and
473	 * controller capabilities are identical.
474	 */
475
476	case DeviceRequest | USB_REQ_GET_STATUS:
477		tbuf [0] = (device_may_wakeup(&hcd->self.root_hub->dev)
478					<< USB_DEVICE_REMOTE_WAKEUP)
479				| (1 << USB_DEVICE_SELF_POWERED);
480		tbuf [1] = 0;
481		len = 2;
482		break;
483	case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
484		if (wValue == USB_DEVICE_REMOTE_WAKEUP)
485			device_set_wakeup_enable(&hcd->self.root_hub->dev, 0);
486		else
487			goto error;
488		break;
489	case DeviceOutRequest | USB_REQ_SET_FEATURE:
490		if (device_can_wakeup(&hcd->self.root_hub->dev)
491				&& wValue == USB_DEVICE_REMOTE_WAKEUP)
492			device_set_wakeup_enable(&hcd->self.root_hub->dev, 1);
493		else
494			goto error;
495		break;
496	case DeviceRequest | USB_REQ_GET_CONFIGURATION:
497		tbuf [0] = 1;
498		len = 1;
499			/* FALLTHROUGH */
500	case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
501		break;
502	case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
503		switch (wValue & 0xff00) {
504		case USB_DT_DEVICE << 8:
505			switch (hcd->driver->flags & HCD_MASK) {
506			case HCD_USB3:
507				bufp = usb3_rh_dev_descriptor;
508				break;
509			case HCD_USB2:
510				bufp = usb2_rh_dev_descriptor;
511				break;
512			case HCD_USB11:
513				bufp = usb11_rh_dev_descriptor;
514				break;
515			default:
516				goto error;
517			}
518			len = 18;
519			if (hcd->has_tt)
520				patch_protocol = 1;
521			break;
522		case USB_DT_CONFIG << 8:
523			switch (hcd->driver->flags & HCD_MASK) {
524			case HCD_USB3:
525				bufp = ss_rh_config_descriptor;
526				len = sizeof ss_rh_config_descriptor;
527				break;
528			case HCD_USB2:
529				bufp = hs_rh_config_descriptor;
530				len = sizeof hs_rh_config_descriptor;
531				break;
532			case HCD_USB11:
533				bufp = fs_rh_config_descriptor;
534				len = sizeof fs_rh_config_descriptor;
535				break;
536			default:
537				goto error;
538			}
539			if (device_can_wakeup(&hcd->self.root_hub->dev))
540				patch_wakeup = 1;
541			break;
542		case USB_DT_STRING << 8:
543			if ((wValue & 0xff) < 4)
544				urb->actual_length = rh_string(wValue & 0xff,
545						hcd, ubuf, wLength);
546			else /* unsupported IDs --> "protocol stall" */
547				goto error;
548			break;
549		default:
550			goto error;
551		}
552		break;
553	case DeviceRequest | USB_REQ_GET_INTERFACE:
554		tbuf [0] = 0;
555		len = 1;
556			/* FALLTHROUGH */
557	case DeviceOutRequest | USB_REQ_SET_INTERFACE:
558		break;
559	case DeviceOutRequest | USB_REQ_SET_ADDRESS:
560		// wValue == urb->dev->devaddr
561		dev_dbg (hcd->self.controller, "root hub device address %d\n",
562			wValue);
563		break;
564
565	/* INTERFACE REQUESTS (no defined feature/status flags) */
566
567	/* ENDPOINT REQUESTS */
568
569	case EndpointRequest | USB_REQ_GET_STATUS:
570		// ENDPOINT_HALT flag
571		tbuf [0] = 0;
572		tbuf [1] = 0;
573		len = 2;
574			/* FALLTHROUGH */
575	case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
576	case EndpointOutRequest | USB_REQ_SET_FEATURE:
577		dev_dbg (hcd->self.controller, "no endpoint features yet\n");
578		break;
579
580	/* CLASS REQUESTS (and errors) */
581
582	default:
583		/* non-generic request */
584		switch (typeReq) {
585		case GetHubStatus:
586		case GetPortStatus:
587			len = 4;
588			break;
589		case GetHubDescriptor:
590			len = sizeof (struct usb_hub_descriptor);
591			break;
592		}
593		status = hcd->driver->hub_control (hcd,
594			typeReq, wValue, wIndex,
595			tbuf, wLength);
596		break;
597error:
598		/* "protocol stall" on error */
599		status = -EPIPE;
600	}
601
602	if (status) {
603		len = 0;
604		if (status != -EPIPE) {
605			dev_dbg (hcd->self.controller,
606				"CTRL: TypeReq=0x%x val=0x%x "
607				"idx=0x%x len=%d ==> %d\n",
608				typeReq, wValue, wIndex,
609				wLength, status);
610		}
611	}
612	if (len) {
613		if (urb->transfer_buffer_length < len)
614			len = urb->transfer_buffer_length;
615		urb->actual_length = len;
616		// always USB_DIR_IN, toward host
617		memcpy (ubuf, bufp, len);
618
619		/* report whether RH hardware supports remote wakeup */
620		if (patch_wakeup &&
621				len > offsetof (struct usb_config_descriptor,
622						bmAttributes))
623			((struct usb_config_descriptor *)ubuf)->bmAttributes
624				|= USB_CONFIG_ATT_WAKEUP;
625
626		/* report whether RH hardware has an integrated TT */
627		if (patch_protocol &&
628				len > offsetof(struct usb_device_descriptor,
629						bDeviceProtocol))
630			((struct usb_device_descriptor *) ubuf)->
631					bDeviceProtocol = 1;
632	}
633
634	/* any errors get returned through the urb completion */
635	spin_lock_irq(&hcd_root_hub_lock);
636	usb_hcd_unlink_urb_from_ep(hcd, urb);
637
638	/* This peculiar use of spinlocks echoes what real HC drivers do.
639	 * Avoiding calls to local_irq_disable/enable makes the code
640	 * RT-friendly.
641	 */
642	spin_unlock(&hcd_root_hub_lock);
643	usb_hcd_giveback_urb(hcd, urb, status);
644	spin_lock(&hcd_root_hub_lock);
645
646	spin_unlock_irq(&hcd_root_hub_lock);
647	return 0;
648}
649
650/*-------------------------------------------------------------------------*/
651
652/*
653 * Root Hub interrupt transfers are polled using a timer if the
654 * driver requests it; otherwise the driver is responsible for
655 * calling usb_hcd_poll_rh_status() when an event occurs.
656 *
657 * Completions are called in_interrupt(), but they may or may not
658 * be in_irq().
659 */
660void usb_hcd_poll_rh_status(struct usb_hcd *hcd)
661{
662	struct urb	*urb;
663	int		length;
664	unsigned long	flags;
665	char		buffer[6];	/* Any root hubs with > 31 ports? */
666
667	if (unlikely(!hcd->rh_pollable))
668		return;
669	if (!hcd->uses_new_polling && !hcd->status_urb)
670		return;
671
672	length = hcd->driver->hub_status_data(hcd, buffer);
673	if (length > 0) {
674
675		/* try to complete the status urb */
676		spin_lock_irqsave(&hcd_root_hub_lock, flags);
677		urb = hcd->status_urb;
678		if (urb) {
679			clear_bit(HCD_FLAG_POLL_PENDING, &hcd->flags);
680			hcd->status_urb = NULL;
681			urb->actual_length = length;
682			memcpy(urb->transfer_buffer, buffer, length);
683
684			usb_hcd_unlink_urb_from_ep(hcd, urb);
685			spin_unlock(&hcd_root_hub_lock);
686			usb_hcd_giveback_urb(hcd, urb, 0);
687			spin_lock(&hcd_root_hub_lock);
688		} else {
689			length = 0;
690			set_bit(HCD_FLAG_POLL_PENDING, &hcd->flags);
691		}
692		spin_unlock_irqrestore(&hcd_root_hub_lock, flags);
693	}
694
695	/* The USB 2.0 spec says 256 ms.  This is close enough and won't
696	 * exceed that limit if HZ is 100. The math is more clunky than
697	 * maybe expected, this is to make sure that all timers for USB devices
698	 * fire at the same time to give the CPU a break inbetween */
699	if (hcd->uses_new_polling ? HCD_POLL_RH(hcd) :
700			(length == 0 && hcd->status_urb != NULL))
701		mod_timer (&hcd->rh_timer, (jiffies/(HZ/4) + 1) * (HZ/4));
702}
703EXPORT_SYMBOL_GPL(usb_hcd_poll_rh_status);
704
705/* timer callback */
706static void rh_timer_func (unsigned long _hcd)
707{
708	usb_hcd_poll_rh_status((struct usb_hcd *) _hcd);
709}
710
711/*-------------------------------------------------------------------------*/
712
713static int rh_queue_status (struct usb_hcd *hcd, struct urb *urb)
714{
715	int		retval;
716	unsigned long	flags;
717	unsigned	len = 1 + (urb->dev->maxchild / 8);
718
719	spin_lock_irqsave (&hcd_root_hub_lock, flags);
720	if (hcd->status_urb || urb->transfer_buffer_length < len) {
721		dev_dbg (hcd->self.controller, "not queuing rh status urb\n");
722		retval = -EINVAL;
723		goto done;
724	}
725
726	retval = usb_hcd_link_urb_to_ep(hcd, urb);
727	if (retval)
728		goto done;
729
730	hcd->status_urb = urb;
731	urb->hcpriv = hcd;	/* indicate it's queued */
732	if (!hcd->uses_new_polling)
733		mod_timer(&hcd->rh_timer, (jiffies/(HZ/4) + 1) * (HZ/4));
734
735	/* If a status change has already occurred, report it ASAP */
736	else if (HCD_POLL_PENDING(hcd))
737		mod_timer(&hcd->rh_timer, jiffies);
738	retval = 0;
739 done:
740	spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
741	return retval;
742}
743
744static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
745{
746	if (usb_endpoint_xfer_int(&urb->ep->desc))
747		return rh_queue_status (hcd, urb);
748	if (usb_endpoint_xfer_control(&urb->ep->desc))
749		return rh_call_control (hcd, urb);
750	return -EINVAL;
751}
752
753/*-------------------------------------------------------------------------*/
754
755/* Unlinks of root-hub control URBs are legal, but they don't do anything
756 * since these URBs always execute synchronously.
757 */
758static int usb_rh_urb_dequeue(struct usb_hcd *hcd, struct urb *urb, int status)
759{
760	unsigned long	flags;
761	int		rc;
762
763	spin_lock_irqsave(&hcd_root_hub_lock, flags);
764	rc = usb_hcd_check_unlink_urb(hcd, urb, status);
765	if (rc)
766		goto done;
767
768	if (usb_endpoint_num(&urb->ep->desc) == 0) {	/* Control URB */
769		;	/* Do nothing */
770
771	} else {				/* Status URB */
772		if (!hcd->uses_new_polling)
773			del_timer (&hcd->rh_timer);
774		if (urb == hcd->status_urb) {
775			hcd->status_urb = NULL;
776			usb_hcd_unlink_urb_from_ep(hcd, urb);
777
778			spin_unlock(&hcd_root_hub_lock);
779			usb_hcd_giveback_urb(hcd, urb, status);
780			spin_lock(&hcd_root_hub_lock);
781		}
782	}
783 done:
784	spin_unlock_irqrestore(&hcd_root_hub_lock, flags);
785	return rc;
786}
787
788
789
790/*
791 * Show & store the current value of authorized_default
792 */
793static ssize_t usb_host_authorized_default_show(struct device *dev,
794						struct device_attribute *attr,
795						char *buf)
796{
797	struct usb_device *rh_usb_dev = to_usb_device(dev);
798	struct usb_bus *usb_bus = rh_usb_dev->bus;
799	struct usb_hcd *usb_hcd;
800
801	if (usb_bus == NULL)
802		return -ENODEV;
803	usb_hcd = bus_to_hcd(usb_bus);
804	return snprintf(buf, PAGE_SIZE, "%u\n", usb_hcd->authorized_default);
805}
806
807static ssize_t usb_host_authorized_default_store(struct device *dev,
808						 struct device_attribute *attr,
809						 const char *buf, size_t size)
810{
811	ssize_t result;
812	unsigned val;
813	struct usb_device *rh_usb_dev = to_usb_device(dev);
814	struct usb_bus *usb_bus = rh_usb_dev->bus;
815	struct usb_hcd *usb_hcd;
816
817	if (usb_bus == NULL)
818		return -ENODEV;
819	usb_hcd = bus_to_hcd(usb_bus);
820	result = sscanf(buf, "%u\n", &val);
821	if (result == 1) {
822		usb_hcd->authorized_default = val? 1 : 0;
823		result = size;
824	}
825	else
826		result = -EINVAL;
827	return result;
828}
829
830static DEVICE_ATTR(authorized_default, 0644,
831	    usb_host_authorized_default_show,
832	    usb_host_authorized_default_store);
833
834
835/* Group all the USB bus attributes */
836static struct attribute *usb_bus_attrs[] = {
837		&dev_attr_authorized_default.attr,
838		NULL,
839};
840
841static struct attribute_group usb_bus_attr_group = {
842	.name = NULL,	/* we want them in the same directory */
843	.attrs = usb_bus_attrs,
844};
845
846
847
848/*-------------------------------------------------------------------------*/
849
850/**
851 * usb_bus_init - shared initialization code
852 * @bus: the bus structure being initialized
853 *
854 * This code is used to initialize a usb_bus structure, memory for which is
855 * separately managed.
856 */
857static void usb_bus_init (struct usb_bus *bus)
858{
859	memset (&bus->devmap, 0, sizeof(struct usb_devmap));
860
861	bus->devnum_next = 1;
862
863	bus->root_hub = NULL;
864	bus->busnum = -1;
865	bus->bandwidth_allocated = 0;
866	bus->bandwidth_int_reqs  = 0;
867	bus->bandwidth_isoc_reqs = 0;
868
869	INIT_LIST_HEAD (&bus->bus_list);
870}
871
872/*-------------------------------------------------------------------------*/
873
874/**
875 * usb_register_bus - registers the USB host controller with the usb core
876 * @bus: pointer to the bus to register
877 * Context: !in_interrupt()
878 *
879 * Assigns a bus number, and links the controller into usbcore data
880 * structures so that it can be seen by scanning the bus list.
881 */
882static int usb_register_bus(struct usb_bus *bus)
883{
884	int result = -E2BIG;
885	int busnum;
886
887	mutex_lock(&usb_bus_list_lock);
888	busnum = find_next_zero_bit (busmap.busmap, USB_MAXBUS, 1);
889	if (busnum >= USB_MAXBUS) {
890		printk (KERN_ERR "%s: too many buses\n", usbcore_name);
891		goto error_find_busnum;
892	}
893	set_bit (busnum, busmap.busmap);
894	bus->busnum = busnum;
895
896	/* Add it to the local list of buses */
897	list_add (&bus->bus_list, &usb_bus_list);
898	mutex_unlock(&usb_bus_list_lock);
899
900	usb_notify_add_bus(bus);
901
902	dev_info (bus->controller, "new USB bus registered, assigned bus "
903		  "number %d\n", bus->busnum);
904	return 0;
905
906error_find_busnum:
907	mutex_unlock(&usb_bus_list_lock);
908	return result;
909}
910
911/**
912 * usb_deregister_bus - deregisters the USB host controller
913 * @bus: pointer to the bus to deregister
914 * Context: !in_interrupt()
915 *
916 * Recycles the bus number, and unlinks the controller from usbcore data
917 * structures so that it won't be seen by scanning the bus list.
918 */
919static void usb_deregister_bus (struct usb_bus *bus)
920{
921	dev_info (bus->controller, "USB bus %d deregistered\n", bus->busnum);
922
923	/*
924	 * NOTE: make sure that all the devices are removed by the
925	 * controller code, as well as having it call this when cleaning
926	 * itself up
927	 */
928	mutex_lock(&usb_bus_list_lock);
929	list_del (&bus->bus_list);
930	mutex_unlock(&usb_bus_list_lock);
931
932	usb_notify_remove_bus(bus);
933
934	clear_bit (bus->busnum, busmap.busmap);
935}
936
937/**
938 * register_root_hub - called by usb_add_hcd() to register a root hub
939 * @hcd: host controller for this root hub
940 *
941 * This function registers the root hub with the USB subsystem.  It sets up
942 * the device properly in the device tree and then calls usb_new_device()
943 * to register the usb device.  It also assigns the root hub's USB address
944 * (always 1).
945 */
946static int register_root_hub(struct usb_hcd *hcd)
947{
948	struct device *parent_dev = hcd->self.controller;
949	struct usb_device *usb_dev = hcd->self.root_hub;
950	const int devnum = 1;
951	int retval;
952
953	usb_dev->devnum = devnum;
954	usb_dev->bus->devnum_next = devnum + 1;
955	memset (&usb_dev->bus->devmap.devicemap, 0,
956			sizeof usb_dev->bus->devmap.devicemap);
957	set_bit (devnum, usb_dev->bus->devmap.devicemap);
958	usb_set_device_state(usb_dev, USB_STATE_ADDRESS);
959
960	mutex_lock(&usb_bus_list_lock);
961
962	usb_dev->ep0.desc.wMaxPacketSize = cpu_to_le16(64);
963	retval = usb_get_device_descriptor(usb_dev, USB_DT_DEVICE_SIZE);
964	if (retval != sizeof usb_dev->descriptor) {
965		mutex_unlock(&usb_bus_list_lock);
966		dev_dbg (parent_dev, "can't read %s device descriptor %d\n",
967				dev_name(&usb_dev->dev), retval);
968		return (retval < 0) ? retval : -EMSGSIZE;
969	}
970
971	retval = usb_new_device (usb_dev);
972	if (retval) {
973		dev_err (parent_dev, "can't register root hub for %s, %d\n",
974				dev_name(&usb_dev->dev), retval);
975	}
976	mutex_unlock(&usb_bus_list_lock);
977
978	if (retval == 0) {
979		spin_lock_irq (&hcd_root_hub_lock);
980		hcd->rh_registered = 1;
981		spin_unlock_irq (&hcd_root_hub_lock);
982
983		/* Did the HC die before the root hub was registered? */
984		if (hcd->state == HC_STATE_HALT)
985			usb_hc_died (hcd);	/* This time clean up */
986	}
987
988	return retval;
989}
990
991
992/*-------------------------------------------------------------------------*/
993
994/**
995 * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
996 * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
997 * @is_input: true iff the transaction sends data to the host
998 * @isoc: true for isochronous transactions, false for interrupt ones
999 * @bytecount: how many bytes in the transaction.
1000 *
1001 * Returns approximate bus time in nanoseconds for a periodic transaction.
1002 * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
1003 * scheduled in software, this function is only used for such scheduling.
1004 */
1005long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
1006{
1007	unsigned long	tmp;
1008
1009	switch (speed) {
1010	case USB_SPEED_LOW: 	/* INTR only */
1011		if (is_input) {
1012			tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
1013			return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
1014		} else {
1015			tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
1016			return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
1017		}
1018	case USB_SPEED_FULL:	/* ISOC or INTR */
1019		if (isoc) {
1020			tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
1021			return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
1022		} else {
1023			tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
1024			return (9107L + BW_HOST_DELAY + tmp);
1025		}
1026	case USB_SPEED_HIGH:	/* ISOC or INTR */
1027		if (isoc)
1028			tmp = HS_NSECS_ISO (bytecount);
1029		else
1030			tmp = HS_NSECS (bytecount);
1031		return tmp;
1032	default:
1033		pr_debug ("%s: bogus device speed!\n", usbcore_name);
1034		return -1;
1035	}
1036}
1037EXPORT_SYMBOL_GPL(usb_calc_bus_time);
1038
1039
1040/*-------------------------------------------------------------------------*/
1041
1042/*
1043 * Generic HC operations.
1044 */
1045
1046/*-------------------------------------------------------------------------*/
1047
1048/**
1049 * usb_hcd_link_urb_to_ep - add an URB to its endpoint queue
1050 * @hcd: host controller to which @urb was submitted
1051 * @urb: URB being submitted
1052 *
1053 * Host controller drivers should call this routine in their enqueue()
1054 * method.  The HCD's private spinlock must be held and interrupts must
1055 * be disabled.  The actions carried out here are required for URB
1056 * submission, as well as for endpoint shutdown and for usb_kill_urb.
1057 *
1058 * Returns 0 for no error, otherwise a negative error code (in which case
1059 * the enqueue() method must fail).  If no error occurs but enqueue() fails
1060 * anyway, it must call usb_hcd_unlink_urb_from_ep() before releasing
1061 * the private spinlock and returning.
1062 */
1063int usb_hcd_link_urb_to_ep(struct usb_hcd *hcd, struct urb *urb)
1064{
1065	int		rc = 0;
1066
1067	spin_lock(&hcd_urb_list_lock);
1068
1069	/* Check that the URB isn't being killed */
1070	if (unlikely(atomic_read(&urb->reject))) {
1071		rc = -EPERM;
1072		goto done;
1073	}
1074
1075	if (unlikely(!urb->ep->enabled)) {
1076		rc = -ENOENT;
1077		goto done;
1078	}
1079
1080	if (unlikely(!urb->dev->can_submit)) {
1081		rc = -EHOSTUNREACH;
1082		goto done;
1083	}
1084
1085	/*
1086	 * Check the host controller's state and add the URB to the
1087	 * endpoint's queue.
1088	 */
1089	switch (hcd->state) {
1090	case HC_STATE_RUNNING:
1091	case HC_STATE_RESUMING:
1092		urb->unlinked = 0;
1093		list_add_tail(&urb->urb_list, &urb->ep->urb_list);
1094		break;
1095	default:
1096		rc = -ESHUTDOWN;
1097		goto done;
1098	}
1099 done:
1100	spin_unlock(&hcd_urb_list_lock);
1101	return rc;
1102}
1103EXPORT_SYMBOL_GPL(usb_hcd_link_urb_to_ep);
1104
1105/**
1106 * usb_hcd_check_unlink_urb - check whether an URB may be unlinked
1107 * @hcd: host controller to which @urb was submitted
1108 * @urb: URB being checked for unlinkability
1109 * @status: error code to store in @urb if the unlink succeeds
1110 *
1111 * Host controller drivers should call this routine in their dequeue()
1112 * method.  The HCD's private spinlock must be held and interrupts must
1113 * be disabled.  The actions carried out here are required for making
1114 * sure than an unlink is valid.
1115 *
1116 * Returns 0 for no error, otherwise a negative error code (in which case
1117 * the dequeue() method must fail).  The possible error codes are:
1118 *
1119 *	-EIDRM: @urb was not submitted or has already completed.
1120 *		The completion function may not have been called yet.
1121 *
1122 *	-EBUSY: @urb has already been unlinked.
1123 */
1124int usb_hcd_check_unlink_urb(struct usb_hcd *hcd, struct urb *urb,
1125		int status)
1126{
1127	struct list_head	*tmp;
1128
1129	/* insist the urb is still queued */
1130	list_for_each(tmp, &urb->ep->urb_list) {
1131		if (tmp == &urb->urb_list)
1132			break;
1133	}
1134	if (tmp != &urb->urb_list)
1135		return -EIDRM;
1136
1137	/* Any status except -EINPROGRESS means something already started to
1138	 * unlink this URB from the hardware.  So there's no more work to do.
1139	 */
1140	if (urb->unlinked)
1141		return -EBUSY;
1142	urb->unlinked = status;
1143
1144	/* IRQ setup can easily be broken so that USB controllers
1145	 * never get completion IRQs ... maybe even the ones we need to
1146	 * finish unlinking the initial failed usb_set_address()
1147	 * or device descriptor fetch.
1148	 */
1149	if (!HCD_SAW_IRQ(hcd) && !is_root_hub(urb->dev)) {
1150		dev_warn(hcd->self.controller, "Unlink after no-IRQ?  "
1151			"Controller is probably using the wrong IRQ.\n");
1152		set_bit(HCD_FLAG_SAW_IRQ, &hcd->flags);
1153	}
1154
1155	return 0;
1156}
1157EXPORT_SYMBOL_GPL(usb_hcd_check_unlink_urb);
1158
1159/**
1160 * usb_hcd_unlink_urb_from_ep - remove an URB from its endpoint queue
1161 * @hcd: host controller to which @urb was submitted
1162 * @urb: URB being unlinked
1163 *
1164 * Host controller drivers should call this routine before calling
1165 * usb_hcd_giveback_urb().  The HCD's private spinlock must be held and
1166 * interrupts must be disabled.  The actions carried out here are required
1167 * for URB completion.
1168 */
1169void usb_hcd_unlink_urb_from_ep(struct usb_hcd *hcd, struct urb *urb)
1170{
1171	/* clear all state linking urb to this dev (and hcd) */
1172	spin_lock(&hcd_urb_list_lock);
1173	list_del_init(&urb->urb_list);
1174	spin_unlock(&hcd_urb_list_lock);
1175}
1176EXPORT_SYMBOL_GPL(usb_hcd_unlink_urb_from_ep);
1177
1178/*
1179 * Some usb host controllers can only perform dma using a small SRAM area.
1180 * The usb core itself is however optimized for host controllers that can dma
1181 * using regular system memory - like pci devices doing bus mastering.
1182 *
1183 * To support host controllers with limited dma capabilites we provide dma
1184 * bounce buffers. This feature can be enabled using the HCD_LOCAL_MEM flag.
1185 * For this to work properly the host controller code must first use the
1186 * function dma_declare_coherent_memory() to point out which memory area
1187 * that should be used for dma allocations.
1188 *
1189 * The HCD_LOCAL_MEM flag then tells the usb code to allocate all data for
1190 * dma using dma_alloc_coherent() which in turn allocates from the memory
1191 * area pointed out with dma_declare_coherent_memory().
1192 *
1193 * So, to summarize...
1194 *
1195 * - We need "local" memory, canonical example being
1196 *   a small SRAM on a discrete controller being the
1197 *   only memory that the controller can read ...
1198 *   (a) "normal" kernel memory is no good, and
1199 *   (b) there's not enough to share
1200 *
1201 * - The only *portable* hook for such stuff in the
1202 *   DMA framework is dma_declare_coherent_memory()
1203 *
1204 * - So we use that, even though the primary requirement
1205 *   is that the memory be "local" (hence addressible
1206 *   by that device), not "coherent".
1207 *
1208 */
1209
1210static int hcd_alloc_coherent(struct usb_bus *bus,
1211			      gfp_t mem_flags, dma_addr_t *dma_handle,
1212			      void **vaddr_handle, size_t size,
1213			      enum dma_data_direction dir)
1214{
1215	unsigned char *vaddr;
1216
1217	if (*vaddr_handle == NULL) {
1218		WARN_ON_ONCE(1);
1219		return -EFAULT;
1220	}
1221
1222	vaddr = hcd_buffer_alloc(bus, size + sizeof(vaddr),
1223				 mem_flags, dma_handle);
1224	if (!vaddr)
1225		return -ENOMEM;
1226
1227	/*
1228	 * Store the virtual address of the buffer at the end
1229	 * of the allocated dma buffer. The size of the buffer
1230	 * may be uneven so use unaligned functions instead
1231	 * of just rounding up. It makes sense to optimize for
1232	 * memory footprint over access speed since the amount
1233	 * of memory available for dma may be limited.
1234	 */
1235	put_unaligned((unsigned long)*vaddr_handle,
1236		      (unsigned long *)(vaddr + size));
1237
1238	if (dir == DMA_TO_DEVICE)
1239		memcpy(vaddr, *vaddr_handle, size);
1240
1241	*vaddr_handle = vaddr;
1242	return 0;
1243}
1244
1245static void hcd_free_coherent(struct usb_bus *bus, dma_addr_t *dma_handle,
1246			      void **vaddr_handle, size_t size,
1247			      enum dma_data_direction dir)
1248{
1249	unsigned char *vaddr = *vaddr_handle;
1250
1251	vaddr = (void *)get_unaligned((unsigned long *)(vaddr + size));
1252
1253	if (dir == DMA_FROM_DEVICE)
1254		memcpy(vaddr, *vaddr_handle, size);
1255
1256	hcd_buffer_free(bus, size + sizeof(vaddr), *vaddr_handle, *dma_handle);
1257
1258	*vaddr_handle = vaddr;
1259	*dma_handle = 0;
1260}
1261
1262static void unmap_urb_for_dma(struct usb_hcd *hcd, struct urb *urb)
1263{
1264	enum dma_data_direction dir;
1265
1266	if (urb->transfer_flags & URB_SETUP_MAP_SINGLE)
1267		dma_unmap_single(hcd->self.controller,
1268				urb->setup_dma,
1269				sizeof(struct usb_ctrlrequest),
1270				DMA_TO_DEVICE);
1271	else if (urb->transfer_flags & URB_SETUP_MAP_LOCAL)
1272		hcd_free_coherent(urb->dev->bus,
1273				&urb->setup_dma,
1274				(void **) &urb->setup_packet,
1275				sizeof(struct usb_ctrlrequest),
1276				DMA_TO_DEVICE);
1277
1278	dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1279	if (urb->transfer_flags & URB_DMA_MAP_SG)
1280		dma_unmap_sg(hcd->self.controller,
1281				urb->sg,
1282				urb->num_sgs,
1283				dir);
1284	else if (urb->transfer_flags & URB_DMA_MAP_PAGE)
1285		dma_unmap_page(hcd->self.controller,
1286				urb->transfer_dma,
1287				urb->transfer_buffer_length,
1288				dir);
1289	else if (urb->transfer_flags & URB_DMA_MAP_SINGLE)
1290		dma_unmap_single(hcd->self.controller,
1291				urb->transfer_dma,
1292				urb->transfer_buffer_length,
1293				dir);
1294	else if (urb->transfer_flags & URB_MAP_LOCAL)
1295		hcd_free_coherent(urb->dev->bus,
1296				&urb->transfer_dma,
1297				&urb->transfer_buffer,
1298				urb->transfer_buffer_length,
1299				dir);
1300
1301	/* Make it safe to call this routine more than once */
1302	urb->transfer_flags &= ~(URB_SETUP_MAP_SINGLE | URB_SETUP_MAP_LOCAL |
1303			URB_DMA_MAP_SG | URB_DMA_MAP_PAGE |
1304			URB_DMA_MAP_SINGLE | URB_MAP_LOCAL);
1305}
1306
1307static int map_urb_for_dma(struct usb_hcd *hcd, struct urb *urb,
1308			   gfp_t mem_flags)
1309{
1310	enum dma_data_direction dir;
1311	int ret = 0;
1312
1313	/* Map the URB's buffers for DMA access.
1314	 * Lower level HCD code should use *_dma exclusively,
1315	 * unless it uses pio or talks to another transport,
1316	 * or uses the provided scatter gather list for bulk.
1317	 */
1318
1319	if (usb_endpoint_xfer_control(&urb->ep->desc)) {
1320		if (hcd->self.uses_dma) {
1321			urb->setup_dma = dma_map_single(
1322					hcd->self.controller,
1323					urb->setup_packet,
1324					sizeof(struct usb_ctrlrequest),
1325					DMA_TO_DEVICE);
1326			if (dma_mapping_error(hcd->self.controller,
1327						urb->setup_dma))
1328				return -EAGAIN;
1329			urb->transfer_flags |= URB_SETUP_MAP_SINGLE;
1330		} else if (hcd->driver->flags & HCD_LOCAL_MEM) {
1331			ret = hcd_alloc_coherent(
1332					urb->dev->bus, mem_flags,
1333					&urb->setup_dma,
1334					(void **)&urb->setup_packet,
1335					sizeof(struct usb_ctrlrequest),
1336					DMA_TO_DEVICE);
1337			if (ret)
1338				return ret;
1339			urb->transfer_flags |= URB_SETUP_MAP_LOCAL;
1340		}
1341	}
1342
1343	dir = usb_urb_dir_in(urb) ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
1344	if (urb->transfer_buffer_length != 0
1345	    && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)) {
1346		if (hcd->self.uses_dma) {
1347			if (urb->num_sgs) {
1348				int n = dma_map_sg(
1349						hcd->self.controller,
1350						urb->sg,
1351						urb->num_sgs,
1352						dir);
1353				if (n <= 0)
1354					ret = -EAGAIN;
1355				else
1356					urb->transfer_flags |= URB_DMA_MAP_SG;
1357				if (n != urb->num_sgs) {
1358					urb->num_sgs = n;
1359					urb->transfer_flags |=
1360							URB_DMA_SG_COMBINED;
1361				}
1362			} else if (urb->sg) {
1363				struct scatterlist *sg = urb->sg;
1364				urb->transfer_dma = dma_map_page(
1365						hcd->self.controller,
1366						sg_page(sg),
1367						sg->offset,
1368						urb->transfer_buffer_length,
1369						dir);
1370				if (dma_mapping_error(hcd->self.controller,
1371						urb->transfer_dma))
1372					ret = -EAGAIN;
1373				else
1374					urb->transfer_flags |= URB_DMA_MAP_PAGE;
1375			} else {
1376				urb->transfer_dma = dma_map_single(
1377						hcd->self.controller,
1378						urb->transfer_buffer,
1379						urb->transfer_buffer_length,
1380						dir);
1381				if (dma_mapping_error(hcd->self.controller,
1382						urb->transfer_dma))
1383					ret = -EAGAIN;
1384				else
1385					urb->transfer_flags |= URB_DMA_MAP_SINGLE;
1386			}
1387		} else if (hcd->driver->flags & HCD_LOCAL_MEM) {
1388			ret = hcd_alloc_coherent(
1389					urb->dev->bus, mem_flags,
1390					&urb->transfer_dma,
1391					&urb->transfer_buffer,
1392					urb->transfer_buffer_length,
1393					dir);
1394			if (ret == 0)
1395				urb->transfer_flags |= URB_MAP_LOCAL;
1396		}
1397		if (ret && (urb->transfer_flags & (URB_SETUP_MAP_SINGLE |
1398				URB_SETUP_MAP_LOCAL)))
1399			unmap_urb_for_dma(hcd, urb);
1400	}
1401	return ret;
1402}
1403
1404/*-------------------------------------------------------------------------*/
1405
1406/* may be called in any context with a valid urb->dev usecount
1407 * caller surrenders "ownership" of urb
1408 * expects usb_submit_urb() to have sanity checked and conditioned all
1409 * inputs in the urb
1410 */
1411int usb_hcd_submit_urb (struct urb *urb, gfp_t mem_flags)
1412{
1413	int			status;
1414	struct usb_hcd		*hcd = bus_to_hcd(urb->dev->bus);
1415
1416	/* increment urb's reference count as part of giving it to the HCD
1417	 * (which will control it).  HCD guarantees that it either returns
1418	 * an error or calls giveback(), but not both.
1419	 */
1420	usb_get_urb(urb);
1421	atomic_inc(&urb->use_count);
1422	atomic_inc(&urb->dev->urbnum);
1423	usbmon_urb_submit(&hcd->self, urb);
1424
1425	/* NOTE requirements on root-hub callers (usbfs and the hub
1426	 * driver, for now):  URBs' urb->transfer_buffer must be
1427	 * valid and usb_buffer_{sync,unmap}() not be needed, since
1428	 * they could clobber root hub response data.  Also, control
1429	 * URBs must be submitted in process context with interrupts
1430	 * enabled.
1431	 */
1432
1433	if (is_root_hub(urb->dev)) {
1434		status = rh_urb_enqueue(hcd, urb);
1435	} else {
1436		status = map_urb_for_dma(hcd, urb, mem_flags);
1437		if (likely(status == 0)) {
1438			status = hcd->driver->urb_enqueue(hcd, urb, mem_flags);
1439			if (unlikely(status))
1440				unmap_urb_for_dma(hcd, urb);
1441		}
1442	}
1443
1444	if (unlikely(status)) {
1445		usbmon_urb_submit_error(&hcd->self, urb, status);
1446		urb->hcpriv = NULL;
1447		INIT_LIST_HEAD(&urb->urb_list);
1448		atomic_dec(&urb->use_count);
1449		atomic_dec(&urb->dev->urbnum);
1450		if (atomic_read(&urb->reject))
1451			wake_up(&usb_kill_urb_queue);
1452		usb_put_urb(urb);
1453	}
1454	return status;
1455}
1456
1457/*-------------------------------------------------------------------------*/
1458
1459/* this makes the hcd giveback() the urb more quickly, by kicking it
1460 * off hardware queues (which may take a while) and returning it as
1461 * soon as practical.  we've already set up the urb's return status,
1462 * but we can't know if the callback completed already.
1463 */
1464static int unlink1(struct usb_hcd *hcd, struct urb *urb, int status)
1465{
1466	int		value;
1467
1468	if (is_root_hub(urb->dev))
1469		value = usb_rh_urb_dequeue(hcd, urb, status);
1470	else {
1471
1472		/* The only reason an HCD might fail this call is if
1473		 * it has not yet fully queued the urb to begin with.
1474		 * Such failures should be harmless. */
1475		value = hcd->driver->urb_dequeue(hcd, urb, status);
1476	}
1477	return value;
1478}
1479
1480/*
1481 * called in any context
1482 *
1483 * caller guarantees urb won't be recycled till both unlink()
1484 * and the urb's completion function return
1485 */
1486int usb_hcd_unlink_urb (struct urb *urb, int status)
1487{
1488	struct usb_hcd		*hcd;
1489	int			retval = -EIDRM;
1490	unsigned long		flags;
1491
1492	/* Prevent the device and bus from going away while
1493	 * the unlink is carried out.  If they are already gone
1494	 * then urb->use_count must be 0, since disconnected
1495	 * devices can't have any active URBs.
1496	 */
1497	spin_lock_irqsave(&hcd_urb_unlink_lock, flags);
1498	if (atomic_read(&urb->use_count) > 0) {
1499		retval = 0;
1500		usb_get_dev(urb->dev);
1501	}
1502	spin_unlock_irqrestore(&hcd_urb_unlink_lock, flags);
1503	if (retval == 0) {
1504		hcd = bus_to_hcd(urb->dev->bus);
1505		retval = unlink1(hcd, urb, status);
1506		usb_put_dev(urb->dev);
1507	}
1508
1509	if (retval == 0)
1510		retval = -EINPROGRESS;
1511	else if (retval != -EIDRM && retval != -EBUSY)
1512		dev_dbg(&urb->dev->dev, "hcd_unlink_urb %p fail %d\n",
1513				urb, retval);
1514	return retval;
1515}
1516
1517/*-------------------------------------------------------------------------*/
1518
1519/**
1520 * usb_hcd_giveback_urb - return URB from HCD to device driver
1521 * @hcd: host controller returning the URB
1522 * @urb: urb being returned to the USB device driver.
1523 * @status: completion status code for the URB.
1524 * Context: in_interrupt()
1525 *
1526 * This hands the URB from HCD to its USB device driver, using its
1527 * completion function.  The HCD has freed all per-urb resources
1528 * (and is done using urb->hcpriv).  It also released all HCD locks;
1529 * the device driver won't cause problems if it frees, modifies,
1530 * or resubmits this URB.
1531 *
1532 * If @urb was unlinked, the value of @status will be overridden by
1533 * @urb->unlinked.  Erroneous short transfers are detected in case
1534 * the HCD hasn't checked for them.
1535 */
1536void usb_hcd_giveback_urb(struct usb_hcd *hcd, struct urb *urb, int status)
1537{
1538	urb->hcpriv = NULL;
1539	if (unlikely(urb->unlinked))
1540		status = urb->unlinked;
1541	else if (unlikely((urb->transfer_flags & URB_SHORT_NOT_OK) &&
1542			urb->actual_length < urb->transfer_buffer_length &&
1543			!status))
1544		status = -EREMOTEIO;
1545
1546	unmap_urb_for_dma(hcd, urb);
1547	usbmon_urb_complete(&hcd->self, urb, status);
1548	usb_unanchor_urb(urb);
1549
1550	/* pass ownership to the completion handler */
1551	urb->status = status;
1552	urb->complete (urb);
1553	atomic_dec (&urb->use_count);
1554	if (unlikely(atomic_read(&urb->reject)))
1555		wake_up (&usb_kill_urb_queue);
1556	usb_put_urb (urb);
1557}
1558EXPORT_SYMBOL_GPL(usb_hcd_giveback_urb);
1559
1560/*-------------------------------------------------------------------------*/
1561
1562/* Cancel all URBs pending on this endpoint and wait for the endpoint's
1563 * queue to drain completely.  The caller must first insure that no more
1564 * URBs can be submitted for this endpoint.
1565 */
1566void usb_hcd_flush_endpoint(struct usb_device *udev,
1567		struct usb_host_endpoint *ep)
1568{
1569	struct usb_hcd		*hcd;
1570	struct urb		*urb;
1571
1572	if (!ep)
1573		return;
1574	might_sleep();
1575	hcd = bus_to_hcd(udev->bus);
1576
1577	/* No more submits can occur */
1578	spin_lock_irq(&hcd_urb_list_lock);
1579rescan:
1580	list_for_each_entry (urb, &ep->urb_list, urb_list) {
1581		int	is_in;
1582
1583		if (urb->unlinked)
1584			continue;
1585		usb_get_urb (urb);
1586		is_in = usb_urb_dir_in(urb);
1587		spin_unlock(&hcd_urb_list_lock);
1588
1589		/* kick hcd */
1590		unlink1(hcd, urb, -ESHUTDOWN);
1591		dev_dbg (hcd->self.controller,
1592			"shutdown urb %p ep%d%s%s\n",
1593			urb, usb_endpoint_num(&ep->desc),
1594			is_in ? "in" : "out",
1595			({	char *s;
1596
1597				 switch (usb_endpoint_type(&ep->desc)) {
1598				 case USB_ENDPOINT_XFER_CONTROL:
1599					s = ""; break;
1600				 case USB_ENDPOINT_XFER_BULK:
1601					s = "-bulk"; break;
1602				 case USB_ENDPOINT_XFER_INT:
1603					s = "-intr"; break;
1604				 default:
1605			 		s = "-iso"; break;
1606				};
1607				s;
1608			}));
1609		usb_put_urb (urb);
1610
1611		/* list contents may have changed */
1612		spin_lock(&hcd_urb_list_lock);
1613		goto rescan;
1614	}
1615	spin_unlock_irq(&hcd_urb_list_lock);
1616
1617	/* Wait until the endpoint queue is completely empty */
1618	while (!list_empty (&ep->urb_list)) {
1619		spin_lock_irq(&hcd_urb_list_lock);
1620
1621		/* The list may have changed while we acquired the spinlock */
1622		urb = NULL;
1623		if (!list_empty (&ep->urb_list)) {
1624			urb = list_entry (ep->urb_list.prev, struct urb,
1625					urb_list);
1626			usb_get_urb (urb);
1627		}
1628		spin_unlock_irq(&hcd_urb_list_lock);
1629
1630		if (urb) {
1631			usb_kill_urb (urb);
1632			usb_put_urb (urb);
1633		}
1634	}
1635}
1636
1637/**
1638 * usb_hcd_alloc_bandwidth - check whether a new bandwidth setting exceeds
1639 *				the bus bandwidth
1640 * @udev: target &usb_device
1641 * @new_config: new configuration to install
1642 * @cur_alt: the current alternate interface setting
1643 * @new_alt: alternate interface setting that is being installed
1644 *
1645 * To change configurations, pass in the new configuration in new_config,
1646 * and pass NULL for cur_alt and new_alt.
1647 *
1648 * To reset a device's configuration (put the device in the ADDRESSED state),
1649 * pass in NULL for new_config, cur_alt, and new_alt.
1650 *
1651 * To change alternate interface settings, pass in NULL for new_config,
1652 * pass in the current alternate interface setting in cur_alt,
1653 * and pass in the new alternate interface setting in new_alt.
1654 *
1655 * Returns an error if the requested bandwidth change exceeds the
1656 * bus bandwidth or host controller internal resources.
1657 */
1658int usb_hcd_alloc_bandwidth(struct usb_device *udev,
1659		struct usb_host_config *new_config,
1660		struct usb_host_interface *cur_alt,
1661		struct usb_host_interface *new_alt)
1662{
1663	int num_intfs, i, j;
1664	struct usb_host_interface *alt = NULL;
1665	int ret = 0;
1666	struct usb_hcd *hcd;
1667	struct usb_host_endpoint *ep;
1668
1669	hcd = bus_to_hcd(udev->bus);
1670	if (!hcd->driver->check_bandwidth)
1671		return 0;
1672
1673	/* Configuration is being removed - set configuration 0 */
1674	if (!new_config && !cur_alt) {
1675		for (i = 1; i < 16; ++i) {
1676			ep = udev->ep_out[i];
1677			if (ep)
1678				hcd->driver->drop_endpoint(hcd, udev, ep);
1679			ep = udev->ep_in[i];
1680			if (ep)
1681				hcd->driver->drop_endpoint(hcd, udev, ep);
1682		}
1683		hcd->driver->check_bandwidth(hcd, udev);
1684		return 0;
1685	}
1686	/* Check if the HCD says there's enough bandwidth.  Enable all endpoints
1687	 * each interface's alt setting 0 and ask the HCD to check the bandwidth
1688	 * of the bus.  There will always be bandwidth for endpoint 0, so it's
1689	 * ok to exclude it.
1690	 */
1691	if (new_config) {
1692		num_intfs = new_config->desc.bNumInterfaces;
1693		/* Remove endpoints (except endpoint 0, which is always on the
1694		 * schedule) from the old config from the schedule
1695		 */
1696		for (i = 1; i < 16; ++i) {
1697			ep = udev->ep_out[i];
1698			if (ep) {
1699				ret = hcd->driver->drop_endpoint(hcd, udev, ep);
1700				if (ret < 0)
1701					goto reset;
1702			}
1703			ep = udev->ep_in[i];
1704			if (ep) {
1705				ret = hcd->driver->drop_endpoint(hcd, udev, ep);
1706				if (ret < 0)
1707					goto reset;
1708			}
1709		}
1710		for (i = 0; i < num_intfs; ++i) {
1711			struct usb_host_interface *first_alt;
1712			int iface_num;
1713
1714			first_alt = &new_config->intf_cache[i]->altsetting[0];
1715			iface_num = first_alt->desc.bInterfaceNumber;
1716			/* Set up endpoints for alternate interface setting 0 */
1717			alt = usb_find_alt_setting(new_config, iface_num, 0);
1718			if (!alt)
1719				/* No alt setting 0? Pick the first setting. */
1720				alt = first_alt;
1721
1722			for (j = 0; j < alt->desc.bNumEndpoints; j++) {
1723				ret = hcd->driver->add_endpoint(hcd, udev, &alt->endpoint[j]);
1724				if (ret < 0)
1725					goto reset;
1726			}
1727		}
1728	}
1729	if (cur_alt && new_alt) {
1730		struct usb_interface *iface = usb_ifnum_to_if(udev,
1731				cur_alt->desc.bInterfaceNumber);
1732
1733		if (iface->resetting_device) {
1734			/*
1735			 * The USB core just reset the device, so the xHCI host
1736			 * and the device will think alt setting 0 is installed.
1737			 * However, the USB core will pass in the alternate
1738			 * setting installed before the reset as cur_alt.  Dig
1739			 * out the alternate setting 0 structure, or the first
1740			 * alternate setting if a broken device doesn't have alt
1741			 * setting 0.
1742			 */
1743			cur_alt = usb_altnum_to_altsetting(iface, 0);
1744			if (!cur_alt)
1745				cur_alt = &iface->altsetting[0];
1746		}
1747
1748		/* Drop all the endpoints in the current alt setting */
1749		for (i = 0; i < cur_alt->desc.bNumEndpoints; i++) {
1750			ret = hcd->driver->drop_endpoint(hcd, udev,
1751					&cur_alt->endpoint[i]);
1752			if (ret < 0)
1753				goto reset;
1754		}
1755		/* Add all the endpoints in the new alt setting */
1756		for (i = 0; i < new_alt->desc.bNumEndpoints; i++) {
1757			ret = hcd->driver->add_endpoint(hcd, udev,
1758					&new_alt->endpoint[i]);
1759			if (ret < 0)
1760				goto reset;
1761		}
1762	}
1763	ret = hcd->driver->check_bandwidth(hcd, udev);
1764reset:
1765	if (ret < 0)
1766		hcd->driver->reset_bandwidth(hcd, udev);
1767	return ret;
1768}
1769
1770/* Disables the endpoint: synchronizes with the hcd to make sure all
1771 * endpoint state is gone from hardware.  usb_hcd_flush_endpoint() must
1772 * have been called previously.  Use for set_configuration, set_interface,
1773 * driver removal, physical disconnect.
1774 *
1775 * example:  a qh stored in ep->hcpriv, holding state related to endpoint
1776 * type, maxpacket size, toggle, halt status, and scheduling.
1777 */
1778void usb_hcd_disable_endpoint(struct usb_device *udev,
1779		struct usb_host_endpoint *ep)
1780{
1781	struct usb_hcd		*hcd;
1782
1783	might_sleep();
1784	hcd = bus_to_hcd(udev->bus);
1785	if (hcd->driver->endpoint_disable)
1786		hcd->driver->endpoint_disable(hcd, ep);
1787}
1788
1789/**
1790 * usb_hcd_reset_endpoint - reset host endpoint state
1791 * @udev: USB device.
1792 * @ep:   the endpoint to reset.
1793 *
1794 * Resets any host endpoint state such as the toggle bit, sequence
1795 * number and current window.
1796 */
1797void usb_hcd_reset_endpoint(struct usb_device *udev,
1798			    struct usb_host_endpoint *ep)
1799{
1800	struct usb_hcd *hcd = bus_to_hcd(udev->bus);
1801
1802	if (hcd->driver->endpoint_reset)
1803		hcd->driver->endpoint_reset(hcd, ep);
1804	else {
1805		int epnum = usb_endpoint_num(&ep->desc);
1806		int is_out = usb_endpoint_dir_out(&ep->desc);
1807		int is_control = usb_endpoint_xfer_control(&ep->desc);
1808
1809		usb_settoggle(udev, epnum, is_out, 0);
1810		if (is_control)
1811			usb_settoggle(udev, epnum, !is_out, 0);
1812	}
1813}
1814
1815/**
1816 * usb_alloc_streams - allocate bulk endpoint stream IDs.
1817 * @interface:		alternate setting that includes all endpoints.
1818 * @eps:		array of endpoints that need streams.
1819 * @num_eps:		number of endpoints in the array.
1820 * @num_streams:	number of streams to allocate.
1821 * @mem_flags:		flags hcd should use to allocate memory.
1822 *
1823 * Sets up a group of bulk endpoints to have num_streams stream IDs available.
1824 * Drivers may queue multiple transfers to different stream IDs, which may
1825 * complete in a different order than they were queued.
1826 */
1827int usb_alloc_streams(struct usb_interface *interface,
1828		struct usb_host_endpoint **eps, unsigned int num_eps,
1829		unsigned int num_streams, gfp_t mem_flags)
1830{
1831	struct usb_hcd *hcd;
1832	struct usb_device *dev;
1833	int i;
1834
1835	dev = interface_to_usbdev(interface);
1836	hcd = bus_to_hcd(dev->bus);
1837	if (!hcd->driver->alloc_streams || !hcd->driver->free_streams)
1838		return -EINVAL;
1839	if (dev->speed != USB_SPEED_SUPER)
1840		return -EINVAL;
1841
1842	/* Streams only apply to bulk endpoints. */
1843	for (i = 0; i < num_eps; i++)
1844		if (!usb_endpoint_xfer_bulk(&eps[i]->desc))
1845			return -EINVAL;
1846
1847	return hcd->driver->alloc_streams(hcd, dev, eps, num_eps,
1848			num_streams, mem_flags);
1849}
1850EXPORT_SYMBOL_GPL(usb_alloc_streams);
1851
1852/**
1853 * usb_free_streams - free bulk endpoint stream IDs.
1854 * @interface:	alternate setting that includes all endpoints.
1855 * @eps:	array of endpoints to remove streams from.
1856 * @num_eps:	number of endpoints in the array.
1857 * @mem_flags:	flags hcd should use to allocate memory.
1858 *
1859 * Reverts a group of bulk endpoints back to not using stream IDs.
1860 * Can fail if we are given bad arguments, or HCD is broken.
1861 */
1862void usb_free_streams(struct usb_interface *interface,
1863		struct usb_host_endpoint **eps, unsigned int num_eps,
1864		gfp_t mem_flags)
1865{
1866	struct usb_hcd *hcd;
1867	struct usb_device *dev;
1868	int i;
1869
1870	dev = interface_to_usbdev(interface);
1871	hcd = bus_to_hcd(dev->bus);
1872	if (dev->speed != USB_SPEED_SUPER)
1873		return;
1874
1875	/* Streams only apply to bulk endpoints. */
1876	for (i = 0; i < num_eps; i++)
1877		if (!usb_endpoint_xfer_bulk(&eps[i]->desc))
1878			return;
1879
1880	hcd->driver->free_streams(hcd, dev, eps, num_eps, mem_flags);
1881}
1882EXPORT_SYMBOL_GPL(usb_free_streams);
1883
1884/* Protect against drivers that try to unlink URBs after the device
1885 * is gone, by waiting until all unlinks for @udev are finished.
1886 * Since we don't currently track URBs by device, simply wait until
1887 * nothing is running in the locked region of usb_hcd_unlink_urb().
1888 */
1889void usb_hcd_synchronize_unlinks(struct usb_device *udev)
1890{
1891	spin_lock_irq(&hcd_urb_unlink_lock);
1892	spin_unlock_irq(&hcd_urb_unlink_lock);
1893}
1894
1895/*-------------------------------------------------------------------------*/
1896
1897/* called in any context */
1898int usb_hcd_get_frame_number (struct usb_device *udev)
1899{
1900	struct usb_hcd	*hcd = bus_to_hcd(udev->bus);
1901
1902	if (!HC_IS_RUNNING (hcd->state))
1903		return -ESHUTDOWN;
1904	return hcd->driver->get_frame_number (hcd);
1905}
1906
1907/*-------------------------------------------------------------------------*/
1908
1909#ifdef	CONFIG_PM
1910
1911int hcd_bus_suspend(struct usb_device *rhdev, pm_message_t msg)
1912{
1913	struct usb_hcd	*hcd = container_of(rhdev->bus, struct usb_hcd, self);
1914	int		status;
1915	int		old_state = hcd->state;
1916
1917	dev_dbg(&rhdev->dev, "bus %s%s\n",
1918			(msg.event & PM_EVENT_AUTO ? "auto-" : ""), "suspend");
1919	if (!hcd->driver->bus_suspend) {
1920		status = -ENOENT;
1921	} else {
1922		hcd->state = HC_STATE_QUIESCING;
1923		status = hcd->driver->bus_suspend(hcd);
1924	}
1925	if (status == 0) {
1926		usb_set_device_state(rhdev, USB_STATE_SUSPENDED);
1927		hcd->state = HC_STATE_SUSPENDED;
1928	} else {
1929		hcd->state = old_state;
1930		dev_dbg(&rhdev->dev, "bus %s fail, err %d\n",
1931				"suspend", status);
1932	}
1933	return status;
1934}
1935
1936int hcd_bus_resume(struct usb_device *rhdev, pm_message_t msg)
1937{
1938	struct usb_hcd	*hcd = container_of(rhdev->bus, struct usb_hcd, self);
1939	int		status;
1940	int		old_state = hcd->state;
1941
1942	dev_dbg(&rhdev->dev, "usb %s%s\n",
1943			(msg.event & PM_EVENT_AUTO ? "auto-" : ""), "resume");
1944	if (!hcd->driver->bus_resume)
1945		return -ENOENT;
1946	if (hcd->state == HC_STATE_RUNNING)
1947		return 0;
1948
1949	hcd->state = HC_STATE_RESUMING;
1950	status = hcd->driver->bus_resume(hcd);
1951	clear_bit(HCD_FLAG_WAKEUP_PENDING, &hcd->flags);
1952	if (status == 0) {
1953		/* TRSMRCY = 10 msec */
1954		msleep(10);
1955		usb_set_device_state(rhdev, rhdev->actconfig
1956				? USB_STATE_CONFIGURED
1957				: USB_STATE_ADDRESS);
1958		hcd->state = HC_STATE_RUNNING;
1959	} else {
1960		hcd->state = old_state;
1961		dev_dbg(&rhdev->dev, "bus %s fail, err %d\n",
1962				"resume", status);
1963		if (status != -ESHUTDOWN)
1964			usb_hc_died(hcd);
1965	}
1966	return status;
1967}
1968
1969#endif	/* CONFIG_PM */
1970
1971#ifdef	CONFIG_USB_SUSPEND
1972
1973/* Workqueue routine for root-hub remote wakeup */
1974static void hcd_resume_work(struct work_struct *work)
1975{
1976	struct usb_hcd *hcd = container_of(work, struct usb_hcd, wakeup_work);
1977	struct usb_device *udev = hcd->self.root_hub;
1978
1979	usb_lock_device(udev);
1980	usb_remote_wakeup(udev);
1981	usb_unlock_device(udev);
1982}
1983
1984/**
1985 * usb_hcd_resume_root_hub - called by HCD to resume its root hub
1986 * @hcd: host controller for this root hub
1987 *
1988 * The USB host controller calls this function when its root hub is
1989 * suspended (with the remote wakeup feature enabled) and a remote
1990 * wakeup request is received.  The routine submits a workqueue request
1991 * to resume the root hub (that is, manage its downstream ports again).
1992 */
1993void usb_hcd_resume_root_hub (struct usb_hcd *hcd)
1994{
1995	unsigned long flags;
1996
1997	spin_lock_irqsave (&hcd_root_hub_lock, flags);
1998	if (hcd->rh_registered) {
1999		set_bit(HCD_FLAG_WAKEUP_PENDING, &hcd->flags);
2000		queue_work(pm_wq, &hcd->wakeup_work);
2001	}
2002	spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
2003}
2004EXPORT_SYMBOL_GPL(usb_hcd_resume_root_hub);
2005
2006#endif	/* CONFIG_USB_SUSPEND */
2007
2008/*-------------------------------------------------------------------------*/
2009
2010#ifdef	CONFIG_USB_OTG
2011
2012/**
2013 * usb_bus_start_enum - start immediate enumeration (for OTG)
2014 * @bus: the bus (must use hcd framework)
2015 * @port_num: 1-based number of port; usually bus->otg_port
2016 * Context: in_interrupt()
2017 *
2018 * Starts enumeration, with an immediate reset followed later by
2019 * khubd identifying and possibly configuring the device.
2020 * This is needed by OTG controller drivers, where it helps meet
2021 * HNP protocol timing requirements for starting a port reset.
2022 */
2023int usb_bus_start_enum(struct usb_bus *bus, unsigned port_num)
2024{
2025	struct usb_hcd		*hcd;
2026	int			status = -EOPNOTSUPP;
2027
2028	/* NOTE: since HNP can't start by grabbing the bus's address0_sem,
2029	 * boards with root hubs hooked up to internal devices (instead of
2030	 * just the OTG port) may need more attention to resetting...
2031	 */
2032	hcd = container_of (bus, struct usb_hcd, self);
2033	if (port_num && hcd->driver->start_port_reset)
2034		status = hcd->driver->start_port_reset(hcd, port_num);
2035
2036	/* run khubd shortly after (first) root port reset finishes;
2037	 * it may issue others, until at least 50 msecs have passed.
2038	 */
2039	if (status == 0)
2040		mod_timer(&hcd->rh_timer, jiffies + msecs_to_jiffies(10));
2041	return status;
2042}
2043EXPORT_SYMBOL_GPL(usb_bus_start_enum);
2044
2045#endif
2046
2047/*-------------------------------------------------------------------------*/
2048
2049/**
2050 * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
2051 * @irq: the IRQ being raised
2052 * @__hcd: pointer to the HCD whose IRQ is being signaled
2053 *
2054 * If the controller isn't HALTed, calls the driver's irq handler.
2055 * Checks whether the controller is now dead.
2056 */
2057irqreturn_t usb_hcd_irq (int irq, void *__hcd)
2058{
2059	struct usb_hcd		*hcd = __hcd;
2060	unsigned long		flags;
2061	irqreturn_t		rc;
2062
2063	/* IRQF_DISABLED doesn't work correctly with shared IRQs
2064	 * when the first handler doesn't use it.  So let's just
2065	 * assume it's never used.
2066	 */
2067	local_irq_save(flags);
2068
2069	if (unlikely(hcd->state == HC_STATE_HALT || !HCD_HW_ACCESSIBLE(hcd))) {
2070		rc = IRQ_NONE;
2071	} else if (hcd->driver->irq(hcd) == IRQ_NONE) {
2072		rc = IRQ_NONE;
2073	} else {
2074		set_bit(HCD_FLAG_SAW_IRQ, &hcd->flags);
2075
2076		if (unlikely(hcd->state == HC_STATE_HALT))
2077			usb_hc_died(hcd);
2078		rc = IRQ_HANDLED;
2079	}
2080
2081	local_irq_restore(flags);
2082	return rc;
2083}
2084EXPORT_SYMBOL_GPL(usb_hcd_irq);
2085
2086/*-------------------------------------------------------------------------*/
2087
2088/**
2089 * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
2090 * @hcd: pointer to the HCD representing the controller
2091 *
2092 * This is called by bus glue to report a USB host controller that died
2093 * while operations may still have been pending.  It's called automatically
2094 * by the PCI glue, so only glue for non-PCI busses should need to call it.
2095 */
2096void usb_hc_died (struct usb_hcd *hcd)
2097{
2098	unsigned long flags;
2099
2100	dev_err (hcd->self.controller, "HC died; cleaning up\n");
2101
2102	spin_lock_irqsave (&hcd_root_hub_lock, flags);
2103	if (hcd->rh_registered) {
2104		clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2105
2106		/* make khubd clean up old urbs and devices */
2107		usb_set_device_state (hcd->self.root_hub,
2108				USB_STATE_NOTATTACHED);
2109		usb_kick_khubd (hcd->self.root_hub);
2110	}
2111	spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
2112}
2113EXPORT_SYMBOL_GPL (usb_hc_died);
2114
2115/*-------------------------------------------------------------------------*/
2116
2117/**
2118 * usb_create_hcd - create and initialize an HCD structure
2119 * @driver: HC driver that will use this hcd
2120 * @dev: device for this HC, stored in hcd->self.controller
2121 * @bus_name: value to store in hcd->self.bus_name
2122 * Context: !in_interrupt()
2123 *
2124 * Allocate a struct usb_hcd, with extra space at the end for the
2125 * HC driver's private data.  Initialize the generic members of the
2126 * hcd structure.
2127 *
2128 * If memory is unavailable, returns NULL.
2129 */
2130struct usb_hcd *usb_create_hcd (const struct hc_driver *driver,
2131		struct device *dev, const char *bus_name)
2132{
2133	struct usb_hcd *hcd;
2134
2135	hcd = kzalloc(sizeof(*hcd) + driver->hcd_priv_size, GFP_KERNEL);
2136	if (!hcd) {
2137		dev_dbg (dev, "hcd alloc failed\n");
2138		return NULL;
2139	}
2140	dev_set_drvdata(dev, hcd);
2141	kref_init(&hcd->kref);
2142
2143	usb_bus_init(&hcd->self);
2144	hcd->self.controller = dev;
2145	hcd->self.bus_name = bus_name;
2146	hcd->self.uses_dma = (dev->dma_mask != NULL);
2147
2148	init_timer(&hcd->rh_timer);
2149	hcd->rh_timer.function = rh_timer_func;
2150	hcd->rh_timer.data = (unsigned long) hcd;
2151#ifdef CONFIG_USB_SUSPEND
2152	INIT_WORK(&hcd->wakeup_work, hcd_resume_work);
2153#endif
2154	mutex_init(&hcd->bandwidth_mutex);
2155
2156	hcd->driver = driver;
2157	hcd->product_desc = (driver->product_desc) ? driver->product_desc :
2158			"USB Host Controller";
2159	return hcd;
2160}
2161EXPORT_SYMBOL_GPL(usb_create_hcd);
2162
2163static void hcd_release (struct kref *kref)
2164{
2165	struct usb_hcd *hcd = container_of (kref, struct usb_hcd, kref);
2166
2167	kfree(hcd);
2168}
2169
2170struct usb_hcd *usb_get_hcd (struct usb_hcd *hcd)
2171{
2172	if (hcd)
2173		kref_get (&hcd->kref);
2174	return hcd;
2175}
2176EXPORT_SYMBOL_GPL(usb_get_hcd);
2177
2178void usb_put_hcd (struct usb_hcd *hcd)
2179{
2180	if (hcd)
2181		kref_put (&hcd->kref, hcd_release);
2182}
2183EXPORT_SYMBOL_GPL(usb_put_hcd);
2184
2185/**
2186 * usb_add_hcd - finish generic HCD structure initialization and register
2187 * @hcd: the usb_hcd structure to initialize
2188 * @irqnum: Interrupt line to allocate
2189 * @irqflags: Interrupt type flags
2190 *
2191 * Finish the remaining parts of generic HCD initialization: allocate the
2192 * buffers of consistent memory, register the bus, request the IRQ line,
2193 * and call the driver's reset() and start() routines.
2194 */
2195int usb_add_hcd(struct usb_hcd *hcd,
2196		unsigned int irqnum, unsigned long irqflags)
2197{
2198	int retval;
2199	struct usb_device *rhdev;
2200
2201	dev_info(hcd->self.controller, "%s\n", hcd->product_desc);
2202
2203	hcd->authorized_default = hcd->wireless? 0 : 1;
2204	set_bit(HCD_FLAG_HW_ACCESSIBLE, &hcd->flags);
2205
2206	/* HC is in reset state, but accessible.  Now do the one-time init,
2207	 * bottom up so that hcds can customize the root hubs before khubd
2208	 * starts talking to them.  (Note, bus id is assigned early too.)
2209	 */
2210	if ((retval = hcd_buffer_create(hcd)) != 0) {
2211		dev_dbg(hcd->self.controller, "pool alloc failed\n");
2212		return retval;
2213	}
2214
2215	if ((retval = usb_register_bus(&hcd->self)) < 0)
2216		goto err_register_bus;
2217
2218	if ((rhdev = usb_alloc_dev(NULL, &hcd->self, 0)) == NULL) {
2219		dev_err(hcd->self.controller, "unable to allocate root hub\n");
2220		retval = -ENOMEM;
2221		goto err_allocate_root_hub;
2222	}
2223	hcd->self.root_hub = rhdev;
2224
2225	switch (hcd->driver->flags & HCD_MASK) {
2226	case HCD_USB11:
2227		rhdev->speed = USB_SPEED_FULL;
2228		break;
2229	case HCD_USB2:
2230		rhdev->speed = USB_SPEED_HIGH;
2231		break;
2232	case HCD_USB3:
2233		rhdev->speed = USB_SPEED_SUPER;
2234		break;
2235	default:
2236		goto err_set_rh_speed;
2237	}
2238
2239	/* wakeup flag init defaults to "everything works" for root hubs,
2240	 * but drivers can override it in reset() if needed, along with
2241	 * recording the overall controller's system wakeup capability.
2242	 */
2243	device_init_wakeup(&rhdev->dev, 1);
2244
2245	/* "reset" is misnamed; its role is now one-time init. the controller
2246	 * should already have been reset (and boot firmware kicked off etc).
2247	 */
2248	if (hcd->driver->reset && (retval = hcd->driver->reset(hcd)) < 0) {
2249		dev_err(hcd->self.controller, "can't setup\n");
2250		goto err_hcd_driver_setup;
2251	}
2252	hcd->rh_pollable = 1;
2253
2254	/* NOTE: root hub and controller capabilities may not be the same */
2255	if (device_can_wakeup(hcd->self.controller)
2256			&& device_can_wakeup(&hcd->self.root_hub->dev))
2257		dev_dbg(hcd->self.controller, "supports USB remote wakeup\n");
2258
2259	/* enable irqs just before we start the controller */
2260	if (hcd->driver->irq) {
2261
2262		/* IRQF_DISABLED doesn't work as advertised when used together
2263		 * with IRQF_SHARED. As usb_hcd_irq() will always disable
2264		 * interrupts we can remove it here.
2265		 */
2266		if (irqflags & IRQF_SHARED)
2267			irqflags &= ~IRQF_DISABLED;
2268
2269		snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
2270				hcd->driver->description, hcd->self.busnum);
2271		if ((retval = request_irq(irqnum, &usb_hcd_irq, irqflags,
2272				hcd->irq_descr, hcd)) != 0) {
2273			dev_err(hcd->self.controller,
2274					"request interrupt %d failed\n", irqnum);
2275			goto err_request_irq;
2276		}
2277		hcd->irq = irqnum;
2278		dev_info(hcd->self.controller, "irq %d, %s 0x%08llx\n", irqnum,
2279				(hcd->driver->flags & HCD_MEMORY) ?
2280					"io mem" : "io base",
2281					(unsigned long long)hcd->rsrc_start);
2282	} else {
2283		hcd->irq = -1;
2284		if (hcd->rsrc_start)
2285			dev_info(hcd->self.controller, "%s 0x%08llx\n",
2286					(hcd->driver->flags & HCD_MEMORY) ?
2287					"io mem" : "io base",
2288					(unsigned long long)hcd->rsrc_start);
2289	}
2290
2291	if ((retval = hcd->driver->start(hcd)) < 0) {
2292		dev_err(hcd->self.controller, "startup error %d\n", retval);
2293		goto err_hcd_driver_start;
2294	}
2295
2296	/* starting here, usbcore will pay attention to this root hub */
2297	rhdev->bus_mA = min(500u, hcd->power_budget);
2298	if ((retval = register_root_hub(hcd)) != 0)
2299		goto err_register_root_hub;
2300
2301	retval = sysfs_create_group(&rhdev->dev.kobj, &usb_bus_attr_group);
2302	if (retval < 0) {
2303		printk(KERN_ERR "Cannot register USB bus sysfs attributes: %d\n",
2304		       retval);
2305		goto error_create_attr_group;
2306	}
2307	if (hcd->uses_new_polling && HCD_POLL_RH(hcd))
2308		usb_hcd_poll_rh_status(hcd);
2309	return retval;
2310
2311error_create_attr_group:
2312	if (HC_IS_RUNNING(hcd->state))
2313		hcd->state = HC_STATE_QUIESCING;
2314	spin_lock_irq(&hcd_root_hub_lock);
2315	hcd->rh_registered = 0;
2316	spin_unlock_irq(&hcd_root_hub_lock);
2317
2318#ifdef CONFIG_USB_SUSPEND
2319	cancel_work_sync(&hcd->wakeup_work);
2320#endif
2321	mutex_lock(&usb_bus_list_lock);
2322	usb_disconnect(&rhdev);		/* Sets rhdev to NULL */
2323	mutex_unlock(&usb_bus_list_lock);
2324err_register_root_hub:
2325	hcd->rh_pollable = 0;
2326	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2327	del_timer_sync(&hcd->rh_timer);
2328	hcd->driver->stop(hcd);
2329	hcd->state = HC_STATE_HALT;
2330	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2331	del_timer_sync(&hcd->rh_timer);
2332err_hcd_driver_start:
2333	if (hcd->irq >= 0)
2334		free_irq(irqnum, hcd);
2335err_request_irq:
2336err_hcd_driver_setup:
2337err_set_rh_speed:
2338	usb_put_dev(hcd->self.root_hub);
2339err_allocate_root_hub:
2340	usb_deregister_bus(&hcd->self);
2341err_register_bus:
2342	hcd_buffer_destroy(hcd);
2343	return retval;
2344}
2345EXPORT_SYMBOL_GPL(usb_add_hcd);
2346
2347/**
2348 * usb_remove_hcd - shutdown processing for generic HCDs
2349 * @hcd: the usb_hcd structure to remove
2350 * Context: !in_interrupt()
2351 *
2352 * Disconnects the root hub, then reverses the effects of usb_add_hcd(),
2353 * invoking the HCD's stop() method.
2354 */
2355void usb_remove_hcd(struct usb_hcd *hcd)
2356{
2357	struct usb_device *rhdev = hcd->self.root_hub;
2358
2359	dev_info(hcd->self.controller, "remove, state %x\n", hcd->state);
2360
2361	usb_get_dev(rhdev);
2362	sysfs_remove_group(&rhdev->dev.kobj, &usb_bus_attr_group);
2363
2364	if (HC_IS_RUNNING (hcd->state))
2365		hcd->state = HC_STATE_QUIESCING;
2366
2367	dev_dbg(hcd->self.controller, "roothub graceful disconnect\n");
2368	spin_lock_irq (&hcd_root_hub_lock);
2369	hcd->rh_registered = 0;
2370	spin_unlock_irq (&hcd_root_hub_lock);
2371
2372#ifdef CONFIG_USB_SUSPEND
2373	cancel_work_sync(&hcd->wakeup_work);
2374#endif
2375
2376	mutex_lock(&usb_bus_list_lock);
2377	usb_disconnect(&rhdev);		/* Sets rhdev to NULL */
2378	mutex_unlock(&usb_bus_list_lock);
2379
2380	/* Prevent any more root-hub status calls from the timer.
2381	 * The HCD might still restart the timer (if a port status change
2382	 * interrupt occurs), but usb_hcd_poll_rh_status() won't invoke
2383	 * the hub_status_data() callback.
2384	 */
2385	hcd->rh_pollable = 0;
2386	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2387	del_timer_sync(&hcd->rh_timer);
2388
2389	hcd->driver->stop(hcd);
2390	hcd->state = HC_STATE_HALT;
2391
2392	/* In case the HCD restarted the timer, stop it again. */
2393	clear_bit(HCD_FLAG_POLL_RH, &hcd->flags);
2394	del_timer_sync(&hcd->rh_timer);
2395
2396	if (hcd->irq >= 0)
2397		free_irq(hcd->irq, hcd);
2398
2399	usb_put_dev(hcd->self.root_hub);
2400	usb_deregister_bus(&hcd->self);
2401	hcd_buffer_destroy(hcd);
2402}
2403EXPORT_SYMBOL_GPL(usb_remove_hcd);
2404
2405void
2406usb_hcd_platform_shutdown(struct platform_device* dev)
2407{
2408	struct usb_hcd *hcd = platform_get_drvdata(dev);
2409
2410	if (hcd->driver->shutdown)
2411		hcd->driver->shutdown(hcd);
2412}
2413EXPORT_SYMBOL_GPL(usb_hcd_platform_shutdown);
2414
2415/*-------------------------------------------------------------------------*/
2416
2417#if defined(CONFIG_USB_MON) || defined(CONFIG_USB_MON_MODULE)
2418
2419struct usb_mon_operations *mon_ops;
2420
2421/*
2422 * The registration is unlocked.
2423 * We do it this way because we do not want to lock in hot paths.
2424 *
2425 * Notice that the code is minimally error-proof. Because usbmon needs
2426 * symbols from usbcore, usbcore gets referenced and cannot be unloaded first.
2427 */
2428
2429int usb_mon_register (struct usb_mon_operations *ops)
2430{
2431
2432	if (mon_ops)
2433		return -EBUSY;
2434
2435	mon_ops = ops;
2436	mb();
2437	return 0;
2438}
2439EXPORT_SYMBOL_GPL (usb_mon_register);
2440
2441void usb_mon_deregister (void)
2442{
2443
2444	if (mon_ops == NULL) {
2445		printk(KERN_ERR "USB: monitor was not registered\n");
2446		return;
2447	}
2448	mon_ops = NULL;
2449	mb();
2450}
2451EXPORT_SYMBOL_GPL (usb_mon_deregister);
2452
2453#endif /* CONFIG_USB_MON || CONFIG_USB_MON_MODULE */
2454