aboutsummaryrefslogtreecommitdiffstats
path: root/drivers/usb/core
diff options
context:
space:
mode:
authorLinus Torvalds <torvalds@ppc970.osdl.org>2005-04-16 18:20:36 -0400
committerLinus Torvalds <torvalds@ppc970.osdl.org>2005-04-16 18:20:36 -0400
commit1da177e4c3f41524e886b7f1b8a0c1fc7321cac2 (patch)
tree0bba044c4ce775e45a88a51686b5d9f90697ea9d /drivers/usb/core
Linux-2.6.12-rc2v2.6.12-rc2
Initial git repository build. I'm not bothering with the full history, even though we have it. We can create a separate "historical" git archive of that later if we want to, and in the meantime it's about 3.2GB when imported into git - space that would just make the early git days unnecessarily complicated, when we don't have a lot of good infrastructure for it. Let it rip!
Diffstat (limited to 'drivers/usb/core')
-rw-r--r--drivers/usb/core/Kconfig99
-rw-r--r--drivers/usb/core/Makefile16
-rw-r--r--drivers/usb/core/buffer.c154
-rw-r--r--drivers/usb/core/config.c534
-rw-r--r--drivers/usb/core/devices.c677
-rw-r--r--drivers/usb/core/devio.c1483
-rw-r--r--drivers/usb/core/file.c227
-rw-r--r--drivers/usb/core/hcd-pci.c358
-rw-r--r--drivers/usb/core/hcd.c1840
-rw-r--r--drivers/usb/core/hcd.h476
-rw-r--r--drivers/usb/core/hub.c3057
-rw-r--r--drivers/usb/core/hub.h238
-rw-r--r--drivers/usb/core/inode.c764
-rw-r--r--drivers/usb/core/message.c1480
-rw-r--r--drivers/usb/core/otg_whitelist.h112
-rw-r--r--drivers/usb/core/sysfs.c318
-rw-r--r--drivers/usb/core/urb.c511
-rw-r--r--drivers/usb/core/usb.c1573
-rw-r--r--drivers/usb/core/usb.h46
19 files changed, 13963 insertions, 0 deletions
diff --git a/drivers/usb/core/Kconfig b/drivers/usb/core/Kconfig
new file mode 100644
index 000000000000..1a9ff6184943
--- /dev/null
+++ b/drivers/usb/core/Kconfig
@@ -0,0 +1,99 @@
1#
2# USB Core configuration
3#
4config USB_DEBUG
5 bool "USB verbose debug messages"
6 depends on USB
7 help
8 Say Y here if you want the USB core & hub drivers to produce a bunch
9 of debug messages to the system log. Select this if you are having a
10 problem with USB support and want to see more of what is going on.
11
12comment "Miscellaneous USB options"
13 depends on USB
14
15config USB_DEVICEFS
16 bool "USB device filesystem"
17 depends on USB
18 ---help---
19 If you say Y here (and to "/proc file system support" in the "File
20 systems" section, above), you will get a file /proc/bus/usb/devices
21 which lists the devices currently connected to your USB bus or
22 busses, and for every connected device a file named
23 "/proc/bus/usb/xxx/yyy", where xxx is the bus number and yyy the
24 device number; the latter files can be used by user space programs
25 to talk directly to the device. These files are "virtual", meaning
26 they are generated on the fly and not stored on the hard drive.
27
28 You may need to mount the usbfs file system to see the files, use
29 mount -t usbfs none /proc/bus/usb
30
31 For the format of the various /proc/bus/usb/ files, please read
32 <file:Documentation/usb/proc_usb_info.txt>.
33
34 Please note that this code is completely unrelated to devfs, the
35 "/dev file system support".
36
37 Most users want to say Y here.
38
39config USB_BANDWIDTH
40 bool "Enforce USB bandwidth allocation (EXPERIMENTAL)"
41 depends on USB && EXPERIMENTAL
42 help
43 If you say Y here, the USB subsystem enforces USB bandwidth
44 allocation and will prevent some device opens from succeeding
45 if they would cause USB bandwidth usage to go above 90% of
46 the bus bandwidth.
47
48 If you say N here, these conditions will cause warning messages
49 about USB bandwidth usage to be logged and some devices or
50 drivers may not work correctly.
51
52config USB_DYNAMIC_MINORS
53 bool "Dynamic USB minor allocation (EXPERIMENTAL)"
54 depends on USB && EXPERIMENTAL
55 help
56 If you say Y here, the USB subsystem will use dynamic minor
57 allocation for any device that uses the USB major number.
58 This means that you can have more than 16 of a single type
59 of device (like USB printers).
60
61 If you are unsure about this, say N here.
62
63config USB_SUSPEND
64 bool "USB suspend/resume (EXPERIMENTAL)"
65 depends on USB && PM && EXPERIMENTAL
66 help
67 If you say Y here, you can use driver calls or the sysfs
68 "power/state" file to suspend or resume individual USB
69 peripherals. There are many related features, such as
70 remote wakeup and driver-specific suspend processing, that
71 may not yet work as expected.
72
73 If you are unsure about this, say N here.
74
75
76config USB_OTG
77 bool
78 depends on USB && EXPERIMENTAL
79 select USB_SUSPEND
80 default n
81
82
83config USB_OTG_WHITELIST
84 bool "Rely on OTG Targeted Peripherals List"
85 depends on USB_OTG
86 default y
87 help
88 If you say Y here, the "otg_whitelist.h" file will be used as a
89 product whitelist, so USB peripherals not listed there will be
90 rejected during enumeration. This behavior is required by the
91 USB OTG specification for all devices not on your product's
92 "Targeted Peripherals List".
93
94 Otherwise, peripherals not listed there will only generate a
95 warning and enumeration will continue. That's more like what
96 normal Linux-USB hosts do (other than the warning), and is
97 convenient for many stages of product development.
98
99
diff --git a/drivers/usb/core/Makefile b/drivers/usb/core/Makefile
new file mode 100644
index 000000000000..9e8c377b8161
--- /dev/null
+++ b/drivers/usb/core/Makefile
@@ -0,0 +1,16 @@
1#
2# Makefile for USB Core files and filesystem
3#
4
5usbcore-objs := usb.o hub.o hcd.o urb.o message.o \
6 config.o file.o buffer.o sysfs.o
7
8ifeq ($(CONFIG_PCI),y)
9 usbcore-objs += hcd-pci.o
10endif
11
12ifeq ($(CONFIG_USB_DEVICEFS),y)
13 usbcore-objs += devio.o inode.o devices.o
14endif
15
16obj-$(CONFIG_USB) += usbcore.o
diff --git a/drivers/usb/core/buffer.c b/drivers/usb/core/buffer.c
new file mode 100644
index 000000000000..b7827df21f48
--- /dev/null
+++ b/drivers/usb/core/buffer.c
@@ -0,0 +1,154 @@
1/*
2 * DMA memory management for framework level HCD code (hc_driver)
3 *
4 * This implementation plugs in through generic "usb_bus" level methods,
5 * and should work with all USB controllers, regardles of bus type.
6 */
7
8#include <linux/config.h>
9#include <linux/module.h>
10#include <linux/kernel.h>
11#include <linux/slab.h>
12#include <linux/device.h>
13#include <linux/mm.h>
14#include <asm/io.h>
15#include <asm/scatterlist.h>
16#include <linux/dma-mapping.h>
17#include <linux/dmapool.h>
18
19
20#ifdef CONFIG_USB_DEBUG
21 #define DEBUG
22#else
23 #undef DEBUG
24#endif
25
26#include <linux/usb.h>
27#include "hcd.h"
28
29
30/*
31 * DMA-Coherent Buffers
32 */
33
34/* FIXME tune these based on pool statistics ... */
35static const size_t pool_max [HCD_BUFFER_POOLS] = {
36 /* platforms without dma-friendly caches might need to
37 * prevent cacheline sharing...
38 */
39 32,
40 128,
41 512,
42 PAGE_SIZE / 2
43 /* bigger --> allocate pages */
44};
45
46
47/* SETUP primitives */
48
49/**
50 * hcd_buffer_create - initialize buffer pools
51 * @hcd: the bus whose buffer pools are to be initialized
52 * Context: !in_interrupt()
53 *
54 * Call this as part of initializing a host controller that uses the dma
55 * memory allocators. It initializes some pools of dma-coherent memory that
56 * will be shared by all drivers using that controller, or returns a negative
57 * errno value on error.
58 *
59 * Call hcd_buffer_destroy() to clean up after using those pools.
60 */
61int hcd_buffer_create (struct usb_hcd *hcd)
62{
63 char name [16];
64 int i, size;
65
66 for (i = 0; i < HCD_BUFFER_POOLS; i++) {
67 if (!(size = pool_max [i]))
68 continue;
69 snprintf (name, sizeof name, "buffer-%d", size);
70 hcd->pool [i] = dma_pool_create (name, hcd->self.controller,
71 size, size, 0);
72 if (!hcd->pool [i]) {
73 hcd_buffer_destroy (hcd);
74 return -ENOMEM;
75 }
76 }
77 return 0;
78}
79
80
81/**
82 * hcd_buffer_destroy - deallocate buffer pools
83 * @hcd: the bus whose buffer pools are to be destroyed
84 * Context: !in_interrupt()
85 *
86 * This frees the buffer pools created by hcd_buffer_create().
87 */
88void hcd_buffer_destroy (struct usb_hcd *hcd)
89{
90 int i;
91
92 for (i = 0; i < HCD_BUFFER_POOLS; i++) {
93 struct dma_pool *pool = hcd->pool [i];
94 if (pool) {
95 dma_pool_destroy (pool);
96 hcd->pool[i] = NULL;
97 }
98 }
99}
100
101
102/* sometimes alloc/free could use kmalloc with SLAB_DMA, for
103 * better sharing and to leverage mm/slab.c intelligence.
104 */
105
106void *hcd_buffer_alloc (
107 struct usb_bus *bus,
108 size_t size,
109 int mem_flags,
110 dma_addr_t *dma
111)
112{
113 struct usb_hcd *hcd = bus->hcpriv;
114 int i;
115
116 /* some USB hosts just use PIO */
117 if (!bus->controller->dma_mask) {
118 *dma = ~(dma_addr_t) 0;
119 return kmalloc (size, mem_flags);
120 }
121
122 for (i = 0; i < HCD_BUFFER_POOLS; i++) {
123 if (size <= pool_max [i])
124 return dma_pool_alloc (hcd->pool [i], mem_flags, dma);
125 }
126 return dma_alloc_coherent (hcd->self.controller, size, dma, 0);
127}
128
129void hcd_buffer_free (
130 struct usb_bus *bus,
131 size_t size,
132 void *addr,
133 dma_addr_t dma
134)
135{
136 struct usb_hcd *hcd = bus->hcpriv;
137 int i;
138
139 if (!addr)
140 return;
141
142 if (!bus->controller->dma_mask) {
143 kfree (addr);
144 return;
145 }
146
147 for (i = 0; i < HCD_BUFFER_POOLS; i++) {
148 if (size <= pool_max [i]) {
149 dma_pool_free (hcd->pool [i], addr, dma);
150 return;
151 }
152 }
153 dma_free_coherent (hcd->self.controller, size, addr, dma);
154}
diff --git a/drivers/usb/core/config.c b/drivers/usb/core/config.c
new file mode 100644
index 000000000000..0b092bdf98f3
--- /dev/null
+++ b/drivers/usb/core/config.c
@@ -0,0 +1,534 @@
1#include <linux/config.h>
2
3#ifdef CONFIG_USB_DEBUG
4#define DEBUG
5#endif
6
7#include <linux/usb.h>
8#include <linux/module.h>
9#include <linux/init.h>
10#include <linux/slab.h>
11#include <linux/device.h>
12#include <asm/byteorder.h>
13
14
15#define USB_MAXALTSETTING 128 /* Hard limit */
16#define USB_MAXENDPOINTS 30 /* Hard limit */
17
18#define USB_MAXCONFIG 8 /* Arbitrary limit */
19
20
21static inline const char *plural(int n)
22{
23 return (n == 1 ? "" : "s");
24}
25
26static int find_next_descriptor(unsigned char *buffer, int size,
27 int dt1, int dt2, int *num_skipped)
28{
29 struct usb_descriptor_header *h;
30 int n = 0;
31 unsigned char *buffer0 = buffer;
32
33 /* Find the next descriptor of type dt1 or dt2 */
34 while (size > 0) {
35 h = (struct usb_descriptor_header *) buffer;
36 if (h->bDescriptorType == dt1 || h->bDescriptorType == dt2)
37 break;
38 buffer += h->bLength;
39 size -= h->bLength;
40 ++n;
41 }
42
43 /* Store the number of descriptors skipped and return the
44 * number of bytes skipped */
45 if (num_skipped)
46 *num_skipped = n;
47 return buffer - buffer0;
48}
49
50static int usb_parse_endpoint(struct device *ddev, int cfgno, int inum,
51 int asnum, struct usb_host_interface *ifp, int num_ep,
52 unsigned char *buffer, int size)
53{
54 unsigned char *buffer0 = buffer;
55 struct usb_endpoint_descriptor *d;
56 struct usb_host_endpoint *endpoint;
57 int n, i;
58
59 d = (struct usb_endpoint_descriptor *) buffer;
60 buffer += d->bLength;
61 size -= d->bLength;
62
63 if (d->bLength >= USB_DT_ENDPOINT_AUDIO_SIZE)
64 n = USB_DT_ENDPOINT_AUDIO_SIZE;
65 else if (d->bLength >= USB_DT_ENDPOINT_SIZE)
66 n = USB_DT_ENDPOINT_SIZE;
67 else {
68 dev_warn(ddev, "config %d interface %d altsetting %d has an "
69 "invalid endpoint descriptor of length %d, skipping\n",
70 cfgno, inum, asnum, d->bLength);
71 goto skip_to_next_endpoint_or_interface_descriptor;
72 }
73
74 i = d->bEndpointAddress & ~USB_ENDPOINT_DIR_MASK;
75 if (i >= 16 || i == 0) {
76 dev_warn(ddev, "config %d interface %d altsetting %d has an "
77 "invalid endpoint with address 0x%X, skipping\n",
78 cfgno, inum, asnum, d->bEndpointAddress);
79 goto skip_to_next_endpoint_or_interface_descriptor;
80 }
81
82 /* Only store as many endpoints as we have room for */
83 if (ifp->desc.bNumEndpoints >= num_ep)
84 goto skip_to_next_endpoint_or_interface_descriptor;
85
86 endpoint = &ifp->endpoint[ifp->desc.bNumEndpoints];
87 ++ifp->desc.bNumEndpoints;
88
89 memcpy(&endpoint->desc, d, n);
90 INIT_LIST_HEAD(&endpoint->urb_list);
91
92 /* Skip over any Class Specific or Vendor Specific descriptors;
93 * find the next endpoint or interface descriptor */
94 endpoint->extra = buffer;
95 i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
96 USB_DT_INTERFACE, &n);
97 endpoint->extralen = i;
98 if (n > 0)
99 dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
100 n, plural(n), "endpoint");
101 return buffer - buffer0 + i;
102
103skip_to_next_endpoint_or_interface_descriptor:
104 i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
105 USB_DT_INTERFACE, NULL);
106 return buffer - buffer0 + i;
107}
108
109void usb_release_interface_cache(struct kref *ref)
110{
111 struct usb_interface_cache *intfc = ref_to_usb_interface_cache(ref);
112 int j;
113
114 for (j = 0; j < intfc->num_altsetting; j++)
115 kfree(intfc->altsetting[j].endpoint);
116 kfree(intfc);
117}
118
119static int usb_parse_interface(struct device *ddev, int cfgno,
120 struct usb_host_config *config, unsigned char *buffer, int size,
121 u8 inums[], u8 nalts[])
122{
123 unsigned char *buffer0 = buffer;
124 struct usb_interface_descriptor *d;
125 int inum, asnum;
126 struct usb_interface_cache *intfc;
127 struct usb_host_interface *alt;
128 int i, n;
129 int len, retval;
130 int num_ep, num_ep_orig;
131
132 d = (struct usb_interface_descriptor *) buffer;
133 buffer += d->bLength;
134 size -= d->bLength;
135
136 if (d->bLength < USB_DT_INTERFACE_SIZE)
137 goto skip_to_next_interface_descriptor;
138
139 /* Which interface entry is this? */
140 intfc = NULL;
141 inum = d->bInterfaceNumber;
142 for (i = 0; i < config->desc.bNumInterfaces; ++i) {
143 if (inums[i] == inum) {
144 intfc = config->intf_cache[i];
145 break;
146 }
147 }
148 if (!intfc || intfc->num_altsetting >= nalts[i])
149 goto skip_to_next_interface_descriptor;
150
151 /* Check for duplicate altsetting entries */
152 asnum = d->bAlternateSetting;
153 for ((i = 0, alt = &intfc->altsetting[0]);
154 i < intfc->num_altsetting;
155 (++i, ++alt)) {
156 if (alt->desc.bAlternateSetting == asnum) {
157 dev_warn(ddev, "Duplicate descriptor for config %d "
158 "interface %d altsetting %d, skipping\n",
159 cfgno, inum, asnum);
160 goto skip_to_next_interface_descriptor;
161 }
162 }
163
164 ++intfc->num_altsetting;
165 memcpy(&alt->desc, d, USB_DT_INTERFACE_SIZE);
166
167 /* Skip over any Class Specific or Vendor Specific descriptors;
168 * find the first endpoint or interface descriptor */
169 alt->extra = buffer;
170 i = find_next_descriptor(buffer, size, USB_DT_ENDPOINT,
171 USB_DT_INTERFACE, &n);
172 alt->extralen = i;
173 if (n > 0)
174 dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
175 n, plural(n), "interface");
176 buffer += i;
177 size -= i;
178
179 /* Allocate space for the right(?) number of endpoints */
180 num_ep = num_ep_orig = alt->desc.bNumEndpoints;
181 alt->desc.bNumEndpoints = 0; // Use as a counter
182 if (num_ep > USB_MAXENDPOINTS) {
183 dev_warn(ddev, "too many endpoints for config %d interface %d "
184 "altsetting %d: %d, using maximum allowed: %d\n",
185 cfgno, inum, asnum, num_ep, USB_MAXENDPOINTS);
186 num_ep = USB_MAXENDPOINTS;
187 }
188
189 len = sizeof(struct usb_host_endpoint) * num_ep;
190 alt->endpoint = kmalloc(len, GFP_KERNEL);
191 if (!alt->endpoint)
192 return -ENOMEM;
193 memset(alt->endpoint, 0, len);
194
195 /* Parse all the endpoint descriptors */
196 n = 0;
197 while (size > 0) {
198 if (((struct usb_descriptor_header *) buffer)->bDescriptorType
199 == USB_DT_INTERFACE)
200 break;
201 retval = usb_parse_endpoint(ddev, cfgno, inum, asnum, alt,
202 num_ep, buffer, size);
203 if (retval < 0)
204 return retval;
205 ++n;
206
207 buffer += retval;
208 size -= retval;
209 }
210
211 if (n != num_ep_orig)
212 dev_warn(ddev, "config %d interface %d altsetting %d has %d "
213 "endpoint descriptor%s, different from the interface "
214 "descriptor's value: %d\n",
215 cfgno, inum, asnum, n, plural(n), num_ep_orig);
216 return buffer - buffer0;
217
218skip_to_next_interface_descriptor:
219 i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
220 USB_DT_INTERFACE, NULL);
221 return buffer - buffer0 + i;
222}
223
224static int usb_parse_configuration(struct device *ddev, int cfgidx,
225 struct usb_host_config *config, unsigned char *buffer, int size)
226{
227 unsigned char *buffer0 = buffer;
228 int cfgno;
229 int nintf, nintf_orig;
230 int i, j, n;
231 struct usb_interface_cache *intfc;
232 unsigned char *buffer2;
233 int size2;
234 struct usb_descriptor_header *header;
235 int len, retval;
236 u8 inums[USB_MAXINTERFACES], nalts[USB_MAXINTERFACES];
237
238 memcpy(&config->desc, buffer, USB_DT_CONFIG_SIZE);
239 if (config->desc.bDescriptorType != USB_DT_CONFIG ||
240 config->desc.bLength < USB_DT_CONFIG_SIZE) {
241 dev_err(ddev, "invalid descriptor for config index %d: "
242 "type = 0x%X, length = %d\n", cfgidx,
243 config->desc.bDescriptorType, config->desc.bLength);
244 return -EINVAL;
245 }
246 cfgno = config->desc.bConfigurationValue;
247
248 buffer += config->desc.bLength;
249 size -= config->desc.bLength;
250
251 nintf = nintf_orig = config->desc.bNumInterfaces;
252 if (nintf > USB_MAXINTERFACES) {
253 dev_warn(ddev, "config %d has too many interfaces: %d, "
254 "using maximum allowed: %d\n",
255 cfgno, nintf, USB_MAXINTERFACES);
256 nintf = USB_MAXINTERFACES;
257 }
258
259 /* Go through the descriptors, checking their length and counting the
260 * number of altsettings for each interface */
261 n = 0;
262 for ((buffer2 = buffer, size2 = size);
263 size2 > 0;
264 (buffer2 += header->bLength, size2 -= header->bLength)) {
265
266 if (size2 < sizeof(struct usb_descriptor_header)) {
267 dev_warn(ddev, "config %d descriptor has %d excess "
268 "byte%s, ignoring\n",
269 cfgno, size2, plural(size2));
270 break;
271 }
272
273 header = (struct usb_descriptor_header *) buffer2;
274 if ((header->bLength > size2) || (header->bLength < 2)) {
275 dev_warn(ddev, "config %d has an invalid descriptor "
276 "of length %d, skipping remainder of the config\n",
277 cfgno, header->bLength);
278 break;
279 }
280
281 if (header->bDescriptorType == USB_DT_INTERFACE) {
282 struct usb_interface_descriptor *d;
283 int inum;
284
285 d = (struct usb_interface_descriptor *) header;
286 if (d->bLength < USB_DT_INTERFACE_SIZE) {
287 dev_warn(ddev, "config %d has an invalid "
288 "interface descriptor of length %d, "
289 "skipping\n", cfgno, d->bLength);
290 continue;
291 }
292
293 inum = d->bInterfaceNumber;
294 if (inum >= nintf_orig)
295 dev_warn(ddev, "config %d has an invalid "
296 "interface number: %d but max is %d\n",
297 cfgno, inum, nintf_orig - 1);
298
299 /* Have we already encountered this interface?
300 * Count its altsettings */
301 for (i = 0; i < n; ++i) {
302 if (inums[i] == inum)
303 break;
304 }
305 if (i < n) {
306 if (nalts[i] < 255)
307 ++nalts[i];
308 } else if (n < USB_MAXINTERFACES) {
309 inums[n] = inum;
310 nalts[n] = 1;
311 ++n;
312 }
313
314 } else if (header->bDescriptorType == USB_DT_DEVICE ||
315 header->bDescriptorType == USB_DT_CONFIG)
316 dev_warn(ddev, "config %d contains an unexpected "
317 "descriptor of type 0x%X, skipping\n",
318 cfgno, header->bDescriptorType);
319
320 } /* for ((buffer2 = buffer, size2 = size); ...) */
321 size = buffer2 - buffer;
322 config->desc.wTotalLength = cpu_to_le16(buffer2 - buffer0);
323
324 if (n != nintf)
325 dev_warn(ddev, "config %d has %d interface%s, different from "
326 "the descriptor's value: %d\n",
327 cfgno, n, plural(n), nintf_orig);
328 else if (n == 0)
329 dev_warn(ddev, "config %d has no interfaces?\n", cfgno);
330 config->desc.bNumInterfaces = nintf = n;
331
332 /* Check for missing interface numbers */
333 for (i = 0; i < nintf; ++i) {
334 for (j = 0; j < nintf; ++j) {
335 if (inums[j] == i)
336 break;
337 }
338 if (j >= nintf)
339 dev_warn(ddev, "config %d has no interface number "
340 "%d\n", cfgno, i);
341 }
342
343 /* Allocate the usb_interface_caches and altsetting arrays */
344 for (i = 0; i < nintf; ++i) {
345 j = nalts[i];
346 if (j > USB_MAXALTSETTING) {
347 dev_warn(ddev, "too many alternate settings for "
348 "config %d interface %d: %d, "
349 "using maximum allowed: %d\n",
350 cfgno, inums[i], j, USB_MAXALTSETTING);
351 nalts[i] = j = USB_MAXALTSETTING;
352 }
353
354 len = sizeof(*intfc) + sizeof(struct usb_host_interface) * j;
355 config->intf_cache[i] = intfc = kmalloc(len, GFP_KERNEL);
356 if (!intfc)
357 return -ENOMEM;
358 memset(intfc, 0, len);
359 kref_init(&intfc->ref);
360 }
361
362 /* Skip over any Class Specific or Vendor Specific descriptors;
363 * find the first interface descriptor */
364 config->extra = buffer;
365 i = find_next_descriptor(buffer, size, USB_DT_INTERFACE,
366 USB_DT_INTERFACE, &n);
367 config->extralen = i;
368 if (n > 0)
369 dev_dbg(ddev, "skipped %d descriptor%s after %s\n",
370 n, plural(n), "configuration");
371 buffer += i;
372 size -= i;
373
374 /* Parse all the interface/altsetting descriptors */
375 while (size > 0) {
376 retval = usb_parse_interface(ddev, cfgno, config,
377 buffer, size, inums, nalts);
378 if (retval < 0)
379 return retval;
380
381 buffer += retval;
382 size -= retval;
383 }
384
385 /* Check for missing altsettings */
386 for (i = 0; i < nintf; ++i) {
387 intfc = config->intf_cache[i];
388 for (j = 0; j < intfc->num_altsetting; ++j) {
389 for (n = 0; n < intfc->num_altsetting; ++n) {
390 if (intfc->altsetting[n].desc.
391 bAlternateSetting == j)
392 break;
393 }
394 if (n >= intfc->num_altsetting)
395 dev_warn(ddev, "config %d interface %d has no "
396 "altsetting %d\n", cfgno, inums[i], j);
397 }
398 }
399
400 return 0;
401}
402
403// hub-only!! ... and only exported for reset/reinit path.
404// otherwise used internally on disconnect/destroy path
405void usb_destroy_configuration(struct usb_device *dev)
406{
407 int c, i;
408
409 if (!dev->config)
410 return;
411
412 if (dev->rawdescriptors) {
413 for (i = 0; i < dev->descriptor.bNumConfigurations; i++)
414 kfree(dev->rawdescriptors[i]);
415
416 kfree(dev->rawdescriptors);
417 dev->rawdescriptors = NULL;
418 }
419
420 for (c = 0; c < dev->descriptor.bNumConfigurations; c++) {
421 struct usb_host_config *cf = &dev->config[c];
422
423 kfree(cf->string);
424 cf->string = NULL;
425
426 for (i = 0; i < cf->desc.bNumInterfaces; i++) {
427 if (cf->intf_cache[i])
428 kref_put(&cf->intf_cache[i]->ref,
429 usb_release_interface_cache);
430 }
431 }
432 kfree(dev->config);
433 dev->config = NULL;
434}
435
436
437// hub-only!! ... and only in reset path, or usb_new_device()
438// (used by real hubs and virtual root hubs)
439int usb_get_configuration(struct usb_device *dev)
440{
441 struct device *ddev = &dev->dev;
442 int ncfg = dev->descriptor.bNumConfigurations;
443 int result = -ENOMEM;
444 unsigned int cfgno, length;
445 unsigned char *buffer;
446 unsigned char *bigbuffer;
447 struct usb_config_descriptor *desc;
448
449 if (ncfg > USB_MAXCONFIG) {
450 dev_warn(ddev, "too many configurations: %d, "
451 "using maximum allowed: %d\n", ncfg, USB_MAXCONFIG);
452 dev->descriptor.bNumConfigurations = ncfg = USB_MAXCONFIG;
453 }
454
455 if (ncfg < 1) {
456 dev_err(ddev, "no configurations\n");
457 return -EINVAL;
458 }
459
460 length = ncfg * sizeof(struct usb_host_config);
461 dev->config = kmalloc(length, GFP_KERNEL);
462 if (!dev->config)
463 goto err2;
464 memset(dev->config, 0, length);
465
466 length = ncfg * sizeof(char *);
467 dev->rawdescriptors = kmalloc(length, GFP_KERNEL);
468 if (!dev->rawdescriptors)
469 goto err2;
470 memset(dev->rawdescriptors, 0, length);
471
472 buffer = kmalloc(USB_DT_CONFIG_SIZE, GFP_KERNEL);
473 if (!buffer)
474 goto err2;
475 desc = (struct usb_config_descriptor *)buffer;
476
477 for (cfgno = 0; cfgno < ncfg; cfgno++) {
478 /* We grab just the first descriptor so we know how long
479 * the whole configuration is */
480 result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
481 buffer, USB_DT_CONFIG_SIZE);
482 if (result < 0) {
483 dev_err(ddev, "unable to read config index %d "
484 "descriptor/%s\n", cfgno, "start");
485 goto err;
486 } else if (result < 4) {
487 dev_err(ddev, "config index %d descriptor too short "
488 "(expected %i, got %i)\n", cfgno,
489 USB_DT_CONFIG_SIZE, result);
490 result = -EINVAL;
491 goto err;
492 }
493 length = max((int) le16_to_cpu(desc->wTotalLength),
494 USB_DT_CONFIG_SIZE);
495
496 /* Now that we know the length, get the whole thing */
497 bigbuffer = kmalloc(length, GFP_KERNEL);
498 if (!bigbuffer) {
499 result = -ENOMEM;
500 goto err;
501 }
502 result = usb_get_descriptor(dev, USB_DT_CONFIG, cfgno,
503 bigbuffer, length);
504 if (result < 0) {
505 dev_err(ddev, "unable to read config index %d "
506 "descriptor/%s\n", cfgno, "all");
507 kfree(bigbuffer);
508 goto err;
509 }
510 if (result < length) {
511 dev_warn(ddev, "config index %d descriptor too short "
512 "(expected %i, got %i)\n", cfgno, length, result);
513 length = result;
514 }
515
516 dev->rawdescriptors[cfgno] = bigbuffer;
517
518 result = usb_parse_configuration(&dev->dev, cfgno,
519 &dev->config[cfgno], bigbuffer, length);
520 if (result < 0) {
521 ++cfgno;
522 goto err;
523 }
524 }
525 result = 0;
526
527err:
528 kfree(buffer);
529 dev->descriptor.bNumConfigurations = cfgno;
530err2:
531 if (result == -ENOMEM)
532 dev_err(ddev, "out of memory\n");
533 return result;
534}
diff --git a/drivers/usb/core/devices.c b/drivers/usb/core/devices.c
new file mode 100644
index 000000000000..8b61bcd742ca
--- /dev/null
+++ b/drivers/usb/core/devices.c
@@ -0,0 +1,677 @@
1/*
2 * devices.c
3 * (C) Copyright 1999 Randy Dunlap.
4 * (C) Copyright 1999,2000 Thomas Sailer <sailer@ife.ee.ethz.ch>. (proc file per device)
5 * (C) Copyright 1999 Deti Fliegl (new USB architecture)
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 *
21 *************************************************************
22 *
23 * <mountpoint>/devices contains USB topology, device, config, class,
24 * interface, & endpoint data.
25 *
26 * I considered using /proc/bus/usb/devices/device# for each device
27 * as it is attached or detached, but I didn't like this for some
28 * reason -- maybe it's just too deep of a directory structure.
29 * I also don't like looking in multiple places to gather and view
30 * the data. Having only one file for ./devices also prevents race
31 * conditions that could arise if a program was reading device info
32 * for devices that are being removed (unplugged). (That is, the
33 * program may find a directory for devnum_12 then try to open it,
34 * but it was just unplugged, so the directory is now deleted.
35 * But programs would just have to be prepared for situations like
36 * this in any plug-and-play environment.)
37 *
38 * 1999-12-16: Thomas Sailer <sailer@ife.ee.ethz.ch>
39 * Converted the whole proc stuff to real
40 * read methods. Now not the whole device list needs to fit
41 * into one page, only the device list for one bus.
42 * Added a poll method to /proc/bus/usb/devices, to wake
43 * up an eventual usbd
44 * 2000-01-04: Thomas Sailer <sailer@ife.ee.ethz.ch>
45 * Turned into its own filesystem
46 * 2000-07-05: Ashley Montanaro <ashley@compsoc.man.ac.uk>
47 * Converted file reading routine to dump to buffer once
48 * per device, not per bus
49 *
50 * $Id: devices.c,v 1.5 2000/01/11 13:58:21 tom Exp $
51 */
52
53#include <linux/fs.h>
54#include <linux/mm.h>
55#include <linux/slab.h>
56#include <linux/poll.h>
57#include <linux/usb.h>
58#include <linux/smp_lock.h>
59#include <linux/usbdevice_fs.h>
60#include <asm/uaccess.h>
61
62#include "hcd.h"
63
64#define MAX_TOPO_LEVEL 6
65
66/* Define ALLOW_SERIAL_NUMBER if you want to see the serial number of devices */
67#define ALLOW_SERIAL_NUMBER
68
69static char *format_topo =
70/* T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=ddd MxCh=dd */
71"\nT: Bus=%2.2d Lev=%2.2d Prnt=%2.2d Port=%2.2d Cnt=%2.2d Dev#=%3d Spd=%3s MxCh=%2d\n";
72
73static char *format_string_manufacturer =
74/* S: Manufacturer=xxxx */
75 "S: Manufacturer=%.100s\n";
76
77static char *format_string_product =
78/* S: Product=xxxx */
79 "S: Product=%.100s\n";
80
81#ifdef ALLOW_SERIAL_NUMBER
82static char *format_string_serialnumber =
83/* S: SerialNumber=xxxx */
84 "S: SerialNumber=%.100s\n";
85#endif
86
87static char *format_bandwidth =
88/* B: Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd */
89 "B: Alloc=%3d/%3d us (%2d%%), #Int=%3d, #Iso=%3d\n";
90
91static char *format_device1 =
92/* D: Ver=xx.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd */
93 "D: Ver=%2x.%02x Cls=%02x(%-5s) Sub=%02x Prot=%02x MxPS=%2d #Cfgs=%3d\n";
94
95static char *format_device2 =
96/* P: Vendor=xxxx ProdID=xxxx Rev=xx.xx */
97 "P: Vendor=%04x ProdID=%04x Rev=%2x.%02x\n";
98
99static char *format_config =
100/* C: #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA */
101 "C:%c #Ifs=%2d Cfg#=%2d Atr=%02x MxPwr=%3dmA\n";
102
103static char *format_iface =
104/* I: If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=xxxx*/
105 "I: If#=%2d Alt=%2d #EPs=%2d Cls=%02x(%-5s) Sub=%02x Prot=%02x Driver=%s\n";
106
107static char *format_endpt =
108/* E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=D?s */
109 "E: Ad=%02x(%c) Atr=%02x(%-4s) MxPS=%4d Ivl=%d%cs\n";
110
111
112/*
113 * Need access to the driver and USB bus lists.
114 * extern struct list_head usb_bus_list;
115 * However, these will come from functions that return ptrs to each of them.
116 */
117
118static DECLARE_WAIT_QUEUE_HEAD(deviceconndiscwq);
119static unsigned int conndiscevcnt = 0;
120
121/* this struct stores the poll state for <mountpoint>/devices pollers */
122struct usb_device_status {
123 unsigned int lastev;
124};
125
126struct class_info {
127 int class;
128 char *class_name;
129};
130
131static const struct class_info clas_info[] =
132{ /* max. 5 chars. per name string */
133 {USB_CLASS_PER_INTERFACE, ">ifc"},
134 {USB_CLASS_AUDIO, "audio"},
135 {USB_CLASS_COMM, "comm."},
136 {USB_CLASS_HID, "HID"},
137 {USB_CLASS_HUB, "hub"},
138 {USB_CLASS_PHYSICAL, "PID"},
139 {USB_CLASS_PRINTER, "print"},
140 {USB_CLASS_MASS_STORAGE, "stor."},
141 {USB_CLASS_CDC_DATA, "data"},
142 {USB_CLASS_APP_SPEC, "app."},
143 {USB_CLASS_VENDOR_SPEC, "vend."},
144 {USB_CLASS_STILL_IMAGE, "still"},
145 {USB_CLASS_CSCID, "scard"},
146 {USB_CLASS_CONTENT_SEC, "c-sec"},
147 {-1, "unk."} /* leave as last */
148};
149
150/*****************************************************************/
151
152void usbfs_conn_disc_event(void)
153{
154 conndiscevcnt++;
155 wake_up(&deviceconndiscwq);
156}
157
158static const char *class_decode(const int class)
159{
160 int ix;
161
162 for (ix = 0; clas_info[ix].class != -1; ix++)
163 if (clas_info[ix].class == class)
164 break;
165 return (clas_info[ix].class_name);
166}
167
168static char *usb_dump_endpoint_descriptor (
169 int speed,
170 char *start,
171 char *end,
172 const struct usb_endpoint_descriptor *desc
173)
174{
175 char dir, unit, *type;
176 unsigned interval, in, bandwidth = 1;
177
178 if (start > end)
179 return start;
180 in = (desc->bEndpointAddress & USB_DIR_IN);
181 dir = in ? 'I' : 'O';
182 if (speed == USB_SPEED_HIGH) {
183 switch (le16_to_cpu(desc->wMaxPacketSize) & (0x03 << 11)) {
184 case 1 << 11: bandwidth = 2; break;
185 case 2 << 11: bandwidth = 3; break;
186 }
187 }
188
189 /* this isn't checking for illegal values */
190 switch (desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
191 case USB_ENDPOINT_XFER_CONTROL:
192 type = "Ctrl";
193 if (speed == USB_SPEED_HIGH) /* uframes per NAK */
194 interval = desc->bInterval;
195 else
196 interval = 0;
197 dir = 'B'; /* ctrl is bidirectional */
198 break;
199 case USB_ENDPOINT_XFER_ISOC:
200 type = "Isoc";
201 interval = 1 << (desc->bInterval - 1);
202 break;
203 case USB_ENDPOINT_XFER_BULK:
204 type = "Bulk";
205 if (speed == USB_SPEED_HIGH && !in) /* uframes per NAK */
206 interval = desc->bInterval;
207 else
208 interval = 0;
209 break;
210 case USB_ENDPOINT_XFER_INT:
211 type = "Int.";
212 if (speed == USB_SPEED_HIGH) {
213 interval = 1 << (desc->bInterval - 1);
214 } else
215 interval = desc->bInterval;
216 break;
217 default: /* "can't happen" */
218 return start;
219 }
220 interval *= (speed == USB_SPEED_HIGH) ? 125 : 1000;
221 if (interval % 1000)
222 unit = 'u';
223 else {
224 unit = 'm';
225 interval /= 1000;
226 }
227
228 start += sprintf(start, format_endpt, desc->bEndpointAddress, dir,
229 desc->bmAttributes, type,
230 (le16_to_cpu(desc->wMaxPacketSize) & 0x07ff) * bandwidth,
231 interval, unit);
232 return start;
233}
234
235static char *usb_dump_interface_descriptor(char *start, char *end,
236 const struct usb_interface_cache *intfc,
237 const struct usb_interface *iface,
238 int setno)
239{
240 const struct usb_interface_descriptor *desc = &intfc->altsetting[setno].desc;
241 char *driver_name = "";
242
243 if (start > end)
244 return start;
245 down_read(&usb_bus_type.subsys.rwsem);
246 if (iface)
247 driver_name = (iface->dev.driver
248 ? iface->dev.driver->name
249 : "(none)");
250 start += sprintf(start, format_iface,
251 desc->bInterfaceNumber,
252 desc->bAlternateSetting,
253 desc->bNumEndpoints,
254 desc->bInterfaceClass,
255 class_decode(desc->bInterfaceClass),
256 desc->bInterfaceSubClass,
257 desc->bInterfaceProtocol,
258 driver_name);
259 up_read(&usb_bus_type.subsys.rwsem);
260 return start;
261}
262
263static char *usb_dump_interface(
264 int speed,
265 char *start,
266 char *end,
267 const struct usb_interface_cache *intfc,
268 const struct usb_interface *iface,
269 int setno
270) {
271 const struct usb_host_interface *desc = &intfc->altsetting[setno];
272 int i;
273
274 start = usb_dump_interface_descriptor(start, end, intfc, iface, setno);
275 for (i = 0; i < desc->desc.bNumEndpoints; i++) {
276 if (start > end)
277 return start;
278 start = usb_dump_endpoint_descriptor(speed,
279 start, end, &desc->endpoint[i].desc);
280 }
281 return start;
282}
283
284/* TBD:
285 * 0. TBDs
286 * 1. marking active interface altsettings (code lists all, but should mark
287 * which ones are active, if any)
288 */
289
290static char *usb_dump_config_descriptor(char *start, char *end, const struct usb_config_descriptor *desc, int active)
291{
292 if (start > end)
293 return start;
294 start += sprintf(start, format_config,
295 active ? '*' : ' ', /* mark active/actual/current cfg. */
296 desc->bNumInterfaces,
297 desc->bConfigurationValue,
298 desc->bmAttributes,
299 desc->bMaxPower * 2);
300 return start;
301}
302
303static char *usb_dump_config (
304 int speed,
305 char *start,
306 char *end,
307 const struct usb_host_config *config,
308 int active
309)
310{
311 int i, j;
312 struct usb_interface_cache *intfc;
313 struct usb_interface *interface;
314
315 if (start > end)
316 return start;
317 if (!config) /* getting these some in 2.3.7; none in 2.3.6 */
318 return start + sprintf(start, "(null Cfg. desc.)\n");
319 start = usb_dump_config_descriptor(start, end, &config->desc, active);
320 for (i = 0; i < config->desc.bNumInterfaces; i++) {
321 intfc = config->intf_cache[i];
322 interface = config->interface[i];
323 for (j = 0; j < intfc->num_altsetting; j++) {
324 if (start > end)
325 return start;
326 start = usb_dump_interface(speed,
327 start, end, intfc, interface, j);
328 }
329 }
330 return start;
331}
332
333/*
334 * Dump the different USB descriptors.
335 */
336static char *usb_dump_device_descriptor(char *start, char *end, const struct usb_device_descriptor *desc)
337{
338 u16 bcdUSB = le16_to_cpu(desc->bcdUSB);
339 u16 bcdDevice = le16_to_cpu(desc->bcdDevice);
340
341 if (start > end)
342 return start;
343 start += sprintf (start, format_device1,
344 bcdUSB >> 8, bcdUSB & 0xff,
345 desc->bDeviceClass,
346 class_decode (desc->bDeviceClass),
347 desc->bDeviceSubClass,
348 desc->bDeviceProtocol,
349 desc->bMaxPacketSize0,
350 desc->bNumConfigurations);
351 if (start > end)
352 return start;
353 start += sprintf(start, format_device2,
354 le16_to_cpu(desc->idVendor),
355 le16_to_cpu(desc->idProduct),
356 bcdDevice >> 8, bcdDevice & 0xff);
357 return start;
358}
359
360/*
361 * Dump the different strings that this device holds.
362 */
363static char *usb_dump_device_strings (char *start, char *end, struct usb_device *dev)
364{
365 if (start > end)
366 return start;
367 if (dev->manufacturer)
368 start += sprintf(start, format_string_manufacturer, dev->manufacturer);
369 if (start > end)
370 goto out;
371 if (dev->product)
372 start += sprintf(start, format_string_product, dev->product);
373 if (start > end)
374 goto out;
375#ifdef ALLOW_SERIAL_NUMBER
376 if (dev->serial)
377 start += sprintf(start, format_string_serialnumber, dev->serial);
378#endif
379 out:
380 return start;
381}
382
383static char *usb_dump_desc(char *start, char *end, struct usb_device *dev)
384{
385 int i;
386
387 if (start > end)
388 return start;
389
390 start = usb_dump_device_descriptor(start, end, &dev->descriptor);
391
392 if (start > end)
393 return start;
394
395 start = usb_dump_device_strings (start, end, dev);
396
397 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
398 if (start > end)
399 return start;
400 start = usb_dump_config(dev->speed,
401 start, end, dev->config + i,
402 /* active ? */
403 (dev->config + i) == dev->actconfig);
404 }
405 return start;
406}
407
408
409#ifdef PROC_EXTRA /* TBD: may want to add this code later */
410
411static char *usb_dump_hub_descriptor(char *start, char *end, const struct usb_hub_descriptor * desc)
412{
413 int leng = USB_DT_HUB_NONVAR_SIZE;
414 unsigned char *ptr = (unsigned char *)desc;
415
416 if (start > end)
417 return start;
418 start += sprintf(start, "Interface:");
419 while (leng && start <= end) {
420 start += sprintf(start, " %02x", *ptr);
421 ptr++; leng--;
422 }
423 *start++ = '\n';
424 return start;
425}
426
427static char *usb_dump_string(char *start, char *end, const struct usb_device *dev, char *id, int index)
428{
429 if (start > end)
430 return start;
431 start += sprintf(start, "Interface:");
432 if (index <= dev->maxstring && dev->stringindex && dev->stringindex[index])
433 start += sprintf(start, "%s: %.100s ", id, dev->stringindex[index]);
434 return start;
435}
436
437#endif /* PROC_EXTRA */
438
439/*****************************************************************/
440
441/* This is a recursive function. Parameters:
442 * buffer - the user-space buffer to write data into
443 * nbytes - the maximum number of bytes to write
444 * skip_bytes - the number of bytes to skip before writing anything
445 * file_offset - the offset into the devices file on completion
446 * The caller must own the device lock.
447 */
448static ssize_t usb_device_dump(char __user **buffer, size_t *nbytes, loff_t *skip_bytes, loff_t *file_offset,
449 struct usb_device *usbdev, struct usb_bus *bus, int level, int index, int count)
450{
451 int chix;
452 int ret, cnt = 0;
453 int parent_devnum = 0;
454 char *pages_start, *data_end, *speed;
455 unsigned int length;
456 ssize_t total_written = 0;
457
458 /* don't bother with anything else if we're not writing any data */
459 if (*nbytes <= 0)
460 return 0;
461
462 if (level > MAX_TOPO_LEVEL)
463 return 0;
464 /* allocate 2^1 pages = 8K (on i386); should be more than enough for one device */
465 if (!(pages_start = (char*) __get_free_pages(GFP_KERNEL,1)))
466 return -ENOMEM;
467
468 if (usbdev->parent && usbdev->parent->devnum != -1)
469 parent_devnum = usbdev->parent->devnum;
470 /*
471 * So the root hub's parent is 0 and any device that is
472 * plugged into the root hub has a parent of 0.
473 */
474 switch (usbdev->speed) {
475 case USB_SPEED_LOW:
476 speed = "1.5"; break;
477 case USB_SPEED_UNKNOWN: /* usb 1.1 root hub code */
478 case USB_SPEED_FULL:
479 speed = "12 "; break;
480 case USB_SPEED_HIGH:
481 speed = "480"; break;
482 default:
483 speed = "?? ";
484 }
485 data_end = pages_start + sprintf(pages_start, format_topo,
486 bus->busnum, level, parent_devnum,
487 index, count, usbdev->devnum,
488 speed, usbdev->maxchild);
489 /*
490 * level = topology-tier level;
491 * parent_devnum = parent device number;
492 * index = parent's connector number;
493 * count = device count at this level
494 */
495 /* If this is the root hub, display the bandwidth information */
496 if (level == 0) {
497 int max;
498
499 /* high speed reserves 80%, full/low reserves 90% */
500 if (usbdev->speed == USB_SPEED_HIGH)
501 max = 800;
502 else
503 max = FRAME_TIME_MAX_USECS_ALLOC;
504
505 /* report "average" periodic allocation over a microsecond.
506 * the schedules are actually bursty, HCDs need to deal with
507 * that and just compute/report this average.
508 */
509 data_end += sprintf(data_end, format_bandwidth,
510 bus->bandwidth_allocated, max,
511 (100 * bus->bandwidth_allocated + max / 2)
512 / max,
513 bus->bandwidth_int_reqs,
514 bus->bandwidth_isoc_reqs);
515
516 }
517 data_end = usb_dump_desc(data_end, pages_start + (2 * PAGE_SIZE) - 256, usbdev);
518
519 if (data_end > (pages_start + (2 * PAGE_SIZE) - 256))
520 data_end += sprintf(data_end, "(truncated)\n");
521
522 length = data_end - pages_start;
523 /* if we can start copying some data to the user */
524 if (length > *skip_bytes) {
525 length -= *skip_bytes;
526 if (length > *nbytes)
527 length = *nbytes;
528 if (copy_to_user(*buffer, pages_start + *skip_bytes, length)) {
529 free_pages((unsigned long)pages_start, 1);
530 return -EFAULT;
531 }
532 *nbytes -= length;
533 *file_offset += length;
534 total_written += length;
535 *buffer += length;
536 *skip_bytes = 0;
537 } else
538 *skip_bytes -= length;
539
540 free_pages((unsigned long)pages_start, 1);
541
542 /* Now look at all of this device's children. */
543 for (chix = 0; chix < usbdev->maxchild; chix++) {
544 struct usb_device *childdev = usbdev->children[chix];
545
546 if (childdev) {
547 down(&childdev->serialize);
548 ret = usb_device_dump(buffer, nbytes, skip_bytes, file_offset, childdev,
549 bus, level + 1, chix, ++cnt);
550 up(&childdev->serialize);
551 if (ret == -EFAULT)
552 return total_written;
553 total_written += ret;
554 }
555 }
556 return total_written;
557}
558
559static ssize_t usb_device_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
560{
561 struct usb_bus *bus;
562 ssize_t ret, total_written = 0;
563 loff_t skip_bytes = *ppos;
564
565 if (*ppos < 0)
566 return -EINVAL;
567 if (nbytes <= 0)
568 return 0;
569 if (!access_ok(VERIFY_WRITE, buf, nbytes))
570 return -EFAULT;
571
572 down (&usb_bus_list_lock);
573 /* print devices for all busses */
574 list_for_each_entry(bus, &usb_bus_list, bus_list) {
575 /* recurse through all children of the root hub */
576 if (!bus->root_hub)
577 continue;
578 usb_lock_device(bus->root_hub);
579 ret = usb_device_dump(&buf, &nbytes, &skip_bytes, ppos, bus->root_hub, bus, 0, 0, 0);
580 usb_unlock_device(bus->root_hub);
581 if (ret < 0) {
582 up(&usb_bus_list_lock);
583 return ret;
584 }
585 total_written += ret;
586 }
587 up (&usb_bus_list_lock);
588 return total_written;
589}
590
591/* Kernel lock for "lastev" protection */
592static unsigned int usb_device_poll(struct file *file, struct poll_table_struct *wait)
593{
594 struct usb_device_status *st = (struct usb_device_status *)file->private_data;
595 unsigned int mask = 0;
596
597 lock_kernel();
598 if (!st) {
599 st = kmalloc(sizeof(struct usb_device_status), GFP_KERNEL);
600 if (!st) {
601 unlock_kernel();
602 return POLLIN;
603 }
604
605 /* we may have dropped BKL - need to check for having lost the race */
606 if (file->private_data) {
607 kfree(st);
608 st = file->private_data;
609 goto lost_race;
610 }
611
612 /*
613 * need to prevent the module from being unloaded, since
614 * proc_unregister does not call the release method and
615 * we would have a memory leak
616 */
617 st->lastev = conndiscevcnt;
618 file->private_data = st;
619 mask = POLLIN;
620 }
621lost_race:
622 if (file->f_mode & FMODE_READ)
623 poll_wait(file, &deviceconndiscwq, wait);
624 if (st->lastev != conndiscevcnt)
625 mask |= POLLIN;
626 st->lastev = conndiscevcnt;
627 unlock_kernel();
628 return mask;
629}
630
631static int usb_device_open(struct inode *inode, struct file *file)
632{
633 file->private_data = NULL;
634 return 0;
635}
636
637static int usb_device_release(struct inode *inode, struct file *file)
638{
639 if (file->private_data) {
640 kfree(file->private_data);
641 file->private_data = NULL;
642 }
643
644 return 0;
645}
646
647static loff_t usb_device_lseek(struct file * file, loff_t offset, int orig)
648{
649 loff_t ret;
650
651 lock_kernel();
652
653 switch (orig) {
654 case 0:
655 file->f_pos = offset;
656 ret = file->f_pos;
657 break;
658 case 1:
659 file->f_pos += offset;
660 ret = file->f_pos;
661 break;
662 case 2:
663 default:
664 ret = -EINVAL;
665 }
666
667 unlock_kernel();
668 return ret;
669}
670
671struct file_operations usbfs_devices_fops = {
672 .llseek = usb_device_lseek,
673 .read = usb_device_read,
674 .poll = usb_device_poll,
675 .open = usb_device_open,
676 .release = usb_device_release,
677};
diff --git a/drivers/usb/core/devio.c b/drivers/usb/core/devio.c
new file mode 100644
index 000000000000..a047bc392983
--- /dev/null
+++ b/drivers/usb/core/devio.c
@@ -0,0 +1,1483 @@
1/*****************************************************************************/
2
3/*
4 * devio.c -- User space communication with USB devices.
5 *
6 * Copyright (C) 1999-2000 Thomas Sailer (sailer@ife.ee.ethz.ch)
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 *
22 * $Id: devio.c,v 1.7 2000/02/01 17:28:48 fliegl Exp $
23 *
24 * This file implements the usbfs/x/y files, where
25 * x is the bus number and y the device number.
26 *
27 * It allows user space programs/"drivers" to communicate directly
28 * with USB devices without intervening kernel driver.
29 *
30 * Revision history
31 * 22.12.1999 0.1 Initial release (split from proc_usb.c)
32 * 04.01.2000 0.2 Turned into its own filesystem
33 */
34
35/*****************************************************************************/
36
37#include <linux/fs.h>
38#include <linux/mm.h>
39#include <linux/slab.h>
40#include <linux/smp_lock.h>
41#include <linux/signal.h>
42#include <linux/poll.h>
43#include <linux/module.h>
44#include <linux/usb.h>
45#include <linux/usbdevice_fs.h>
46#include <asm/uaccess.h>
47#include <asm/byteorder.h>
48#include <linux/moduleparam.h>
49
50#include "hcd.h" /* for usbcore internals */
51#include "usb.h"
52
53struct async {
54 struct list_head asynclist;
55 struct dev_state *ps;
56 struct task_struct *task;
57 unsigned int signr;
58 unsigned int ifnum;
59 void __user *userbuffer;
60 void __user *userurb;
61 struct urb *urb;
62};
63
64static int usbfs_snoop = 0;
65module_param (usbfs_snoop, bool, S_IRUGO | S_IWUSR);
66MODULE_PARM_DESC (usbfs_snoop, "true to log all usbfs traffic");
67
68#define snoop(dev, format, arg...) \
69 do { \
70 if (usbfs_snoop) \
71 dev_info( dev , format , ## arg); \
72 } while (0)
73
74
75#define MAX_USBFS_BUFFER_SIZE 16384
76
77static inline int connected (struct usb_device *dev)
78{
79 return dev->state != USB_STATE_NOTATTACHED;
80}
81
82static loff_t usbdev_lseek(struct file *file, loff_t offset, int orig)
83{
84 loff_t ret;
85
86 lock_kernel();
87
88 switch (orig) {
89 case 0:
90 file->f_pos = offset;
91 ret = file->f_pos;
92 break;
93 case 1:
94 file->f_pos += offset;
95 ret = file->f_pos;
96 break;
97 case 2:
98 default:
99 ret = -EINVAL;
100 }
101
102 unlock_kernel();
103 return ret;
104}
105
106static ssize_t usbdev_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
107{
108 struct dev_state *ps = (struct dev_state *)file->private_data;
109 struct usb_device *dev = ps->dev;
110 ssize_t ret = 0;
111 unsigned len;
112 loff_t pos;
113 int i;
114
115 pos = *ppos;
116 usb_lock_device(dev);
117 if (!connected(dev)) {
118 ret = -ENODEV;
119 goto err;
120 } else if (pos < 0) {
121 ret = -EINVAL;
122 goto err;
123 }
124
125 if (pos < sizeof(struct usb_device_descriptor)) {
126 struct usb_device_descriptor *desc = kmalloc(sizeof(*desc), GFP_KERNEL);
127 if (!desc) {
128 ret = -ENOMEM;
129 goto err;
130 }
131 memcpy(desc, &dev->descriptor, sizeof(dev->descriptor));
132 le16_to_cpus(&desc->bcdUSB);
133 le16_to_cpus(&desc->idVendor);
134 le16_to_cpus(&desc->idProduct);
135 le16_to_cpus(&desc->bcdDevice);
136
137 len = sizeof(struct usb_device_descriptor) - pos;
138 if (len > nbytes)
139 len = nbytes;
140 if (copy_to_user(buf, ((char *)desc) + pos, len)) {
141 kfree(desc);
142 ret = -EFAULT;
143 goto err;
144 }
145 kfree(desc);
146
147 *ppos += len;
148 buf += len;
149 nbytes -= len;
150 ret += len;
151 }
152
153 pos = sizeof(struct usb_device_descriptor);
154 for (i = 0; nbytes && i < dev->descriptor.bNumConfigurations; i++) {
155 struct usb_config_descriptor *config =
156 (struct usb_config_descriptor *)dev->rawdescriptors[i];
157 unsigned int length = le16_to_cpu(config->wTotalLength);
158
159 if (*ppos < pos + length) {
160
161 /* The descriptor may claim to be longer than it
162 * really is. Here is the actual allocated length. */
163 unsigned alloclen =
164 le16_to_cpu(dev->config[i].desc.wTotalLength);
165
166 len = length - (*ppos - pos);
167 if (len > nbytes)
168 len = nbytes;
169
170 /* Simply don't write (skip over) unallocated parts */
171 if (alloclen > (*ppos - pos)) {
172 alloclen -= (*ppos - pos);
173 if (copy_to_user(buf,
174 dev->rawdescriptors[i] + (*ppos - pos),
175 min(len, alloclen))) {
176 ret = -EFAULT;
177 goto err;
178 }
179 }
180
181 *ppos += len;
182 buf += len;
183 nbytes -= len;
184 ret += len;
185 }
186
187 pos += length;
188 }
189
190err:
191 usb_unlock_device(dev);
192 return ret;
193}
194
195/*
196 * async list handling
197 */
198
199static struct async *alloc_async(unsigned int numisoframes)
200{
201 unsigned int assize = sizeof(struct async) + numisoframes * sizeof(struct usb_iso_packet_descriptor);
202 struct async *as = kmalloc(assize, GFP_KERNEL);
203 if (!as)
204 return NULL;
205 memset(as, 0, assize);
206 as->urb = usb_alloc_urb(numisoframes, GFP_KERNEL);
207 if (!as->urb) {
208 kfree(as);
209 return NULL;
210 }
211 return as;
212}
213
214static void free_async(struct async *as)
215{
216 if (as->urb->transfer_buffer)
217 kfree(as->urb->transfer_buffer);
218 if (as->urb->setup_packet)
219 kfree(as->urb->setup_packet);
220 usb_free_urb(as->urb);
221 kfree(as);
222}
223
224static inline void async_newpending(struct async *as)
225{
226 struct dev_state *ps = as->ps;
227 unsigned long flags;
228
229 spin_lock_irqsave(&ps->lock, flags);
230 list_add_tail(&as->asynclist, &ps->async_pending);
231 spin_unlock_irqrestore(&ps->lock, flags);
232}
233
234static inline void async_removepending(struct async *as)
235{
236 struct dev_state *ps = as->ps;
237 unsigned long flags;
238
239 spin_lock_irqsave(&ps->lock, flags);
240 list_del_init(&as->asynclist);
241 spin_unlock_irqrestore(&ps->lock, flags);
242}
243
244static inline struct async *async_getcompleted(struct dev_state *ps)
245{
246 unsigned long flags;
247 struct async *as = NULL;
248
249 spin_lock_irqsave(&ps->lock, flags);
250 if (!list_empty(&ps->async_completed)) {
251 as = list_entry(ps->async_completed.next, struct async, asynclist);
252 list_del_init(&as->asynclist);
253 }
254 spin_unlock_irqrestore(&ps->lock, flags);
255 return as;
256}
257
258static inline struct async *async_getpending(struct dev_state *ps, void __user *userurb)
259{
260 unsigned long flags;
261 struct async *as;
262
263 spin_lock_irqsave(&ps->lock, flags);
264 list_for_each_entry(as, &ps->async_pending, asynclist)
265 if (as->userurb == userurb) {
266 list_del_init(&as->asynclist);
267 spin_unlock_irqrestore(&ps->lock, flags);
268 return as;
269 }
270 spin_unlock_irqrestore(&ps->lock, flags);
271 return NULL;
272}
273
274static void async_completed(struct urb *urb, struct pt_regs *regs)
275{
276 struct async *as = (struct async *)urb->context;
277 struct dev_state *ps = as->ps;
278 struct siginfo sinfo;
279
280 spin_lock(&ps->lock);
281 list_move_tail(&as->asynclist, &ps->async_completed);
282 spin_unlock(&ps->lock);
283 if (as->signr) {
284 sinfo.si_signo = as->signr;
285 sinfo.si_errno = as->urb->status;
286 sinfo.si_code = SI_ASYNCIO;
287 sinfo.si_addr = as->userurb;
288 send_sig_info(as->signr, &sinfo, as->task);
289 }
290 wake_up(&ps->wait);
291}
292
293static void destroy_async (struct dev_state *ps, struct list_head *list)
294{
295 struct async *as;
296 unsigned long flags;
297
298 spin_lock_irqsave(&ps->lock, flags);
299 while (!list_empty(list)) {
300 as = list_entry(list->next, struct async, asynclist);
301 list_del_init(&as->asynclist);
302
303 /* drop the spinlock so the completion handler can run */
304 spin_unlock_irqrestore(&ps->lock, flags);
305 usb_kill_urb(as->urb);
306 spin_lock_irqsave(&ps->lock, flags);
307 }
308 spin_unlock_irqrestore(&ps->lock, flags);
309 as = async_getcompleted(ps);
310 while (as) {
311 free_async(as);
312 as = async_getcompleted(ps);
313 }
314}
315
316static void destroy_async_on_interface (struct dev_state *ps, unsigned int ifnum)
317{
318 struct list_head *p, *q, hitlist;
319 unsigned long flags;
320
321 INIT_LIST_HEAD(&hitlist);
322 spin_lock_irqsave(&ps->lock, flags);
323 list_for_each_safe(p, q, &ps->async_pending)
324 if (ifnum == list_entry(p, struct async, asynclist)->ifnum)
325 list_move_tail(p, &hitlist);
326 spin_unlock_irqrestore(&ps->lock, flags);
327 destroy_async(ps, &hitlist);
328}
329
330static inline void destroy_all_async(struct dev_state *ps)
331{
332 destroy_async(ps, &ps->async_pending);
333}
334
335/*
336 * interface claims are made only at the request of user level code,
337 * which can also release them (explicitly or by closing files).
338 * they're also undone when devices disconnect.
339 */
340
341static int driver_probe (struct usb_interface *intf,
342 const struct usb_device_id *id)
343{
344 return -ENODEV;
345}
346
347static void driver_disconnect(struct usb_interface *intf)
348{
349 struct dev_state *ps = usb_get_intfdata (intf);
350 unsigned int ifnum = intf->altsetting->desc.bInterfaceNumber;
351
352 if (!ps)
353 return;
354
355 /* NOTE: this relies on usbcore having canceled and completed
356 * all pending I/O requests; 2.6 does that.
357 */
358
359 if (likely(ifnum < 8*sizeof(ps->ifclaimed)))
360 clear_bit(ifnum, &ps->ifclaimed);
361 else
362 warn("interface number %u out of range", ifnum);
363
364 usb_set_intfdata (intf, NULL);
365
366 /* force async requests to complete */
367 destroy_async_on_interface(ps, ifnum);
368}
369
370struct usb_driver usbfs_driver = {
371 .owner = THIS_MODULE,
372 .name = "usbfs",
373 .probe = driver_probe,
374 .disconnect = driver_disconnect,
375};
376
377static int claimintf(struct dev_state *ps, unsigned int ifnum)
378{
379 struct usb_device *dev = ps->dev;
380 struct usb_interface *intf;
381 int err;
382
383 if (ifnum >= 8*sizeof(ps->ifclaimed))
384 return -EINVAL;
385 /* already claimed */
386 if (test_bit(ifnum, &ps->ifclaimed))
387 return 0;
388
389 /* lock against other changes to driver bindings */
390 down_write(&usb_bus_type.subsys.rwsem);
391 intf = usb_ifnum_to_if(dev, ifnum);
392 if (!intf)
393 err = -ENOENT;
394 else
395 err = usb_driver_claim_interface(&usbfs_driver, intf, ps);
396 up_write(&usb_bus_type.subsys.rwsem);
397 if (err == 0)
398 set_bit(ifnum, &ps->ifclaimed);
399 return err;
400}
401
402static int releaseintf(struct dev_state *ps, unsigned int ifnum)
403{
404 struct usb_device *dev;
405 struct usb_interface *intf;
406 int err;
407
408 err = -EINVAL;
409 if (ifnum >= 8*sizeof(ps->ifclaimed))
410 return err;
411 dev = ps->dev;
412 /* lock against other changes to driver bindings */
413 down_write(&usb_bus_type.subsys.rwsem);
414 intf = usb_ifnum_to_if(dev, ifnum);
415 if (!intf)
416 err = -ENOENT;
417 else if (test_and_clear_bit(ifnum, &ps->ifclaimed)) {
418 usb_driver_release_interface(&usbfs_driver, intf);
419 err = 0;
420 }
421 up_write(&usb_bus_type.subsys.rwsem);
422 return err;
423}
424
425static int checkintf(struct dev_state *ps, unsigned int ifnum)
426{
427 if (ps->dev->state != USB_STATE_CONFIGURED)
428 return -EHOSTUNREACH;
429 if (ifnum >= 8*sizeof(ps->ifclaimed))
430 return -EINVAL;
431 if (test_bit(ifnum, &ps->ifclaimed))
432 return 0;
433 /* if not yet claimed, claim it for the driver */
434 dev_warn(&ps->dev->dev, "usbfs: process %d (%s) did not claim interface %u before use\n",
435 current->pid, current->comm, ifnum);
436 return claimintf(ps, ifnum);
437}
438
439static int findintfep(struct usb_device *dev, unsigned int ep)
440{
441 unsigned int i, j, e;
442 struct usb_interface *intf;
443 struct usb_host_interface *alts;
444 struct usb_endpoint_descriptor *endpt;
445
446 if (ep & ~(USB_DIR_IN|0xf))
447 return -EINVAL;
448 if (!dev->actconfig)
449 return -ESRCH;
450 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
451 intf = dev->actconfig->interface[i];
452 for (j = 0; j < intf->num_altsetting; j++) {
453 alts = &intf->altsetting[j];
454 for (e = 0; e < alts->desc.bNumEndpoints; e++) {
455 endpt = &alts->endpoint[e].desc;
456 if (endpt->bEndpointAddress == ep)
457 return alts->desc.bInterfaceNumber;
458 }
459 }
460 }
461 return -ENOENT;
462}
463
464static int check_ctrlrecip(struct dev_state *ps, unsigned int requesttype, unsigned int index)
465{
466 int ret = 0;
467
468 if (ps->dev->state != USB_STATE_CONFIGURED)
469 return -EHOSTUNREACH;
470 if (USB_TYPE_VENDOR == (USB_TYPE_MASK & requesttype))
471 return 0;
472
473 index &= 0xff;
474 switch (requesttype & USB_RECIP_MASK) {
475 case USB_RECIP_ENDPOINT:
476 if ((ret = findintfep(ps->dev, index)) >= 0)
477 ret = checkintf(ps, ret);
478 break;
479
480 case USB_RECIP_INTERFACE:
481 ret = checkintf(ps, index);
482 break;
483 }
484 return ret;
485}
486
487/*
488 * file operations
489 */
490static int usbdev_open(struct inode *inode, struct file *file)
491{
492 struct usb_device *dev;
493 struct dev_state *ps;
494 int ret;
495
496 /*
497 * no locking necessary here, as chrdev_open has the kernel lock
498 * (still acquire the kernel lock for safety)
499 */
500 ret = -ENOMEM;
501 if (!(ps = kmalloc(sizeof(struct dev_state), GFP_KERNEL)))
502 goto out_nolock;
503
504 lock_kernel();
505 ret = -ENOENT;
506 dev = usb_get_dev(inode->u.generic_ip);
507 if (!dev) {
508 kfree(ps);
509 goto out;
510 }
511 ret = 0;
512 ps->dev = dev;
513 ps->file = file;
514 spin_lock_init(&ps->lock);
515 INIT_LIST_HEAD(&ps->async_pending);
516 INIT_LIST_HEAD(&ps->async_completed);
517 init_waitqueue_head(&ps->wait);
518 ps->discsignr = 0;
519 ps->disctask = current;
520 ps->disccontext = NULL;
521 ps->ifclaimed = 0;
522 wmb();
523 list_add_tail(&ps->list, &dev->filelist);
524 file->private_data = ps;
525 out:
526 unlock_kernel();
527 out_nolock:
528 return ret;
529}
530
531static int usbdev_release(struct inode *inode, struct file *file)
532{
533 struct dev_state *ps = (struct dev_state *)file->private_data;
534 struct usb_device *dev = ps->dev;
535 unsigned int ifnum;
536
537 usb_lock_device(dev);
538 list_del_init(&ps->list);
539 for (ifnum = 0; ps->ifclaimed && ifnum < 8*sizeof(ps->ifclaimed);
540 ifnum++) {
541 if (test_bit(ifnum, &ps->ifclaimed))
542 releaseintf(ps, ifnum);
543 }
544 destroy_all_async(ps);
545 usb_unlock_device(dev);
546 usb_put_dev(dev);
547 ps->dev = NULL;
548 kfree(ps);
549 return 0;
550}
551
552static int proc_control(struct dev_state *ps, void __user *arg)
553{
554 struct usb_device *dev = ps->dev;
555 struct usbdevfs_ctrltransfer ctrl;
556 unsigned int tmo;
557 unsigned char *tbuf;
558 int i, j, ret;
559
560 if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
561 return -EFAULT;
562 if ((ret = check_ctrlrecip(ps, ctrl.bRequestType, ctrl.wIndex)))
563 return ret;
564 if (ctrl.wLength > PAGE_SIZE)
565 return -EINVAL;
566 if (!(tbuf = (unsigned char *)__get_free_page(GFP_KERNEL)))
567 return -ENOMEM;
568 tmo = ctrl.timeout;
569 if (ctrl.bRequestType & 0x80) {
570 if (ctrl.wLength && !access_ok(VERIFY_WRITE, ctrl.data, ctrl.wLength)) {
571 free_page((unsigned long)tbuf);
572 return -EINVAL;
573 }
574 snoop(&dev->dev, "control read: bRequest=%02x bRrequestType=%02x wValue=%04x wIndex=%04x\n",
575 ctrl.bRequest, ctrl.bRequestType, ctrl.wValue, ctrl.wIndex);
576
577 usb_unlock_device(dev);
578 i = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0), ctrl.bRequest, ctrl.bRequestType,
579 ctrl.wValue, ctrl.wIndex, tbuf, ctrl.wLength, tmo);
580 usb_lock_device(dev);
581 if ((i > 0) && ctrl.wLength) {
582 if (usbfs_snoop) {
583 dev_info(&dev->dev, "control read: data ");
584 for (j = 0; j < ctrl.wLength; ++j)
585 printk ("%02x ", (unsigned char)(tbuf)[j]);
586 printk("\n");
587 }
588 if (copy_to_user(ctrl.data, tbuf, ctrl.wLength)) {
589 free_page((unsigned long)tbuf);
590 return -EFAULT;
591 }
592 }
593 } else {
594 if (ctrl.wLength) {
595 if (copy_from_user(tbuf, ctrl.data, ctrl.wLength)) {
596 free_page((unsigned long)tbuf);
597 return -EFAULT;
598 }
599 }
600 snoop(&dev->dev, "control write: bRequest=%02x bRrequestType=%02x wValue=%04x wIndex=%04x\n",
601 ctrl.bRequest, ctrl.bRequestType, ctrl.wValue, ctrl.wIndex);
602 if (usbfs_snoop) {
603 dev_info(&dev->dev, "control write: data: ");
604 for (j = 0; j < ctrl.wLength; ++j)
605 printk ("%02x ", (unsigned char)(tbuf)[j]);
606 printk("\n");
607 }
608 usb_unlock_device(dev);
609 i = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), ctrl.bRequest, ctrl.bRequestType,
610 ctrl.wValue, ctrl.wIndex, tbuf, ctrl.wLength, tmo);
611 usb_lock_device(dev);
612 }
613 free_page((unsigned long)tbuf);
614 if (i<0 && i != -EPIPE) {
615 dev_printk(KERN_DEBUG, &dev->dev, "usbfs: USBDEVFS_CONTROL "
616 "failed cmd %s rqt %u rq %u len %u ret %d\n",
617 current->comm, ctrl.bRequestType, ctrl.bRequest,
618 ctrl.wLength, i);
619 }
620 return i;
621}
622
623static int proc_bulk(struct dev_state *ps, void __user *arg)
624{
625 struct usb_device *dev = ps->dev;
626 struct usbdevfs_bulktransfer bulk;
627 unsigned int tmo, len1, pipe;
628 int len2;
629 unsigned char *tbuf;
630 int i, ret;
631
632 if (copy_from_user(&bulk, arg, sizeof(bulk)))
633 return -EFAULT;
634 if ((ret = findintfep(ps->dev, bulk.ep)) < 0)
635 return ret;
636 if ((ret = checkintf(ps, ret)))
637 return ret;
638 if (bulk.ep & USB_DIR_IN)
639 pipe = usb_rcvbulkpipe(dev, bulk.ep & 0x7f);
640 else
641 pipe = usb_sndbulkpipe(dev, bulk.ep & 0x7f);
642 if (!usb_maxpacket(dev, pipe, !(bulk.ep & USB_DIR_IN)))
643 return -EINVAL;
644 len1 = bulk.len;
645 if (len1 > MAX_USBFS_BUFFER_SIZE)
646 return -EINVAL;
647 if (!(tbuf = kmalloc(len1, GFP_KERNEL)))
648 return -ENOMEM;
649 tmo = bulk.timeout;
650 if (bulk.ep & 0x80) {
651 if (len1 && !access_ok(VERIFY_WRITE, bulk.data, len1)) {
652 kfree(tbuf);
653 return -EINVAL;
654 }
655 usb_unlock_device(dev);
656 i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo);
657 usb_lock_device(dev);
658 if (!i && len2) {
659 if (copy_to_user(bulk.data, tbuf, len2)) {
660 kfree(tbuf);
661 return -EFAULT;
662 }
663 }
664 } else {
665 if (len1) {
666 if (copy_from_user(tbuf, bulk.data, len1)) {
667 kfree(tbuf);
668 return -EFAULT;
669 }
670 }
671 usb_unlock_device(dev);
672 i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo);
673 usb_lock_device(dev);
674 }
675 kfree(tbuf);
676 if (i < 0)
677 return i;
678 return len2;
679}
680
681static int proc_resetep(struct dev_state *ps, void __user *arg)
682{
683 unsigned int ep;
684 int ret;
685
686 if (get_user(ep, (unsigned int __user *)arg))
687 return -EFAULT;
688 if ((ret = findintfep(ps->dev, ep)) < 0)
689 return ret;
690 if ((ret = checkintf(ps, ret)))
691 return ret;
692 usb_settoggle(ps->dev, ep & 0xf, !(ep & USB_DIR_IN), 0);
693 return 0;
694}
695
696static int proc_clearhalt(struct dev_state *ps, void __user *arg)
697{
698 unsigned int ep;
699 int pipe;
700 int ret;
701
702 if (get_user(ep, (unsigned int __user *)arg))
703 return -EFAULT;
704 if ((ret = findintfep(ps->dev, ep)) < 0)
705 return ret;
706 if ((ret = checkintf(ps, ret)))
707 return ret;
708 if (ep & USB_DIR_IN)
709 pipe = usb_rcvbulkpipe(ps->dev, ep & 0x7f);
710 else
711 pipe = usb_sndbulkpipe(ps->dev, ep & 0x7f);
712
713 return usb_clear_halt(ps->dev, pipe);
714}
715
716
717static int proc_getdriver(struct dev_state *ps, void __user *arg)
718{
719 struct usbdevfs_getdriver gd;
720 struct usb_interface *intf;
721 int ret;
722
723 if (copy_from_user(&gd, arg, sizeof(gd)))
724 return -EFAULT;
725 down_read(&usb_bus_type.subsys.rwsem);
726 intf = usb_ifnum_to_if(ps->dev, gd.interface);
727 if (!intf || !intf->dev.driver)
728 ret = -ENODATA;
729 else {
730 strncpy(gd.driver, intf->dev.driver->name,
731 sizeof(gd.driver));
732 ret = (copy_to_user(arg, &gd, sizeof(gd)) ? -EFAULT : 0);
733 }
734 up_read(&usb_bus_type.subsys.rwsem);
735 return ret;
736}
737
738static int proc_connectinfo(struct dev_state *ps, void __user *arg)
739{
740 struct usbdevfs_connectinfo ci;
741
742 ci.devnum = ps->dev->devnum;
743 ci.slow = ps->dev->speed == USB_SPEED_LOW;
744 if (copy_to_user(arg, &ci, sizeof(ci)))
745 return -EFAULT;
746 return 0;
747}
748
749static int proc_resetdevice(struct dev_state *ps)
750{
751 return usb_reset_device(ps->dev);
752
753}
754
755static int proc_setintf(struct dev_state *ps, void __user *arg)
756{
757 struct usbdevfs_setinterface setintf;
758 int ret;
759
760 if (copy_from_user(&setintf, arg, sizeof(setintf)))
761 return -EFAULT;
762 if ((ret = checkintf(ps, setintf.interface)))
763 return ret;
764 return usb_set_interface(ps->dev, setintf.interface,
765 setintf.altsetting);
766}
767
768static int proc_setconfig(struct dev_state *ps, void __user *arg)
769{
770 unsigned int u;
771 int status = 0;
772 struct usb_host_config *actconfig;
773
774 if (get_user(u, (unsigned int __user *)arg))
775 return -EFAULT;
776
777 actconfig = ps->dev->actconfig;
778
779 /* Don't touch the device if any interfaces are claimed.
780 * It could interfere with other drivers' operations, and if
781 * an interface is claimed by usbfs it could easily deadlock.
782 */
783 if (actconfig) {
784 int i;
785
786 for (i = 0; i < actconfig->desc.bNumInterfaces; ++i) {
787 if (usb_interface_claimed(actconfig->interface[i])) {
788 dev_warn (&ps->dev->dev,
789 "usbfs: interface %d claimed "
790 "while '%s' sets config #%d\n",
791 actconfig->interface[i]
792 ->cur_altsetting
793 ->desc.bInterfaceNumber,
794 current->comm, u);
795#if 0 /* FIXME: enable in 2.6.10 or so */
796 status = -EBUSY;
797 break;
798#endif
799 }
800 }
801 }
802
803 /* SET_CONFIGURATION is often abused as a "cheap" driver reset,
804 * so avoid usb_set_configuration()'s kick to sysfs
805 */
806 if (status == 0) {
807 if (actconfig && actconfig->desc.bConfigurationValue == u)
808 status = usb_reset_configuration(ps->dev);
809 else
810 status = usb_set_configuration(ps->dev, u);
811 }
812
813 return status;
814}
815
816
817static int proc_do_submiturb(struct dev_state *ps, struct usbdevfs_urb *uurb,
818 struct usbdevfs_iso_packet_desc __user *iso_frame_desc,
819 void __user *arg)
820{
821 struct usbdevfs_iso_packet_desc *isopkt = NULL;
822 struct usb_host_endpoint *ep;
823 struct async *as;
824 struct usb_ctrlrequest *dr = NULL;
825 unsigned int u, totlen, isofrmlen;
826 int ret, interval = 0, ifnum = -1;
827
828 if (uurb->flags & ~(USBDEVFS_URB_ISO_ASAP|USBDEVFS_URB_SHORT_NOT_OK|
829 URB_NO_FSBR|URB_ZERO_PACKET))
830 return -EINVAL;
831 if (!uurb->buffer)
832 return -EINVAL;
833 if (uurb->signr != 0 && (uurb->signr < SIGRTMIN || uurb->signr > SIGRTMAX))
834 return -EINVAL;
835 if (!(uurb->type == USBDEVFS_URB_TYPE_CONTROL && (uurb->endpoint & ~USB_ENDPOINT_DIR_MASK) == 0)) {
836 if ((ifnum = findintfep(ps->dev, uurb->endpoint)) < 0)
837 return ifnum;
838 if ((ret = checkintf(ps, ifnum)))
839 return ret;
840 }
841 if ((uurb->endpoint & USB_ENDPOINT_DIR_MASK) != 0)
842 ep = ps->dev->ep_in [uurb->endpoint & USB_ENDPOINT_NUMBER_MASK];
843 else
844 ep = ps->dev->ep_out [uurb->endpoint & USB_ENDPOINT_NUMBER_MASK];
845 if (!ep)
846 return -ENOENT;
847 switch(uurb->type) {
848 case USBDEVFS_URB_TYPE_CONTROL:
849 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
850 != USB_ENDPOINT_XFER_CONTROL)
851 return -EINVAL;
852 /* min 8 byte setup packet, max arbitrary */
853 if (uurb->buffer_length < 8 || uurb->buffer_length > PAGE_SIZE)
854 return -EINVAL;
855 if (!(dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL)))
856 return -ENOMEM;
857 if (copy_from_user(dr, uurb->buffer, 8)) {
858 kfree(dr);
859 return -EFAULT;
860 }
861 if (uurb->buffer_length < (le16_to_cpup(&dr->wLength) + 8)) {
862 kfree(dr);
863 return -EINVAL;
864 }
865 if ((ret = check_ctrlrecip(ps, dr->bRequestType, le16_to_cpup(&dr->wIndex)))) {
866 kfree(dr);
867 return ret;
868 }
869 uurb->endpoint = (uurb->endpoint & ~USB_ENDPOINT_DIR_MASK) | (dr->bRequestType & USB_ENDPOINT_DIR_MASK);
870 uurb->number_of_packets = 0;
871 uurb->buffer_length = le16_to_cpup(&dr->wLength);
872 uurb->buffer += 8;
873 if (!access_ok((uurb->endpoint & USB_DIR_IN) ? VERIFY_WRITE : VERIFY_READ, uurb->buffer, uurb->buffer_length)) {
874 kfree(dr);
875 return -EFAULT;
876 }
877 break;
878
879 case USBDEVFS_URB_TYPE_BULK:
880 switch (ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
881 case USB_ENDPOINT_XFER_CONTROL:
882 case USB_ENDPOINT_XFER_ISOC:
883 return -EINVAL;
884 /* allow single-shot interrupt transfers, at bogus rates */
885 }
886 uurb->number_of_packets = 0;
887 if (uurb->buffer_length > MAX_USBFS_BUFFER_SIZE)
888 return -EINVAL;
889 if (!access_ok((uurb->endpoint & USB_DIR_IN) ? VERIFY_WRITE : VERIFY_READ, uurb->buffer, uurb->buffer_length))
890 return -EFAULT;
891 break;
892
893 case USBDEVFS_URB_TYPE_ISO:
894 /* arbitrary limit */
895 if (uurb->number_of_packets < 1 || uurb->number_of_packets > 128)
896 return -EINVAL;
897 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
898 != USB_ENDPOINT_XFER_ISOC)
899 return -EINVAL;
900 interval = 1 << min (15, ep->desc.bInterval - 1);
901 isofrmlen = sizeof(struct usbdevfs_iso_packet_desc) * uurb->number_of_packets;
902 if (!(isopkt = kmalloc(isofrmlen, GFP_KERNEL)))
903 return -ENOMEM;
904 if (copy_from_user(isopkt, iso_frame_desc, isofrmlen)) {
905 kfree(isopkt);
906 return -EFAULT;
907 }
908 for (totlen = u = 0; u < uurb->number_of_packets; u++) {
909 if (isopkt[u].length > 1023) {
910 kfree(isopkt);
911 return -EINVAL;
912 }
913 totlen += isopkt[u].length;
914 }
915 if (totlen > 32768) {
916 kfree(isopkt);
917 return -EINVAL;
918 }
919 uurb->buffer_length = totlen;
920 break;
921
922 case USBDEVFS_URB_TYPE_INTERRUPT:
923 uurb->number_of_packets = 0;
924 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
925 != USB_ENDPOINT_XFER_INT)
926 return -EINVAL;
927 if (ps->dev->speed == USB_SPEED_HIGH)
928 interval = 1 << min (15, ep->desc.bInterval - 1);
929 else
930 interval = ep->desc.bInterval;
931 if (uurb->buffer_length > MAX_USBFS_BUFFER_SIZE)
932 return -EINVAL;
933 if (!access_ok((uurb->endpoint & USB_DIR_IN) ? VERIFY_WRITE : VERIFY_READ, uurb->buffer, uurb->buffer_length))
934 return -EFAULT;
935 break;
936
937 default:
938 return -EINVAL;
939 }
940 if (!(as = alloc_async(uurb->number_of_packets))) {
941 if (isopkt)
942 kfree(isopkt);
943 if (dr)
944 kfree(dr);
945 return -ENOMEM;
946 }
947 if (!(as->urb->transfer_buffer = kmalloc(uurb->buffer_length, GFP_KERNEL))) {
948 if (isopkt)
949 kfree(isopkt);
950 if (dr)
951 kfree(dr);
952 free_async(as);
953 return -ENOMEM;
954 }
955 as->urb->dev = ps->dev;
956 as->urb->pipe = (uurb->type << 30) | __create_pipe(ps->dev, uurb->endpoint & 0xf) | (uurb->endpoint & USB_DIR_IN);
957 as->urb->transfer_flags = uurb->flags;
958 as->urb->transfer_buffer_length = uurb->buffer_length;
959 as->urb->setup_packet = (unsigned char*)dr;
960 as->urb->start_frame = uurb->start_frame;
961 as->urb->number_of_packets = uurb->number_of_packets;
962 as->urb->interval = interval;
963 as->urb->context = as;
964 as->urb->complete = async_completed;
965 for (totlen = u = 0; u < uurb->number_of_packets; u++) {
966 as->urb->iso_frame_desc[u].offset = totlen;
967 as->urb->iso_frame_desc[u].length = isopkt[u].length;
968 totlen += isopkt[u].length;
969 }
970 if (isopkt)
971 kfree(isopkt);
972 as->ps = ps;
973 as->userurb = arg;
974 if (uurb->endpoint & USB_DIR_IN)
975 as->userbuffer = uurb->buffer;
976 else
977 as->userbuffer = NULL;
978 as->signr = uurb->signr;
979 as->ifnum = ifnum;
980 as->task = current;
981 if (!(uurb->endpoint & USB_DIR_IN)) {
982 if (copy_from_user(as->urb->transfer_buffer, uurb->buffer, as->urb->transfer_buffer_length)) {
983 free_async(as);
984 return -EFAULT;
985 }
986 }
987 async_newpending(as);
988 if ((ret = usb_submit_urb(as->urb, GFP_KERNEL))) {
989 dev_printk(KERN_DEBUG, &ps->dev->dev, "usbfs: usb_submit_urb returned %d\n", ret);
990 async_removepending(as);
991 free_async(as);
992 return ret;
993 }
994 return 0;
995}
996
997static int proc_submiturb(struct dev_state *ps, void __user *arg)
998{
999 struct usbdevfs_urb uurb;
1000
1001 if (copy_from_user(&uurb, arg, sizeof(uurb)))
1002 return -EFAULT;
1003
1004 return proc_do_submiturb(ps, &uurb, (((struct usbdevfs_urb __user *)arg)->iso_frame_desc), arg);
1005}
1006
1007static int proc_unlinkurb(struct dev_state *ps, void __user *arg)
1008{
1009 struct async *as;
1010
1011 as = async_getpending(ps, arg);
1012 if (!as)
1013 return -EINVAL;
1014 usb_kill_urb(as->urb);
1015 return 0;
1016}
1017
1018static int processcompl(struct async *as, void __user * __user *arg)
1019{
1020 struct urb *urb = as->urb;
1021 struct usbdevfs_urb __user *userurb = as->userurb;
1022 void __user *addr = as->userurb;
1023 unsigned int i;
1024
1025 if (as->userbuffer)
1026 if (copy_to_user(as->userbuffer, urb->transfer_buffer, urb->transfer_buffer_length))
1027 return -EFAULT;
1028 if (put_user(urb->status, &userurb->status))
1029 return -EFAULT;
1030 if (put_user(urb->actual_length, &userurb->actual_length))
1031 return -EFAULT;
1032 if (put_user(urb->error_count, &userurb->error_count))
1033 return -EFAULT;
1034
1035 if (!(usb_pipeisoc(urb->pipe)))
1036 return 0;
1037 for (i = 0; i < urb->number_of_packets; i++) {
1038 if (put_user(urb->iso_frame_desc[i].actual_length,
1039 &userurb->iso_frame_desc[i].actual_length))
1040 return -EFAULT;
1041 if (put_user(urb->iso_frame_desc[i].status,
1042 &userurb->iso_frame_desc[i].status))
1043 return -EFAULT;
1044 }
1045
1046 free_async(as);
1047
1048 if (put_user(addr, (void __user * __user *)arg))
1049 return -EFAULT;
1050 return 0;
1051}
1052
1053static struct async* reap_as(struct dev_state *ps)
1054{
1055 DECLARE_WAITQUEUE(wait, current);
1056 struct async *as = NULL;
1057 struct usb_device *dev = ps->dev;
1058
1059 add_wait_queue(&ps->wait, &wait);
1060 for (;;) {
1061 __set_current_state(TASK_INTERRUPTIBLE);
1062 if ((as = async_getcompleted(ps)))
1063 break;
1064 if (signal_pending(current))
1065 break;
1066 usb_unlock_device(dev);
1067 schedule();
1068 usb_lock_device(dev);
1069 }
1070 remove_wait_queue(&ps->wait, &wait);
1071 set_current_state(TASK_RUNNING);
1072 return as;
1073}
1074
1075static int proc_reapurb(struct dev_state *ps, void __user *arg)
1076{
1077 struct async *as = reap_as(ps);
1078 if (as)
1079 return processcompl(as, (void __user * __user *)arg);
1080 if (signal_pending(current))
1081 return -EINTR;
1082 return -EIO;
1083}
1084
1085static int proc_reapurbnonblock(struct dev_state *ps, void __user *arg)
1086{
1087 struct async *as;
1088
1089 if (!(as = async_getcompleted(ps)))
1090 return -EAGAIN;
1091 return processcompl(as, (void __user * __user *)arg);
1092}
1093
1094#ifdef CONFIG_COMPAT
1095
1096static int get_urb32(struct usbdevfs_urb *kurb,
1097 struct usbdevfs_urb32 __user *uurb)
1098{
1099 __u32 uptr;
1100 if (get_user(kurb->type, &uurb->type) ||
1101 __get_user(kurb->endpoint, &uurb->endpoint) ||
1102 __get_user(kurb->status, &uurb->status) ||
1103 __get_user(kurb->flags, &uurb->flags) ||
1104 __get_user(kurb->buffer_length, &uurb->buffer_length) ||
1105 __get_user(kurb->actual_length, &uurb->actual_length) ||
1106 __get_user(kurb->start_frame, &uurb->start_frame) ||
1107 __get_user(kurb->number_of_packets, &uurb->number_of_packets) ||
1108 __get_user(kurb->error_count, &uurb->error_count) ||
1109 __get_user(kurb->signr, &uurb->signr))
1110 return -EFAULT;
1111
1112 if (__get_user(uptr, &uurb->buffer))
1113 return -EFAULT;
1114 kurb->buffer = compat_ptr(uptr);
1115 if (__get_user(uptr, &uurb->buffer))
1116 return -EFAULT;
1117 kurb->usercontext = compat_ptr(uptr);
1118
1119 return 0;
1120}
1121
1122static int proc_submiturb_compat(struct dev_state *ps, void __user *arg)
1123{
1124 struct usbdevfs_urb uurb;
1125
1126 if (get_urb32(&uurb,(struct usbdevfs_urb32 *)arg))
1127 return -EFAULT;
1128
1129 return proc_do_submiturb(ps, &uurb, ((struct usbdevfs_urb __user *)arg)->iso_frame_desc, arg);
1130}
1131
1132static int processcompl_compat(struct async *as, void __user * __user *arg)
1133{
1134 struct urb *urb = as->urb;
1135 struct usbdevfs_urb32 __user *userurb = as->userurb;
1136 void __user *addr = as->userurb;
1137 unsigned int i;
1138
1139 if (as->userbuffer)
1140 if (copy_to_user(as->userbuffer, urb->transfer_buffer, urb->transfer_buffer_length))
1141 return -EFAULT;
1142 if (put_user(urb->status, &userurb->status))
1143 return -EFAULT;
1144 if (put_user(urb->actual_length, &userurb->actual_length))
1145 return -EFAULT;
1146 if (put_user(urb->error_count, &userurb->error_count))
1147 return -EFAULT;
1148
1149 if (!(usb_pipeisoc(urb->pipe)))
1150 return 0;
1151 for (i = 0; i < urb->number_of_packets; i++) {
1152 if (put_user(urb->iso_frame_desc[i].actual_length,
1153 &userurb->iso_frame_desc[i].actual_length))
1154 return -EFAULT;
1155 if (put_user(urb->iso_frame_desc[i].status,
1156 &userurb->iso_frame_desc[i].status))
1157 return -EFAULT;
1158 }
1159
1160 free_async(as);
1161 if (put_user((u32)(u64)addr, (u32 __user *)arg))
1162 return -EFAULT;
1163 return 0;
1164}
1165
1166static int proc_reapurb_compat(struct dev_state *ps, void __user *arg)
1167{
1168 struct async *as = reap_as(ps);
1169 if (as)
1170 return processcompl_compat(as, (void __user * __user *)arg);
1171 if (signal_pending(current))
1172 return -EINTR;
1173 return -EIO;
1174}
1175
1176static int proc_reapurbnonblock_compat(struct dev_state *ps, void __user *arg)
1177{
1178 struct async *as;
1179
1180 printk("reapurbnblock\n");
1181 if (!(as = async_getcompleted(ps)))
1182 return -EAGAIN;
1183 printk("reap got as %p\n", as);
1184 return processcompl_compat(as, (void __user * __user *)arg);
1185}
1186
1187#endif
1188
1189static int proc_disconnectsignal(struct dev_state *ps, void __user *arg)
1190{
1191 struct usbdevfs_disconnectsignal ds;
1192
1193 if (copy_from_user(&ds, arg, sizeof(ds)))
1194 return -EFAULT;
1195 if (ds.signr != 0 && (ds.signr < SIGRTMIN || ds.signr > SIGRTMAX))
1196 return -EINVAL;
1197 ps->discsignr = ds.signr;
1198 ps->disccontext = ds.context;
1199 return 0;
1200}
1201
1202static int proc_claiminterface(struct dev_state *ps, void __user *arg)
1203{
1204 unsigned int ifnum;
1205
1206 if (get_user(ifnum, (unsigned int __user *)arg))
1207 return -EFAULT;
1208 return claimintf(ps, ifnum);
1209}
1210
1211static int proc_releaseinterface(struct dev_state *ps, void __user *arg)
1212{
1213 unsigned int ifnum;
1214 int ret;
1215
1216 if (get_user(ifnum, (unsigned int __user *)arg))
1217 return -EFAULT;
1218 if ((ret = releaseintf(ps, ifnum)) < 0)
1219 return ret;
1220 destroy_async_on_interface (ps, ifnum);
1221 return 0;
1222}
1223
1224static int proc_ioctl (struct dev_state *ps, void __user *arg)
1225{
1226 struct usbdevfs_ioctl ctrl;
1227 int size;
1228 void *buf = NULL;
1229 int retval = 0;
1230 struct usb_interface *intf = NULL;
1231 struct usb_driver *driver = NULL;
1232 int i;
1233
1234 /* get input parameters and alloc buffer */
1235 if (copy_from_user(&ctrl, arg, sizeof (ctrl)))
1236 return -EFAULT;
1237 if ((size = _IOC_SIZE (ctrl.ioctl_code)) > 0) {
1238 if ((buf = kmalloc (size, GFP_KERNEL)) == NULL)
1239 return -ENOMEM;
1240 if ((_IOC_DIR(ctrl.ioctl_code) & _IOC_WRITE)) {
1241 if (copy_from_user (buf, ctrl.data, size)) {
1242 kfree (buf);
1243 return -EFAULT;
1244 }
1245 } else {
1246 memset (buf, 0, size);
1247 }
1248 }
1249
1250 if (!connected(ps->dev)) {
1251 if (buf)
1252 kfree(buf);
1253 return -ENODEV;
1254 }
1255
1256 if (ps->dev->state != USB_STATE_CONFIGURED)
1257 retval = -EHOSTUNREACH;
1258 else if (!(intf = usb_ifnum_to_if (ps->dev, ctrl.ifno)))
1259 retval = -EINVAL;
1260 else switch (ctrl.ioctl_code) {
1261
1262 /* disconnect kernel driver from interface */
1263 case USBDEVFS_DISCONNECT:
1264
1265 /* don't allow the user to unbind the hub driver from
1266 * a hub with children to manage */
1267 for (i = 0; i < ps->dev->maxchild; ++i) {
1268 if (ps->dev->children[i])
1269 retval = -EBUSY;
1270 }
1271 if (retval)
1272 break;
1273
1274 down_write(&usb_bus_type.subsys.rwsem);
1275 if (intf->dev.driver) {
1276 driver = to_usb_driver(intf->dev.driver);
1277 dev_dbg (&intf->dev, "disconnect by usbfs\n");
1278 usb_driver_release_interface(driver, intf);
1279 } else
1280 retval = -ENODATA;
1281 up_write(&usb_bus_type.subsys.rwsem);
1282 break;
1283
1284 /* let kernel drivers try to (re)bind to the interface */
1285 case USBDEVFS_CONNECT:
1286 usb_unlock_device(ps->dev);
1287 usb_lock_all_devices();
1288 bus_rescan_devices(intf->dev.bus);
1289 usb_unlock_all_devices();
1290 usb_lock_device(ps->dev);
1291 break;
1292
1293 /* talk directly to the interface's driver */
1294 default:
1295 down_read(&usb_bus_type.subsys.rwsem);
1296 if (intf->dev.driver)
1297 driver = to_usb_driver(intf->dev.driver);
1298 if (driver == NULL || driver->ioctl == NULL) {
1299 retval = -ENOTTY;
1300 } else {
1301 retval = driver->ioctl (intf, ctrl.ioctl_code, buf);
1302 if (retval == -ENOIOCTLCMD)
1303 retval = -ENOTTY;
1304 }
1305 up_read(&usb_bus_type.subsys.rwsem);
1306 }
1307
1308 /* cleanup and return */
1309 if (retval >= 0
1310 && (_IOC_DIR (ctrl.ioctl_code) & _IOC_READ) != 0
1311 && size > 0
1312 && copy_to_user (ctrl.data, buf, size) != 0)
1313 retval = -EFAULT;
1314 if (buf != NULL)
1315 kfree (buf);
1316 return retval;
1317}
1318
1319/*
1320 * NOTE: All requests here that have interface numbers as parameters
1321 * are assuming that somehow the configuration has been prevented from
1322 * changing. But there's no mechanism to ensure that...
1323 */
1324static int usbdev_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long arg)
1325{
1326 struct dev_state *ps = (struct dev_state *)file->private_data;
1327 struct usb_device *dev = ps->dev;
1328 void __user *p = (void __user *)arg;
1329 int ret = -ENOTTY;
1330
1331 if (!(file->f_mode & FMODE_WRITE))
1332 return -EPERM;
1333 usb_lock_device(dev);
1334 if (!connected(dev)) {
1335 usb_unlock_device(dev);
1336 return -ENODEV;
1337 }
1338
1339 switch (cmd) {
1340 case USBDEVFS_CONTROL:
1341 snoop(&dev->dev, "%s: CONTROL\n", __FUNCTION__);
1342 ret = proc_control(ps, p);
1343 if (ret >= 0)
1344 inode->i_mtime = CURRENT_TIME;
1345 break;
1346
1347 case USBDEVFS_BULK:
1348 snoop(&dev->dev, "%s: BULK\n", __FUNCTION__);
1349 ret = proc_bulk(ps, p);
1350 if (ret >= 0)
1351 inode->i_mtime = CURRENT_TIME;
1352 break;
1353
1354 case USBDEVFS_RESETEP:
1355 snoop(&dev->dev, "%s: RESETEP\n", __FUNCTION__);
1356 ret = proc_resetep(ps, p);
1357 if (ret >= 0)
1358 inode->i_mtime = CURRENT_TIME;
1359 break;
1360
1361 case USBDEVFS_RESET:
1362 snoop(&dev->dev, "%s: RESET\n", __FUNCTION__);
1363 ret = proc_resetdevice(ps);
1364 break;
1365
1366 case USBDEVFS_CLEAR_HALT:
1367 snoop(&dev->dev, "%s: CLEAR_HALT\n", __FUNCTION__);
1368 ret = proc_clearhalt(ps, p);
1369 if (ret >= 0)
1370 inode->i_mtime = CURRENT_TIME;
1371 break;
1372
1373 case USBDEVFS_GETDRIVER:
1374 snoop(&dev->dev, "%s: GETDRIVER\n", __FUNCTION__);
1375 ret = proc_getdriver(ps, p);
1376 break;
1377
1378 case USBDEVFS_CONNECTINFO:
1379 snoop(&dev->dev, "%s: CONNECTINFO\n", __FUNCTION__);
1380 ret = proc_connectinfo(ps, p);
1381 break;
1382
1383 case USBDEVFS_SETINTERFACE:
1384 snoop(&dev->dev, "%s: SETINTERFACE\n", __FUNCTION__);
1385 ret = proc_setintf(ps, p);
1386 break;
1387
1388 case USBDEVFS_SETCONFIGURATION:
1389 snoop(&dev->dev, "%s: SETCONFIGURATION\n", __FUNCTION__);
1390 ret = proc_setconfig(ps, p);
1391 break;
1392
1393 case USBDEVFS_SUBMITURB:
1394 snoop(&dev->dev, "%s: SUBMITURB\n", __FUNCTION__);
1395 ret = proc_submiturb(ps, p);
1396 if (ret >= 0)
1397 inode->i_mtime = CURRENT_TIME;
1398 break;
1399
1400#ifdef CONFIG_COMPAT
1401
1402 case USBDEVFS_SUBMITURB32:
1403 snoop(&dev->dev, "%s: SUBMITURB32\n", __FUNCTION__);
1404 ret = proc_submiturb_compat(ps, p);
1405 if (ret >= 0)
1406 inode->i_mtime = CURRENT_TIME;
1407 break;
1408
1409 case USBDEVFS_REAPURB32:
1410 snoop(&dev->dev, "%s: REAPURB32\n", __FUNCTION__);
1411 ret = proc_reapurb_compat(ps, p);
1412 break;
1413
1414 case USBDEVFS_REAPURBNDELAY32:
1415 snoop(&dev->dev, "%s: REAPURBDELAY32\n", __FUNCTION__);
1416 ret = proc_reapurbnonblock_compat(ps, p);
1417 break;
1418
1419#endif
1420
1421 case USBDEVFS_DISCARDURB:
1422 snoop(&dev->dev, "%s: DISCARDURB\n", __FUNCTION__);
1423 ret = proc_unlinkurb(ps, p);
1424 break;
1425
1426 case USBDEVFS_REAPURB:
1427 snoop(&dev->dev, "%s: REAPURB\n", __FUNCTION__);
1428 ret = proc_reapurb(ps, p);
1429 break;
1430
1431 case USBDEVFS_REAPURBNDELAY:
1432 snoop(&dev->dev, "%s: REAPURBDELAY\n", __FUNCTION__);
1433 ret = proc_reapurbnonblock(ps, p);
1434 break;
1435
1436 case USBDEVFS_DISCSIGNAL:
1437 snoop(&dev->dev, "%s: DISCSIGNAL\n", __FUNCTION__);
1438 ret = proc_disconnectsignal(ps, p);
1439 break;
1440
1441 case USBDEVFS_CLAIMINTERFACE:
1442 snoop(&dev->dev, "%s: CLAIMINTERFACE\n", __FUNCTION__);
1443 ret = proc_claiminterface(ps, p);
1444 break;
1445
1446 case USBDEVFS_RELEASEINTERFACE:
1447 snoop(&dev->dev, "%s: RELEASEINTERFACE\n", __FUNCTION__);
1448 ret = proc_releaseinterface(ps, p);
1449 break;
1450
1451 case USBDEVFS_IOCTL:
1452 snoop(&dev->dev, "%s: IOCTL\n", __FUNCTION__);
1453 ret = proc_ioctl(ps, p);
1454 break;
1455 }
1456 usb_unlock_device(dev);
1457 if (ret >= 0)
1458 inode->i_atime = CURRENT_TIME;
1459 return ret;
1460}
1461
1462/* No kernel lock - fine */
1463static unsigned int usbdev_poll(struct file *file, struct poll_table_struct *wait)
1464{
1465 struct dev_state *ps = (struct dev_state *)file->private_data;
1466 unsigned int mask = 0;
1467
1468 poll_wait(file, &ps->wait, wait);
1469 if (file->f_mode & FMODE_WRITE && !list_empty(&ps->async_completed))
1470 mask |= POLLOUT | POLLWRNORM;
1471 if (!connected(ps->dev))
1472 mask |= POLLERR | POLLHUP;
1473 return mask;
1474}
1475
1476struct file_operations usbfs_device_file_operations = {
1477 .llseek = usbdev_lseek,
1478 .read = usbdev_read,
1479 .poll = usbdev_poll,
1480 .ioctl = usbdev_ioctl,
1481 .open = usbdev_open,
1482 .release = usbdev_release,
1483};
diff --git a/drivers/usb/core/file.c b/drivers/usb/core/file.c
new file mode 100644
index 000000000000..80ce9644d0ee
--- /dev/null
+++ b/drivers/usb/core/file.c
@@ -0,0 +1,227 @@
1/*
2 * drivers/usb/file.c
3 *
4 * (C) Copyright Linus Torvalds 1999
5 * (C) Copyright Johannes Erdfelt 1999-2001
6 * (C) Copyright Andreas Gal 1999
7 * (C) Copyright Gregory P. Smith 1999
8 * (C) Copyright Deti Fliegl 1999 (new USB architecture)
9 * (C) Copyright Randy Dunlap 2000
10 * (C) Copyright David Brownell 2000-2001 (kernel hotplug, usb_device_id,
11 more docs, etc)
12 * (C) Copyright Yggdrasil Computing, Inc. 2000
13 * (usb_device_id matching changes by Adam J. Richter)
14 * (C) Copyright Greg Kroah-Hartman 2002-2003
15 *
16 */
17
18#include <linux/config.h>
19#include <linux/module.h>
20#include <linux/devfs_fs_kernel.h>
21#include <linux/spinlock.h>
22#include <linux/errno.h>
23
24#ifdef CONFIG_USB_DEBUG
25 #define DEBUG
26#else
27 #undef DEBUG
28#endif
29#include <linux/usb.h>
30
31#define MAX_USB_MINORS 256
32static struct file_operations *usb_minors[MAX_USB_MINORS];
33static DEFINE_SPINLOCK(minor_lock);
34
35static int usb_open(struct inode * inode, struct file * file)
36{
37 int minor = iminor(inode);
38 struct file_operations *c;
39 int err = -ENODEV;
40 struct file_operations *old_fops, *new_fops = NULL;
41
42 spin_lock (&minor_lock);
43 c = usb_minors[minor];
44
45 if (!c || !(new_fops = fops_get(c))) {
46 spin_unlock(&minor_lock);
47 return err;
48 }
49 spin_unlock(&minor_lock);
50
51 old_fops = file->f_op;
52 file->f_op = new_fops;
53 /* Curiouser and curiouser... NULL ->open() as "no device" ? */
54 if (file->f_op->open)
55 err = file->f_op->open(inode,file);
56 if (err) {
57 fops_put(file->f_op);
58 file->f_op = fops_get(old_fops);
59 }
60 fops_put(old_fops);
61 return err;
62}
63
64static struct file_operations usb_fops = {
65 .owner = THIS_MODULE,
66 .open = usb_open,
67};
68
69static struct class_simple *usb_class;
70
71int usb_major_init(void)
72{
73 int error;
74
75 error = register_chrdev(USB_MAJOR, "usb", &usb_fops);
76 if (error) {
77 err("unable to get major %d for usb devices", USB_MAJOR);
78 goto out;
79 }
80
81 usb_class = class_simple_create(THIS_MODULE, "usb");
82 if (IS_ERR(usb_class)) {
83 err("class_simple_create failed for usb devices");
84 unregister_chrdev(USB_MAJOR, "usb");
85 goto out;
86 }
87
88 devfs_mk_dir("usb");
89
90out:
91 return error;
92}
93
94void usb_major_cleanup(void)
95{
96 class_simple_destroy(usb_class);
97 devfs_remove("usb");
98 unregister_chrdev(USB_MAJOR, "usb");
99}
100
101/**
102 * usb_register_dev - register a USB device, and ask for a minor number
103 * @intf: pointer to the usb_interface that is being registered
104 * @class_driver: pointer to the usb_class_driver for this device
105 *
106 * This should be called by all USB drivers that use the USB major number.
107 * If CONFIG_USB_DYNAMIC_MINORS is enabled, the minor number will be
108 * dynamically allocated out of the list of available ones. If it is not
109 * enabled, the minor number will be based on the next available free minor,
110 * starting at the class_driver->minor_base.
111 *
112 * This function also creates the devfs file for the usb device, if devfs
113 * is enabled, and creates a usb class device in the sysfs tree.
114 *
115 * usb_deregister_dev() must be called when the driver is done with
116 * the minor numbers given out by this function.
117 *
118 * Returns -EINVAL if something bad happens with trying to register a
119 * device, and 0 on success.
120 */
121int usb_register_dev(struct usb_interface *intf,
122 struct usb_class_driver *class_driver)
123{
124 int retval = -EINVAL;
125 int minor_base = class_driver->minor_base;
126 int minor = 0;
127 char name[BUS_ID_SIZE];
128 char *temp;
129
130#ifdef CONFIG_USB_DYNAMIC_MINORS
131 /*
132 * We don't care what the device tries to start at, we want to start
133 * at zero to pack the devices into the smallest available space with
134 * no holes in the minor range.
135 */
136 minor_base = 0;
137#endif
138 intf->minor = -1;
139
140 dbg ("looking for a minor, starting at %d", minor_base);
141
142 if (class_driver->fops == NULL)
143 goto exit;
144
145 spin_lock (&minor_lock);
146 for (minor = minor_base; minor < MAX_USB_MINORS; ++minor) {
147 if (usb_minors[minor])
148 continue;
149
150 usb_minors[minor] = class_driver->fops;
151
152 retval = 0;
153 break;
154 }
155 spin_unlock (&minor_lock);
156
157 if (retval)
158 goto exit;
159
160 intf->minor = minor;
161
162 /* handle the devfs registration */
163 snprintf(name, BUS_ID_SIZE, class_driver->name, minor - minor_base);
164 devfs_mk_cdev(MKDEV(USB_MAJOR, minor), class_driver->mode, name);
165
166 /* create a usb class device for this usb interface */
167 temp = strrchr(name, '/');
168 if (temp && (temp[1] != 0x00))
169 ++temp;
170 else
171 temp = name;
172 intf->class_dev = class_simple_device_add(usb_class, MKDEV(USB_MAJOR, minor), &intf->dev, "%s", temp);
173 if (IS_ERR(intf->class_dev)) {
174 spin_lock (&minor_lock);
175 usb_minors[intf->minor] = NULL;
176 spin_unlock (&minor_lock);
177 devfs_remove (name);
178 retval = PTR_ERR(intf->class_dev);
179 }
180exit:
181 return retval;
182}
183EXPORT_SYMBOL(usb_register_dev);
184
185/**
186 * usb_deregister_dev - deregister a USB device's dynamic minor.
187 * @intf: pointer to the usb_interface that is being deregistered
188 * @class_driver: pointer to the usb_class_driver for this device
189 *
190 * Used in conjunction with usb_register_dev(). This function is called
191 * when the USB driver is finished with the minor numbers gotten from a
192 * call to usb_register_dev() (usually when the device is disconnected
193 * from the system.)
194 *
195 * This function also cleans up the devfs file for the usb device, if devfs
196 * is enabled, and removes the usb class device from the sysfs tree.
197 *
198 * This should be called by all drivers that use the USB major number.
199 */
200void usb_deregister_dev(struct usb_interface *intf,
201 struct usb_class_driver *class_driver)
202{
203 int minor_base = class_driver->minor_base;
204 char name[BUS_ID_SIZE];
205
206#ifdef CONFIG_USB_DYNAMIC_MINORS
207 minor_base = 0;
208#endif
209
210 if (intf->minor == -1)
211 return;
212
213 dbg ("removing %d minor", intf->minor);
214
215 spin_lock (&minor_lock);
216 usb_minors[intf->minor] = NULL;
217 spin_unlock (&minor_lock);
218
219 snprintf(name, BUS_ID_SIZE, class_driver->name, intf->minor - minor_base);
220 devfs_remove (name);
221 class_simple_device_remove(MKDEV(USB_MAJOR, intf->minor));
222 intf->class_dev = NULL;
223 intf->minor = -1;
224}
225EXPORT_SYMBOL(usb_deregister_dev);
226
227
diff --git a/drivers/usb/core/hcd-pci.c b/drivers/usb/core/hcd-pci.c
new file mode 100644
index 000000000000..b9a3dae07036
--- /dev/null
+++ b/drivers/usb/core/hcd-pci.c
@@ -0,0 +1,358 @@
1/*
2 * (C) Copyright David Brownell 2000-2002
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19#include <linux/config.h>
20
21#ifdef CONFIG_USB_DEBUG
22 #define DEBUG
23#else
24 #undef DEBUG
25#endif
26
27#include <linux/kernel.h>
28#include <linux/module.h>
29#include <linux/pci.h>
30#include <asm/io.h>
31#include <asm/irq.h>
32#include <linux/usb.h>
33#include "hcd.h"
34
35
36/* PCI-based HCs are normal, but custom bus glue should be ok */
37
38
39/*-------------------------------------------------------------------------*/
40
41/* configure so an HC device and id are always provided */
42/* always called with process context; sleeping is OK */
43
44/**
45 * usb_hcd_pci_probe - initialize PCI-based HCDs
46 * @dev: USB Host Controller being probed
47 * @id: pci hotplug id connecting controller to HCD framework
48 * Context: !in_interrupt()
49 *
50 * Allocates basic PCI resources for this USB host controller, and
51 * then invokes the start() method for the HCD associated with it
52 * through the hotplug entry's driver_data.
53 *
54 * Store this function in the HCD's struct pci_driver as probe().
55 */
56int usb_hcd_pci_probe (struct pci_dev *dev, const struct pci_device_id *id)
57{
58 struct hc_driver *driver;
59 struct usb_hcd *hcd;
60 int retval;
61
62 if (usb_disabled())
63 return -ENODEV;
64
65 if (!id || !(driver = (struct hc_driver *) id->driver_data))
66 return -EINVAL;
67
68 if (pci_enable_device (dev) < 0)
69 return -ENODEV;
70 dev->current_state = 0;
71 dev->dev.power.power_state = 0;
72
73 if (!dev->irq) {
74 dev_err (&dev->dev,
75 "Found HC with no IRQ. Check BIOS/PCI %s setup!\n",
76 pci_name(dev));
77 retval = -ENODEV;
78 goto err1;
79 }
80
81 hcd = usb_create_hcd (driver, &dev->dev, pci_name(dev));
82 if (!hcd) {
83 retval = -ENOMEM;
84 goto err1;
85 }
86
87 if (driver->flags & HCD_MEMORY) { // EHCI, OHCI
88 hcd->rsrc_start = pci_resource_start (dev, 0);
89 hcd->rsrc_len = pci_resource_len (dev, 0);
90 if (!request_mem_region (hcd->rsrc_start, hcd->rsrc_len,
91 driver->description)) {
92 dev_dbg (&dev->dev, "controller already in use\n");
93 retval = -EBUSY;
94 goto err2;
95 }
96 hcd->regs = ioremap_nocache (hcd->rsrc_start, hcd->rsrc_len);
97 if (hcd->regs == NULL) {
98 dev_dbg (&dev->dev, "error mapping memory\n");
99 retval = -EFAULT;
100 goto err3;
101 }
102
103 } else { // UHCI
104 int region;
105
106 for (region = 0; region < PCI_ROM_RESOURCE; region++) {
107 if (!(pci_resource_flags (dev, region) &
108 IORESOURCE_IO))
109 continue;
110
111 hcd->rsrc_start = pci_resource_start (dev, region);
112 hcd->rsrc_len = pci_resource_len (dev, region);
113 if (request_region (hcd->rsrc_start, hcd->rsrc_len,
114 driver->description))
115 break;
116 }
117 if (region == PCI_ROM_RESOURCE) {
118 dev_dbg (&dev->dev, "no i/o regions available\n");
119 retval = -EBUSY;
120 goto err1;
121 }
122 }
123
124#ifdef CONFIG_PCI_NAMES
125 hcd->product_desc = dev->pretty_name;
126#endif
127
128 pci_set_master (dev);
129
130 retval = usb_add_hcd (hcd, dev->irq, SA_SHIRQ);
131 if (retval != 0)
132 goto err4;
133 return retval;
134
135 err4:
136 if (driver->flags & HCD_MEMORY) {
137 iounmap (hcd->regs);
138 err3:
139 release_mem_region (hcd->rsrc_start, hcd->rsrc_len);
140 } else
141 release_region (hcd->rsrc_start, hcd->rsrc_len);
142 err2:
143 usb_put_hcd (hcd);
144 err1:
145 pci_disable_device (dev);
146 dev_err (&dev->dev, "init %s fail, %d\n", pci_name(dev), retval);
147 return retval;
148}
149EXPORT_SYMBOL (usb_hcd_pci_probe);
150
151
152/* may be called without controller electrically present */
153/* may be called with controller, bus, and devices active */
154
155/**
156 * usb_hcd_pci_remove - shutdown processing for PCI-based HCDs
157 * @dev: USB Host Controller being removed
158 * Context: !in_interrupt()
159 *
160 * Reverses the effect of usb_hcd_pci_probe(), first invoking
161 * the HCD's stop() method. It is always called from a thread
162 * context, normally "rmmod", "apmd", or something similar.
163 *
164 * Store this function in the HCD's struct pci_driver as remove().
165 */
166void usb_hcd_pci_remove (struct pci_dev *dev)
167{
168 struct usb_hcd *hcd;
169
170 hcd = pci_get_drvdata(dev);
171 if (!hcd)
172 return;
173
174 usb_remove_hcd (hcd);
175 if (hcd->driver->flags & HCD_MEMORY) {
176 iounmap (hcd->regs);
177 release_mem_region (hcd->rsrc_start, hcd->rsrc_len);
178 } else {
179 release_region (hcd->rsrc_start, hcd->rsrc_len);
180 }
181 usb_put_hcd (hcd);
182 pci_disable_device(dev);
183}
184EXPORT_SYMBOL (usb_hcd_pci_remove);
185
186
187#ifdef CONFIG_PM
188
189static char __attribute_used__ *pci_state(u32 state)
190{
191 switch (state) {
192 case 0: return "D0";
193 case 1: return "D1";
194 case 2: return "D2";
195 case 3: return "D3hot";
196 case 4: return "D3cold";
197 }
198 return NULL;
199}
200
201/**
202 * usb_hcd_pci_suspend - power management suspend of a PCI-based HCD
203 * @dev: USB Host Controller being suspended
204 * @state: state that the controller is going into
205 *
206 * Store this function in the HCD's struct pci_driver as suspend().
207 */
208int usb_hcd_pci_suspend (struct pci_dev *dev, u32 state)
209{
210 struct usb_hcd *hcd;
211 int retval = 0;
212 int has_pci_pm;
213
214 hcd = pci_get_drvdata(dev);
215
216 /* even when the PCI layer rejects some of the PCI calls
217 * below, HCs can try global suspend and reduce DMA traffic.
218 * PM-sensitive HCDs may already have done this.
219 */
220 has_pci_pm = pci_find_capability(dev, PCI_CAP_ID_PM);
221 if (state > 4)
222 state = 4;
223
224 switch (hcd->state) {
225
226 /* entry if root hub wasn't yet suspended ... from sysfs,
227 * without autosuspend, or if USB_SUSPEND isn't configured.
228 */
229 case HC_STATE_RUNNING:
230 hcd->state = HC_STATE_QUIESCING;
231 retval = hcd->driver->suspend (hcd, state);
232 if (retval) {
233 dev_dbg (hcd->self.controller,
234 "suspend fail, retval %d\n",
235 retval);
236 break;
237 }
238 hcd->state = HC_STATE_SUSPENDED;
239 /* FALLTHROUGH */
240
241 /* entry with CONFIG_USB_SUSPEND, or hcds that autosuspend: the
242 * controller and/or root hub will already have been suspended,
243 * but it won't be ready for a PCI resume call.
244 *
245 * FIXME only CONFIG_USB_SUSPEND guarantees hub_suspend() will
246 * have been called, otherwise root hub timers still run ...
247 */
248 case HC_STATE_SUSPENDED:
249 if (state <= dev->current_state)
250 break;
251
252 /* no DMA or IRQs except in D0 */
253 if (!dev->current_state) {
254 pci_save_state (dev);
255 pci_disable_device (dev);
256 free_irq (hcd->irq, hcd);
257 }
258
259 if (!has_pci_pm) {
260 dev_dbg (hcd->self.controller, "--> PCI D0/legacy\n");
261 break;
262 }
263
264 /* POLICY: ignore D1/D2/D3hot differences;
265 * we know D3hot will always work.
266 */
267 retval = pci_set_power_state (dev, state);
268 if (retval < 0 && state < 3) {
269 retval = pci_set_power_state (dev, 3);
270 if (retval == 0)
271 state = 3;
272 }
273 if (retval == 0) {
274 dev_dbg (hcd->self.controller, "--> PCI %s\n",
275 pci_state(dev->current_state));
276#ifdef CONFIG_USB_SUSPEND
277 pci_enable_wake (dev, state, hcd->remote_wakeup);
278 pci_enable_wake (dev, 4, hcd->remote_wakeup);
279#endif
280 } else if (retval < 0) {
281 dev_dbg (&dev->dev, "PCI %s suspend fail, %d\n",
282 pci_state(state), retval);
283 (void) usb_hcd_pci_resume (dev);
284 break;
285 }
286 break;
287 default:
288 dev_dbg (hcd->self.controller, "hcd state %d; not suspended\n",
289 hcd->state);
290 retval = -EINVAL;
291 break;
292 }
293
294 /* update power_state **ONLY** to make sysfs happier */
295 if (retval == 0)
296 dev->dev.power.power_state = state;
297 return retval;
298}
299EXPORT_SYMBOL (usb_hcd_pci_suspend);
300
301/**
302 * usb_hcd_pci_resume - power management resume of a PCI-based HCD
303 * @dev: USB Host Controller being resumed
304 *
305 * Store this function in the HCD's struct pci_driver as resume().
306 */
307int usb_hcd_pci_resume (struct pci_dev *dev)
308{
309 struct usb_hcd *hcd;
310 int retval;
311 int has_pci_pm;
312
313 hcd = pci_get_drvdata(dev);
314 if (hcd->state != HC_STATE_SUSPENDED) {
315 dev_dbg (hcd->self.controller,
316 "can't resume, not suspended!\n");
317 return 0;
318 }
319 has_pci_pm = pci_find_capability(dev, PCI_CAP_ID_PM);
320
321 /* D3cold resume isn't usually reported this way... */
322 dev_dbg(hcd->self.controller, "resume from PCI %s%s\n",
323 pci_state(dev->current_state),
324 has_pci_pm ? "" : " (legacy)");
325
326 hcd->state = HC_STATE_RESUMING;
327
328 if (has_pci_pm)
329 pci_set_power_state (dev, 0);
330 dev->dev.power.power_state = 0;
331 retval = request_irq (dev->irq, usb_hcd_irq, SA_SHIRQ,
332 hcd->driver->description, hcd);
333 if (retval < 0) {
334 dev_err (hcd->self.controller,
335 "can't restore IRQ after resume!\n");
336 return retval;
337 }
338 hcd->saw_irq = 0;
339 pci_restore_state (dev);
340#ifdef CONFIG_USB_SUSPEND
341 pci_enable_wake (dev, dev->current_state, 0);
342 pci_enable_wake (dev, 4, 0);
343#endif
344
345 retval = hcd->driver->resume (hcd);
346 if (!HC_IS_RUNNING (hcd->state)) {
347 dev_dbg (hcd->self.controller,
348 "resume fail, retval %d\n", retval);
349 usb_hc_died (hcd);
350 }
351
352 return retval;
353}
354EXPORT_SYMBOL (usb_hcd_pci_resume);
355
356#endif /* CONFIG_PM */
357
358
diff --git a/drivers/usb/core/hcd.c b/drivers/usb/core/hcd.c
new file mode 100644
index 000000000000..266e9e06a9f5
--- /dev/null
+++ b/drivers/usb/core/hcd.c
@@ -0,0 +1,1840 @@
1/*
2 * (C) Copyright Linus Torvalds 1999
3 * (C) Copyright Johannes Erdfelt 1999-2001
4 * (C) Copyright Andreas Gal 1999
5 * (C) Copyright Gregory P. Smith 1999
6 * (C) Copyright Deti Fliegl 1999
7 * (C) Copyright Randy Dunlap 2000
8 * (C) Copyright David Brownell 2000-2002
9 *
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU General Public License as published by the
12 * Free Software Foundation; either version 2 of the License, or (at your
13 * option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
18 * for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25#include <linux/config.h>
26
27#ifdef CONFIG_USB_DEBUG
28#define DEBUG
29#endif
30
31#include <linux/module.h>
32#include <linux/version.h>
33#include <linux/kernel.h>
34#include <linux/slab.h>
35#include <linux/completion.h>
36#include <linux/utsname.h>
37#include <linux/mm.h>
38#include <asm/io.h>
39#include <asm/scatterlist.h>
40#include <linux/device.h>
41#include <linux/dma-mapping.h>
42#include <asm/irq.h>
43#include <asm/byteorder.h>
44
45#include <linux/usb.h>
46
47#include "usb.h"
48#include "hcd.h"
49#include "hub.h"
50
51
52// #define USB_BANDWIDTH_MESSAGES
53
54/*-------------------------------------------------------------------------*/
55
56/*
57 * USB Host Controller Driver framework
58 *
59 * Plugs into usbcore (usb_bus) and lets HCDs share code, minimizing
60 * HCD-specific behaviors/bugs.
61 *
62 * This does error checks, tracks devices and urbs, and delegates to a
63 * "hc_driver" only for code (and data) that really needs to know about
64 * hardware differences. That includes root hub registers, i/o queues,
65 * and so on ... but as little else as possible.
66 *
67 * Shared code includes most of the "root hub" code (these are emulated,
68 * though each HC's hardware works differently) and PCI glue, plus request
69 * tracking overhead. The HCD code should only block on spinlocks or on
70 * hardware handshaking; blocking on software events (such as other kernel
71 * threads releasing resources, or completing actions) is all generic.
72 *
73 * Happens the USB 2.0 spec says this would be invisible inside the "USBD",
74 * and includes mostly a "HCDI" (HCD Interface) along with some APIs used
75 * only by the hub driver ... and that neither should be seen or used by
76 * usb client device drivers.
77 *
78 * Contributors of ideas or unattributed patches include: David Brownell,
79 * Roman Weissgaerber, Rory Bolt, Greg Kroah-Hartman, ...
80 *
81 * HISTORY:
82 * 2002-02-21 Pull in most of the usb_bus support from usb.c; some
83 * associated cleanup. "usb_hcd" still != "usb_bus".
84 * 2001-12-12 Initial patch version for Linux 2.5.1 kernel.
85 */
86
87/*-------------------------------------------------------------------------*/
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 */
101DECLARE_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 hcd data */
108static DEFINE_SPINLOCK(hcd_data_lock);
109
110/* wait queue for synchronous unlinks */
111DECLARE_WAIT_QUEUE_HEAD(usb_kill_urb_queue);
112
113/*-------------------------------------------------------------------------*/
114
115/*
116 * Sharable chunks of root hub code.
117 */
118
119/*-------------------------------------------------------------------------*/
120
121#define KERNEL_REL ((LINUX_VERSION_CODE >> 16) & 0x0ff)
122#define KERNEL_VER ((LINUX_VERSION_CODE >> 8) & 0x0ff)
123
124/* usb 2.0 root hub device descriptor */
125static const u8 usb2_rh_dev_descriptor [18] = {
126 0x12, /* __u8 bLength; */
127 0x01, /* __u8 bDescriptorType; Device */
128 0x00, 0x02, /* __le16 bcdUSB; v2.0 */
129
130 0x09, /* __u8 bDeviceClass; HUB_CLASSCODE */
131 0x00, /* __u8 bDeviceSubClass; */
132 0x01, /* __u8 bDeviceProtocol; [ usb 2.0 single TT ]*/
133 0x08, /* __u8 bMaxPacketSize0; 8 Bytes */
134
135 0x00, 0x00, /* __le16 idVendor; */
136 0x00, 0x00, /* __le16 idProduct; */
137 KERNEL_VER, KERNEL_REL, /* __le16 bcdDevice */
138
139 0x03, /* __u8 iManufacturer; */
140 0x02, /* __u8 iProduct; */
141 0x01, /* __u8 iSerialNumber; */
142 0x01 /* __u8 bNumConfigurations; */
143};
144
145/* no usb 2.0 root hub "device qualifier" descriptor: one speed only */
146
147/* usb 1.1 root hub device descriptor */
148static const u8 usb11_rh_dev_descriptor [18] = {
149 0x12, /* __u8 bLength; */
150 0x01, /* __u8 bDescriptorType; Device */
151 0x10, 0x01, /* __le16 bcdUSB; v1.1 */
152
153 0x09, /* __u8 bDeviceClass; HUB_CLASSCODE */
154 0x00, /* __u8 bDeviceSubClass; */
155 0x00, /* __u8 bDeviceProtocol; [ low/full speeds only ] */
156 0x08, /* __u8 bMaxPacketSize0; 8 Bytes */
157
158 0x00, 0x00, /* __le16 idVendor; */
159 0x00, 0x00, /* __le16 idProduct; */
160 KERNEL_VER, KERNEL_REL, /* __le16 bcdDevice */
161
162 0x03, /* __u8 iManufacturer; */
163 0x02, /* __u8 iProduct; */
164 0x01, /* __u8 iSerialNumber; */
165 0x01 /* __u8 bNumConfigurations; */
166};
167
168
169/*-------------------------------------------------------------------------*/
170
171/* Configuration descriptors for our root hubs */
172
173static const u8 fs_rh_config_descriptor [] = {
174
175 /* one configuration */
176 0x09, /* __u8 bLength; */
177 0x02, /* __u8 bDescriptorType; Configuration */
178 0x19, 0x00, /* __le16 wTotalLength; */
179 0x01, /* __u8 bNumInterfaces; (1) */
180 0x01, /* __u8 bConfigurationValue; */
181 0x00, /* __u8 iConfiguration; */
182 0xc0, /* __u8 bmAttributes;
183 Bit 7: must be set,
184 6: Self-powered,
185 5: Remote wakeup,
186 4..0: resvd */
187 0x00, /* __u8 MaxPower; */
188
189 /* USB 1.1:
190 * USB 2.0, single TT organization (mandatory):
191 * one interface, protocol 0
192 *
193 * USB 2.0, multiple TT organization (optional):
194 * two interfaces, protocols 1 (like single TT)
195 * and 2 (multiple TT mode) ... config is
196 * sometimes settable
197 * NOT IMPLEMENTED
198 */
199
200 /* one interface */
201 0x09, /* __u8 if_bLength; */
202 0x04, /* __u8 if_bDescriptorType; Interface */
203 0x00, /* __u8 if_bInterfaceNumber; */
204 0x00, /* __u8 if_bAlternateSetting; */
205 0x01, /* __u8 if_bNumEndpoints; */
206 0x09, /* __u8 if_bInterfaceClass; HUB_CLASSCODE */
207 0x00, /* __u8 if_bInterfaceSubClass; */
208 0x00, /* __u8 if_bInterfaceProtocol; [usb1.1 or single tt] */
209 0x00, /* __u8 if_iInterface; */
210
211 /* one endpoint (status change endpoint) */
212 0x07, /* __u8 ep_bLength; */
213 0x05, /* __u8 ep_bDescriptorType; Endpoint */
214 0x81, /* __u8 ep_bEndpointAddress; IN Endpoint 1 */
215 0x03, /* __u8 ep_bmAttributes; Interrupt */
216 0x02, 0x00, /* __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
217 0xff /* __u8 ep_bInterval; (255ms -- usb 2.0 spec) */
218};
219
220static const u8 hs_rh_config_descriptor [] = {
221
222 /* one configuration */
223 0x09, /* __u8 bLength; */
224 0x02, /* __u8 bDescriptorType; Configuration */
225 0x19, 0x00, /* __le16 wTotalLength; */
226 0x01, /* __u8 bNumInterfaces; (1) */
227 0x01, /* __u8 bConfigurationValue; */
228 0x00, /* __u8 iConfiguration; */
229 0xc0, /* __u8 bmAttributes;
230 Bit 7: must be set,
231 6: Self-powered,
232 5: Remote wakeup,
233 4..0: resvd */
234 0x00, /* __u8 MaxPower; */
235
236 /* USB 1.1:
237 * USB 2.0, single TT organization (mandatory):
238 * one interface, protocol 0
239 *
240 * USB 2.0, multiple TT organization (optional):
241 * two interfaces, protocols 1 (like single TT)
242 * and 2 (multiple TT mode) ... config is
243 * sometimes settable
244 * NOT IMPLEMENTED
245 */
246
247 /* one interface */
248 0x09, /* __u8 if_bLength; */
249 0x04, /* __u8 if_bDescriptorType; Interface */
250 0x00, /* __u8 if_bInterfaceNumber; */
251 0x00, /* __u8 if_bAlternateSetting; */
252 0x01, /* __u8 if_bNumEndpoints; */
253 0x09, /* __u8 if_bInterfaceClass; HUB_CLASSCODE */
254 0x00, /* __u8 if_bInterfaceSubClass; */
255 0x00, /* __u8 if_bInterfaceProtocol; [usb1.1 or single tt] */
256 0x00, /* __u8 if_iInterface; */
257
258 /* one endpoint (status change endpoint) */
259 0x07, /* __u8 ep_bLength; */
260 0x05, /* __u8 ep_bDescriptorType; Endpoint */
261 0x81, /* __u8 ep_bEndpointAddress; IN Endpoint 1 */
262 0x03, /* __u8 ep_bmAttributes; Interrupt */
263 0x02, 0x00, /* __le16 ep_wMaxPacketSize; 1 + (MAX_ROOT_PORTS / 8) */
264 0x0c /* __u8 ep_bInterval; (256ms -- usb 2.0 spec) */
265};
266
267/*-------------------------------------------------------------------------*/
268
269/*
270 * helper routine for returning string descriptors in UTF-16LE
271 * input can actually be ISO-8859-1; ASCII is its 7-bit subset
272 */
273static int ascii2utf (char *s, u8 *utf, int utfmax)
274{
275 int retval;
276
277 for (retval = 0; *s && utfmax > 1; utfmax -= 2, retval += 2) {
278 *utf++ = *s++;
279 *utf++ = 0;
280 }
281 if (utfmax > 0) {
282 *utf = *s;
283 ++retval;
284 }
285 return retval;
286}
287
288/*
289 * rh_string - provides manufacturer, product and serial strings for root hub
290 * @id: the string ID number (1: serial number, 2: product, 3: vendor)
291 * @hcd: the host controller for this root hub
292 * @type: string describing our driver
293 * @data: return packet in UTF-16 LE
294 * @len: length of the return packet
295 *
296 * Produces either a manufacturer, product or serial number string for the
297 * virtual root hub device.
298 */
299static int rh_string (
300 int id,
301 struct usb_hcd *hcd,
302 u8 *data,
303 int len
304) {
305 char buf [100];
306
307 // language ids
308 if (id == 0) {
309 buf[0] = 4; buf[1] = 3; /* 4 bytes string data */
310 buf[2] = 0x09; buf[3] = 0x04; /* MSFT-speak for "en-us" */
311 len = min (len, 4);
312 memcpy (data, buf, len);
313 return len;
314
315 // serial number
316 } else if (id == 1) {
317 strlcpy (buf, hcd->self.bus_name, sizeof buf);
318
319 // product description
320 } else if (id == 2) {
321 strlcpy (buf, hcd->product_desc, sizeof buf);
322
323 // id 3 == vendor description
324 } else if (id == 3) {
325 snprintf (buf, sizeof buf, "%s %s %s", system_utsname.sysname,
326 system_utsname.release, hcd->driver->description);
327
328 // unsupported IDs --> "protocol stall"
329 } else
330 return -EPIPE;
331
332 switch (len) { /* All cases fall through */
333 default:
334 len = 2 + ascii2utf (buf, data + 2, len - 2);
335 case 2:
336 data [1] = 3; /* type == string */
337 case 1:
338 data [0] = 2 * (strlen (buf) + 1);
339 case 0:
340 ; /* Compiler wants a statement here */
341 }
342 return len;
343}
344
345
346/* Root hub control transfers execute synchronously */
347static int rh_call_control (struct usb_hcd *hcd, struct urb *urb)
348{
349 struct usb_ctrlrequest *cmd;
350 u16 typeReq, wValue, wIndex, wLength;
351 u8 *ubuf = urb->transfer_buffer;
352 u8 tbuf [sizeof (struct usb_hub_descriptor)];
353 const u8 *bufp = tbuf;
354 int len = 0;
355 int patch_wakeup = 0;
356 unsigned long flags;
357 int status = 0;
358 int n;
359
360 cmd = (struct usb_ctrlrequest *) urb->setup_packet;
361 typeReq = (cmd->bRequestType << 8) | cmd->bRequest;
362 wValue = le16_to_cpu (cmd->wValue);
363 wIndex = le16_to_cpu (cmd->wIndex);
364 wLength = le16_to_cpu (cmd->wLength);
365
366 if (wLength > urb->transfer_buffer_length)
367 goto error;
368
369 urb->actual_length = 0;
370 switch (typeReq) {
371
372 /* DEVICE REQUESTS */
373
374 case DeviceRequest | USB_REQ_GET_STATUS:
375 tbuf [0] = (hcd->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP)
376 | (1 << USB_DEVICE_SELF_POWERED);
377 tbuf [1] = 0;
378 len = 2;
379 break;
380 case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
381 if (wValue == USB_DEVICE_REMOTE_WAKEUP)
382 hcd->remote_wakeup = 0;
383 else
384 goto error;
385 break;
386 case DeviceOutRequest | USB_REQ_SET_FEATURE:
387 if (hcd->can_wakeup && wValue == USB_DEVICE_REMOTE_WAKEUP)
388 hcd->remote_wakeup = 1;
389 else
390 goto error;
391 break;
392 case DeviceRequest | USB_REQ_GET_CONFIGURATION:
393 tbuf [0] = 1;
394 len = 1;
395 /* FALLTHROUGH */
396 case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
397 break;
398 case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
399 switch (wValue & 0xff00) {
400 case USB_DT_DEVICE << 8:
401 if (hcd->driver->flags & HCD_USB2)
402 bufp = usb2_rh_dev_descriptor;
403 else if (hcd->driver->flags & HCD_USB11)
404 bufp = usb11_rh_dev_descriptor;
405 else
406 goto error;
407 len = 18;
408 break;
409 case USB_DT_CONFIG << 8:
410 if (hcd->driver->flags & HCD_USB2) {
411 bufp = hs_rh_config_descriptor;
412 len = sizeof hs_rh_config_descriptor;
413 } else {
414 bufp = fs_rh_config_descriptor;
415 len = sizeof fs_rh_config_descriptor;
416 }
417 if (hcd->can_wakeup)
418 patch_wakeup = 1;
419 break;
420 case USB_DT_STRING << 8:
421 n = rh_string (wValue & 0xff, hcd, ubuf, wLength);
422 if (n < 0)
423 goto error;
424 urb->actual_length = n;
425 break;
426 default:
427 goto error;
428 }
429 break;
430 case DeviceRequest | USB_REQ_GET_INTERFACE:
431 tbuf [0] = 0;
432 len = 1;
433 /* FALLTHROUGH */
434 case DeviceOutRequest | USB_REQ_SET_INTERFACE:
435 break;
436 case DeviceOutRequest | USB_REQ_SET_ADDRESS:
437 // wValue == urb->dev->devaddr
438 dev_dbg (hcd->self.controller, "root hub device address %d\n",
439 wValue);
440 break;
441
442 /* INTERFACE REQUESTS (no defined feature/status flags) */
443
444 /* ENDPOINT REQUESTS */
445
446 case EndpointRequest | USB_REQ_GET_STATUS:
447 // ENDPOINT_HALT flag
448 tbuf [0] = 0;
449 tbuf [1] = 0;
450 len = 2;
451 /* FALLTHROUGH */
452 case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:
453 case EndpointOutRequest | USB_REQ_SET_FEATURE:
454 dev_dbg (hcd->self.controller, "no endpoint features yet\n");
455 break;
456
457 /* CLASS REQUESTS (and errors) */
458
459 default:
460 /* non-generic request */
461 if (HC_IS_SUSPENDED (hcd->state))
462 status = -EAGAIN;
463 else {
464 switch (typeReq) {
465 case GetHubStatus:
466 case GetPortStatus:
467 len = 4;
468 break;
469 case GetHubDescriptor:
470 len = sizeof (struct usb_hub_descriptor);
471 break;
472 }
473 status = hcd->driver->hub_control (hcd,
474 typeReq, wValue, wIndex,
475 tbuf, wLength);
476 }
477 break;
478error:
479 /* "protocol stall" on error */
480 status = -EPIPE;
481 }
482
483 if (status) {
484 len = 0;
485 if (status != -EPIPE) {
486 dev_dbg (hcd->self.controller,
487 "CTRL: TypeReq=0x%x val=0x%x "
488 "idx=0x%x len=%d ==> %d\n",
489 typeReq, wValue, wIndex,
490 wLength, urb->status);
491 }
492 }
493 if (len) {
494 if (urb->transfer_buffer_length < len)
495 len = urb->transfer_buffer_length;
496 urb->actual_length = len;
497 // always USB_DIR_IN, toward host
498 memcpy (ubuf, bufp, len);
499
500 /* report whether RH hardware supports remote wakeup */
501 if (patch_wakeup &&
502 len > offsetof (struct usb_config_descriptor,
503 bmAttributes))
504 ((struct usb_config_descriptor *)ubuf)->bmAttributes
505 |= USB_CONFIG_ATT_WAKEUP;
506 }
507
508 /* any errors get returned through the urb completion */
509 local_irq_save (flags);
510 spin_lock (&urb->lock);
511 if (urb->status == -EINPROGRESS)
512 urb->status = status;
513 spin_unlock (&urb->lock);
514 usb_hcd_giveback_urb (hcd, urb, NULL);
515 local_irq_restore (flags);
516 return 0;
517}
518
519/*-------------------------------------------------------------------------*/
520
521/*
522 * Root Hub interrupt transfers are synthesized with a timer.
523 * Completions are called in_interrupt() but not in_irq().
524 *
525 * Note: some root hubs (including common UHCI based designs) can't
526 * correctly issue port change IRQs. They're the ones that _need_ a
527 * timer; most other root hubs don't. Some systems could save a
528 * lot of battery power by eliminating these root hub timer IRQs.
529 */
530
531static void rh_report_status (unsigned long ptr);
532
533static int rh_status_urb (struct usb_hcd *hcd, struct urb *urb)
534{
535 int len = 1 + (urb->dev->maxchild / 8);
536
537 /* rh_timer protected by hcd_data_lock */
538 if (hcd->rh_timer.data || urb->transfer_buffer_length < len) {
539 dev_dbg (hcd->self.controller,
540 "not queuing rh status urb, stat %d\n",
541 urb->status);
542 return -EINVAL;
543 }
544
545 init_timer (&hcd->rh_timer);
546 hcd->rh_timer.function = rh_report_status;
547 hcd->rh_timer.data = (unsigned long) urb;
548 /* USB 2.0 spec says 256msec; this is close enough */
549 hcd->rh_timer.expires = jiffies + HZ/4;
550 add_timer (&hcd->rh_timer);
551 urb->hcpriv = hcd; /* nonzero to indicate it's queued */
552 return 0;
553}
554
555/* timer callback */
556
557static void rh_report_status (unsigned long ptr)
558{
559 struct urb *urb;
560 struct usb_hcd *hcd;
561 int length = 0;
562 unsigned long flags;
563
564 urb = (struct urb *) ptr;
565 local_irq_save (flags);
566 spin_lock (&urb->lock);
567
568 /* do nothing if the urb's been unlinked */
569 if (!urb->dev
570 || urb->status != -EINPROGRESS
571 || (hcd = urb->dev->bus->hcpriv) == NULL) {
572 spin_unlock (&urb->lock);
573 local_irq_restore (flags);
574 return;
575 }
576
577 /* complete the status urb, or retrigger the timer */
578 spin_lock (&hcd_data_lock);
579 if (urb->dev->state == USB_STATE_CONFIGURED) {
580 length = hcd->driver->hub_status_data (
581 hcd, urb->transfer_buffer);
582 if (length > 0) {
583 hcd->rh_timer.data = 0;
584 urb->actual_length = length;
585 urb->status = 0;
586 urb->hcpriv = NULL;
587 } else
588 mod_timer (&hcd->rh_timer, jiffies + HZ/4);
589 }
590 spin_unlock (&hcd_data_lock);
591 spin_unlock (&urb->lock);
592
593 /* local irqs are always blocked in completions */
594 if (length > 0)
595 usb_hcd_giveback_urb (hcd, urb, NULL);
596 local_irq_restore (flags);
597}
598
599/*-------------------------------------------------------------------------*/
600
601static int rh_urb_enqueue (struct usb_hcd *hcd, struct urb *urb)
602{
603 if (usb_pipeint (urb->pipe)) {
604 int retval;
605 unsigned long flags;
606
607 spin_lock_irqsave (&hcd_data_lock, flags);
608 retval = rh_status_urb (hcd, urb);
609 spin_unlock_irqrestore (&hcd_data_lock, flags);
610 return retval;
611 }
612 if (usb_pipecontrol (urb->pipe))
613 return rh_call_control (hcd, urb);
614 else
615 return -EINVAL;
616}
617
618/*-------------------------------------------------------------------------*/
619
620static int usb_rh_urb_dequeue (struct usb_hcd *hcd, struct urb *urb)
621{
622 unsigned long flags;
623
624 /* note: always a synchronous unlink */
625 if ((unsigned long) urb == hcd->rh_timer.data) {
626 del_timer_sync (&hcd->rh_timer);
627 hcd->rh_timer.data = 0;
628
629 local_irq_save (flags);
630 urb->hcpriv = NULL;
631 usb_hcd_giveback_urb (hcd, urb, NULL);
632 local_irq_restore (flags);
633
634 } else if (usb_pipeendpoint(urb->pipe) == 0) {
635 spin_lock_irq(&urb->lock); /* from usb_kill_urb */
636 ++urb->reject;
637 spin_unlock_irq(&urb->lock);
638
639 wait_event(usb_kill_urb_queue,
640 atomic_read(&urb->use_count) == 0);
641
642 spin_lock_irq(&urb->lock);
643 --urb->reject;
644 spin_unlock_irq(&urb->lock);
645 } else
646 return -EINVAL;
647
648 return 0;
649}
650
651/*-------------------------------------------------------------------------*/
652
653/* exported only within usbcore */
654struct usb_bus *usb_bus_get (struct usb_bus *bus)
655{
656 struct class_device *tmp;
657
658 if (!bus)
659 return NULL;
660
661 tmp = class_device_get(&bus->class_dev);
662 if (tmp)
663 return to_usb_bus(tmp);
664 else
665 return NULL;
666}
667
668/* exported only within usbcore */
669void usb_bus_put (struct usb_bus *bus)
670{
671 if (bus)
672 class_device_put(&bus->class_dev);
673}
674
675/*-------------------------------------------------------------------------*/
676
677static void usb_host_release(struct class_device *class_dev)
678{
679 struct usb_bus *bus = to_usb_bus(class_dev);
680
681 if (bus->release)
682 bus->release(bus);
683}
684
685static struct class usb_host_class = {
686 .name = "usb_host",
687 .release = &usb_host_release,
688};
689
690int usb_host_init(void)
691{
692 return class_register(&usb_host_class);
693}
694
695void usb_host_cleanup(void)
696{
697 class_unregister(&usb_host_class);
698}
699
700/**
701 * usb_bus_init - shared initialization code
702 * @bus: the bus structure being initialized
703 *
704 * This code is used to initialize a usb_bus structure, memory for which is
705 * separately managed.
706 */
707static void usb_bus_init (struct usb_bus *bus)
708{
709 memset (&bus->devmap, 0, sizeof(struct usb_devmap));
710
711 bus->devnum_next = 1;
712
713 bus->root_hub = NULL;
714 bus->hcpriv = NULL;
715 bus->busnum = -1;
716 bus->bandwidth_allocated = 0;
717 bus->bandwidth_int_reqs = 0;
718 bus->bandwidth_isoc_reqs = 0;
719
720 INIT_LIST_HEAD (&bus->bus_list);
721
722 class_device_initialize(&bus->class_dev);
723 bus->class_dev.class = &usb_host_class;
724}
725
726/**
727 * usb_alloc_bus - creates a new USB host controller structure
728 * @op: pointer to a struct usb_operations that this bus structure should use
729 * Context: !in_interrupt()
730 *
731 * Creates a USB host controller bus structure with the specified
732 * usb_operations and initializes all the necessary internal objects.
733 *
734 * If no memory is available, NULL is returned.
735 *
736 * The caller should call usb_put_bus() when it is finished with the structure.
737 */
738struct usb_bus *usb_alloc_bus (struct usb_operations *op)
739{
740 struct usb_bus *bus;
741
742 bus = kmalloc (sizeof *bus, GFP_KERNEL);
743 if (!bus)
744 return NULL;
745 memset(bus, 0, sizeof(struct usb_bus));
746 usb_bus_init (bus);
747 bus->op = op;
748 return bus;
749}
750
751/*-------------------------------------------------------------------------*/
752
753/**
754 * usb_register_bus - registers the USB host controller with the usb core
755 * @bus: pointer to the bus to register
756 * Context: !in_interrupt()
757 *
758 * Assigns a bus number, and links the controller into usbcore data
759 * structures so that it can be seen by scanning the bus list.
760 */
761static int usb_register_bus(struct usb_bus *bus)
762{
763 int busnum;
764 int retval;
765
766 down (&usb_bus_list_lock);
767 busnum = find_next_zero_bit (busmap.busmap, USB_MAXBUS, 1);
768 if (busnum < USB_MAXBUS) {
769 set_bit (busnum, busmap.busmap);
770 bus->busnum = busnum;
771 } else {
772 printk (KERN_ERR "%s: too many buses\n", usbcore_name);
773 up(&usb_bus_list_lock);
774 return -E2BIG;
775 }
776
777 snprintf(bus->class_dev.class_id, BUS_ID_SIZE, "usb%d", busnum);
778 bus->class_dev.dev = bus->controller;
779 retval = class_device_add(&bus->class_dev);
780 if (retval) {
781 clear_bit(busnum, busmap.busmap);
782 up(&usb_bus_list_lock);
783 return retval;
784 }
785
786 /* Add it to the local list of buses */
787 list_add (&bus->bus_list, &usb_bus_list);
788 up (&usb_bus_list_lock);
789
790 usbfs_add_bus (bus);
791 usbmon_notify_bus_add (bus);
792
793 dev_info (bus->controller, "new USB bus registered, assigned bus number %d\n", bus->busnum);
794 return 0;
795}
796
797/**
798 * usb_deregister_bus - deregisters the USB host controller
799 * @bus: pointer to the bus to deregister
800 * Context: !in_interrupt()
801 *
802 * Recycles the bus number, and unlinks the controller from usbcore data
803 * structures so that it won't be seen by scanning the bus list.
804 */
805static void usb_deregister_bus (struct usb_bus *bus)
806{
807 dev_info (bus->controller, "USB bus %d deregistered\n", bus->busnum);
808
809 /*
810 * NOTE: make sure that all the devices are removed by the
811 * controller code, as well as having it call this when cleaning
812 * itself up
813 */
814 down (&usb_bus_list_lock);
815 list_del (&bus->bus_list);
816 up (&usb_bus_list_lock);
817
818 usbmon_notify_bus_remove (bus);
819 usbfs_remove_bus (bus);
820
821 clear_bit (bus->busnum, busmap.busmap);
822
823 class_device_del(&bus->class_dev);
824}
825
826/**
827 * usb_hcd_register_root_hub - called by HCD to register its root hub
828 * @usb_dev: the usb root hub device to be registered.
829 * @hcd: host controller for this root hub
830 *
831 * The USB host controller calls this function to register the root hub
832 * properly with the USB subsystem. It sets up the device properly in
833 * the device tree and stores the root_hub pointer in the bus structure,
834 * then calls usb_new_device() to register the usb device. It also
835 * assigns the root hub's USB address (always 1).
836 */
837int usb_hcd_register_root_hub (struct usb_device *usb_dev, struct usb_hcd *hcd)
838{
839 struct device *parent_dev = hcd->self.controller;
840 const int devnum = 1;
841 int retval;
842
843 /* hcd->driver->start() reported can_wakeup, probably with
844 * assistance from board's boot firmware.
845 * NOTE: normal devices won't enable wakeup by default.
846 */
847 if (hcd->can_wakeup)
848 dev_dbg (parent_dev, "supports USB remote wakeup\n");
849 hcd->remote_wakeup = hcd->can_wakeup;
850
851 usb_dev->devnum = devnum;
852 usb_dev->bus->devnum_next = devnum + 1;
853 memset (&usb_dev->bus->devmap.devicemap, 0,
854 sizeof usb_dev->bus->devmap.devicemap);
855 set_bit (devnum, usb_dev->bus->devmap.devicemap);
856 usb_set_device_state(usb_dev, USB_STATE_ADDRESS);
857
858 down (&usb_bus_list_lock);
859 usb_dev->bus->root_hub = usb_dev;
860
861 usb_dev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(64);
862 retval = usb_get_device_descriptor(usb_dev, USB_DT_DEVICE_SIZE);
863 if (retval != sizeof usb_dev->descriptor) {
864 usb_dev->bus->root_hub = NULL;
865 up (&usb_bus_list_lock);
866 dev_dbg (parent_dev, "can't read %s device descriptor %d\n",
867 usb_dev->dev.bus_id, retval);
868 return (retval < 0) ? retval : -EMSGSIZE;
869 }
870
871 usb_lock_device (usb_dev);
872 retval = usb_new_device (usb_dev);
873 usb_unlock_device (usb_dev);
874 if (retval) {
875 usb_dev->bus->root_hub = NULL;
876 dev_err (parent_dev, "can't register root hub for %s, %d\n",
877 usb_dev->dev.bus_id, retval);
878 }
879 up (&usb_bus_list_lock);
880
881 if (retval == 0) {
882 spin_lock_irq (&hcd_root_hub_lock);
883 hcd->rh_registered = 1;
884 spin_unlock_irq (&hcd_root_hub_lock);
885
886 /* Did the HC die before the root hub was registered? */
887 if (hcd->state == HC_STATE_HALT)
888 usb_hc_died (hcd); /* This time clean up */
889 }
890
891 return retval;
892}
893EXPORT_SYMBOL_GPL(usb_hcd_register_root_hub);
894
895
896/*-------------------------------------------------------------------------*/
897
898/**
899 * usb_calc_bus_time - approximate periodic transaction time in nanoseconds
900 * @speed: from dev->speed; USB_SPEED_{LOW,FULL,HIGH}
901 * @is_input: true iff the transaction sends data to the host
902 * @isoc: true for isochronous transactions, false for interrupt ones
903 * @bytecount: how many bytes in the transaction.
904 *
905 * Returns approximate bus time in nanoseconds for a periodic transaction.
906 * See USB 2.0 spec section 5.11.3; only periodic transfers need to be
907 * scheduled in software, this function is only used for such scheduling.
908 */
909long usb_calc_bus_time (int speed, int is_input, int isoc, int bytecount)
910{
911 unsigned long tmp;
912
913 switch (speed) {
914 case USB_SPEED_LOW: /* INTR only */
915 if (is_input) {
916 tmp = (67667L * (31L + 10L * BitTime (bytecount))) / 1000L;
917 return (64060L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
918 } else {
919 tmp = (66700L * (31L + 10L * BitTime (bytecount))) / 1000L;
920 return (64107L + (2 * BW_HUB_LS_SETUP) + BW_HOST_DELAY + tmp);
921 }
922 case USB_SPEED_FULL: /* ISOC or INTR */
923 if (isoc) {
924 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
925 return (((is_input) ? 7268L : 6265L) + BW_HOST_DELAY + tmp);
926 } else {
927 tmp = (8354L * (31L + 10L * BitTime (bytecount))) / 1000L;
928 return (9107L + BW_HOST_DELAY + tmp);
929 }
930 case USB_SPEED_HIGH: /* ISOC or INTR */
931 // FIXME adjust for input vs output
932 if (isoc)
933 tmp = HS_USECS (bytecount);
934 else
935 tmp = HS_USECS_ISO (bytecount);
936 return tmp;
937 default:
938 pr_debug ("%s: bogus device speed!\n", usbcore_name);
939 return -1;
940 }
941}
942EXPORT_SYMBOL (usb_calc_bus_time);
943
944/*
945 * usb_check_bandwidth():
946 *
947 * old_alloc is from host_controller->bandwidth_allocated in microseconds;
948 * bustime is from calc_bus_time(), but converted to microseconds.
949 *
950 * returns <bustime in us> if successful,
951 * or -ENOSPC if bandwidth request fails.
952 *
953 * FIXME:
954 * This initial implementation does not use Endpoint.bInterval
955 * in managing bandwidth allocation.
956 * It probably needs to be expanded to use Endpoint.bInterval.
957 * This can be done as a later enhancement (correction).
958 *
959 * This will also probably require some kind of
960 * frame allocation tracking...meaning, for example,
961 * that if multiple drivers request interrupts every 10 USB frames,
962 * they don't all have to be allocated at
963 * frame numbers N, N+10, N+20, etc. Some of them could be at
964 * N+11, N+21, N+31, etc., and others at
965 * N+12, N+22, N+32, etc.
966 *
967 * Similarly for isochronous transfers...
968 *
969 * Individual HCDs can schedule more directly ... this logic
970 * is not correct for high speed transfers.
971 */
972int usb_check_bandwidth (struct usb_device *dev, struct urb *urb)
973{
974 unsigned int pipe = urb->pipe;
975 long bustime;
976 int is_in = usb_pipein (pipe);
977 int is_iso = usb_pipeisoc (pipe);
978 int old_alloc = dev->bus->bandwidth_allocated;
979 int new_alloc;
980
981
982 bustime = NS_TO_US (usb_calc_bus_time (dev->speed, is_in, is_iso,
983 usb_maxpacket (dev, pipe, !is_in)));
984 if (is_iso)
985 bustime /= urb->number_of_packets;
986
987 new_alloc = old_alloc + (int) bustime;
988 if (new_alloc > FRAME_TIME_MAX_USECS_ALLOC) {
989#ifdef DEBUG
990 char *mode =
991#ifdef CONFIG_USB_BANDWIDTH
992 "";
993#else
994 "would have ";
995#endif
996 dev_dbg (&dev->dev, "usb_check_bandwidth %sFAILED: %d + %ld = %d usec\n",
997 mode, old_alloc, bustime, new_alloc);
998#endif
999#ifdef CONFIG_USB_BANDWIDTH
1000 bustime = -ENOSPC; /* report error */
1001#endif
1002 }
1003
1004 return bustime;
1005}
1006EXPORT_SYMBOL (usb_check_bandwidth);
1007
1008
1009/**
1010 * usb_claim_bandwidth - records bandwidth for a periodic transfer
1011 * @dev: source/target of request
1012 * @urb: request (urb->dev == dev)
1013 * @bustime: bandwidth consumed, in (average) microseconds per frame
1014 * @isoc: true iff the request is isochronous
1015 *
1016 * Bus bandwidth reservations are recorded purely for diagnostic purposes.
1017 * HCDs are expected not to overcommit periodic bandwidth, and to record such
1018 * reservations whenever endpoints are added to the periodic schedule.
1019 *
1020 * FIXME averaging per-frame is suboptimal. Better to sum over the HCD's
1021 * entire periodic schedule ... 32 frames for OHCI, 1024 for UHCI, settable
1022 * for EHCI (256/512/1024 frames, default 1024) and have the bus expose how
1023 * large its periodic schedule is.
1024 */
1025void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb, int bustime, int isoc)
1026{
1027 dev->bus->bandwidth_allocated += bustime;
1028 if (isoc)
1029 dev->bus->bandwidth_isoc_reqs++;
1030 else
1031 dev->bus->bandwidth_int_reqs++;
1032 urb->bandwidth = bustime;
1033
1034#ifdef USB_BANDWIDTH_MESSAGES
1035 dev_dbg (&dev->dev, "bandwidth alloc increased by %d (%s) to %d for %d requesters\n",
1036 bustime,
1037 isoc ? "ISOC" : "INTR",
1038 dev->bus->bandwidth_allocated,
1039 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
1040#endif
1041}
1042EXPORT_SYMBOL (usb_claim_bandwidth);
1043
1044
1045/**
1046 * usb_release_bandwidth - reverses effect of usb_claim_bandwidth()
1047 * @dev: source/target of request
1048 * @urb: request (urb->dev == dev)
1049 * @isoc: true iff the request is isochronous
1050 *
1051 * This records that previously allocated bandwidth has been released.
1052 * Bandwidth is released when endpoints are removed from the host controller's
1053 * periodic schedule.
1054 */
1055void usb_release_bandwidth (struct usb_device *dev, struct urb *urb, int isoc)
1056{
1057 dev->bus->bandwidth_allocated -= urb->bandwidth;
1058 if (isoc)
1059 dev->bus->bandwidth_isoc_reqs--;
1060 else
1061 dev->bus->bandwidth_int_reqs--;
1062
1063#ifdef USB_BANDWIDTH_MESSAGES
1064 dev_dbg (&dev->dev, "bandwidth alloc reduced by %d (%s) to %d for %d requesters\n",
1065 urb->bandwidth,
1066 isoc ? "ISOC" : "INTR",
1067 dev->bus->bandwidth_allocated,
1068 dev->bus->bandwidth_int_reqs + dev->bus->bandwidth_isoc_reqs);
1069#endif
1070 urb->bandwidth = 0;
1071}
1072EXPORT_SYMBOL (usb_release_bandwidth);
1073
1074
1075/*-------------------------------------------------------------------------*/
1076
1077/*
1078 * Generic HC operations.
1079 */
1080
1081/*-------------------------------------------------------------------------*/
1082
1083static void urb_unlink (struct urb *urb)
1084{
1085 unsigned long flags;
1086
1087 /* Release any periodic transfer bandwidth */
1088 if (urb->bandwidth)
1089 usb_release_bandwidth (urb->dev, urb,
1090 usb_pipeisoc (urb->pipe));
1091
1092 /* clear all state linking urb to this dev (and hcd) */
1093
1094 spin_lock_irqsave (&hcd_data_lock, flags);
1095 list_del_init (&urb->urb_list);
1096 spin_unlock_irqrestore (&hcd_data_lock, flags);
1097 usb_put_dev (urb->dev);
1098}
1099
1100
1101/* may be called in any context with a valid urb->dev usecount
1102 * caller surrenders "ownership" of urb
1103 * expects usb_submit_urb() to have sanity checked and conditioned all
1104 * inputs in the urb
1105 */
1106static int hcd_submit_urb (struct urb *urb, int mem_flags)
1107{
1108 int status;
1109 struct usb_hcd *hcd = urb->dev->bus->hcpriv;
1110 struct usb_host_endpoint *ep;
1111 unsigned long flags;
1112
1113 if (!hcd)
1114 return -ENODEV;
1115
1116 usbmon_urb_submit(&hcd->self, urb);
1117
1118 /*
1119 * Atomically queue the urb, first to our records, then to the HCD.
1120 * Access to urb->status is controlled by urb->lock ... changes on
1121 * i/o completion (normal or fault) or unlinking.
1122 */
1123
1124 // FIXME: verify that quiescing hc works right (RH cleans up)
1125
1126 spin_lock_irqsave (&hcd_data_lock, flags);
1127 ep = (usb_pipein(urb->pipe) ? urb->dev->ep_in : urb->dev->ep_out)
1128 [usb_pipeendpoint(urb->pipe)];
1129 if (unlikely (!ep))
1130 status = -ENOENT;
1131 else if (unlikely (urb->reject))
1132 status = -EPERM;
1133 else switch (hcd->state) {
1134 case HC_STATE_RUNNING:
1135 case HC_STATE_RESUMING:
1136 usb_get_dev (urb->dev);
1137 list_add_tail (&urb->urb_list, &ep->urb_list);
1138 status = 0;
1139 break;
1140 default:
1141 status = -ESHUTDOWN;
1142 break;
1143 }
1144 spin_unlock_irqrestore (&hcd_data_lock, flags);
1145 if (status) {
1146 INIT_LIST_HEAD (&urb->urb_list);
1147 usbmon_urb_submit_error(&hcd->self, urb, status);
1148 return status;
1149 }
1150
1151 /* increment urb's reference count as part of giving it to the HCD
1152 * (which now controls it). HCD guarantees that it either returns
1153 * an error or calls giveback(), but not both.
1154 */
1155 urb = usb_get_urb (urb);
1156 atomic_inc (&urb->use_count);
1157
1158 if (urb->dev == hcd->self.root_hub) {
1159 /* NOTE: requirement on hub callers (usbfs and the hub
1160 * driver, for now) that URBs' urb->transfer_buffer be
1161 * valid and usb_buffer_{sync,unmap}() not be needed, since
1162 * they could clobber root hub response data.
1163 */
1164 status = rh_urb_enqueue (hcd, urb);
1165 goto done;
1166 }
1167
1168 /* lower level hcd code should use *_dma exclusively,
1169 * unless it uses pio or talks to another transport.
1170 */
1171 if (hcd->self.controller->dma_mask) {
1172 if (usb_pipecontrol (urb->pipe)
1173 && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1174 urb->setup_dma = dma_map_single (
1175 hcd->self.controller,
1176 urb->setup_packet,
1177 sizeof (struct usb_ctrlrequest),
1178 DMA_TO_DEVICE);
1179 if (urb->transfer_buffer_length != 0
1180 && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1181 urb->transfer_dma = dma_map_single (
1182 hcd->self.controller,
1183 urb->transfer_buffer,
1184 urb->transfer_buffer_length,
1185 usb_pipein (urb->pipe)
1186 ? DMA_FROM_DEVICE
1187 : DMA_TO_DEVICE);
1188 }
1189
1190 status = hcd->driver->urb_enqueue (hcd, ep, urb, mem_flags);
1191done:
1192 if (unlikely (status)) {
1193 urb_unlink (urb);
1194 atomic_dec (&urb->use_count);
1195 if (urb->reject)
1196 wake_up (&usb_kill_urb_queue);
1197 usb_put_urb (urb);
1198 usbmon_urb_submit_error(&hcd->self, urb, status);
1199 }
1200 return status;
1201}
1202
1203/*-------------------------------------------------------------------------*/
1204
1205/* called in any context */
1206static int hcd_get_frame_number (struct usb_device *udev)
1207{
1208 struct usb_hcd *hcd = (struct usb_hcd *)udev->bus->hcpriv;
1209 if (!HC_IS_RUNNING (hcd->state))
1210 return -ESHUTDOWN;
1211 return hcd->driver->get_frame_number (hcd);
1212}
1213
1214/*-------------------------------------------------------------------------*/
1215
1216/* this makes the hcd giveback() the urb more quickly, by kicking it
1217 * off hardware queues (which may take a while) and returning it as
1218 * soon as practical. we've already set up the urb's return status,
1219 * but we can't know if the callback completed already.
1220 */
1221static int
1222unlink1 (struct usb_hcd *hcd, struct urb *urb)
1223{
1224 int value;
1225
1226 if (urb->dev == hcd->self.root_hub)
1227 value = usb_rh_urb_dequeue (hcd, urb);
1228 else {
1229
1230 /* The only reason an HCD might fail this call is if
1231 * it has not yet fully queued the urb to begin with.
1232 * Such failures should be harmless. */
1233 value = hcd->driver->urb_dequeue (hcd, urb);
1234 }
1235
1236 if (value != 0)
1237 dev_dbg (hcd->self.controller, "dequeue %p --> %d\n",
1238 urb, value);
1239 return value;
1240}
1241
1242/*
1243 * called in any context
1244 *
1245 * caller guarantees urb won't be recycled till both unlink()
1246 * and the urb's completion function return
1247 */
1248static int hcd_unlink_urb (struct urb *urb, int status)
1249{
1250 struct usb_host_endpoint *ep;
1251 struct usb_hcd *hcd = NULL;
1252 struct device *sys = NULL;
1253 unsigned long flags;
1254 struct list_head *tmp;
1255 int retval;
1256
1257 if (!urb)
1258 return -EINVAL;
1259 if (!urb->dev || !urb->dev->bus)
1260 return -ENODEV;
1261 ep = (usb_pipein(urb->pipe) ? urb->dev->ep_in : urb->dev->ep_out)
1262 [usb_pipeendpoint(urb->pipe)];
1263 if (!ep)
1264 return -ENODEV;
1265
1266 /*
1267 * we contend for urb->status with the hcd core,
1268 * which changes it while returning the urb.
1269 *
1270 * Caller guaranteed that the urb pointer hasn't been freed, and
1271 * that it was submitted. But as a rule it can't know whether or
1272 * not it's already been unlinked ... so we respect the reversed
1273 * lock sequence needed for the usb_hcd_giveback_urb() code paths
1274 * (urb lock, then hcd_data_lock) in case some other CPU is now
1275 * unlinking it.
1276 */
1277 spin_lock_irqsave (&urb->lock, flags);
1278 spin_lock (&hcd_data_lock);
1279
1280 sys = &urb->dev->dev;
1281 hcd = urb->dev->bus->hcpriv;
1282 if (hcd == NULL) {
1283 retval = -ENODEV;
1284 goto done;
1285 }
1286
1287 /* running ~= hc unlink handshake works (irq, timer, etc)
1288 * halted ~= no unlink handshake is needed
1289 * suspended, resuming == should never happen
1290 */
1291 WARN_ON (!HC_IS_RUNNING (hcd->state) && hcd->state != HC_STATE_HALT);
1292
1293 /* insist the urb is still queued */
1294 list_for_each(tmp, &ep->urb_list) {
1295 if (tmp == &urb->urb_list)
1296 break;
1297 }
1298 if (tmp != &urb->urb_list) {
1299 retval = -EIDRM;
1300 goto done;
1301 }
1302
1303 /* Any status except -EINPROGRESS means something already started to
1304 * unlink this URB from the hardware. So there's no more work to do.
1305 */
1306 if (urb->status != -EINPROGRESS) {
1307 retval = -EBUSY;
1308 goto done;
1309 }
1310
1311 /* IRQ setup can easily be broken so that USB controllers
1312 * never get completion IRQs ... maybe even the ones we need to
1313 * finish unlinking the initial failed usb_set_address()
1314 * or device descriptor fetch.
1315 */
1316 if (!hcd->saw_irq && hcd->self.root_hub != urb->dev) {
1317 dev_warn (hcd->self.controller, "Unlink after no-IRQ? "
1318 "Controller is probably using the wrong IRQ."
1319 "\n");
1320 hcd->saw_irq = 1;
1321 }
1322
1323 urb->status = status;
1324
1325 spin_unlock (&hcd_data_lock);
1326 spin_unlock_irqrestore (&urb->lock, flags);
1327
1328 retval = unlink1 (hcd, urb);
1329 if (retval == 0)
1330 retval = -EINPROGRESS;
1331 return retval;
1332
1333done:
1334 spin_unlock (&hcd_data_lock);
1335 spin_unlock_irqrestore (&urb->lock, flags);
1336 if (retval != -EIDRM && sys && sys->driver)
1337 dev_dbg (sys, "hcd_unlink_urb %p fail %d\n", urb, retval);
1338 return retval;
1339}
1340
1341/*-------------------------------------------------------------------------*/
1342
1343/* disables the endpoint: cancels any pending urbs, then synchronizes with
1344 * the hcd to make sure all endpoint state is gone from hardware. use for
1345 * set_configuration, set_interface, driver removal, physical disconnect.
1346 *
1347 * example: a qh stored in ep->hcpriv, holding state related to endpoint
1348 * type, maxpacket size, toggle, halt status, and scheduling.
1349 */
1350static void
1351hcd_endpoint_disable (struct usb_device *udev, struct usb_host_endpoint *ep)
1352{
1353 struct usb_hcd *hcd;
1354 struct urb *urb;
1355
1356 hcd = udev->bus->hcpriv;
1357
1358 WARN_ON (!HC_IS_RUNNING (hcd->state) && hcd->state != HC_STATE_HALT);
1359
1360 local_irq_disable ();
1361
1362 /* FIXME move most of this into message.c as part of its
1363 * endpoint disable logic
1364 */
1365
1366 /* ep is already gone from udev->ep_{in,out}[]; no more submits */
1367rescan:
1368 spin_lock (&hcd_data_lock);
1369 list_for_each_entry (urb, &ep->urb_list, urb_list) {
1370 int tmp;
1371
1372 /* another cpu may be in hcd, spinning on hcd_data_lock
1373 * to giveback() this urb. the races here should be
1374 * small, but a full fix needs a new "can't submit"
1375 * urb state.
1376 * FIXME urb->reject should allow that...
1377 */
1378 if (urb->status != -EINPROGRESS)
1379 continue;
1380 usb_get_urb (urb);
1381 spin_unlock (&hcd_data_lock);
1382
1383 spin_lock (&urb->lock);
1384 tmp = urb->status;
1385 if (tmp == -EINPROGRESS)
1386 urb->status = -ESHUTDOWN;
1387 spin_unlock (&urb->lock);
1388
1389 /* kick hcd unless it's already returning this */
1390 if (tmp == -EINPROGRESS) {
1391 tmp = urb->pipe;
1392 unlink1 (hcd, urb);
1393 dev_dbg (hcd->self.controller,
1394 "shutdown urb %p pipe %08x ep%d%s%s\n",
1395 urb, tmp, usb_pipeendpoint (tmp),
1396 (tmp & USB_DIR_IN) ? "in" : "out",
1397 ({ char *s; \
1398 switch (usb_pipetype (tmp)) { \
1399 case PIPE_CONTROL: s = ""; break; \
1400 case PIPE_BULK: s = "-bulk"; break; \
1401 case PIPE_INTERRUPT: s = "-intr"; break; \
1402 default: s = "-iso"; break; \
1403 }; s;}));
1404 }
1405 usb_put_urb (urb);
1406
1407 /* list contents may have changed */
1408 goto rescan;
1409 }
1410 spin_unlock (&hcd_data_lock);
1411 local_irq_enable ();
1412
1413 /* synchronize with the hardware, so old configuration state
1414 * clears out immediately (and will be freed).
1415 */
1416 might_sleep ();
1417 if (hcd->driver->endpoint_disable)
1418 hcd->driver->endpoint_disable (hcd, ep);
1419}
1420
1421/*-------------------------------------------------------------------------*/
1422
1423#ifdef CONFIG_USB_SUSPEND
1424
1425static int hcd_hub_suspend (struct usb_bus *bus)
1426{
1427 struct usb_hcd *hcd;
1428
1429 hcd = container_of (bus, struct usb_hcd, self);
1430 if (hcd->driver->hub_suspend)
1431 return hcd->driver->hub_suspend (hcd);
1432 return 0;
1433}
1434
1435static int hcd_hub_resume (struct usb_bus *bus)
1436{
1437 struct usb_hcd *hcd;
1438
1439 hcd = container_of (bus, struct usb_hcd, self);
1440 if (hcd->driver->hub_resume)
1441 return hcd->driver->hub_resume (hcd);
1442 return 0;
1443}
1444
1445/**
1446 * usb_hcd_resume_root_hub - called by HCD to resume its root hub
1447 * @hcd: host controller for this root hub
1448 *
1449 * The USB host controller calls this function when its root hub is
1450 * suspended (with the remote wakeup feature enabled) and a remote
1451 * wakeup request is received. It queues a request for khubd to
1452 * resume the root hub.
1453 */
1454void usb_hcd_resume_root_hub (struct usb_hcd *hcd)
1455{
1456 unsigned long flags;
1457
1458 spin_lock_irqsave (&hcd_root_hub_lock, flags);
1459 if (hcd->rh_registered)
1460 usb_resume_root_hub (hcd->self.root_hub);
1461 spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
1462}
1463
1464#else
1465void usb_hcd_resume_root_hub (struct usb_hcd *hcd)
1466{
1467}
1468#endif
1469EXPORT_SYMBOL_GPL(usb_hcd_resume_root_hub);
1470
1471/*-------------------------------------------------------------------------*/
1472
1473#ifdef CONFIG_USB_OTG
1474
1475/**
1476 * usb_bus_start_enum - start immediate enumeration (for OTG)
1477 * @bus: the bus (must use hcd framework)
1478 * @port_num: 1-based number of port; usually bus->otg_port
1479 * Context: in_interrupt()
1480 *
1481 * Starts enumeration, with an immediate reset followed later by
1482 * khubd identifying and possibly configuring the device.
1483 * This is needed by OTG controller drivers, where it helps meet
1484 * HNP protocol timing requirements for starting a port reset.
1485 */
1486int usb_bus_start_enum(struct usb_bus *bus, unsigned port_num)
1487{
1488 struct usb_hcd *hcd;
1489 int status = -EOPNOTSUPP;
1490
1491 /* NOTE: since HNP can't start by grabbing the bus's address0_sem,
1492 * boards with root hubs hooked up to internal devices (instead of
1493 * just the OTG port) may need more attention to resetting...
1494 */
1495 hcd = container_of (bus, struct usb_hcd, self);
1496 if (port_num && hcd->driver->start_port_reset)
1497 status = hcd->driver->start_port_reset(hcd, port_num);
1498
1499 /* run khubd shortly after (first) root port reset finishes;
1500 * it may issue others, until at least 50 msecs have passed.
1501 */
1502 if (status == 0)
1503 mod_timer(&hcd->rh_timer, jiffies + msecs_to_jiffies(10));
1504 return status;
1505}
1506EXPORT_SYMBOL (usb_bus_start_enum);
1507
1508#endif
1509
1510/*-------------------------------------------------------------------------*/
1511
1512/*
1513 * usb_hcd_operations - adapts usb_bus framework to HCD framework (bus glue)
1514 */
1515static struct usb_operations usb_hcd_operations = {
1516 .get_frame_number = hcd_get_frame_number,
1517 .submit_urb = hcd_submit_urb,
1518 .unlink_urb = hcd_unlink_urb,
1519 .buffer_alloc = hcd_buffer_alloc,
1520 .buffer_free = hcd_buffer_free,
1521 .disable = hcd_endpoint_disable,
1522#ifdef CONFIG_USB_SUSPEND
1523 .hub_suspend = hcd_hub_suspend,
1524 .hub_resume = hcd_hub_resume,
1525#endif
1526};
1527
1528/*-------------------------------------------------------------------------*/
1529
1530/**
1531 * usb_hcd_giveback_urb - return URB from HCD to device driver
1532 * @hcd: host controller returning the URB
1533 * @urb: urb being returned to the USB device driver.
1534 * @regs: pt_regs, passed down to the URB completion handler
1535 * Context: in_interrupt()
1536 *
1537 * This hands the URB from HCD to its USB device driver, using its
1538 * completion function. The HCD has freed all per-urb resources
1539 * (and is done using urb->hcpriv). It also released all HCD locks;
1540 * the device driver won't cause problems if it frees, modifies,
1541 * or resubmits this URB.
1542 */
1543void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb, struct pt_regs *regs)
1544{
1545 int at_root_hub;
1546
1547 at_root_hub = (urb->dev == hcd->self.root_hub);
1548 urb_unlink (urb);
1549
1550 /* lower level hcd code should use *_dma exclusively */
1551 if (hcd->self.controller->dma_mask && !at_root_hub) {
1552 if (usb_pipecontrol (urb->pipe)
1553 && !(urb->transfer_flags & URB_NO_SETUP_DMA_MAP))
1554 dma_unmap_single (hcd->self.controller, urb->setup_dma,
1555 sizeof (struct usb_ctrlrequest),
1556 DMA_TO_DEVICE);
1557 if (urb->transfer_buffer_length != 0
1558 && !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP))
1559 dma_unmap_single (hcd->self.controller,
1560 urb->transfer_dma,
1561 urb->transfer_buffer_length,
1562 usb_pipein (urb->pipe)
1563 ? DMA_FROM_DEVICE
1564 : DMA_TO_DEVICE);
1565 }
1566
1567 usbmon_urb_complete (&hcd->self, urb);
1568 /* pass ownership to the completion handler */
1569 urb->complete (urb, regs);
1570 atomic_dec (&urb->use_count);
1571 if (unlikely (urb->reject))
1572 wake_up (&usb_kill_urb_queue);
1573 usb_put_urb (urb);
1574}
1575EXPORT_SYMBOL (usb_hcd_giveback_urb);
1576
1577/*-------------------------------------------------------------------------*/
1578
1579/**
1580 * usb_hcd_irq - hook IRQs to HCD framework (bus glue)
1581 * @irq: the IRQ being raised
1582 * @__hcd: pointer to the HCD whose IRQ is being signaled
1583 * @r: saved hardware registers
1584 *
1585 * If the controller isn't HALTed, calls the driver's irq handler.
1586 * Checks whether the controller is now dead.
1587 */
1588irqreturn_t usb_hcd_irq (int irq, void *__hcd, struct pt_regs * r)
1589{
1590 struct usb_hcd *hcd = __hcd;
1591 int start = hcd->state;
1592
1593 if (start == HC_STATE_HALT)
1594 return IRQ_NONE;
1595 if (hcd->driver->irq (hcd, r) == IRQ_NONE)
1596 return IRQ_NONE;
1597
1598 hcd->saw_irq = 1;
1599 if (hcd->state != start && hcd->state == HC_STATE_HALT)
1600 usb_hc_died (hcd);
1601 return IRQ_HANDLED;
1602}
1603
1604/*-------------------------------------------------------------------------*/
1605
1606/**
1607 * usb_hc_died - report abnormal shutdown of a host controller (bus glue)
1608 * @hcd: pointer to the HCD representing the controller
1609 *
1610 * This is called by bus glue to report a USB host controller that died
1611 * while operations may still have been pending. It's called automatically
1612 * by the PCI glue, so only glue for non-PCI busses should need to call it.
1613 */
1614void usb_hc_died (struct usb_hcd *hcd)
1615{
1616 unsigned long flags;
1617
1618 dev_err (hcd->self.controller, "HC died; cleaning up\n");
1619
1620 spin_lock_irqsave (&hcd_root_hub_lock, flags);
1621 if (hcd->rh_registered) {
1622
1623 /* make khubd clean up old urbs and devices */
1624 usb_set_device_state (hcd->self.root_hub,
1625 USB_STATE_NOTATTACHED);
1626 usb_kick_khubd (hcd->self.root_hub);
1627 }
1628 spin_unlock_irqrestore (&hcd_root_hub_lock, flags);
1629}
1630EXPORT_SYMBOL_GPL (usb_hc_died);
1631
1632/*-------------------------------------------------------------------------*/
1633
1634static void hcd_release (struct usb_bus *bus)
1635{
1636 struct usb_hcd *hcd;
1637
1638 hcd = container_of(bus, struct usb_hcd, self);
1639 kfree(hcd);
1640}
1641
1642/**
1643 * usb_create_hcd - create and initialize an HCD structure
1644 * @driver: HC driver that will use this hcd
1645 * @dev: device for this HC, stored in hcd->self.controller
1646 * @bus_name: value to store in hcd->self.bus_name
1647 * Context: !in_interrupt()
1648 *
1649 * Allocate a struct usb_hcd, with extra space at the end for the
1650 * HC driver's private data. Initialize the generic members of the
1651 * hcd structure.
1652 *
1653 * If memory is unavailable, returns NULL.
1654 */
1655struct usb_hcd *usb_create_hcd (const struct hc_driver *driver,
1656 struct device *dev, char *bus_name)
1657{
1658 struct usb_hcd *hcd;
1659
1660 hcd = kcalloc(1, sizeof(*hcd) + driver->hcd_priv_size, GFP_KERNEL);
1661 if (!hcd) {
1662 dev_dbg (dev, "hcd alloc failed\n");
1663 return NULL;
1664 }
1665 dev_set_drvdata(dev, hcd);
1666
1667 usb_bus_init(&hcd->self);
1668 hcd->self.op = &usb_hcd_operations;
1669 hcd->self.hcpriv = hcd;
1670 hcd->self.release = &hcd_release;
1671 hcd->self.controller = dev;
1672 hcd->self.bus_name = bus_name;
1673
1674 init_timer(&hcd->rh_timer);
1675
1676 hcd->driver = driver;
1677 hcd->product_desc = (driver->product_desc) ? driver->product_desc :
1678 "USB Host Controller";
1679
1680 return hcd;
1681}
1682EXPORT_SYMBOL (usb_create_hcd);
1683
1684void usb_put_hcd (struct usb_hcd *hcd)
1685{
1686 dev_set_drvdata(hcd->self.controller, NULL);
1687 usb_bus_put(&hcd->self);
1688}
1689EXPORT_SYMBOL (usb_put_hcd);
1690
1691/**
1692 * usb_add_hcd - finish generic HCD structure initialization and register
1693 * @hcd: the usb_hcd structure to initialize
1694 * @irqnum: Interrupt line to allocate
1695 * @irqflags: Interrupt type flags
1696 *
1697 * Finish the remaining parts of generic HCD initialization: allocate the
1698 * buffers of consistent memory, register the bus, request the IRQ line,
1699 * and call the driver's reset() and start() routines.
1700 */
1701int usb_add_hcd(struct usb_hcd *hcd,
1702 unsigned int irqnum, unsigned long irqflags)
1703{
1704 int retval;
1705
1706 dev_info(hcd->self.controller, "%s\n", hcd->product_desc);
1707
1708 /* till now HC has been in an indeterminate state ... */
1709 if (hcd->driver->reset && (retval = hcd->driver->reset(hcd)) < 0) {
1710 dev_err(hcd->self.controller, "can't reset\n");
1711 return retval;
1712 }
1713
1714 if ((retval = hcd_buffer_create(hcd)) != 0) {
1715 dev_dbg(hcd->self.controller, "pool alloc failed\n");
1716 return retval;
1717 }
1718
1719 if ((retval = usb_register_bus(&hcd->self)) < 0)
1720 goto err1;
1721
1722 if (hcd->driver->irq) {
1723 char buf[8], *bufp = buf;
1724
1725#ifdef __sparc__
1726 bufp = __irq_itoa(irqnum);
1727#else
1728 sprintf(buf, "%d", irqnum);
1729#endif
1730
1731 snprintf(hcd->irq_descr, sizeof(hcd->irq_descr), "%s:usb%d",
1732 hcd->driver->description, hcd->self.busnum);
1733 if ((retval = request_irq(irqnum, &usb_hcd_irq, irqflags,
1734 hcd->irq_descr, hcd)) != 0) {
1735 dev_err(hcd->self.controller,
1736 "request interrupt %s failed\n", bufp);
1737 goto err2;
1738 }
1739 hcd->irq = irqnum;
1740 dev_info(hcd->self.controller, "irq %s, %s 0x%08llx\n", bufp,
1741 (hcd->driver->flags & HCD_MEMORY) ?
1742 "io mem" : "io base",
1743 (unsigned long long)hcd->rsrc_start);
1744 } else {
1745 hcd->irq = -1;
1746 if (hcd->rsrc_start)
1747 dev_info(hcd->self.controller, "%s 0x%08llx\n",
1748 (hcd->driver->flags & HCD_MEMORY) ?
1749 "io mem" : "io base",
1750 (unsigned long long)hcd->rsrc_start);
1751 }
1752
1753 if ((retval = hcd->driver->start(hcd)) < 0) {
1754 dev_err(hcd->self.controller, "startup error %d\n", retval);
1755 goto err3;
1756 }
1757
1758 return retval;
1759
1760 err3:
1761 if (hcd->irq >= 0)
1762 free_irq(irqnum, hcd);
1763 err2:
1764 usb_deregister_bus(&hcd->self);
1765 err1:
1766 hcd_buffer_destroy(hcd);
1767 return retval;
1768}
1769EXPORT_SYMBOL (usb_add_hcd);
1770
1771/**
1772 * usb_remove_hcd - shutdown processing for generic HCDs
1773 * @hcd: the usb_hcd structure to remove
1774 * Context: !in_interrupt()
1775 *
1776 * Disconnects the root hub, then reverses the effects of usb_add_hcd(),
1777 * invoking the HCD's stop() method.
1778 */
1779void usb_remove_hcd(struct usb_hcd *hcd)
1780{
1781 dev_info(hcd->self.controller, "remove, state %x\n", hcd->state);
1782
1783 if (HC_IS_RUNNING (hcd->state))
1784 hcd->state = HC_STATE_QUIESCING;
1785
1786 dev_dbg(hcd->self.controller, "roothub graceful disconnect\n");
1787 spin_lock_irq (&hcd_root_hub_lock);
1788 hcd->rh_registered = 0;
1789 spin_unlock_irq (&hcd_root_hub_lock);
1790 usb_disconnect(&hcd->self.root_hub);
1791
1792 hcd->driver->stop(hcd);
1793 hcd->state = HC_STATE_HALT;
1794
1795 if (hcd->irq >= 0)
1796 free_irq(hcd->irq, hcd);
1797 usb_deregister_bus(&hcd->self);
1798 hcd_buffer_destroy(hcd);
1799}
1800EXPORT_SYMBOL (usb_remove_hcd);
1801
1802/*-------------------------------------------------------------------------*/
1803
1804#if defined(CONFIG_USB_MON) || defined(CONFIG_USB_MON_MODULE)
1805
1806struct usb_mon_operations *mon_ops;
1807
1808/*
1809 * The registration is unlocked.
1810 * We do it this way because we do not want to lock in hot paths.
1811 *
1812 * Notice that the code is minimally error-proof. Because usbmon needs
1813 * symbols from usbcore, usbcore gets referenced and cannot be unloaded first.
1814 */
1815
1816int usb_mon_register (struct usb_mon_operations *ops)
1817{
1818
1819 if (mon_ops)
1820 return -EBUSY;
1821
1822 mon_ops = ops;
1823 mb();
1824 return 0;
1825}
1826EXPORT_SYMBOL_GPL (usb_mon_register);
1827
1828void usb_mon_deregister (void)
1829{
1830
1831 if (mon_ops == NULL) {
1832 printk(KERN_ERR "USB: monitor was not registered\n");
1833 return;
1834 }
1835 mon_ops = NULL;
1836 mb();
1837}
1838EXPORT_SYMBOL_GPL (usb_mon_deregister);
1839
1840#endif /* CONFIG_USB_MON */
diff --git a/drivers/usb/core/hcd.h b/drivers/usb/core/hcd.h
new file mode 100644
index 000000000000..6c625b35fa0c
--- /dev/null
+++ b/drivers/usb/core/hcd.h
@@ -0,0 +1,476 @@
1/*
2 * Copyright (c) 2001-2002 by David Brownell
3 *
4 * This program is free software; you can redistribute it and/or modify it
5 * under the terms of the GNU General Public License as published by the
6 * Free Software Foundation; either version 2 of the License, or (at your
7 * option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
11 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19
20#ifdef __KERNEL__
21
22/* This file contains declarations of usbcore internals that are mostly
23 * used or exposed by Host Controller Drivers.
24 */
25
26/*
27 * USB Packet IDs (PIDs)
28 */
29#define USB_PID_UNDEF_0 0xf0
30#define USB_PID_OUT 0xe1
31#define USB_PID_ACK 0xd2
32#define USB_PID_DATA0 0xc3
33#define USB_PID_PING 0xb4 /* USB 2.0 */
34#define USB_PID_SOF 0xa5
35#define USB_PID_NYET 0x96 /* USB 2.0 */
36#define USB_PID_DATA2 0x87 /* USB 2.0 */
37#define USB_PID_SPLIT 0x78 /* USB 2.0 */
38#define USB_PID_IN 0x69
39#define USB_PID_NAK 0x5a
40#define USB_PID_DATA1 0x4b
41#define USB_PID_PREAMBLE 0x3c /* Token mode */
42#define USB_PID_ERR 0x3c /* USB 2.0: handshake mode */
43#define USB_PID_SETUP 0x2d
44#define USB_PID_STALL 0x1e
45#define USB_PID_MDATA 0x0f /* USB 2.0 */
46
47/*-------------------------------------------------------------------------*/
48
49/*
50 * USB Host Controller Driver (usb_hcd) framework
51 *
52 * Since "struct usb_bus" is so thin, you can't share much code in it.
53 * This framework is a layer over that, and should be more sharable.
54 */
55
56/*-------------------------------------------------------------------------*/
57
58struct usb_hcd { /* usb_bus.hcpriv points to this */
59
60 /*
61 * housekeeping
62 */
63 struct usb_bus self; /* hcd is-a bus */
64
65 const char *product_desc; /* product/vendor string */
66 char irq_descr[24]; /* driver + bus # */
67
68 struct timer_list rh_timer; /* drives root hub */
69
70 /*
71 * hardware info/state
72 */
73 const struct hc_driver *driver; /* hw-specific hooks */
74 unsigned saw_irq : 1;
75 unsigned can_wakeup:1; /* hw supports wakeup? */
76 unsigned remote_wakeup:1;/* sw should use wakeup? */
77 unsigned rh_registered:1;/* is root hub registered? */
78
79 int irq; /* irq allocated */
80 void __iomem *regs; /* device memory/io */
81 u64 rsrc_start; /* memory/io resource start */
82 u64 rsrc_len; /* memory/io resource length */
83
84#define HCD_BUFFER_POOLS 4
85 struct dma_pool *pool [HCD_BUFFER_POOLS];
86
87 int state;
88# define __ACTIVE 0x01
89# define __SUSPEND 0x04
90# define __TRANSIENT 0x80
91
92# define HC_STATE_HALT 0
93# define HC_STATE_RUNNING (__ACTIVE)
94# define HC_STATE_QUIESCING (__SUSPEND|__TRANSIENT|__ACTIVE)
95# define HC_STATE_RESUMING (__SUSPEND|__TRANSIENT)
96# define HC_STATE_SUSPENDED (__SUSPEND)
97
98#define HC_IS_RUNNING(state) ((state) & __ACTIVE)
99#define HC_IS_SUSPENDED(state) ((state) & __SUSPEND)
100
101 /* more shared queuing code would be good; it should support
102 * smarter scheduling, handle transaction translators, etc;
103 * input size of periodic table to an interrupt scheduler.
104 * (ohci 32, uhci 1024, ehci 256/512/1024).
105 */
106
107 /* The HC driver's private data is stored at the end of
108 * this structure.
109 */
110 unsigned long hcd_priv[0]
111 __attribute__ ((aligned (sizeof(unsigned long))));
112};
113
114/* 2.4 does this a bit differently ... */
115static inline struct usb_bus *hcd_to_bus (struct usb_hcd *hcd)
116{
117 return &hcd->self;
118}
119
120
121// urb.hcpriv is really hardware-specific
122
123struct hcd_timeout { /* timeouts we allocate */
124 struct list_head timeout_list;
125 struct timer_list timer;
126};
127
128/*-------------------------------------------------------------------------*/
129
130/*
131 * FIXME usb_operations should vanish or become hc_driver,
132 * when usb_bus and usb_hcd become the same thing.
133 */
134
135struct usb_operations {
136 int (*get_frame_number) (struct usb_device *usb_dev);
137 int (*submit_urb) (struct urb *urb, int mem_flags);
138 int (*unlink_urb) (struct urb *urb, int status);
139
140 /* allocate dma-consistent buffer for URB_DMA_NOMAPPING */
141 void *(*buffer_alloc)(struct usb_bus *bus, size_t size,
142 int mem_flags,
143 dma_addr_t *dma);
144 void (*buffer_free)(struct usb_bus *bus, size_t size,
145 void *addr, dma_addr_t dma);
146
147 void (*disable)(struct usb_device *udev,
148 struct usb_host_endpoint *ep);
149
150 /* global suspend/resume of bus */
151 int (*hub_suspend)(struct usb_bus *);
152 int (*hub_resume)(struct usb_bus *);
153};
154
155/* each driver provides one of these, and hardware init support */
156
157struct pt_regs;
158
159struct hc_driver {
160 const char *description; /* "ehci-hcd" etc */
161 const char *product_desc; /* product/vendor string */
162 size_t hcd_priv_size; /* size of private data */
163
164 /* irq handler */
165 irqreturn_t (*irq) (struct usb_hcd *hcd, struct pt_regs *regs);
166
167 int flags;
168#define HCD_MEMORY 0x0001 /* HC regs use memory (else I/O) */
169#define HCD_USB11 0x0010 /* USB 1.1 */
170#define HCD_USB2 0x0020 /* USB 2.0 */
171
172 /* called to init HCD and root hub */
173 int (*reset) (struct usb_hcd *hcd);
174 int (*start) (struct usb_hcd *hcd);
175
176 /* NOTE: these suspend/resume calls relate to the HC as
177 * a whole, not just the root hub; they're for bus glue.
178 */
179 /* called after all devices were suspended */
180 int (*suspend) (struct usb_hcd *hcd, u32 state);
181
182 /* called before any devices get resumed */
183 int (*resume) (struct usb_hcd *hcd);
184
185 /* cleanly make HCD stop writing memory and doing I/O */
186 void (*stop) (struct usb_hcd *hcd);
187
188 /* return current frame number */
189 int (*get_frame_number) (struct usb_hcd *hcd);
190
191 /* manage i/o requests, device state */
192 int (*urb_enqueue) (struct usb_hcd *hcd,
193 struct usb_host_endpoint *ep,
194 struct urb *urb,
195 int mem_flags);
196 int (*urb_dequeue) (struct usb_hcd *hcd, struct urb *urb);
197
198 /* hw synch, freeing endpoint resources that urb_dequeue can't */
199 void (*endpoint_disable)(struct usb_hcd *hcd,
200 struct usb_host_endpoint *ep);
201
202 /* root hub support */
203 int (*hub_status_data) (struct usb_hcd *hcd, char *buf);
204 int (*hub_control) (struct usb_hcd *hcd,
205 u16 typeReq, u16 wValue, u16 wIndex,
206 char *buf, u16 wLength);
207 int (*hub_suspend)(struct usb_hcd *);
208 int (*hub_resume)(struct usb_hcd *);
209 int (*start_port_reset)(struct usb_hcd *, unsigned port_num);
210};
211
212extern void usb_hcd_giveback_urb (struct usb_hcd *hcd, struct urb *urb, struct pt_regs *regs);
213
214extern struct usb_hcd *usb_create_hcd (const struct hc_driver *driver,
215 struct device *dev, char *bus_name);
216extern void usb_put_hcd (struct usb_hcd *hcd);
217extern int usb_add_hcd(struct usb_hcd *hcd,
218 unsigned int irqnum, unsigned long irqflags);
219extern void usb_remove_hcd(struct usb_hcd *hcd);
220
221#ifdef CONFIG_PCI
222struct pci_dev;
223struct pci_device_id;
224extern int usb_hcd_pci_probe (struct pci_dev *dev,
225 const struct pci_device_id *id);
226extern void usb_hcd_pci_remove (struct pci_dev *dev);
227
228#ifdef CONFIG_PM
229extern int usb_hcd_pci_suspend (struct pci_dev *dev, u32 state);
230extern int usb_hcd_pci_resume (struct pci_dev *dev);
231#endif /* CONFIG_PM */
232
233#endif /* CONFIG_PCI */
234
235/* pci-ish (pdev null is ok) buffer alloc/mapping support */
236int hcd_buffer_create (struct usb_hcd *hcd);
237void hcd_buffer_destroy (struct usb_hcd *hcd);
238
239void *hcd_buffer_alloc (struct usb_bus *bus, size_t size,
240 int mem_flags, dma_addr_t *dma);
241void hcd_buffer_free (struct usb_bus *bus, size_t size,
242 void *addr, dma_addr_t dma);
243
244/* generic bus glue, needed for host controllers that don't use PCI */
245extern irqreturn_t usb_hcd_irq (int irq, void *__hcd, struct pt_regs *r);
246extern void usb_hc_died (struct usb_hcd *hcd);
247
248/* -------------------------------------------------------------------------- */
249
250/* Enumeration is only for the hub driver, or HCD virtual root hubs */
251extern struct usb_device *usb_alloc_dev(struct usb_device *parent,
252 struct usb_bus *, unsigned port);
253extern int usb_new_device(struct usb_device *dev);
254extern void usb_disconnect(struct usb_device **);
255
256extern int usb_get_configuration(struct usb_device *dev);
257extern void usb_destroy_configuration(struct usb_device *dev);
258
259/*-------------------------------------------------------------------------*/
260
261/*
262 * HCD Root Hub support
263 */
264
265#include "hub.h"
266
267/* (shifted) direction/type/recipient from the USB 2.0 spec, table 9.2 */
268#define DeviceRequest \
269 ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8)
270#define DeviceOutRequest \
271 ((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_DEVICE)<<8)
272
273#define InterfaceRequest \
274 ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8)
275
276#define EndpointRequest \
277 ((USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8)
278#define EndpointOutRequest \
279 ((USB_DIR_OUT|USB_TYPE_STANDARD|USB_RECIP_INTERFACE)<<8)
280
281/* class requests from the USB 2.0 hub spec, table 11-15 */
282/* GetBusState and SetHubDescriptor are optional, omitted */
283#define ClearHubFeature (0x2000 | USB_REQ_CLEAR_FEATURE)
284#define ClearPortFeature (0x2300 | USB_REQ_CLEAR_FEATURE)
285#define GetHubDescriptor (0xa000 | USB_REQ_GET_DESCRIPTOR)
286#define GetHubStatus (0xa000 | USB_REQ_GET_STATUS)
287#define GetPortStatus (0xa300 | USB_REQ_GET_STATUS)
288#define SetHubFeature (0x2000 | USB_REQ_SET_FEATURE)
289#define SetPortFeature (0x2300 | USB_REQ_SET_FEATURE)
290
291
292/*-------------------------------------------------------------------------*/
293
294/*
295 * Generic bandwidth allocation constants/support
296 */
297#define FRAME_TIME_USECS 1000L
298#define BitTime(bytecount) (7 * 8 * bytecount / 6) /* with integer truncation */
299 /* Trying not to use worst-case bit-stuffing
300 of (7/6 * 8 * bytecount) = 9.33 * bytecount */
301 /* bytecount = data payload byte count */
302
303#define NS_TO_US(ns) ((ns + 500L) / 1000L)
304 /* convert & round nanoseconds to microseconds */
305
306extern void usb_claim_bandwidth (struct usb_device *dev, struct urb *urb,
307 int bustime, int isoc);
308extern void usb_release_bandwidth (struct usb_device *dev, struct urb *urb,
309 int isoc);
310
311/*
312 * Full/low speed bandwidth allocation constants/support.
313 */
314#define BW_HOST_DELAY 1000L /* nanoseconds */
315#define BW_HUB_LS_SETUP 333L /* nanoseconds */
316 /* 4 full-speed bit times (est.) */
317
318#define FRAME_TIME_BITS 12000L /* frame = 1 millisecond */
319#define FRAME_TIME_MAX_BITS_ALLOC (90L * FRAME_TIME_BITS / 100L)
320#define FRAME_TIME_MAX_USECS_ALLOC (90L * FRAME_TIME_USECS / 100L)
321
322extern int usb_check_bandwidth (struct usb_device *dev, struct urb *urb);
323
324/*
325 * Ceiling microseconds (typical) for that many bytes at high speed
326 * ISO is a bit less, no ACK ... from USB 2.0 spec, 5.11.3 (and needed
327 * to preallocate bandwidth)
328 */
329#define USB2_HOST_DELAY 5 /* nsec, guess */
330#define HS_USECS(bytes) NS_TO_US ( ((55 * 8 * 2083)/1000) \
331 + ((2083UL * (3167 + BitTime (bytes)))/1000) \
332 + USB2_HOST_DELAY)
333#define HS_USECS_ISO(bytes) NS_TO_US ( ((38 * 8 * 2083)/1000) \
334 + ((2083UL * (3167 + BitTime (bytes)))/1000) \
335 + USB2_HOST_DELAY)
336
337extern long usb_calc_bus_time (int speed, int is_input,
338 int isoc, int bytecount);
339
340/*-------------------------------------------------------------------------*/
341
342extern struct usb_bus *usb_alloc_bus (struct usb_operations *);
343
344extern int usb_hcd_register_root_hub (struct usb_device *usb_dev,
345 struct usb_hcd *hcd);
346
347extern void usb_hcd_resume_root_hub (struct usb_hcd *hcd);
348
349extern void usb_set_device_state(struct usb_device *udev,
350 enum usb_device_state new_state);
351
352/*-------------------------------------------------------------------------*/
353
354/* exported only within usbcore */
355
356extern struct list_head usb_bus_list;
357extern struct semaphore usb_bus_list_lock;
358extern wait_queue_head_t usb_kill_urb_queue;
359
360extern struct usb_bus *usb_bus_get (struct usb_bus *bus);
361extern void usb_bus_put (struct usb_bus *bus);
362
363extern int usb_find_interface_driver (struct usb_device *dev,
364 struct usb_interface *interface);
365
366#define usb_endpoint_out(ep_dir) (!((ep_dir) & USB_DIR_IN))
367
368/*
369 * USB device fs stuff
370 */
371
372#ifdef CONFIG_USB_DEVICEFS
373
374/*
375 * these are expected to be called from the USB core/hub thread
376 * with the kernel lock held
377 */
378extern void usbfs_add_bus(struct usb_bus *bus);
379extern void usbfs_remove_bus(struct usb_bus *bus);
380extern void usbfs_add_device(struct usb_device *dev);
381extern void usbfs_remove_device(struct usb_device *dev);
382extern void usbfs_update_special (void);
383
384extern int usbfs_init(void);
385extern void usbfs_cleanup(void);
386
387#else /* CONFIG_USB_DEVICEFS */
388
389static inline void usbfs_add_bus(struct usb_bus *bus) {}
390static inline void usbfs_remove_bus(struct usb_bus *bus) {}
391static inline void usbfs_add_device(struct usb_device *dev) {}
392static inline void usbfs_remove_device(struct usb_device *dev) {}
393static inline void usbfs_update_special (void) {}
394
395static inline int usbfs_init(void) { return 0; }
396static inline void usbfs_cleanup(void) { }
397
398#endif /* CONFIG_USB_DEVICEFS */
399
400/*-------------------------------------------------------------------------*/
401
402#if defined(CONFIG_USB_MON) || defined(CONFIG_USB_MON_MODULE)
403
404struct usb_mon_operations {
405 void (*urb_submit)(struct usb_bus *bus, struct urb *urb);
406 void (*urb_submit_error)(struct usb_bus *bus, struct urb *urb, int err);
407 void (*urb_complete)(struct usb_bus *bus, struct urb *urb);
408 /* void (*urb_unlink)(struct usb_bus *bus, struct urb *urb); */
409 void (*bus_add)(struct usb_bus *bus);
410 void (*bus_remove)(struct usb_bus *bus);
411};
412
413extern struct usb_mon_operations *mon_ops;
414
415static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb)
416{
417 if (bus->monitored)
418 (*mon_ops->urb_submit)(bus, urb);
419}
420
421static inline void usbmon_urb_submit_error(struct usb_bus *bus, struct urb *urb,
422 int error)
423{
424 if (bus->monitored)
425 (*mon_ops->urb_submit_error)(bus, urb, error);
426}
427
428static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb)
429{
430 if (bus->monitored)
431 (*mon_ops->urb_complete)(bus, urb);
432}
433
434static inline void usbmon_notify_bus_add(struct usb_bus *bus)
435{
436 if (mon_ops)
437 (*mon_ops->bus_add)(bus);
438}
439
440static inline void usbmon_notify_bus_remove(struct usb_bus *bus)
441{
442 if (mon_ops)
443 (*mon_ops->bus_remove)(bus);
444}
445
446int usb_mon_register(struct usb_mon_operations *ops);
447void usb_mon_deregister(void);
448
449#else
450
451static inline void usbmon_urb_submit(struct usb_bus *bus, struct urb *urb) {}
452static inline void usbmon_urb_submit_error(struct usb_bus *bus, struct urb *urb,
453 int error) {}
454static inline void usbmon_urb_complete(struct usb_bus *bus, struct urb *urb) {}
455static inline void usbmon_notify_bus_add(struct usb_bus *bus) {}
456static inline void usbmon_notify_bus_remove(struct usb_bus *bus) {}
457
458#endif /* CONFIG_USB_MON */
459
460/*-------------------------------------------------------------------------*/
461
462/* hub.h ... DeviceRemovable in 2.4.2-ac11, gone in 2.4.10 */
463// bleech -- resurfaced in 2.4.11 or 2.4.12
464#define bitmap DeviceRemovable
465
466
467/*-------------------------------------------------------------------------*/
468
469/* random stuff */
470
471#define RUN_CONTEXT (in_irq () ? "in_irq" \
472 : (in_interrupt () ? "in_interrupt" : "can sleep"))
473
474
475#endif /* __KERNEL__ */
476
diff --git a/drivers/usb/core/hub.c b/drivers/usb/core/hub.c
new file mode 100644
index 000000000000..fa0dc4f6de47
--- /dev/null
+++ b/drivers/usb/core/hub.c
@@ -0,0 +1,3057 @@
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#ifdef CONFIG_USB_DEBUG
13 #define DEBUG
14#else
15 #undef DEBUG
16#endif
17#include <linux/kernel.h>
18#include <linux/errno.h>
19#include <linux/module.h>
20#include <linux/moduleparam.h>
21#include <linux/completion.h>
22#include <linux/sched.h>
23#include <linux/list.h>
24#include <linux/slab.h>
25#include <linux/smp_lock.h>
26#include <linux/ioctl.h>
27#include <linux/usb.h>
28#include <linux/usbdevice_fs.h>
29
30#include <asm/semaphore.h>
31#include <asm/uaccess.h>
32#include <asm/byteorder.h>
33
34#include "usb.h"
35#include "hcd.h"
36#include "hub.h"
37
38/* Protect struct usb_device->state and ->children members
39 * Note: Both are also protected by ->serialize, except that ->state can
40 * change to USB_STATE_NOTATTACHED even when the semaphore isn't held. */
41static DEFINE_SPINLOCK(device_state_lock);
42
43/* khubd's worklist and its lock */
44static DEFINE_SPINLOCK(hub_event_lock);
45static LIST_HEAD(hub_event_list); /* List of hubs needing servicing */
46
47/* Wakes up khubd */
48static DECLARE_WAIT_QUEUE_HEAD(khubd_wait);
49
50static pid_t khubd_pid = 0; /* PID of khubd */
51static DECLARE_COMPLETION(khubd_exited);
52
53/* cycle leds on hubs that aren't blinking for attention */
54static int blinkenlights = 0;
55module_param (blinkenlights, bool, S_IRUGO);
56MODULE_PARM_DESC (blinkenlights, "true to cycle leds on hubs");
57
58/*
59 * As of 2.6.10 we introduce a new USB device initialization scheme which
60 * closely resembles the way Windows works. Hopefully it will be compatible
61 * with a wider range of devices than the old scheme. However some previously
62 * working devices may start giving rise to "device not accepting address"
63 * errors; if that happens the user can try the old scheme by adjusting the
64 * following module parameters.
65 *
66 * For maximum flexibility there are two boolean parameters to control the
67 * hub driver's behavior. On the first initialization attempt, if the
68 * "old_scheme_first" parameter is set then the old scheme will be used,
69 * otherwise the new scheme is used. If that fails and "use_both_schemes"
70 * is set, then the driver will make another attempt, using the other scheme.
71 */
72static int old_scheme_first = 0;
73module_param(old_scheme_first, bool, S_IRUGO | S_IWUSR);
74MODULE_PARM_DESC(old_scheme_first,
75 "start with the old device initialization scheme");
76
77static int use_both_schemes = 1;
78module_param(use_both_schemes, bool, S_IRUGO | S_IWUSR);
79MODULE_PARM_DESC(use_both_schemes,
80 "try the other device initialization scheme if the "
81 "first one fails");
82
83
84#ifdef DEBUG
85static inline char *portspeed (int portstatus)
86{
87 if (portstatus & (1 << USB_PORT_FEAT_HIGHSPEED))
88 return "480 Mb/s";
89 else if (portstatus & (1 << USB_PORT_FEAT_LOWSPEED))
90 return "1.5 Mb/s";
91 else
92 return "12 Mb/s";
93}
94#endif
95
96/* Note that hdev or one of its children must be locked! */
97static inline struct usb_hub *hdev_to_hub(struct usb_device *hdev)
98{
99 return usb_get_intfdata(hdev->actconfig->interface[0]);
100}
101
102/* USB 2.0 spec Section 11.24.4.5 */
103static int get_hub_descriptor(struct usb_device *hdev, void *data, int size)
104{
105 int i, ret;
106
107 for (i = 0; i < 3; i++) {
108 ret = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
109 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN | USB_RT_HUB,
110 USB_DT_HUB << 8, 0, data, size,
111 USB_CTRL_GET_TIMEOUT);
112 if (ret >= (USB_DT_HUB_NONVAR_SIZE + 2))
113 return ret;
114 }
115 return -EINVAL;
116}
117
118/*
119 * USB 2.0 spec Section 11.24.2.1
120 */
121static int clear_hub_feature(struct usb_device *hdev, int feature)
122{
123 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
124 USB_REQ_CLEAR_FEATURE, USB_RT_HUB, feature, 0, NULL, 0, 1000);
125}
126
127/*
128 * USB 2.0 spec Section 11.24.2.2
129 */
130static int clear_port_feature(struct usb_device *hdev, int port1, int feature)
131{
132 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
133 USB_REQ_CLEAR_FEATURE, USB_RT_PORT, feature, port1,
134 NULL, 0, 1000);
135}
136
137/*
138 * USB 2.0 spec Section 11.24.2.13
139 */
140static int set_port_feature(struct usb_device *hdev, int port1, int feature)
141{
142 return usb_control_msg(hdev, usb_sndctrlpipe(hdev, 0),
143 USB_REQ_SET_FEATURE, USB_RT_PORT, feature, port1,
144 NULL, 0, 1000);
145}
146
147/*
148 * USB 2.0 spec Section 11.24.2.7.1.10 and table 11-7
149 * for info about using port indicators
150 */
151static void set_port_led(
152 struct usb_hub *hub,
153 int port1,
154 int selector
155)
156{
157 int status = set_port_feature(hub->hdev, (selector << 8) | port1,
158 USB_PORT_FEAT_INDICATOR);
159 if (status < 0)
160 dev_dbg (hub->intfdev,
161 "port %d indicator %s status %d\n",
162 port1,
163 ({ char *s; switch (selector) {
164 case HUB_LED_AMBER: s = "amber"; break;
165 case HUB_LED_GREEN: s = "green"; break;
166 case HUB_LED_OFF: s = "off"; break;
167 case HUB_LED_AUTO: s = "auto"; break;
168 default: s = "??"; break;
169 }; s; }),
170 status);
171}
172
173#define LED_CYCLE_PERIOD ((2*HZ)/3)
174
175static void led_work (void *__hub)
176{
177 struct usb_hub *hub = __hub;
178 struct usb_device *hdev = hub->hdev;
179 unsigned i;
180 unsigned changed = 0;
181 int cursor = -1;
182
183 if (hdev->state != USB_STATE_CONFIGURED || hub->quiescing)
184 return;
185
186 for (i = 0; i < hub->descriptor->bNbrPorts; i++) {
187 unsigned selector, mode;
188
189 /* 30%-50% duty cycle */
190
191 switch (hub->indicator[i]) {
192 /* cycle marker */
193 case INDICATOR_CYCLE:
194 cursor = i;
195 selector = HUB_LED_AUTO;
196 mode = INDICATOR_AUTO;
197 break;
198 /* blinking green = sw attention */
199 case INDICATOR_GREEN_BLINK:
200 selector = HUB_LED_GREEN;
201 mode = INDICATOR_GREEN_BLINK_OFF;
202 break;
203 case INDICATOR_GREEN_BLINK_OFF:
204 selector = HUB_LED_OFF;
205 mode = INDICATOR_GREEN_BLINK;
206 break;
207 /* blinking amber = hw attention */
208 case INDICATOR_AMBER_BLINK:
209 selector = HUB_LED_AMBER;
210 mode = INDICATOR_AMBER_BLINK_OFF;
211 break;
212 case INDICATOR_AMBER_BLINK_OFF:
213 selector = HUB_LED_OFF;
214 mode = INDICATOR_AMBER_BLINK;
215 break;
216 /* blink green/amber = reserved */
217 case INDICATOR_ALT_BLINK:
218 selector = HUB_LED_GREEN;
219 mode = INDICATOR_ALT_BLINK_OFF;
220 break;
221 case INDICATOR_ALT_BLINK_OFF:
222 selector = HUB_LED_AMBER;
223 mode = INDICATOR_ALT_BLINK;
224 break;
225 default:
226 continue;
227 }
228 if (selector != HUB_LED_AUTO)
229 changed = 1;
230 set_port_led(hub, i + 1, selector);
231 hub->indicator[i] = mode;
232 }
233 if (!changed && blinkenlights) {
234 cursor++;
235 cursor %= hub->descriptor->bNbrPorts;
236 set_port_led(hub, cursor + 1, HUB_LED_GREEN);
237 hub->indicator[cursor] = INDICATOR_CYCLE;
238 changed++;
239 }
240 if (changed)
241 schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
242}
243
244/* use a short timeout for hub/port status fetches */
245#define USB_STS_TIMEOUT 1000
246#define USB_STS_RETRIES 5
247
248/*
249 * USB 2.0 spec Section 11.24.2.6
250 */
251static int get_hub_status(struct usb_device *hdev,
252 struct usb_hub_status *data)
253{
254 int i, status = -ETIMEDOUT;
255
256 for (i = 0; i < USB_STS_RETRIES && status == -ETIMEDOUT; i++) {
257 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
258 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_HUB, 0, 0,
259 data, sizeof(*data), USB_STS_TIMEOUT);
260 }
261 return status;
262}
263
264/*
265 * USB 2.0 spec Section 11.24.2.7
266 */
267static int get_port_status(struct usb_device *hdev, int port1,
268 struct usb_port_status *data)
269{
270 int i, status = -ETIMEDOUT;
271
272 for (i = 0; i < USB_STS_RETRIES && status == -ETIMEDOUT; i++) {
273 status = usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
274 USB_REQ_GET_STATUS, USB_DIR_IN | USB_RT_PORT, 0, port1,
275 data, sizeof(*data), USB_STS_TIMEOUT);
276 }
277 return status;
278}
279
280static void kick_khubd(struct usb_hub *hub)
281{
282 unsigned long flags;
283
284 spin_lock_irqsave(&hub_event_lock, flags);
285 if (list_empty(&hub->event_list)) {
286 list_add_tail(&hub->event_list, &hub_event_list);
287 wake_up(&khubd_wait);
288 }
289 spin_unlock_irqrestore(&hub_event_lock, flags);
290}
291
292void usb_kick_khubd(struct usb_device *hdev)
293{
294 kick_khubd(hdev_to_hub(hdev));
295}
296
297
298/* completion function, fires on port status changes and various faults */
299static void hub_irq(struct urb *urb, struct pt_regs *regs)
300{
301 struct usb_hub *hub = (struct usb_hub *)urb->context;
302 int status;
303 int i;
304 unsigned long bits;
305
306 switch (urb->status) {
307 case -ENOENT: /* synchronous unlink */
308 case -ECONNRESET: /* async unlink */
309 case -ESHUTDOWN: /* hardware going away */
310 return;
311
312 default: /* presumably an error */
313 /* Cause a hub reset after 10 consecutive errors */
314 dev_dbg (hub->intfdev, "transfer --> %d\n", urb->status);
315 if ((++hub->nerrors < 10) || hub->error)
316 goto resubmit;
317 hub->error = urb->status;
318 /* FALL THROUGH */
319
320 /* let khubd handle things */
321 case 0: /* we got data: port status changed */
322 bits = 0;
323 for (i = 0; i < urb->actual_length; ++i)
324 bits |= ((unsigned long) ((*hub->buffer)[i]))
325 << (i*8);
326 hub->event_bits[0] = bits;
327 break;
328 }
329
330 hub->nerrors = 0;
331
332 /* Something happened, let khubd figure it out */
333 kick_khubd(hub);
334
335resubmit:
336 if (hub->quiescing)
337 return;
338
339 if ((status = usb_submit_urb (hub->urb, GFP_ATOMIC)) != 0
340 && status != -ENODEV && status != -EPERM)
341 dev_err (hub->intfdev, "resubmit --> %d\n", status);
342}
343
344/* USB 2.0 spec Section 11.24.2.3 */
345static inline int
346hub_clear_tt_buffer (struct usb_device *hdev, u16 devinfo, u16 tt)
347{
348 return usb_control_msg(hdev, usb_rcvctrlpipe(hdev, 0),
349 HUB_CLEAR_TT_BUFFER, USB_RT_PORT, devinfo,
350 tt, NULL, 0, 1000);
351}
352
353/*
354 * enumeration blocks khubd for a long time. we use keventd instead, since
355 * long blocking there is the exception, not the rule. accordingly, HCDs
356 * talking to TTs must queue control transfers (not just bulk and iso), so
357 * both can talk to the same hub concurrently.
358 */
359static void hub_tt_kevent (void *arg)
360{
361 struct usb_hub *hub = arg;
362 unsigned long flags;
363
364 spin_lock_irqsave (&hub->tt.lock, flags);
365 while (!list_empty (&hub->tt.clear_list)) {
366 struct list_head *temp;
367 struct usb_tt_clear *clear;
368 struct usb_device *hdev = hub->hdev;
369 int status;
370
371 temp = hub->tt.clear_list.next;
372 clear = list_entry (temp, struct usb_tt_clear, clear_list);
373 list_del (&clear->clear_list);
374
375 /* drop lock so HCD can concurrently report other TT errors */
376 spin_unlock_irqrestore (&hub->tt.lock, flags);
377 status = hub_clear_tt_buffer (hdev, clear->devinfo, clear->tt);
378 spin_lock_irqsave (&hub->tt.lock, flags);
379
380 if (status)
381 dev_err (&hdev->dev,
382 "clear tt %d (%04x) error %d\n",
383 clear->tt, clear->devinfo, status);
384 kfree (clear);
385 }
386 spin_unlock_irqrestore (&hub->tt.lock, flags);
387}
388
389/**
390 * usb_hub_tt_clear_buffer - clear control/bulk TT state in high speed hub
391 * @udev: the device whose split transaction failed
392 * @pipe: identifies the endpoint of the failed transaction
393 *
394 * High speed HCDs use this to tell the hub driver that some split control or
395 * bulk transaction failed in a way that requires clearing internal state of
396 * a transaction translator. This is normally detected (and reported) from
397 * interrupt context.
398 *
399 * It may not be possible for that hub to handle additional full (or low)
400 * speed transactions until that state is fully cleared out.
401 */
402void usb_hub_tt_clear_buffer (struct usb_device *udev, int pipe)
403{
404 struct usb_tt *tt = udev->tt;
405 unsigned long flags;
406 struct usb_tt_clear *clear;
407
408 /* we've got to cope with an arbitrary number of pending TT clears,
409 * since each TT has "at least two" buffers that can need it (and
410 * there can be many TTs per hub). even if they're uncommon.
411 */
412 if ((clear = kmalloc (sizeof *clear, SLAB_ATOMIC)) == NULL) {
413 dev_err (&udev->dev, "can't save CLEAR_TT_BUFFER state\n");
414 /* FIXME recover somehow ... RESET_TT? */
415 return;
416 }
417
418 /* info that CLEAR_TT_BUFFER needs */
419 clear->tt = tt->multi ? udev->ttport : 1;
420 clear->devinfo = usb_pipeendpoint (pipe);
421 clear->devinfo |= udev->devnum << 4;
422 clear->devinfo |= usb_pipecontrol (pipe)
423 ? (USB_ENDPOINT_XFER_CONTROL << 11)
424 : (USB_ENDPOINT_XFER_BULK << 11);
425 if (usb_pipein (pipe))
426 clear->devinfo |= 1 << 15;
427
428 /* tell keventd to clear state for this TT */
429 spin_lock_irqsave (&tt->lock, flags);
430 list_add_tail (&clear->clear_list, &tt->clear_list);
431 schedule_work (&tt->kevent);
432 spin_unlock_irqrestore (&tt->lock, flags);
433}
434
435static void hub_power_on(struct usb_hub *hub)
436{
437 int port1;
438
439 /* if hub supports power switching, enable power on each port */
440 if ((hub->descriptor->wHubCharacteristics & HUB_CHAR_LPSM) < 2) {
441 dev_dbg(hub->intfdev, "enabling power on all ports\n");
442 for (port1 = 1; port1 <= hub->descriptor->bNbrPorts; port1++)
443 set_port_feature(hub->hdev, port1,
444 USB_PORT_FEAT_POWER);
445 }
446
447 /* Wait for power to be enabled */
448 msleep(hub->descriptor->bPwrOn2PwrGood * 2);
449}
450
451static void hub_quiesce(struct usb_hub *hub)
452{
453 /* stop khubd and related activity */
454 hub->quiescing = 1;
455 usb_kill_urb(hub->urb);
456 if (hub->has_indicators)
457 cancel_delayed_work(&hub->leds);
458 if (hub->has_indicators || hub->tt.hub)
459 flush_scheduled_work();
460}
461
462static void hub_activate(struct usb_hub *hub)
463{
464 int status;
465
466 hub->quiescing = 0;
467 hub->activating = 1;
468 status = usb_submit_urb(hub->urb, GFP_NOIO);
469 if (status < 0)
470 dev_err(hub->intfdev, "activate --> %d\n", status);
471 if (hub->has_indicators && blinkenlights)
472 schedule_delayed_work(&hub->leds, LED_CYCLE_PERIOD);
473
474 /* scan all ports ASAP */
475 kick_khubd(hub);
476}
477
478static int hub_hub_status(struct usb_hub *hub,
479 u16 *status, u16 *change)
480{
481 int ret;
482
483 ret = get_hub_status(hub->hdev, &hub->status->hub);
484 if (ret < 0)
485 dev_err (hub->intfdev,
486 "%s failed (err = %d)\n", __FUNCTION__, ret);
487 else {
488 *status = le16_to_cpu(hub->status->hub.wHubStatus);
489 *change = le16_to_cpu(hub->status->hub.wHubChange);
490 ret = 0;
491 }
492 return ret;
493}
494
495static int hub_configure(struct usb_hub *hub,
496 struct usb_endpoint_descriptor *endpoint)
497{
498 struct usb_device *hdev = hub->hdev;
499 struct device *hub_dev = hub->intfdev;
500 u16 hubstatus, hubchange;
501 unsigned int pipe;
502 int maxp, ret;
503 char *message;
504
505 hub->buffer = usb_buffer_alloc(hdev, sizeof(*hub->buffer), GFP_KERNEL,
506 &hub->buffer_dma);
507 if (!hub->buffer) {
508 message = "can't allocate hub irq buffer";
509 ret = -ENOMEM;
510 goto fail;
511 }
512
513 hub->status = kmalloc(sizeof(*hub->status), GFP_KERNEL);
514 if (!hub->status) {
515 message = "can't kmalloc hub status buffer";
516 ret = -ENOMEM;
517 goto fail;
518 }
519
520 hub->descriptor = kmalloc(sizeof(*hub->descriptor), GFP_KERNEL);
521 if (!hub->descriptor) {
522 message = "can't kmalloc hub descriptor";
523 ret = -ENOMEM;
524 goto fail;
525 }
526
527 /* Request the entire hub descriptor.
528 * hub->descriptor can handle USB_MAXCHILDREN ports,
529 * but the hub can/will return fewer bytes here.
530 */
531 ret = get_hub_descriptor(hdev, hub->descriptor,
532 sizeof(*hub->descriptor));
533 if (ret < 0) {
534 message = "can't read hub descriptor";
535 goto fail;
536 } else if (hub->descriptor->bNbrPorts > USB_MAXCHILDREN) {
537 message = "hub has too many ports!";
538 ret = -ENODEV;
539 goto fail;
540 }
541
542 hdev->maxchild = hub->descriptor->bNbrPorts;
543 dev_info (hub_dev, "%d port%s detected\n", hdev->maxchild,
544 (hdev->maxchild == 1) ? "" : "s");
545
546 le16_to_cpus(&hub->descriptor->wHubCharacteristics);
547
548 if (hub->descriptor->wHubCharacteristics & HUB_CHAR_COMPOUND) {
549 int i;
550 char portstr [USB_MAXCHILDREN + 1];
551
552 for (i = 0; i < hdev->maxchild; i++)
553 portstr[i] = hub->descriptor->DeviceRemovable
554 [((i + 1) / 8)] & (1 << ((i + 1) % 8))
555 ? 'F' : 'R';
556 portstr[hdev->maxchild] = 0;
557 dev_dbg(hub_dev, "compound device; port removable status: %s\n", portstr);
558 } else
559 dev_dbg(hub_dev, "standalone hub\n");
560
561 switch (hub->descriptor->wHubCharacteristics & HUB_CHAR_LPSM) {
562 case 0x00:
563 dev_dbg(hub_dev, "ganged power switching\n");
564 break;
565 case 0x01:
566 dev_dbg(hub_dev, "individual port power switching\n");
567 break;
568 case 0x02:
569 case 0x03:
570 dev_dbg(hub_dev, "no power switching (usb 1.0)\n");
571 break;
572 }
573
574 switch (hub->descriptor->wHubCharacteristics & HUB_CHAR_OCPM) {
575 case 0x00:
576 dev_dbg(hub_dev, "global over-current protection\n");
577 break;
578 case 0x08:
579 dev_dbg(hub_dev, "individual port over-current protection\n");
580 break;
581 case 0x10:
582 case 0x18:
583 dev_dbg(hub_dev, "no over-current protection\n");
584 break;
585 }
586
587 spin_lock_init (&hub->tt.lock);
588 INIT_LIST_HEAD (&hub->tt.clear_list);
589 INIT_WORK (&hub->tt.kevent, hub_tt_kevent, hub);
590 switch (hdev->descriptor.bDeviceProtocol) {
591 case 0:
592 break;
593 case 1:
594 dev_dbg(hub_dev, "Single TT\n");
595 hub->tt.hub = hdev;
596 break;
597 case 2:
598 ret = usb_set_interface(hdev, 0, 1);
599 if (ret == 0) {
600 dev_dbg(hub_dev, "TT per port\n");
601 hub->tt.multi = 1;
602 } else
603 dev_err(hub_dev, "Using single TT (err %d)\n",
604 ret);
605 hub->tt.hub = hdev;
606 break;
607 default:
608 dev_dbg(hub_dev, "Unrecognized hub protocol %d\n",
609 hdev->descriptor.bDeviceProtocol);
610 break;
611 }
612
613 switch (hub->descriptor->wHubCharacteristics & HUB_CHAR_TTTT) {
614 case 0x00:
615 if (hdev->descriptor.bDeviceProtocol != 0)
616 dev_dbg(hub_dev, "TT requires at most 8 FS bit times\n");
617 break;
618 case 0x20:
619 dev_dbg(hub_dev, "TT requires at most 16 FS bit times\n");
620 break;
621 case 0x40:
622 dev_dbg(hub_dev, "TT requires at most 24 FS bit times\n");
623 break;
624 case 0x60:
625 dev_dbg(hub_dev, "TT requires at most 32 FS bit times\n");
626 break;
627 }
628
629 /* probe() zeroes hub->indicator[] */
630 if (hub->descriptor->wHubCharacteristics & HUB_CHAR_PORTIND) {
631 hub->has_indicators = 1;
632 dev_dbg(hub_dev, "Port indicators are supported\n");
633 }
634
635 dev_dbg(hub_dev, "power on to power good time: %dms\n",
636 hub->descriptor->bPwrOn2PwrGood * 2);
637
638 /* power budgeting mostly matters with bus-powered hubs,
639 * and battery-powered root hubs (may provide just 8 mA).
640 */
641 ret = usb_get_status(hdev, USB_RECIP_DEVICE, 0, &hubstatus);
642 if (ret < 0) {
643 message = "can't get hub status";
644 goto fail;
645 }
646 cpu_to_le16s(&hubstatus);
647 if ((hubstatus & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
648 dev_dbg(hub_dev, "hub controller current requirement: %dmA\n",
649 hub->descriptor->bHubContrCurrent);
650 hub->power_budget = (501 - hub->descriptor->bHubContrCurrent)
651 / 2;
652 dev_dbg(hub_dev, "%dmA bus power budget for children\n",
653 hub->power_budget * 2);
654 }
655
656
657 ret = hub_hub_status(hub, &hubstatus, &hubchange);
658 if (ret < 0) {
659 message = "can't get hub status";
660 goto fail;
661 }
662
663 /* local power status reports aren't always correct */
664 if (hdev->actconfig->desc.bmAttributes & USB_CONFIG_ATT_SELFPOWER)
665 dev_dbg(hub_dev, "local power source is %s\n",
666 (hubstatus & HUB_STATUS_LOCAL_POWER)
667 ? "lost (inactive)" : "good");
668
669 if ((hub->descriptor->wHubCharacteristics & HUB_CHAR_OCPM) == 0)
670 dev_dbg(hub_dev, "%sover-current condition exists\n",
671 (hubstatus & HUB_STATUS_OVERCURRENT) ? "" : "no ");
672
673 /* set up the interrupt endpoint */
674 pipe = usb_rcvintpipe(hdev, endpoint->bEndpointAddress);
675 maxp = usb_maxpacket(hdev, pipe, usb_pipeout(pipe));
676
677 if (maxp > sizeof(*hub->buffer))
678 maxp = sizeof(*hub->buffer);
679
680 hub->urb = usb_alloc_urb(0, GFP_KERNEL);
681 if (!hub->urb) {
682 message = "couldn't allocate interrupt urb";
683 ret = -ENOMEM;
684 goto fail;
685 }
686
687 usb_fill_int_urb(hub->urb, hdev, pipe, *hub->buffer, maxp, hub_irq,
688 hub, endpoint->bInterval);
689 hub->urb->transfer_dma = hub->buffer_dma;
690 hub->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
691
692 /* maybe cycle the hub leds */
693 if (hub->has_indicators && blinkenlights)
694 hub->indicator [0] = INDICATOR_CYCLE;
695
696 hub_power_on(hub);
697 hub_activate(hub);
698 return 0;
699
700fail:
701 dev_err (hub_dev, "config failed, %s (err %d)\n",
702 message, ret);
703 /* hub_disconnect() frees urb and descriptor */
704 return ret;
705}
706
707static unsigned highspeed_hubs;
708
709static void hub_disconnect(struct usb_interface *intf)
710{
711 struct usb_hub *hub = usb_get_intfdata (intf);
712 struct usb_device *hdev;
713
714 if (!hub)
715 return;
716 hdev = hub->hdev;
717
718 if (hdev->speed == USB_SPEED_HIGH)
719 highspeed_hubs--;
720
721 usb_set_intfdata (intf, NULL);
722
723 hub_quiesce(hub);
724 usb_free_urb(hub->urb);
725 hub->urb = NULL;
726
727 spin_lock_irq(&hub_event_lock);
728 list_del_init(&hub->event_list);
729 spin_unlock_irq(&hub_event_lock);
730
731 if (hub->descriptor) {
732 kfree(hub->descriptor);
733 hub->descriptor = NULL;
734 }
735
736 if (hub->status) {
737 kfree(hub->status);
738 hub->status = NULL;
739 }
740
741 if (hub->buffer) {
742 usb_buffer_free(hdev, sizeof(*hub->buffer), hub->buffer,
743 hub->buffer_dma);
744 hub->buffer = NULL;
745 }
746
747 /* Free the memory */
748 kfree(hub);
749}
750
751static int hub_probe(struct usb_interface *intf, const struct usb_device_id *id)
752{
753 struct usb_host_interface *desc;
754 struct usb_endpoint_descriptor *endpoint;
755 struct usb_device *hdev;
756 struct usb_hub *hub;
757
758 desc = intf->cur_altsetting;
759 hdev = interface_to_usbdev(intf);
760
761 /* Some hubs have a subclass of 1, which AFAICT according to the */
762 /* specs is not defined, but it works */
763 if ((desc->desc.bInterfaceSubClass != 0) &&
764 (desc->desc.bInterfaceSubClass != 1)) {
765descriptor_error:
766 dev_err (&intf->dev, "bad descriptor, ignoring hub\n");
767 return -EIO;
768 }
769
770 /* Multiple endpoints? What kind of mutant ninja-hub is this? */
771 if (desc->desc.bNumEndpoints != 1)
772 goto descriptor_error;
773
774 endpoint = &desc->endpoint[0].desc;
775
776 /* Output endpoint? Curiouser and curiouser.. */
777 if (!(endpoint->bEndpointAddress & USB_DIR_IN))
778 goto descriptor_error;
779
780 /* If it's not an interrupt endpoint, we'd better punt! */
781 if ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
782 != USB_ENDPOINT_XFER_INT)
783 goto descriptor_error;
784
785 /* We found a hub */
786 dev_info (&intf->dev, "USB hub found\n");
787
788 hub = kmalloc(sizeof(*hub), GFP_KERNEL);
789 if (!hub) {
790 dev_dbg (&intf->dev, "couldn't kmalloc hub struct\n");
791 return -ENOMEM;
792 }
793
794 memset(hub, 0, sizeof(*hub));
795
796 INIT_LIST_HEAD(&hub->event_list);
797 hub->intfdev = &intf->dev;
798 hub->hdev = hdev;
799 INIT_WORK(&hub->leds, led_work, hub);
800
801 usb_set_intfdata (intf, hub);
802
803 if (hdev->speed == USB_SPEED_HIGH)
804 highspeed_hubs++;
805
806 if (hub_configure(hub, endpoint) >= 0)
807 return 0;
808
809 hub_disconnect (intf);
810 return -ENODEV;
811}
812
813static int
814hub_ioctl(struct usb_interface *intf, unsigned int code, void *user_data)
815{
816 struct usb_device *hdev = interface_to_usbdev (intf);
817
818 /* assert ifno == 0 (part of hub spec) */
819 switch (code) {
820 case USBDEVFS_HUB_PORTINFO: {
821 struct usbdevfs_hub_portinfo *info = user_data;
822 int i;
823
824 spin_lock_irq(&device_state_lock);
825 if (hdev->devnum <= 0)
826 info->nports = 0;
827 else {
828 info->nports = hdev->maxchild;
829 for (i = 0; i < info->nports; i++) {
830 if (hdev->children[i] == NULL)
831 info->port[i] = 0;
832 else
833 info->port[i] =
834 hdev->children[i]->devnum;
835 }
836 }
837 spin_unlock_irq(&device_state_lock);
838
839 return info->nports + 1;
840 }
841
842 default:
843 return -ENOSYS;
844 }
845}
846
847/* caller has locked the hub device */
848static void hub_pre_reset(struct usb_hub *hub)
849{
850 struct usb_device *hdev = hub->hdev;
851 int i;
852
853 for (i = 0; i < hdev->maxchild; ++i) {
854 if (hdev->children[i])
855 usb_disconnect(&hdev->children[i]);
856 }
857 hub_quiesce(hub);
858}
859
860/* caller has locked the hub device */
861static void hub_post_reset(struct usb_hub *hub)
862{
863 hub_activate(hub);
864 hub_power_on(hub);
865}
866
867
868/* grab device/port lock, returning index of that port (zero based).
869 * protects the upstream link used by this device from concurrent
870 * tree operations like suspend, resume, reset, and disconnect, which
871 * apply to everything downstream of a given port.
872 */
873static int locktree(struct usb_device *udev)
874{
875 int t;
876 struct usb_device *hdev;
877
878 if (!udev)
879 return -ENODEV;
880
881 /* root hub is always the first lock in the series */
882 hdev = udev->parent;
883 if (!hdev) {
884 usb_lock_device(udev);
885 return 0;
886 }
887
888 /* on the path from root to us, lock everything from
889 * top down, dropping parent locks when not needed
890 */
891 t = locktree(hdev);
892 if (t < 0)
893 return t;
894 for (t = 0; t < hdev->maxchild; t++) {
895 if (hdev->children[t] == udev) {
896 /* everything is fail-fast once disconnect
897 * processing starts
898 */
899 if (udev->state == USB_STATE_NOTATTACHED)
900 break;
901
902 /* when everyone grabs locks top->bottom,
903 * non-overlapping work may be concurrent
904 */
905 down(&udev->serialize);
906 up(&hdev->serialize);
907 return t + 1;
908 }
909 }
910 usb_unlock_device(hdev);
911 return -ENODEV;
912}
913
914static void recursively_mark_NOTATTACHED(struct usb_device *udev)
915{
916 int i;
917
918 for (i = 0; i < udev->maxchild; ++i) {
919 if (udev->children[i])
920 recursively_mark_NOTATTACHED(udev->children[i]);
921 }
922 udev->state = USB_STATE_NOTATTACHED;
923}
924
925/**
926 * usb_set_device_state - change a device's current state (usbcore, hcds)
927 * @udev: pointer to device whose state should be changed
928 * @new_state: new state value to be stored
929 *
930 * udev->state is _not_ fully protected by the device lock. Although
931 * most transitions are made only while holding the lock, the state can
932 * can change to USB_STATE_NOTATTACHED at almost any time. This
933 * is so that devices can be marked as disconnected as soon as possible,
934 * without having to wait for any semaphores to be released. As a result,
935 * all changes to any device's state must be protected by the
936 * device_state_lock spinlock.
937 *
938 * Once a device has been added to the device tree, all changes to its state
939 * should be made using this routine. The state should _not_ be set directly.
940 *
941 * If udev->state is already USB_STATE_NOTATTACHED then no change is made.
942 * Otherwise udev->state is set to new_state, and if new_state is
943 * USB_STATE_NOTATTACHED then all of udev's descendants' states are also set
944 * to USB_STATE_NOTATTACHED.
945 */
946void usb_set_device_state(struct usb_device *udev,
947 enum usb_device_state new_state)
948{
949 unsigned long flags;
950
951 spin_lock_irqsave(&device_state_lock, flags);
952 if (udev->state == USB_STATE_NOTATTACHED)
953 ; /* do nothing */
954 else if (new_state != USB_STATE_NOTATTACHED)
955 udev->state = new_state;
956 else
957 recursively_mark_NOTATTACHED(udev);
958 spin_unlock_irqrestore(&device_state_lock, flags);
959}
960EXPORT_SYMBOL(usb_set_device_state);
961
962
963static void choose_address(struct usb_device *udev)
964{
965 int devnum;
966 struct usb_bus *bus = udev->bus;
967
968 /* If khubd ever becomes multithreaded, this will need a lock */
969
970 /* Try to allocate the next devnum beginning at bus->devnum_next. */
971 devnum = find_next_zero_bit(bus->devmap.devicemap, 128,
972 bus->devnum_next);
973 if (devnum >= 128)
974 devnum = find_next_zero_bit(bus->devmap.devicemap, 128, 1);
975
976 bus->devnum_next = ( devnum >= 127 ? 1 : devnum + 1);
977
978 if (devnum < 128) {
979 set_bit(devnum, bus->devmap.devicemap);
980 udev->devnum = devnum;
981 }
982}
983
984static void release_address(struct usb_device *udev)
985{
986 if (udev->devnum > 0) {
987 clear_bit(udev->devnum, udev->bus->devmap.devicemap);
988 udev->devnum = -1;
989 }
990}
991
992/**
993 * usb_disconnect - disconnect a device (usbcore-internal)
994 * @pdev: pointer to device being disconnected
995 * Context: !in_interrupt ()
996 *
997 * Something got disconnected. Get rid of it and all of its children.
998 *
999 * If *pdev is a normal device then the parent hub must already be locked.
1000 * If *pdev is a root hub then this routine will acquire the
1001 * usb_bus_list_lock on behalf of the caller.
1002 *
1003 * Only hub drivers (including virtual root hub drivers for host
1004 * controllers) should ever call this.
1005 *
1006 * This call is synchronous, and may not be used in an interrupt context.
1007 */
1008void usb_disconnect(struct usb_device **pdev)
1009{
1010 struct usb_device *udev = *pdev;
1011 int i;
1012
1013 if (!udev) {
1014 pr_debug ("%s nodev\n", __FUNCTION__);
1015 return;
1016 }
1017
1018 /* mark the device as inactive, so any further urb submissions for
1019 * this device (and any of its children) will fail immediately.
1020 * this quiesces everyting except pending urbs.
1021 */
1022 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1023
1024 /* lock the bus list on behalf of HCDs unregistering their root hubs */
1025 if (!udev->parent) {
1026 down(&usb_bus_list_lock);
1027 usb_lock_device(udev);
1028 } else
1029 down(&udev->serialize);
1030
1031 dev_info (&udev->dev, "USB disconnect, address %d\n", udev->devnum);
1032
1033 /* Free up all the children before we remove this device */
1034 for (i = 0; i < USB_MAXCHILDREN; i++) {
1035 if (udev->children[i])
1036 usb_disconnect(&udev->children[i]);
1037 }
1038
1039 /* deallocate hcd/hardware state ... nuking all pending urbs and
1040 * cleaning up all state associated with the current configuration
1041 * so that the hardware is now fully quiesced.
1042 */
1043 usb_disable_device(udev, 0);
1044
1045 /* Free the device number, remove the /proc/bus/usb entry and
1046 * the sysfs attributes, and delete the parent's children[]
1047 * (or root_hub) pointer.
1048 */
1049 dev_dbg (&udev->dev, "unregistering device\n");
1050 release_address(udev);
1051 usbfs_remove_device(udev);
1052 usb_remove_sysfs_dev_files(udev);
1053
1054 /* Avoid races with recursively_mark_NOTATTACHED() */
1055 spin_lock_irq(&device_state_lock);
1056 *pdev = NULL;
1057 spin_unlock_irq(&device_state_lock);
1058
1059 if (!udev->parent) {
1060 usb_unlock_device(udev);
1061 up(&usb_bus_list_lock);
1062 } else
1063 up(&udev->serialize);
1064
1065 device_unregister(&udev->dev);
1066}
1067
1068static int choose_configuration(struct usb_device *udev)
1069{
1070 int c, i;
1071
1072 /* NOTE: this should interact with hub power budgeting */
1073
1074 c = udev->config[0].desc.bConfigurationValue;
1075 if (udev->descriptor.bNumConfigurations != 1) {
1076 for (i = 0; i < udev->descriptor.bNumConfigurations; i++) {
1077 struct usb_interface_descriptor *desc;
1078
1079 /* heuristic: Linux is more likely to have class
1080 * drivers, so avoid vendor-specific interfaces.
1081 */
1082 desc = &udev->config[i].intf_cache[0]
1083 ->altsetting->desc;
1084 if (desc->bInterfaceClass == USB_CLASS_VENDOR_SPEC)
1085 continue;
1086 /* COMM/2/all is CDC ACM, except 0xff is MSFT RNDIS.
1087 * MSFT needs this to be the first config; never use
1088 * it as the default unless Linux has host-side RNDIS.
1089 * A second config would ideally be CDC-Ethernet, but
1090 * may instead be the "vendor specific" CDC subset
1091 * long used by ARM Linux for sa1100 or pxa255.
1092 */
1093 if (desc->bInterfaceClass == USB_CLASS_COMM
1094 && desc->bInterfaceSubClass == 2
1095 && desc->bInterfaceProtocol == 0xff) {
1096 c = udev->config[1].desc.bConfigurationValue;
1097 continue;
1098 }
1099 c = udev->config[i].desc.bConfigurationValue;
1100 break;
1101 }
1102 dev_info(&udev->dev,
1103 "configuration #%d chosen from %d choices\n",
1104 c, udev->descriptor.bNumConfigurations);
1105 }
1106 return c;
1107}
1108
1109#ifdef DEBUG
1110static void show_string(struct usb_device *udev, char *id, char *string)
1111{
1112 if (!string)
1113 return;
1114 dev_printk(KERN_INFO, &udev->dev, "%s: %s\n", id, string);
1115}
1116
1117#else
1118static inline void show_string(struct usb_device *udev, char *id, char *string)
1119{}
1120#endif
1121
1122static void get_string(struct usb_device *udev, char **string, int index)
1123{
1124 char *buf;
1125
1126 if (!index)
1127 return;
1128 buf = kmalloc(256, GFP_KERNEL);
1129 if (!buf)
1130 return;
1131 if (usb_string(udev, index, buf, 256) > 0)
1132 *string = buf;
1133 else
1134 kfree(buf);
1135}
1136
1137
1138#ifdef CONFIG_USB_OTG
1139#include "otg_whitelist.h"
1140#endif
1141
1142/**
1143 * usb_new_device - perform initial device setup (usbcore-internal)
1144 * @udev: newly addressed device (in ADDRESS state)
1145 *
1146 * This is called with devices which have been enumerated, but not yet
1147 * configured. The device descriptor is available, but not descriptors
1148 * for any device configuration. The caller must have locked udev and
1149 * either the parent hub (if udev is a normal device) or else the
1150 * usb_bus_list_lock (if udev is a root hub). The parent's pointer to
1151 * udev has already been installed, but udev is not yet visible through
1152 * sysfs or other filesystem code.
1153 *
1154 * Returns 0 for success (device is configured and listed, with its
1155 * interfaces, in sysfs); else a negative errno value.
1156 *
1157 * This call is synchronous, and may not be used in an interrupt context.
1158 *
1159 * Only the hub driver should ever call this; root hub registration
1160 * uses it indirectly.
1161 */
1162int usb_new_device(struct usb_device *udev)
1163{
1164 int err;
1165 int c;
1166
1167 err = usb_get_configuration(udev);
1168 if (err < 0) {
1169 dev_err(&udev->dev, "can't read configurations, error %d\n",
1170 err);
1171 goto fail;
1172 }
1173
1174 /* read the standard strings and cache them if present */
1175 get_string(udev, &udev->product, udev->descriptor.iProduct);
1176 get_string(udev, &udev->manufacturer, udev->descriptor.iManufacturer);
1177 get_string(udev, &udev->serial, udev->descriptor.iSerialNumber);
1178
1179 /* Tell the world! */
1180 dev_dbg(&udev->dev, "new device strings: Mfr=%d, Product=%d, "
1181 "SerialNumber=%d\n",
1182 udev->descriptor.iManufacturer,
1183 udev->descriptor.iProduct,
1184 udev->descriptor.iSerialNumber);
1185 show_string(udev, "Product", udev->product);
1186 show_string(udev, "Manufacturer", udev->manufacturer);
1187 show_string(udev, "SerialNumber", udev->serial);
1188
1189#ifdef CONFIG_USB_OTG
1190 /*
1191 * OTG-aware devices on OTG-capable root hubs may be able to use SRP,
1192 * to wake us after we've powered off VBUS; and HNP, switching roles
1193 * "host" to "peripheral". The OTG descriptor helps figure this out.
1194 */
1195 if (!udev->bus->is_b_host
1196 && udev->config
1197 && udev->parent == udev->bus->root_hub) {
1198 struct usb_otg_descriptor *desc = 0;
1199 struct usb_bus *bus = udev->bus;
1200
1201 /* descriptor may appear anywhere in config */
1202 if (__usb_get_extra_descriptor (udev->rawdescriptors[0],
1203 le16_to_cpu(udev->config[0].desc.wTotalLength),
1204 USB_DT_OTG, (void **) &desc) == 0) {
1205 if (desc->bmAttributes & USB_OTG_HNP) {
1206 unsigned port1;
1207 struct usb_device *root = udev->parent;
1208
1209 for (port1 = 1; port1 <= root->maxchild;
1210 port1++) {
1211 if (root->children[port1-1] == udev)
1212 break;
1213 }
1214
1215 dev_info(&udev->dev,
1216 "Dual-Role OTG device on %sHNP port\n",
1217 (port1 == bus->otg_port)
1218 ? "" : "non-");
1219
1220 /* enable HNP before suspend, it's simpler */
1221 if (port1 == bus->otg_port)
1222 bus->b_hnp_enable = 1;
1223 err = usb_control_msg(udev,
1224 usb_sndctrlpipe(udev, 0),
1225 USB_REQ_SET_FEATURE, 0,
1226 bus->b_hnp_enable
1227 ? USB_DEVICE_B_HNP_ENABLE
1228 : USB_DEVICE_A_ALT_HNP_SUPPORT,
1229 0, NULL, 0, USB_CTRL_SET_TIMEOUT);
1230 if (err < 0) {
1231 /* OTG MESSAGE: report errors here,
1232 * customize to match your product.
1233 */
1234 dev_info(&udev->dev,
1235 "can't set HNP mode; %d\n",
1236 err);
1237 bus->b_hnp_enable = 0;
1238 }
1239 }
1240 }
1241 }
1242
1243 if (!is_targeted(udev)) {
1244
1245 /* Maybe it can talk to us, though we can't talk to it.
1246 * (Includes HNP test device.)
1247 */
1248 if (udev->bus->b_hnp_enable || udev->bus->is_b_host) {
1249 static int __usb_suspend_device (struct usb_device *,
1250 int port1, pm_message_t state);
1251 err = __usb_suspend_device(udev,
1252 udev->bus->otg_port,
1253 PMSG_SUSPEND);
1254 if (err < 0)
1255 dev_dbg(&udev->dev, "HNP fail, %d\n", err);
1256 }
1257 err = -ENODEV;
1258 goto fail;
1259 }
1260#endif
1261
1262 /* put device-specific files into sysfs */
1263 err = device_add (&udev->dev);
1264 if (err) {
1265 dev_err(&udev->dev, "can't device_add, error %d\n", err);
1266 goto fail;
1267 }
1268 usb_create_sysfs_dev_files (udev);
1269
1270 /* choose and set the configuration. that registers the interfaces
1271 * with the driver core, and lets usb device drivers bind to them.
1272 */
1273 c = choose_configuration(udev);
1274 if (c < 0)
1275 dev_warn(&udev->dev,
1276 "can't choose an initial configuration\n");
1277 else {
1278 err = usb_set_configuration(udev, c);
1279 if (err) {
1280 dev_err(&udev->dev, "can't set config #%d, error %d\n",
1281 c, err);
1282 usb_remove_sysfs_dev_files(udev);
1283 device_del(&udev->dev);
1284 goto fail;
1285 }
1286 }
1287
1288 /* USB device state == configured ... usable */
1289
1290 /* add a /proc/bus/usb entry */
1291 usbfs_add_device(udev);
1292 return 0;
1293
1294fail:
1295 usb_set_device_state(udev, USB_STATE_NOTATTACHED);
1296 return err;
1297}
1298
1299
1300static int hub_port_status(struct usb_hub *hub, int port1,
1301 u16 *status, u16 *change)
1302{
1303 int ret;
1304
1305 ret = get_port_status(hub->hdev, port1, &hub->status->port);
1306 if (ret < 0)
1307 dev_err (hub->intfdev,
1308 "%s failed (err = %d)\n", __FUNCTION__, ret);
1309 else {
1310 *status = le16_to_cpu(hub->status->port.wPortStatus);
1311 *change = le16_to_cpu(hub->status->port.wPortChange);
1312 ret = 0;
1313 }
1314 return ret;
1315}
1316
1317#define PORT_RESET_TRIES 5
1318#define SET_ADDRESS_TRIES 2
1319#define GET_DESCRIPTOR_TRIES 2
1320#define SET_CONFIG_TRIES (2 * (use_both_schemes + 1))
1321#define USE_NEW_SCHEME(i) ((i) / 2 == old_scheme_first)
1322
1323#define HUB_ROOT_RESET_TIME 50 /* times are in msec */
1324#define HUB_SHORT_RESET_TIME 10
1325#define HUB_LONG_RESET_TIME 200
1326#define HUB_RESET_TIMEOUT 500
1327
1328static int hub_port_wait_reset(struct usb_hub *hub, int port1,
1329 struct usb_device *udev, unsigned int delay)
1330{
1331 int delay_time, ret;
1332 u16 portstatus;
1333 u16 portchange;
1334
1335 for (delay_time = 0;
1336 delay_time < HUB_RESET_TIMEOUT;
1337 delay_time += delay) {
1338 /* wait to give the device a chance to reset */
1339 msleep(delay);
1340
1341 /* read and decode port status */
1342 ret = hub_port_status(hub, port1, &portstatus, &portchange);
1343 if (ret < 0)
1344 return ret;
1345
1346 /* Device went away? */
1347 if (!(portstatus & USB_PORT_STAT_CONNECTION))
1348 return -ENOTCONN;
1349
1350 /* bomb out completely if something weird happened */
1351 if ((portchange & USB_PORT_STAT_C_CONNECTION))
1352 return -EINVAL;
1353
1354 /* if we`ve finished resetting, then break out of the loop */
1355 if (!(portstatus & USB_PORT_STAT_RESET) &&
1356 (portstatus & USB_PORT_STAT_ENABLE)) {
1357 if (portstatus & USB_PORT_STAT_HIGH_SPEED)
1358 udev->speed = USB_SPEED_HIGH;
1359 else if (portstatus & USB_PORT_STAT_LOW_SPEED)
1360 udev->speed = USB_SPEED_LOW;
1361 else
1362 udev->speed = USB_SPEED_FULL;
1363 return 0;
1364 }
1365
1366 /* switch to the long delay after two short delay failures */
1367 if (delay_time >= 2 * HUB_SHORT_RESET_TIME)
1368 delay = HUB_LONG_RESET_TIME;
1369
1370 dev_dbg (hub->intfdev,
1371 "port %d not reset yet, waiting %dms\n",
1372 port1, delay);
1373 }
1374
1375 return -EBUSY;
1376}
1377
1378static int hub_port_reset(struct usb_hub *hub, int port1,
1379 struct usb_device *udev, unsigned int delay)
1380{
1381 int i, status;
1382
1383 /* Reset the port */
1384 for (i = 0; i < PORT_RESET_TRIES; i++) {
1385 status = set_port_feature(hub->hdev,
1386 port1, USB_PORT_FEAT_RESET);
1387 if (status)
1388 dev_err(hub->intfdev,
1389 "cannot reset port %d (err = %d)\n",
1390 port1, status);
1391 else {
1392 status = hub_port_wait_reset(hub, port1, udev, delay);
1393 if (status)
1394 dev_dbg(hub->intfdev,
1395 "port_wait_reset: err = %d\n",
1396 status);
1397 }
1398
1399 /* return on disconnect or reset */
1400 switch (status) {
1401 case 0:
1402 /* TRSTRCY = 10 ms */
1403 msleep(10);
1404 /* FALL THROUGH */
1405 case -ENOTCONN:
1406 case -ENODEV:
1407 clear_port_feature(hub->hdev,
1408 port1, USB_PORT_FEAT_C_RESET);
1409 /* FIXME need disconnect() for NOTATTACHED device */
1410 usb_set_device_state(udev, status
1411 ? USB_STATE_NOTATTACHED
1412 : USB_STATE_DEFAULT);
1413 return status;
1414 }
1415
1416 dev_dbg (hub->intfdev,
1417 "port %d not enabled, trying reset again...\n",
1418 port1);
1419 delay = HUB_LONG_RESET_TIME;
1420 }
1421
1422 dev_err (hub->intfdev,
1423 "Cannot enable port %i. Maybe the USB cable is bad?\n",
1424 port1);
1425
1426 return status;
1427}
1428
1429static int hub_port_disable(struct usb_hub *hub, int port1, int set_state)
1430{
1431 struct usb_device *hdev = hub->hdev;
1432 int ret;
1433
1434 if (hdev->children[port1-1] && set_state) {
1435 usb_set_device_state(hdev->children[port1-1],
1436 USB_STATE_NOTATTACHED);
1437 }
1438 ret = clear_port_feature(hdev, port1, USB_PORT_FEAT_ENABLE);
1439 if (ret)
1440 dev_err(hub->intfdev, "cannot disable port %d (err = %d)\n",
1441 port1, ret);
1442
1443 return ret;
1444}
1445
1446/*
1447 * Disable a port and mark a logical connnect-change event, so that some
1448 * time later khubd will disconnect() any existing usb_device on the port
1449 * and will re-enumerate if there actually is a device attached.
1450 */
1451static void hub_port_logical_disconnect(struct usb_hub *hub, int port1)
1452{
1453 dev_dbg(hub->intfdev, "logical disconnect on port %d\n", port1);
1454 hub_port_disable(hub, port1, 1);
1455
1456 /* FIXME let caller ask to power down the port:
1457 * - some devices won't enumerate without a VBUS power cycle
1458 * - SRP saves power that way
1459 * - usb_suspend_device(dev,PM_SUSPEND_DISK)
1460 * That's easy if this hub can switch power per-port, and
1461 * khubd reactivates the port later (timer, SRP, etc).
1462 * Powerdown must be optional, because of reset/DFU.
1463 */
1464
1465 set_bit(port1, hub->change_bits);
1466 kick_khubd(hub);
1467}
1468
1469
1470#ifdef CONFIG_USB_SUSPEND
1471
1472/*
1473 * Selective port suspend reduces power; most suspended devices draw
1474 * less than 500 uA. It's also used in OTG, along with remote wakeup.
1475 * All devices below the suspended port are also suspended.
1476 *
1477 * Devices leave suspend state when the host wakes them up. Some devices
1478 * also support "remote wakeup", where the device can activate the USB
1479 * tree above them to deliver data, such as a keypress or packet. In
1480 * some cases, this wakes the USB host.
1481 */
1482static int hub_port_suspend(struct usb_hub *hub, int port1,
1483 struct usb_device *udev)
1484{
1485 int status;
1486
1487 // dev_dbg(hub->intfdev, "suspend port %d\n", port1);
1488
1489 /* enable remote wakeup when appropriate; this lets the device
1490 * wake up the upstream hub (including maybe the root hub).
1491 *
1492 * NOTE: OTG devices may issue remote wakeup (or SRP) even when
1493 * we don't explicitly enable it here.
1494 */
1495 if (udev->actconfig
1496 // && FIXME (remote wakeup enabled on this bus)
1497 // ... currently assuming it's always appropriate
1498 && (udev->actconfig->desc.bmAttributes
1499 & USB_CONFIG_ATT_WAKEUP) != 0) {
1500 status = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
1501 USB_REQ_SET_FEATURE, USB_RECIP_DEVICE,
1502 USB_DEVICE_REMOTE_WAKEUP, 0,
1503 NULL, 0,
1504 USB_CTRL_SET_TIMEOUT);
1505 if (status)
1506 dev_dbg(&udev->dev,
1507 "won't remote wakeup, status %d\n",
1508 status);
1509 }
1510
1511 /* see 7.1.7.6 */
1512 status = set_port_feature(hub->hdev, port1, USB_PORT_FEAT_SUSPEND);
1513 if (status) {
1514 dev_dbg(hub->intfdev,
1515 "can't suspend port %d, status %d\n",
1516 port1, status);
1517 /* paranoia: "should not happen" */
1518 (void) usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
1519 USB_REQ_CLEAR_FEATURE, USB_RECIP_DEVICE,
1520 USB_DEVICE_REMOTE_WAKEUP, 0,
1521 NULL, 0,
1522 USB_CTRL_SET_TIMEOUT);
1523 } else {
1524 /* device has up to 10 msec to fully suspend */
1525 dev_dbg(&udev->dev, "usb suspend\n");
1526 usb_set_device_state(udev, USB_STATE_SUSPENDED);
1527 msleep(10);
1528 }
1529 return status;
1530}
1531
1532/*
1533 * Devices on USB hub ports have only one "suspend" state, corresponding
1534 * to ACPI D2 (PM_SUSPEND_MEM), "may cause the device to lose some context".
1535 * State transitions include:
1536 *
1537 * - suspend, resume ... when the VBUS power link stays live
1538 * - suspend, disconnect ... VBUS lost
1539 *
1540 * Once VBUS drop breaks the circuit, the port it's using has to go through
1541 * normal re-enumeration procedures, starting with enabling VBUS power.
1542 * Other than re-initializing the hub (plug/unplug, except for root hubs),
1543 * Linux (2.6) currently has NO mechanisms to initiate that: no khubd
1544 * timer, no SRP, no requests through sysfs.
1545 */
1546static int __usb_suspend_device (struct usb_device *udev, int port1,
1547 pm_message_t state)
1548{
1549 int status;
1550
1551 /* caller owns the udev device lock */
1552 if (port1 < 0)
1553 return port1;
1554
1555 if (udev->state == USB_STATE_SUSPENDED
1556 || udev->state == USB_STATE_NOTATTACHED) {
1557 return 0;
1558 }
1559
1560 /* suspend interface drivers; if this is a hub, it
1561 * suspends the child devices
1562 */
1563 if (udev->actconfig) {
1564 int i;
1565
1566 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
1567 struct usb_interface *intf;
1568 struct usb_driver *driver;
1569
1570 intf = udev->actconfig->interface[i];
1571 if (state <= intf->dev.power.power_state)
1572 continue;
1573 if (!intf->dev.driver)
1574 continue;
1575 driver = to_usb_driver(intf->dev.driver);
1576
1577 if (driver->suspend) {
1578 status = driver->suspend(intf, state);
1579 if (intf->dev.power.power_state != state
1580 || status)
1581 dev_err(&intf->dev,
1582 "suspend %d fail, code %d\n",
1583 state, status);
1584 }
1585
1586 /* only drivers with suspend() can ever resume();
1587 * and after power loss, even they won't.
1588 * bus_rescan_devices() can rebind drivers later.
1589 *
1590 * FIXME the PM core self-deadlocks when unbinding
1591 * drivers during suspend/resume ... everything grabs
1592 * dpm_sem (not a spinlock, ugh). we want to unbind,
1593 * since we know every driver's probe/disconnect works
1594 * even for drivers that can't suspend.
1595 */
1596 if (!driver->suspend || state > PM_SUSPEND_MEM) {
1597#if 1
1598 dev_warn(&intf->dev, "resume is unsafe!\n");
1599#else
1600 down_write(&usb_bus_type.rwsem);
1601 device_release_driver(&intf->dev);
1602 up_write(&usb_bus_type.rwsem);
1603#endif
1604 }
1605 }
1606 }
1607
1608 /*
1609 * FIXME this needs port power off call paths too, to help force
1610 * USB into the "generic" PM model. At least for devices on
1611 * ports that aren't using ganged switching (usually root hubs).
1612 *
1613 * NOTE: SRP-capable links should adopt more aggressive poweroff
1614 * policies (when HNP doesn't apply) once we have mechanisms to
1615 * turn power back on! (Likely not before 2.7...)
1616 */
1617 if (state > PM_SUSPEND_MEM) {
1618 dev_warn(&udev->dev, "no poweroff yet, suspending instead\n");
1619 }
1620
1621 /* "global suspend" of the HC-to-USB interface (root hub), or
1622 * "selective suspend" of just one hub-device link.
1623 */
1624 if (!udev->parent) {
1625 struct usb_bus *bus = udev->bus;
1626 if (bus && bus->op->hub_suspend) {
1627 status = bus->op->hub_suspend (bus);
1628 if (status == 0) {
1629 dev_dbg(&udev->dev, "usb suspend\n");
1630 usb_set_device_state(udev,
1631 USB_STATE_SUSPENDED);
1632 }
1633 } else
1634 status = -EOPNOTSUPP;
1635 } else
1636 status = hub_port_suspend(hdev_to_hub(udev->parent), port1,
1637 udev);
1638
1639 if (status == 0)
1640 udev->dev.power.power_state = state;
1641 return status;
1642}
1643
1644/**
1645 * usb_suspend_device - suspend a usb device
1646 * @udev: device that's no longer in active use
1647 * @state: PMSG_SUSPEND to suspend
1648 * Context: must be able to sleep; device not locked
1649 *
1650 * Suspends a USB device that isn't in active use, conserving power.
1651 * Devices may wake out of a suspend, if anything important happens,
1652 * using the remote wakeup mechanism. They may also be taken out of
1653 * suspend by the host, using usb_resume_device(). It's also routine
1654 * to disconnect devices while they are suspended.
1655 *
1656 * Suspending OTG devices may trigger HNP, if that's been enabled
1657 * between a pair of dual-role devices. That will change roles, such
1658 * as from A-Host to A-Peripheral or from B-Host back to B-Peripheral.
1659 *
1660 * Returns 0 on success, else negative errno.
1661 */
1662int usb_suspend_device(struct usb_device *udev, pm_message_t state)
1663{
1664 int port1, status;
1665
1666 port1 = locktree(udev);
1667 if (port1 < 0)
1668 return port1;
1669
1670 status = __usb_suspend_device(udev, port1, state);
1671 usb_unlock_device(udev);
1672 return status;
1673}
1674
1675/*
1676 * hardware resume signaling is finished, either because of selective
1677 * resume (by host) or remote wakeup (by device) ... now see what changed
1678 * in the tree that's rooted at this device.
1679 */
1680static int finish_port_resume(struct usb_device *udev)
1681{
1682 int status;
1683 u16 devstatus;
1684
1685 /* caller owns the udev device lock */
1686 dev_dbg(&udev->dev, "usb resume\n");
1687
1688 /* usb ch9 identifies four variants of SUSPENDED, based on what
1689 * state the device resumes to. Linux currently won't see the
1690 * first two on the host side; they'd be inside hub_port_init()
1691 * during many timeouts, but khubd can't suspend until later.
1692 */
1693 usb_set_device_state(udev, udev->actconfig
1694 ? USB_STATE_CONFIGURED
1695 : USB_STATE_ADDRESS);
1696 udev->dev.power.power_state = PMSG_ON;
1697
1698 /* 10.5.4.5 says be sure devices in the tree are still there.
1699 * For now let's assume the device didn't go crazy on resume,
1700 * and device drivers will know about any resume quirks.
1701 */
1702 status = usb_get_status(udev, USB_RECIP_DEVICE, 0, &devstatus);
1703 if (status < 0)
1704 dev_dbg(&udev->dev,
1705 "gone after usb resume? status %d\n",
1706 status);
1707 else if (udev->actconfig) {
1708 unsigned i;
1709
1710 le16_to_cpus(&devstatus);
1711 if (devstatus & (1 << USB_DEVICE_REMOTE_WAKEUP)) {
1712 status = usb_control_msg(udev,
1713 usb_sndctrlpipe(udev, 0),
1714 USB_REQ_CLEAR_FEATURE,
1715 USB_RECIP_DEVICE,
1716 USB_DEVICE_REMOTE_WAKEUP, 0,
1717 NULL, 0,
1718 USB_CTRL_SET_TIMEOUT);
1719 if (status) {
1720 dev_dbg(&udev->dev, "disable remote "
1721 "wakeup, status %d\n", status);
1722 status = 0;
1723 }
1724 }
1725
1726 /* resume interface drivers; if this is a hub, it
1727 * resumes the child devices
1728 */
1729 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
1730 struct usb_interface *intf;
1731 struct usb_driver *driver;
1732
1733 intf = udev->actconfig->interface[i];
1734 if (intf->dev.power.power_state == PM_SUSPEND_ON)
1735 continue;
1736 if (!intf->dev.driver) {
1737 /* FIXME maybe force to alt 0 */
1738 continue;
1739 }
1740 driver = to_usb_driver(intf->dev.driver);
1741
1742 /* bus_rescan_devices() may rebind drivers */
1743 if (!driver->resume)
1744 continue;
1745
1746 /* can we do better than just logging errors? */
1747 status = driver->resume(intf);
1748 if (intf->dev.power.power_state != PM_SUSPEND_ON
1749 || status)
1750 dev_dbg(&intf->dev,
1751 "resume fail, state %d code %d\n",
1752 intf->dev.power.power_state, status);
1753 }
1754 status = 0;
1755
1756 } else if (udev->devnum <= 0) {
1757 dev_dbg(&udev->dev, "bogus resume!\n");
1758 status = -EINVAL;
1759 }
1760 return status;
1761}
1762
1763static int
1764hub_port_resume(struct usb_hub *hub, int port1, struct usb_device *udev)
1765{
1766 int status;
1767
1768 // dev_dbg(hub->intfdev, "resume port %d\n", port1);
1769
1770 /* see 7.1.7.7; affects power usage, but not budgeting */
1771 status = clear_port_feature(hub->hdev,
1772 port1, USB_PORT_FEAT_SUSPEND);
1773 if (status) {
1774 dev_dbg(hub->intfdev,
1775 "can't resume port %d, status %d\n",
1776 port1, status);
1777 } else {
1778 u16 devstatus;
1779 u16 portchange;
1780
1781 /* drive resume for at least 20 msec */
1782 if (udev)
1783 dev_dbg(&udev->dev, "RESUME\n");
1784 msleep(25);
1785
1786#define LIVE_FLAGS ( USB_PORT_STAT_POWER \
1787 | USB_PORT_STAT_ENABLE \
1788 | USB_PORT_STAT_CONNECTION)
1789
1790 /* Virtual root hubs can trigger on GET_PORT_STATUS to
1791 * stop resume signaling. Then finish the resume
1792 * sequence.
1793 */
1794 devstatus = portchange = 0;
1795 status = hub_port_status(hub, port1,
1796 &devstatus, &portchange);
1797 if (status < 0
1798 || (devstatus & LIVE_FLAGS) != LIVE_FLAGS
1799 || (devstatus & USB_PORT_STAT_SUSPEND) != 0
1800 ) {
1801 dev_dbg(hub->intfdev,
1802 "port %d status %04x.%04x after resume, %d\n",
1803 port1, portchange, devstatus, status);
1804 } else {
1805 /* TRSMRCY = 10 msec */
1806 msleep(10);
1807 if (udev)
1808 status = finish_port_resume(udev);
1809 }
1810 }
1811 if (status < 0)
1812 hub_port_logical_disconnect(hub, port1);
1813
1814 return status;
1815}
1816
1817static int hub_resume (struct usb_interface *intf);
1818
1819/**
1820 * usb_resume_device - re-activate a suspended usb device
1821 * @udev: device to re-activate
1822 * Context: must be able to sleep; device not locked
1823 *
1824 * This will re-activate the suspended device, increasing power usage
1825 * while letting drivers communicate again with its endpoints.
1826 * USB resume explicitly guarantees that the power session between
1827 * the host and the device is the same as it was when the device
1828 * suspended.
1829 *
1830 * Returns 0 on success, else negative errno.
1831 */
1832int usb_resume_device(struct usb_device *udev)
1833{
1834 int port1, status;
1835
1836 port1 = locktree(udev);
1837 if (port1 < 0)
1838 return port1;
1839
1840 /* "global resume" of the HC-to-USB interface (root hub), or
1841 * selective resume of one hub-to-device port
1842 */
1843 if (!udev->parent) {
1844 struct usb_bus *bus = udev->bus;
1845 if (bus && bus->op->hub_resume) {
1846 status = bus->op->hub_resume (bus);
1847 } else
1848 status = -EOPNOTSUPP;
1849 if (status == 0) {
1850 dev_dbg(&udev->dev, "usb resume\n");
1851 /* TRSMRCY = 10 msec */
1852 msleep(10);
1853 usb_set_device_state (udev, USB_STATE_CONFIGURED);
1854 udev->dev.power.power_state = PMSG_ON;
1855 status = hub_resume (udev
1856 ->actconfig->interface[0]);
1857 }
1858 } else if (udev->state == USB_STATE_SUSPENDED) {
1859 // NOTE this fails if parent is also suspended...
1860 status = hub_port_resume(hdev_to_hub(udev->parent),
1861 port1, udev);
1862 } else {
1863 status = 0;
1864 }
1865 if (status < 0) {
1866 dev_dbg(&udev->dev, "can't resume, status %d\n",
1867 status);
1868 }
1869
1870 usb_unlock_device(udev);
1871
1872 /* rebind drivers that had no suspend() */
1873 if (status == 0) {
1874 usb_lock_all_devices();
1875 bus_rescan_devices(&usb_bus_type);
1876 usb_unlock_all_devices();
1877 }
1878 return status;
1879}
1880
1881static int remote_wakeup(struct usb_device *udev)
1882{
1883 int status = 0;
1884
1885 /* don't repeat RESUME sequence if this device
1886 * was already woken up by some other task
1887 */
1888 down(&udev->serialize);
1889 if (udev->state == USB_STATE_SUSPENDED) {
1890 dev_dbg(&udev->dev, "RESUME (wakeup)\n");
1891 /* TRSMRCY = 10 msec */
1892 msleep(10);
1893 status = finish_port_resume(udev);
1894 }
1895 up(&udev->serialize);
1896 return status;
1897}
1898
1899static int hub_suspend(struct usb_interface *intf, pm_message_t state)
1900{
1901 struct usb_hub *hub = usb_get_intfdata (intf);
1902 struct usb_device *hdev = hub->hdev;
1903 unsigned port1;
1904 int status;
1905
1906 /* stop khubd and related activity */
1907 hub_quiesce(hub);
1908
1909 /* then suspend every port */
1910 for (port1 = 1; port1 <= hdev->maxchild; port1++) {
1911 struct usb_device *udev;
1912
1913 udev = hdev->children [port1-1];
1914 if (!udev)
1915 continue;
1916 down(&udev->serialize);
1917 status = __usb_suspend_device(udev, port1, state);
1918 up(&udev->serialize);
1919 if (status < 0)
1920 dev_dbg(&intf->dev, "suspend port %d --> %d\n",
1921 port1, status);
1922 }
1923
1924 intf->dev.power.power_state = state;
1925 return 0;
1926}
1927
1928static int hub_resume(struct usb_interface *intf)
1929{
1930 struct usb_device *hdev = interface_to_usbdev(intf);
1931 struct usb_hub *hub = usb_get_intfdata (intf);
1932 unsigned port1;
1933 int status;
1934
1935 if (intf->dev.power.power_state == PM_SUSPEND_ON)
1936 return 0;
1937
1938 for (port1 = 1; port1 <= hdev->maxchild; port1++) {
1939 struct usb_device *udev;
1940 u16 portstat, portchange;
1941
1942 udev = hdev->children [port1-1];
1943 status = hub_port_status(hub, port1, &portstat, &portchange);
1944 if (status == 0) {
1945 if (portchange & USB_PORT_STAT_C_SUSPEND) {
1946 clear_port_feature(hdev, port1,
1947 USB_PORT_FEAT_C_SUSPEND);
1948 portchange &= ~USB_PORT_STAT_C_SUSPEND;
1949 }
1950
1951 /* let khubd handle disconnects etc */
1952 if (portchange)
1953 continue;
1954 }
1955
1956 if (!udev || status < 0)
1957 continue;
1958 down (&udev->serialize);
1959 if (portstat & USB_PORT_STAT_SUSPEND)
1960 status = hub_port_resume(hub, port1, udev);
1961 else {
1962 status = finish_port_resume(udev);
1963 if (status < 0) {
1964 dev_dbg(&intf->dev, "resume port %d --> %d\n",
1965 port1, status);
1966 hub_port_logical_disconnect(hub, port1);
1967 }
1968 }
1969 up(&udev->serialize);
1970 }
1971 intf->dev.power.power_state = PMSG_ON;
1972
1973 hub->resume_root_hub = 0;
1974 hub_activate(hub);
1975 return 0;
1976}
1977
1978void usb_resume_root_hub(struct usb_device *hdev)
1979{
1980 struct usb_hub *hub = hdev_to_hub(hdev);
1981
1982 hub->resume_root_hub = 1;
1983 kick_khubd(hub);
1984}
1985
1986#else /* !CONFIG_USB_SUSPEND */
1987
1988int usb_suspend_device(struct usb_device *udev, pm_message_t state)
1989{
1990 return 0;
1991}
1992
1993int usb_resume_device(struct usb_device *udev)
1994{
1995 return 0;
1996}
1997
1998#define hub_suspend NULL
1999#define hub_resume NULL
2000#define remote_wakeup(x) 0
2001
2002#endif /* CONFIG_USB_SUSPEND */
2003
2004EXPORT_SYMBOL(usb_suspend_device);
2005EXPORT_SYMBOL(usb_resume_device);
2006
2007
2008
2009/* USB 2.0 spec, 7.1.7.3 / fig 7-29:
2010 *
2011 * Between connect detection and reset signaling there must be a delay
2012 * of 100ms at least for debounce and power-settling. The corresponding
2013 * timer shall restart whenever the downstream port detects a disconnect.
2014 *
2015 * Apparently there are some bluetooth and irda-dongles and a number of
2016 * low-speed devices for which this debounce period may last over a second.
2017 * Not covered by the spec - but easy to deal with.
2018 *
2019 * This implementation uses a 1500ms total debounce timeout; if the
2020 * connection isn't stable by then it returns -ETIMEDOUT. It checks
2021 * every 25ms for transient disconnects. When the port status has been
2022 * unchanged for 100ms it returns the port status.
2023 */
2024
2025#define HUB_DEBOUNCE_TIMEOUT 1500
2026#define HUB_DEBOUNCE_STEP 25
2027#define HUB_DEBOUNCE_STABLE 100
2028
2029static int hub_port_debounce(struct usb_hub *hub, int port1)
2030{
2031 int ret;
2032 int total_time, stable_time = 0;
2033 u16 portchange, portstatus;
2034 unsigned connection = 0xffff;
2035
2036 for (total_time = 0; ; total_time += HUB_DEBOUNCE_STEP) {
2037 ret = hub_port_status(hub, port1, &portstatus, &portchange);
2038 if (ret < 0)
2039 return ret;
2040
2041 if (!(portchange & USB_PORT_STAT_C_CONNECTION) &&
2042 (portstatus & USB_PORT_STAT_CONNECTION) == connection) {
2043 stable_time += HUB_DEBOUNCE_STEP;
2044 if (stable_time >= HUB_DEBOUNCE_STABLE)
2045 break;
2046 } else {
2047 stable_time = 0;
2048 connection = portstatus & USB_PORT_STAT_CONNECTION;
2049 }
2050
2051 if (portchange & USB_PORT_STAT_C_CONNECTION) {
2052 clear_port_feature(hub->hdev, port1,
2053 USB_PORT_FEAT_C_CONNECTION);
2054 }
2055
2056 if (total_time >= HUB_DEBOUNCE_TIMEOUT)
2057 break;
2058 msleep(HUB_DEBOUNCE_STEP);
2059 }
2060
2061 dev_dbg (hub->intfdev,
2062 "debounce: port %d: total %dms stable %dms status 0x%x\n",
2063 port1, total_time, stable_time, portstatus);
2064
2065 if (stable_time < HUB_DEBOUNCE_STABLE)
2066 return -ETIMEDOUT;
2067 return portstatus;
2068}
2069
2070static void ep0_reinit(struct usb_device *udev)
2071{
2072 usb_disable_endpoint(udev, 0 + USB_DIR_IN);
2073 usb_disable_endpoint(udev, 0 + USB_DIR_OUT);
2074 udev->ep_in[0] = udev->ep_out[0] = &udev->ep0;
2075}
2076
2077#define usb_sndaddr0pipe() (PIPE_CONTROL << 30)
2078#define usb_rcvaddr0pipe() ((PIPE_CONTROL << 30) | USB_DIR_IN)
2079
2080static int hub_set_address(struct usb_device *udev)
2081{
2082 int retval;
2083
2084 if (udev->devnum == 0)
2085 return -EINVAL;
2086 if (udev->state == USB_STATE_ADDRESS)
2087 return 0;
2088 if (udev->state != USB_STATE_DEFAULT)
2089 return -EINVAL;
2090 retval = usb_control_msg(udev, usb_sndaddr0pipe(),
2091 USB_REQ_SET_ADDRESS, 0, udev->devnum, 0,
2092 NULL, 0, USB_CTRL_SET_TIMEOUT);
2093 if (retval == 0) {
2094 usb_set_device_state(udev, USB_STATE_ADDRESS);
2095 ep0_reinit(udev);
2096 }
2097 return retval;
2098}
2099
2100/* Reset device, (re)assign address, get device descriptor.
2101 * Device connection must be stable, no more debouncing needed.
2102 * Returns device in USB_STATE_ADDRESS, except on error.
2103 *
2104 * If this is called for an already-existing device (as part of
2105 * usb_reset_device), the caller must own the device lock. For a
2106 * newly detected device that is not accessible through any global
2107 * pointers, it's not necessary to lock the device.
2108 */
2109static int
2110hub_port_init (struct usb_hub *hub, struct usb_device *udev, int port1,
2111 int retry_counter)
2112{
2113 static DECLARE_MUTEX(usb_address0_sem);
2114
2115 struct usb_device *hdev = hub->hdev;
2116 int i, j, retval;
2117 unsigned delay = HUB_SHORT_RESET_TIME;
2118 enum usb_device_speed oldspeed = udev->speed;
2119
2120 /* root hub ports have a slightly longer reset period
2121 * (from USB 2.0 spec, section 7.1.7.5)
2122 */
2123 if (!hdev->parent) {
2124 delay = HUB_ROOT_RESET_TIME;
2125 if (port1 == hdev->bus->otg_port)
2126 hdev->bus->b_hnp_enable = 0;
2127 }
2128
2129 /* Some low speed devices have problems with the quick delay, so */
2130 /* be a bit pessimistic with those devices. RHbug #23670 */
2131 if (oldspeed == USB_SPEED_LOW)
2132 delay = HUB_LONG_RESET_TIME;
2133
2134 down(&usb_address0_sem);
2135
2136 /* Reset the device; full speed may morph to high speed */
2137 retval = hub_port_reset(hub, port1, udev, delay);
2138 if (retval < 0) /* error or disconnect */
2139 goto fail;
2140 /* success, speed is known */
2141 retval = -ENODEV;
2142
2143 if (oldspeed != USB_SPEED_UNKNOWN && oldspeed != udev->speed) {
2144 dev_dbg(&udev->dev, "device reset changed speed!\n");
2145 goto fail;
2146 }
2147 oldspeed = udev->speed;
2148
2149 /* USB 2.0 section 5.5.3 talks about ep0 maxpacket ...
2150 * it's fixed size except for full speed devices.
2151 */
2152 switch (udev->speed) {
2153 case USB_SPEED_HIGH: /* fixed at 64 */
2154 udev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(64);
2155 break;
2156 case USB_SPEED_FULL: /* 8, 16, 32, or 64 */
2157 /* to determine the ep0 maxpacket size, try to read
2158 * the device descriptor to get bMaxPacketSize0 and
2159 * then correct our initial guess.
2160 */
2161 udev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(64);
2162 break;
2163 case USB_SPEED_LOW: /* fixed at 8 */
2164 udev->ep0.desc.wMaxPacketSize = __constant_cpu_to_le16(8);
2165 break;
2166 default:
2167 goto fail;
2168 }
2169
2170 dev_info (&udev->dev,
2171 "%s %s speed USB device using %s and address %d\n",
2172 (udev->config) ? "reset" : "new",
2173 ({ char *speed; switch (udev->speed) {
2174 case USB_SPEED_LOW: speed = "low"; break;
2175 case USB_SPEED_FULL: speed = "full"; break;
2176 case USB_SPEED_HIGH: speed = "high"; break;
2177 default: speed = "?"; break;
2178 }; speed;}),
2179 udev->bus->controller->driver->name,
2180 udev->devnum);
2181
2182 /* Set up TT records, if needed */
2183 if (hdev->tt) {
2184 udev->tt = hdev->tt;
2185 udev->ttport = hdev->ttport;
2186 } else if (udev->speed != USB_SPEED_HIGH
2187 && hdev->speed == USB_SPEED_HIGH) {
2188 udev->tt = &hub->tt;
2189 udev->ttport = port1;
2190 }
2191
2192 /* Why interleave GET_DESCRIPTOR and SET_ADDRESS this way?
2193 * Because device hardware and firmware is sometimes buggy in
2194 * this area, and this is how Linux has done it for ages.
2195 * Change it cautiously.
2196 *
2197 * NOTE: If USE_NEW_SCHEME() is true we will start by issuing
2198 * a 64-byte GET_DESCRIPTOR request. This is what Windows does,
2199 * so it may help with some non-standards-compliant devices.
2200 * Otherwise we start with SET_ADDRESS and then try to read the
2201 * first 8 bytes of the device descriptor to get the ep0 maxpacket
2202 * value.
2203 */
2204 for (i = 0; i < GET_DESCRIPTOR_TRIES; (++i, msleep(100))) {
2205 if (USE_NEW_SCHEME(retry_counter)) {
2206 struct usb_device_descriptor *buf;
2207 int r = 0;
2208
2209#define GET_DESCRIPTOR_BUFSIZE 64
2210 buf = kmalloc(GET_DESCRIPTOR_BUFSIZE, GFP_NOIO);
2211 if (!buf) {
2212 retval = -ENOMEM;
2213 continue;
2214 }
2215
2216 /* Use a short timeout the first time through,
2217 * so that recalcitrant full-speed devices with
2218 * 8- or 16-byte ep0-maxpackets won't slow things
2219 * down tremendously by NAKing the unexpectedly
2220 * early status stage. Also, retry on all errors;
2221 * some devices are flakey.
2222 */
2223 for (j = 0; j < 3; ++j) {
2224 buf->bMaxPacketSize0 = 0;
2225 r = usb_control_msg(udev, usb_rcvaddr0pipe(),
2226 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
2227 USB_DT_DEVICE << 8, 0,
2228 buf, GET_DESCRIPTOR_BUFSIZE,
2229 (i ? USB_CTRL_GET_TIMEOUT : 1000));
2230 switch (buf->bMaxPacketSize0) {
2231 case 8: case 16: case 32: case 64:
2232 if (buf->bDescriptorType ==
2233 USB_DT_DEVICE) {
2234 r = 0;
2235 break;
2236 }
2237 /* FALL THROUGH */
2238 default:
2239 if (r == 0)
2240 r = -EPROTO;
2241 break;
2242 }
2243 if (r == 0)
2244 break;
2245 }
2246 udev->descriptor.bMaxPacketSize0 =
2247 buf->bMaxPacketSize0;
2248 kfree(buf);
2249
2250 retval = hub_port_reset(hub, port1, udev, delay);
2251 if (retval < 0) /* error or disconnect */
2252 goto fail;
2253 if (oldspeed != udev->speed) {
2254 dev_dbg(&udev->dev,
2255 "device reset changed speed!\n");
2256 retval = -ENODEV;
2257 goto fail;
2258 }
2259 if (r) {
2260 dev_err(&udev->dev, "device descriptor "
2261 "read/%s, error %d\n",
2262 "64", r);
2263 retval = -EMSGSIZE;
2264 continue;
2265 }
2266#undef GET_DESCRIPTOR_BUFSIZE
2267 }
2268
2269 for (j = 0; j < SET_ADDRESS_TRIES; ++j) {
2270 retval = hub_set_address(udev);
2271 if (retval >= 0)
2272 break;
2273 msleep(200);
2274 }
2275 if (retval < 0) {
2276 dev_err(&udev->dev,
2277 "device not accepting address %d, error %d\n",
2278 udev->devnum, retval);
2279 goto fail;
2280 }
2281
2282 /* cope with hardware quirkiness:
2283 * - let SET_ADDRESS settle, some device hardware wants it
2284 * - read ep0 maxpacket even for high and low speed,
2285 */
2286 msleep(10);
2287 if (USE_NEW_SCHEME(retry_counter))
2288 break;
2289
2290 retval = usb_get_device_descriptor(udev, 8);
2291 if (retval < 8) {
2292 dev_err(&udev->dev, "device descriptor "
2293 "read/%s, error %d\n",
2294 "8", retval);
2295 if (retval >= 0)
2296 retval = -EMSGSIZE;
2297 } else {
2298 retval = 0;
2299 break;
2300 }
2301 }
2302 if (retval)
2303 goto fail;
2304
2305 i = udev->descriptor.bMaxPacketSize0;
2306 if (le16_to_cpu(udev->ep0.desc.wMaxPacketSize) != i) {
2307 if (udev->speed != USB_SPEED_FULL ||
2308 !(i == 8 || i == 16 || i == 32 || i == 64)) {
2309 dev_err(&udev->dev, "ep0 maxpacket = %d\n", i);
2310 retval = -EMSGSIZE;
2311 goto fail;
2312 }
2313 dev_dbg(&udev->dev, "ep0 maxpacket = %d\n", i);
2314 udev->ep0.desc.wMaxPacketSize = cpu_to_le16(i);
2315 ep0_reinit(udev);
2316 }
2317
2318 retval = usb_get_device_descriptor(udev, USB_DT_DEVICE_SIZE);
2319 if (retval < (signed)sizeof(udev->descriptor)) {
2320 dev_err(&udev->dev, "device descriptor read/%s, error %d\n",
2321 "all", retval);
2322 if (retval >= 0)
2323 retval = -ENOMSG;
2324 goto fail;
2325 }
2326
2327 retval = 0;
2328
2329fail:
2330 if (retval)
2331 hub_port_disable(hub, port1, 0);
2332 up(&usb_address0_sem);
2333 return retval;
2334}
2335
2336static void
2337check_highspeed (struct usb_hub *hub, struct usb_device *udev, int port1)
2338{
2339 struct usb_qualifier_descriptor *qual;
2340 int status;
2341
2342 qual = kmalloc (sizeof *qual, SLAB_KERNEL);
2343 if (qual == NULL)
2344 return;
2345
2346 status = usb_get_descriptor (udev, USB_DT_DEVICE_QUALIFIER, 0,
2347 qual, sizeof *qual);
2348 if (status == sizeof *qual) {
2349 dev_info(&udev->dev, "not running at top speed; "
2350 "connect to a high speed hub\n");
2351 /* hub LEDs are probably harder to miss than syslog */
2352 if (hub->has_indicators) {
2353 hub->indicator[port1-1] = INDICATOR_GREEN_BLINK;
2354 schedule_work (&hub->leds);
2355 }
2356 }
2357 kfree (qual);
2358}
2359
2360static unsigned
2361hub_power_remaining (struct usb_hub *hub)
2362{
2363 struct usb_device *hdev = hub->hdev;
2364 int remaining;
2365 unsigned i;
2366
2367 remaining = hub->power_budget;
2368 if (!remaining) /* self-powered */
2369 return 0;
2370
2371 for (i = 0; i < hdev->maxchild; i++) {
2372 struct usb_device *udev = hdev->children[i];
2373 int delta, ceiling;
2374
2375 if (!udev)
2376 continue;
2377
2378 /* 100mA per-port ceiling, or 8mA for OTG ports */
2379 if (i != (udev->bus->otg_port - 1) || hdev->parent)
2380 ceiling = 50;
2381 else
2382 ceiling = 4;
2383
2384 if (udev->actconfig)
2385 delta = udev->actconfig->desc.bMaxPower;
2386 else
2387 delta = ceiling;
2388 // dev_dbg(&udev->dev, "budgeted %dmA\n", 2 * delta);
2389 if (delta > ceiling)
2390 dev_warn(&udev->dev, "%dmA over %dmA budget!\n",
2391 2 * (delta - ceiling), 2 * ceiling);
2392 remaining -= delta;
2393 }
2394 if (remaining < 0) {
2395 dev_warn(hub->intfdev,
2396 "%dmA over power budget!\n",
2397 -2 * remaining);
2398 remaining = 0;
2399 }
2400 return remaining;
2401}
2402
2403/* Handle physical or logical connection change events.
2404 * This routine is called when:
2405 * a port connection-change occurs;
2406 * a port enable-change occurs (often caused by EMI);
2407 * usb_reset_device() encounters changed descriptors (as from
2408 * a firmware download)
2409 * caller already locked the hub
2410 */
2411static void hub_port_connect_change(struct usb_hub *hub, int port1,
2412 u16 portstatus, u16 portchange)
2413{
2414 struct usb_device *hdev = hub->hdev;
2415 struct device *hub_dev = hub->intfdev;
2416 int status, i;
2417
2418 dev_dbg (hub_dev,
2419 "port %d, status %04x, change %04x, %s\n",
2420 port1, portstatus, portchange, portspeed (portstatus));
2421
2422 if (hub->has_indicators) {
2423 set_port_led(hub, port1, HUB_LED_AUTO);
2424 hub->indicator[port1-1] = INDICATOR_AUTO;
2425 }
2426
2427 /* Disconnect any existing devices under this port */
2428 if (hdev->children[port1-1])
2429 usb_disconnect(&hdev->children[port1-1]);
2430 clear_bit(port1, hub->change_bits);
2431
2432#ifdef CONFIG_USB_OTG
2433 /* during HNP, don't repeat the debounce */
2434 if (hdev->bus->is_b_host)
2435 portchange &= ~USB_PORT_STAT_C_CONNECTION;
2436#endif
2437
2438 if (portchange & USB_PORT_STAT_C_CONNECTION) {
2439 status = hub_port_debounce(hub, port1);
2440 if (status < 0) {
2441 dev_err (hub_dev,
2442 "connect-debounce failed, port %d disabled\n",
2443 port1);
2444 goto done;
2445 }
2446 portstatus = status;
2447 }
2448
2449 /* Return now if nothing is connected */
2450 if (!(portstatus & USB_PORT_STAT_CONNECTION)) {
2451
2452 /* maybe switch power back on (e.g. root hub was reset) */
2453 if ((hub->descriptor->wHubCharacteristics
2454 & HUB_CHAR_LPSM) < 2
2455 && !(portstatus & (1 << USB_PORT_FEAT_POWER)))
2456 set_port_feature(hdev, port1, USB_PORT_FEAT_POWER);
2457
2458 if (portstatus & USB_PORT_STAT_ENABLE)
2459 goto done;
2460 return;
2461 }
2462
2463#ifdef CONFIG_USB_SUSPEND
2464 /* If something is connected, but the port is suspended, wake it up. */
2465 if (portstatus & USB_PORT_STAT_SUSPEND) {
2466 status = hub_port_resume(hub, port1, NULL);
2467 if (status < 0) {
2468 dev_dbg(hub_dev,
2469 "can't clear suspend on port %d; %d\n",
2470 port1, status);
2471 goto done;
2472 }
2473 }
2474#endif
2475
2476 for (i = 0; i < SET_CONFIG_TRIES; i++) {
2477 struct usb_device *udev;
2478
2479 /* reallocate for each attempt, since references
2480 * to the previous one can escape in various ways
2481 */
2482 udev = usb_alloc_dev(hdev, hdev->bus, port1);
2483 if (!udev) {
2484 dev_err (hub_dev,
2485 "couldn't allocate port %d usb_device\n",
2486 port1);
2487 goto done;
2488 }
2489
2490 usb_set_device_state(udev, USB_STATE_POWERED);
2491 udev->speed = USB_SPEED_UNKNOWN;
2492
2493 /* set the address */
2494 choose_address(udev);
2495 if (udev->devnum <= 0) {
2496 status = -ENOTCONN; /* Don't retry */
2497 goto loop;
2498 }
2499
2500 /* reset and get descriptor */
2501 status = hub_port_init(hub, udev, port1, i);
2502 if (status < 0)
2503 goto loop;
2504
2505 /* consecutive bus-powered hubs aren't reliable; they can
2506 * violate the voltage drop budget. if the new child has
2507 * a "powered" LED, users should notice we didn't enable it
2508 * (without reading syslog), even without per-port LEDs
2509 * on the parent.
2510 */
2511 if (udev->descriptor.bDeviceClass == USB_CLASS_HUB
2512 && hub->power_budget) {
2513 u16 devstat;
2514
2515 status = usb_get_status(udev, USB_RECIP_DEVICE, 0,
2516 &devstat);
2517 if (status < 0) {
2518 dev_dbg(&udev->dev, "get status %d ?\n", status);
2519 goto loop_disable;
2520 }
2521 cpu_to_le16s(&devstat);
2522 if ((devstat & (1 << USB_DEVICE_SELF_POWERED)) == 0) {
2523 dev_err(&udev->dev,
2524 "can't connect bus-powered hub "
2525 "to this port\n");
2526 if (hub->has_indicators) {
2527 hub->indicator[port1-1] =
2528 INDICATOR_AMBER_BLINK;
2529 schedule_work (&hub->leds);
2530 }
2531 status = -ENOTCONN; /* Don't retry */
2532 goto loop_disable;
2533 }
2534 }
2535
2536 /* check for devices running slower than they could */
2537 if (le16_to_cpu(udev->descriptor.bcdUSB) >= 0x0200
2538 && udev->speed == USB_SPEED_FULL
2539 && highspeed_hubs != 0)
2540 check_highspeed (hub, udev, port1);
2541
2542 /* Store the parent's children[] pointer. At this point
2543 * udev becomes globally accessible, although presumably
2544 * no one will look at it until hdev is unlocked.
2545 */
2546 down (&udev->serialize);
2547 status = 0;
2548
2549 /* We mustn't add new devices if the parent hub has
2550 * been disconnected; we would race with the
2551 * recursively_mark_NOTATTACHED() routine.
2552 */
2553 spin_lock_irq(&device_state_lock);
2554 if (hdev->state == USB_STATE_NOTATTACHED)
2555 status = -ENOTCONN;
2556 else
2557 hdev->children[port1-1] = udev;
2558 spin_unlock_irq(&device_state_lock);
2559
2560 /* Run it through the hoops (find a driver, etc) */
2561 if (!status) {
2562 status = usb_new_device(udev);
2563 if (status) {
2564 spin_lock_irq(&device_state_lock);
2565 hdev->children[port1-1] = NULL;
2566 spin_unlock_irq(&device_state_lock);
2567 }
2568 }
2569
2570 up (&udev->serialize);
2571 if (status)
2572 goto loop_disable;
2573
2574 status = hub_power_remaining(hub);
2575 if (status)
2576 dev_dbg(hub_dev,
2577 "%dmA power budget left\n",
2578 2 * status);
2579
2580 return;
2581
2582loop_disable:
2583 hub_port_disable(hub, port1, 1);
2584loop:
2585 ep0_reinit(udev);
2586 release_address(udev);
2587 usb_put_dev(udev);
2588 if (status == -ENOTCONN)
2589 break;
2590 }
2591
2592done:
2593 hub_port_disable(hub, port1, 1);
2594}
2595
2596static void hub_events(void)
2597{
2598 struct list_head *tmp;
2599 struct usb_device *hdev;
2600 struct usb_interface *intf;
2601 struct usb_hub *hub;
2602 struct device *hub_dev;
2603 u16 hubstatus;
2604 u16 hubchange;
2605 u16 portstatus;
2606 u16 portchange;
2607 int i, ret;
2608 int connect_change;
2609
2610 /*
2611 * We restart the list every time to avoid a deadlock with
2612 * deleting hubs downstream from this one. This should be
2613 * safe since we delete the hub from the event list.
2614 * Not the most efficient, but avoids deadlocks.
2615 */
2616 while (1) {
2617
2618 /* Grab the first entry at the beginning of the list */
2619 spin_lock_irq(&hub_event_lock);
2620 if (list_empty(&hub_event_list)) {
2621 spin_unlock_irq(&hub_event_lock);
2622 break;
2623 }
2624
2625 tmp = hub_event_list.next;
2626 list_del_init(tmp);
2627
2628 hub = list_entry(tmp, struct usb_hub, event_list);
2629 hdev = hub->hdev;
2630 intf = to_usb_interface(hub->intfdev);
2631 hub_dev = &intf->dev;
2632
2633 dev_dbg(hub_dev, "state %d ports %d chg %04x evt %04x\n",
2634 hdev->state, hub->descriptor
2635 ? hub->descriptor->bNbrPorts
2636 : 0,
2637 /* NOTE: expects max 15 ports... */
2638 (u16) hub->change_bits[0],
2639 (u16) hub->event_bits[0]);
2640
2641 usb_get_intf(intf);
2642 i = hub->resume_root_hub;
2643 spin_unlock_irq(&hub_event_lock);
2644
2645 /* Is this is a root hub wanting to be resumed? */
2646 if (i)
2647 usb_resume_device(hdev);
2648
2649 /* Lock the device, then check to see if we were
2650 * disconnected while waiting for the lock to succeed. */
2651 if (locktree(hdev) < 0) {
2652 usb_put_intf(intf);
2653 continue;
2654 }
2655 if (hub != usb_get_intfdata(intf))
2656 goto loop;
2657
2658 /* If the hub has died, clean up after it */
2659 if (hdev->state == USB_STATE_NOTATTACHED) {
2660 hub_pre_reset(hub);
2661 goto loop;
2662 }
2663
2664 /* If this is an inactive or suspended hub, do nothing */
2665 if (hub->quiescing)
2666 goto loop;
2667
2668 if (hub->error) {
2669 dev_dbg (hub_dev, "resetting for error %d\n",
2670 hub->error);
2671
2672 ret = usb_reset_device(hdev);
2673 if (ret) {
2674 dev_dbg (hub_dev,
2675 "error resetting hub: %d\n", ret);
2676 goto loop;
2677 }
2678
2679 hub->nerrors = 0;
2680 hub->error = 0;
2681 }
2682
2683 /* deal with port status changes */
2684 for (i = 1; i <= hub->descriptor->bNbrPorts; i++) {
2685 if (test_bit(i, hub->busy_bits))
2686 continue;
2687 connect_change = test_bit(i, hub->change_bits);
2688 if (!test_and_clear_bit(i, hub->event_bits) &&
2689 !connect_change && !hub->activating)
2690 continue;
2691
2692 ret = hub_port_status(hub, i,
2693 &portstatus, &portchange);
2694 if (ret < 0)
2695 continue;
2696
2697 if (hub->activating && !hdev->children[i-1] &&
2698 (portstatus &
2699 USB_PORT_STAT_CONNECTION))
2700 connect_change = 1;
2701
2702 if (portchange & USB_PORT_STAT_C_CONNECTION) {
2703 clear_port_feature(hdev, i,
2704 USB_PORT_FEAT_C_CONNECTION);
2705 connect_change = 1;
2706 }
2707
2708 if (portchange & USB_PORT_STAT_C_ENABLE) {
2709 if (!connect_change)
2710 dev_dbg (hub_dev,
2711 "port %d enable change, "
2712 "status %08x\n",
2713 i, portstatus);
2714 clear_port_feature(hdev, i,
2715 USB_PORT_FEAT_C_ENABLE);
2716
2717 /*
2718 * EM interference sometimes causes badly
2719 * shielded USB devices to be shutdown by
2720 * the hub, this hack enables them again.
2721 * Works at least with mouse driver.
2722 */
2723 if (!(portstatus & USB_PORT_STAT_ENABLE)
2724 && !connect_change
2725 && hdev->children[i-1]) {
2726 dev_err (hub_dev,
2727 "port %i "
2728 "disabled by hub (EMI?), "
2729 "re-enabling...\n",
2730 i);
2731 connect_change = 1;
2732 }
2733 }
2734
2735 if (portchange & USB_PORT_STAT_C_SUSPEND) {
2736 clear_port_feature(hdev, i,
2737 USB_PORT_FEAT_C_SUSPEND);
2738 if (hdev->children[i-1]) {
2739 ret = remote_wakeup(hdev->
2740 children[i-1]);
2741 if (ret < 0)
2742 connect_change = 1;
2743 } else {
2744 ret = -ENODEV;
2745 hub_port_disable(hub, i, 1);
2746 }
2747 dev_dbg (hub_dev,
2748 "resume on port %d, status %d\n",
2749 i, ret);
2750 }
2751
2752 if (portchange & USB_PORT_STAT_C_OVERCURRENT) {
2753 dev_err (hub_dev,
2754 "over-current change on port %d\n",
2755 i);
2756 clear_port_feature(hdev, i,
2757 USB_PORT_FEAT_C_OVER_CURRENT);
2758 hub_power_on(hub);
2759 }
2760
2761 if (portchange & USB_PORT_STAT_C_RESET) {
2762 dev_dbg (hub_dev,
2763 "reset change on port %d\n",
2764 i);
2765 clear_port_feature(hdev, i,
2766 USB_PORT_FEAT_C_RESET);
2767 }
2768
2769 if (connect_change)
2770 hub_port_connect_change(hub, i,
2771 portstatus, portchange);
2772 } /* end for i */
2773
2774 /* deal with hub status changes */
2775 if (test_and_clear_bit(0, hub->event_bits) == 0)
2776 ; /* do nothing */
2777 else if (hub_hub_status(hub, &hubstatus, &hubchange) < 0)
2778 dev_err (hub_dev, "get_hub_status failed\n");
2779 else {
2780 if (hubchange & HUB_CHANGE_LOCAL_POWER) {
2781 dev_dbg (hub_dev, "power change\n");
2782 clear_hub_feature(hdev, C_HUB_LOCAL_POWER);
2783 }
2784 if (hubchange & HUB_CHANGE_OVERCURRENT) {
2785 dev_dbg (hub_dev, "overcurrent change\n");
2786 msleep(500); /* Cool down */
2787 clear_hub_feature(hdev, C_HUB_OVER_CURRENT);
2788 hub_power_on(hub);
2789 }
2790 }
2791
2792 hub->activating = 0;
2793
2794loop:
2795 usb_unlock_device(hdev);
2796 usb_put_intf(intf);
2797
2798 } /* end while (1) */
2799}
2800
2801static int hub_thread(void *__unused)
2802{
2803 /*
2804 * This thread doesn't need any user-level access,
2805 * so get rid of all our resources
2806 */
2807
2808 daemonize("khubd");
2809 allow_signal(SIGKILL);
2810
2811 /* Send me a signal to get me die (for debugging) */
2812 do {
2813 hub_events();
2814 wait_event_interruptible(khubd_wait, !list_empty(&hub_event_list));
2815 try_to_freeze(PF_FREEZE);
2816 } while (!signal_pending(current));
2817
2818 pr_debug ("%s: khubd exiting\n", usbcore_name);
2819 complete_and_exit(&khubd_exited, 0);
2820}
2821
2822static struct usb_device_id hub_id_table [] = {
2823 { .match_flags = USB_DEVICE_ID_MATCH_DEV_CLASS,
2824 .bDeviceClass = USB_CLASS_HUB},
2825 { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS,
2826 .bInterfaceClass = USB_CLASS_HUB},
2827 { } /* Terminating entry */
2828};
2829
2830MODULE_DEVICE_TABLE (usb, hub_id_table);
2831
2832static struct usb_driver hub_driver = {
2833 .owner = THIS_MODULE,
2834 .name = "hub",
2835 .probe = hub_probe,
2836 .disconnect = hub_disconnect,
2837 .suspend = hub_suspend,
2838 .resume = hub_resume,
2839 .ioctl = hub_ioctl,
2840 .id_table = hub_id_table,
2841};
2842
2843int usb_hub_init(void)
2844{
2845 pid_t pid;
2846
2847 if (usb_register(&hub_driver) < 0) {
2848 printk(KERN_ERR "%s: can't register hub driver\n",
2849 usbcore_name);
2850 return -1;
2851 }
2852
2853 pid = kernel_thread(hub_thread, NULL, CLONE_KERNEL);
2854 if (pid >= 0) {
2855 khubd_pid = pid;
2856
2857 return 0;
2858 }
2859
2860 /* Fall through if kernel_thread failed */
2861 usb_deregister(&hub_driver);
2862 printk(KERN_ERR "%s: can't start khubd\n", usbcore_name);
2863
2864 return -1;
2865}
2866
2867void usb_hub_cleanup(void)
2868{
2869 int ret;
2870
2871 /* Kill the thread */
2872 ret = kill_proc(khubd_pid, SIGKILL, 1);
2873
2874 wait_for_completion(&khubd_exited);
2875
2876 /*
2877 * Hub resources are freed for us by usb_deregister. It calls
2878 * usb_driver_purge on every device which in turn calls that
2879 * devices disconnect function if it is using this driver.
2880 * The hub_disconnect function takes care of releasing the
2881 * individual hub resources. -greg
2882 */
2883 usb_deregister(&hub_driver);
2884} /* usb_hub_cleanup() */
2885
2886
2887static int config_descriptors_changed(struct usb_device *udev)
2888{
2889 unsigned index;
2890 unsigned len = 0;
2891 struct usb_config_descriptor *buf;
2892
2893 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
2894 if (len < le16_to_cpu(udev->config[index].desc.wTotalLength))
2895 len = le16_to_cpu(udev->config[index].desc.wTotalLength);
2896 }
2897 buf = kmalloc (len, SLAB_KERNEL);
2898 if (buf == NULL) {
2899 dev_err(&udev->dev, "no mem to re-read configs after reset\n");
2900 /* assume the worst */
2901 return 1;
2902 }
2903 for (index = 0; index < udev->descriptor.bNumConfigurations; index++) {
2904 int length;
2905 int old_length = le16_to_cpu(udev->config[index].desc.wTotalLength);
2906
2907 length = usb_get_descriptor(udev, USB_DT_CONFIG, index, buf,
2908 old_length);
2909 if (length < old_length) {
2910 dev_dbg(&udev->dev, "config index %d, error %d\n",
2911 index, length);
2912 break;
2913 }
2914 if (memcmp (buf, udev->rawdescriptors[index], old_length)
2915 != 0) {
2916 dev_dbg(&udev->dev, "config index %d changed (#%d)\n",
2917 index, buf->bConfigurationValue);
2918 break;
2919 }
2920 }
2921 kfree(buf);
2922 return index != udev->descriptor.bNumConfigurations;
2923}
2924
2925/**
2926 * usb_reset_device - perform a USB port reset to reinitialize a device
2927 * @udev: device to reset (not in SUSPENDED or NOTATTACHED state)
2928 *
2929 * WARNING - don't reset any device unless drivers for all of its
2930 * interfaces are expecting that reset! Maybe some driver->reset()
2931 * method should eventually help ensure sufficient cooperation.
2932 *
2933 * Do a port reset, reassign the device's address, and establish its
2934 * former operating configuration. If the reset fails, or the device's
2935 * descriptors change from their values before the reset, or the original
2936 * configuration and altsettings cannot be restored, a flag will be set
2937 * telling khubd to pretend the device has been disconnected and then
2938 * re-connected. All drivers will be unbound, and the device will be
2939 * re-enumerated and probed all over again.
2940 *
2941 * Returns 0 if the reset succeeded, -ENODEV if the device has been
2942 * flagged for logical disconnection, or some other negative error code
2943 * if the reset wasn't even attempted.
2944 *
2945 * The caller must own the device lock. For example, it's safe to use
2946 * this from a driver probe() routine after downloading new firmware.
2947 * For calls that might not occur during probe(), drivers should lock
2948 * the device using usb_lock_device_for_reset().
2949 */
2950int usb_reset_device(struct usb_device *udev)
2951{
2952 struct usb_device *parent_hdev = udev->parent;
2953 struct usb_hub *parent_hub;
2954 struct usb_device_descriptor descriptor = udev->descriptor;
2955 struct usb_hub *hub = NULL;
2956 int i, ret = 0, port1 = -1;
2957
2958 if (udev->state == USB_STATE_NOTATTACHED ||
2959 udev->state == USB_STATE_SUSPENDED) {
2960 dev_dbg(&udev->dev, "device reset not allowed in state %d\n",
2961 udev->state);
2962 return -EINVAL;
2963 }
2964
2965 if (!parent_hdev) {
2966 /* this requires hcd-specific logic; see OHCI hc_restart() */
2967 dev_dbg(&udev->dev, "%s for root hub!\n", __FUNCTION__);
2968 return -EISDIR;
2969 }
2970
2971 for (i = 0; i < parent_hdev->maxchild; i++)
2972 if (parent_hdev->children[i] == udev) {
2973 port1 = i + 1;
2974 break;
2975 }
2976
2977 if (port1 < 0) {
2978 /* If this ever happens, it's very bad */
2979 dev_err(&udev->dev, "Can't locate device's port!\n");
2980 return -ENOENT;
2981 }
2982 parent_hub = hdev_to_hub(parent_hdev);
2983
2984 /* If we're resetting an active hub, take some special actions */
2985 if (udev->actconfig &&
2986 udev->actconfig->interface[0]->dev.driver ==
2987 &hub_driver.driver &&
2988 (hub = hdev_to_hub(udev)) != NULL) {
2989 hub_pre_reset(hub);
2990 }
2991
2992 set_bit(port1, parent_hub->busy_bits);
2993 for (i = 0; i < SET_CONFIG_TRIES; ++i) {
2994
2995 /* ep0 maxpacket size may change; let the HCD know about it.
2996 * Other endpoints will be handled by re-enumeration. */
2997 ep0_reinit(udev);
2998 ret = hub_port_init(parent_hub, udev, port1, i);
2999 if (ret >= 0)
3000 break;
3001 }
3002 clear_bit(port1, parent_hub->busy_bits);
3003 if (ret < 0)
3004 goto re_enumerate;
3005
3006 /* Device might have changed firmware (DFU or similar) */
3007 if (memcmp(&udev->descriptor, &descriptor, sizeof descriptor)
3008 || config_descriptors_changed (udev)) {
3009 dev_info(&udev->dev, "device firmware changed\n");
3010 udev->descriptor = descriptor; /* for disconnect() calls */
3011 goto re_enumerate;
3012 }
3013
3014 if (!udev->actconfig)
3015 goto done;
3016
3017 ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
3018 USB_REQ_SET_CONFIGURATION, 0,
3019 udev->actconfig->desc.bConfigurationValue, 0,
3020 NULL, 0, USB_CTRL_SET_TIMEOUT);
3021 if (ret < 0) {
3022 dev_err(&udev->dev,
3023 "can't restore configuration #%d (error=%d)\n",
3024 udev->actconfig->desc.bConfigurationValue, ret);
3025 goto re_enumerate;
3026 }
3027 usb_set_device_state(udev, USB_STATE_CONFIGURED);
3028
3029 for (i = 0; i < udev->actconfig->desc.bNumInterfaces; i++) {
3030 struct usb_interface *intf = udev->actconfig->interface[i];
3031 struct usb_interface_descriptor *desc;
3032
3033 /* set_interface resets host side toggle even
3034 * for altsetting zero. the interface may have no driver.
3035 */
3036 desc = &intf->cur_altsetting->desc;
3037 ret = usb_set_interface(udev, desc->bInterfaceNumber,
3038 desc->bAlternateSetting);
3039 if (ret < 0) {
3040 dev_err(&udev->dev, "failed to restore interface %d "
3041 "altsetting %d (error=%d)\n",
3042 desc->bInterfaceNumber,
3043 desc->bAlternateSetting,
3044 ret);
3045 goto re_enumerate;
3046 }
3047 }
3048
3049done:
3050 if (hub)
3051 hub_post_reset(hub);
3052 return 0;
3053
3054re_enumerate:
3055 hub_port_logical_disconnect(parent_hub, port1);
3056 return -ENODEV;
3057}
diff --git a/drivers/usb/core/hub.h b/drivers/usb/core/hub.h
new file mode 100644
index 000000000000..d114b847d56f
--- /dev/null
+++ b/drivers/usb/core/hub.h
@@ -0,0 +1,238 @@
1#ifndef __LINUX_HUB_H
2#define __LINUX_HUB_H
3
4/*
5 * Hub protocol and driver data structures.
6 *
7 * Some of these are known to the "virtual root hub" code
8 * in host controller drivers.
9 */
10
11#include <linux/list.h>
12#include <linux/workqueue.h>
13#include <linux/compiler.h> /* likely()/unlikely() */
14
15/*
16 * Hub request types
17 */
18
19#define USB_RT_HUB (USB_TYPE_CLASS | USB_RECIP_DEVICE)
20#define USB_RT_PORT (USB_TYPE_CLASS | USB_RECIP_OTHER)
21
22/*
23 * Hub class requests
24 * See USB 2.0 spec Table 11-16
25 */
26#define HUB_CLEAR_TT_BUFFER 8
27#define HUB_RESET_TT 9
28#define HUB_GET_TT_STATE 10
29#define HUB_STOP_TT 11
30
31/*
32 * Hub Class feature numbers
33 * See USB 2.0 spec Table 11-17
34 */
35#define C_HUB_LOCAL_POWER 0
36#define C_HUB_OVER_CURRENT 1
37
38/*
39 * Port feature numbers
40 * See USB 2.0 spec Table 11-17
41 */
42#define USB_PORT_FEAT_CONNECTION 0
43#define USB_PORT_FEAT_ENABLE 1
44#define USB_PORT_FEAT_SUSPEND 2
45#define USB_PORT_FEAT_OVER_CURRENT 3
46#define USB_PORT_FEAT_RESET 4
47#define USB_PORT_FEAT_POWER 8
48#define USB_PORT_FEAT_LOWSPEED 9
49#define USB_PORT_FEAT_HIGHSPEED 10
50#define USB_PORT_FEAT_C_CONNECTION 16
51#define USB_PORT_FEAT_C_ENABLE 17
52#define USB_PORT_FEAT_C_SUSPEND 18
53#define USB_PORT_FEAT_C_OVER_CURRENT 19
54#define USB_PORT_FEAT_C_RESET 20
55#define USB_PORT_FEAT_TEST 21
56#define USB_PORT_FEAT_INDICATOR 22
57
58/*
59 * Hub Status and Hub Change results
60 * See USB 2.0 spec Table 11-19 and Table 11-20
61 */
62struct usb_port_status {
63 __le16 wPortStatus;
64 __le16 wPortChange;
65} __attribute__ ((packed));
66
67/*
68 * wPortStatus bit field
69 * See USB 2.0 spec Table 11-21
70 */
71#define USB_PORT_STAT_CONNECTION 0x0001
72#define USB_PORT_STAT_ENABLE 0x0002
73#define USB_PORT_STAT_SUSPEND 0x0004
74#define USB_PORT_STAT_OVERCURRENT 0x0008
75#define USB_PORT_STAT_RESET 0x0010
76/* bits 5 to 7 are reserved */
77#define USB_PORT_STAT_POWER 0x0100
78#define USB_PORT_STAT_LOW_SPEED 0x0200
79#define USB_PORT_STAT_HIGH_SPEED 0x0400
80#define USB_PORT_STAT_TEST 0x0800
81#define USB_PORT_STAT_INDICATOR 0x1000
82/* bits 13 to 15 are reserved */
83
84/*
85 * wPortChange bit field
86 * See USB 2.0 spec Table 11-22
87 * Bits 0 to 4 shown, bits 5 to 15 are reserved
88 */
89#define USB_PORT_STAT_C_CONNECTION 0x0001
90#define USB_PORT_STAT_C_ENABLE 0x0002
91#define USB_PORT_STAT_C_SUSPEND 0x0004
92#define USB_PORT_STAT_C_OVERCURRENT 0x0008
93#define USB_PORT_STAT_C_RESET 0x0010
94
95/*
96 * wHubCharacteristics (masks)
97 * See USB 2.0 spec Table 11-13, offset 3
98 */
99#define HUB_CHAR_LPSM 0x0003 /* D1 .. D0 */
100#define HUB_CHAR_COMPOUND 0x0004 /* D2 */
101#define HUB_CHAR_OCPM 0x0018 /* D4 .. D3 */
102#define HUB_CHAR_TTTT 0x0060 /* D6 .. D5 */
103#define HUB_CHAR_PORTIND 0x0080 /* D7 */
104
105struct usb_hub_status {
106 __le16 wHubStatus;
107 __le16 wHubChange;
108} __attribute__ ((packed));
109
110/*
111 * Hub Status & Hub Change bit masks
112 * See USB 2.0 spec Table 11-19 and Table 11-20
113 * Bits 0 and 1 for wHubStatus and wHubChange
114 * Bits 2 to 15 are reserved for both
115 */
116#define HUB_STATUS_LOCAL_POWER 0x0001
117#define HUB_STATUS_OVERCURRENT 0x0002
118#define HUB_CHANGE_LOCAL_POWER 0x0001
119#define HUB_CHANGE_OVERCURRENT 0x0002
120
121
122/*
123 * Hub descriptor
124 * See USB 2.0 spec Table 11-13
125 */
126
127#define USB_DT_HUB (USB_TYPE_CLASS | 0x09)
128#define USB_DT_HUB_NONVAR_SIZE 7
129
130struct usb_hub_descriptor {
131 __u8 bDescLength;
132 __u8 bDescriptorType;
133 __u8 bNbrPorts;
134 __u16 wHubCharacteristics;
135 __u8 bPwrOn2PwrGood;
136 __u8 bHubContrCurrent;
137 /* add 1 bit for hub status change; round to bytes */
138 __u8 DeviceRemovable[(USB_MAXCHILDREN + 1 + 7) / 8];
139 __u8 PortPwrCtrlMask[(USB_MAXCHILDREN + 1 + 7) / 8];
140} __attribute__ ((packed));
141
142
143/* port indicator status selectors, tables 11-7 and 11-25 */
144#define HUB_LED_AUTO 0
145#define HUB_LED_AMBER 1
146#define HUB_LED_GREEN 2
147#define HUB_LED_OFF 3
148
149enum hub_led_mode {
150 INDICATOR_AUTO = 0,
151 INDICATOR_CYCLE,
152 /* software blinks for attention: software, hardware, reserved */
153 INDICATOR_GREEN_BLINK, INDICATOR_GREEN_BLINK_OFF,
154 INDICATOR_AMBER_BLINK, INDICATOR_AMBER_BLINK_OFF,
155 INDICATOR_ALT_BLINK, INDICATOR_ALT_BLINK_OFF
156} __attribute__ ((packed));
157
158struct usb_device;
159
160/*
161 * As of USB 2.0, full/low speed devices are segregated into trees.
162 * One type grows from USB 1.1 host controllers (OHCI, UHCI etc).
163 * The other type grows from high speed hubs when they connect to
164 * full/low speed devices using "Transaction Translators" (TTs).
165 *
166 * TTs should only be known to the hub driver, and high speed bus
167 * drivers (only EHCI for now). They affect periodic scheduling and
168 * sometimes control/bulk error recovery.
169 */
170struct usb_tt {
171 struct usb_device *hub; /* upstream highspeed hub */
172 int multi; /* true means one TT per port */
173
174 /* for control/bulk error recovery (CLEAR_TT_BUFFER) */
175 spinlock_t lock;
176 struct list_head clear_list; /* of usb_tt_clear */
177 struct work_struct kevent;
178};
179
180struct usb_tt_clear {
181 struct list_head clear_list;
182 unsigned tt;
183 u16 devinfo;
184};
185
186extern void usb_hub_tt_clear_buffer (struct usb_device *dev, int pipe);
187
188struct usb_hub {
189 struct device *intfdev; /* the "interface" device */
190 struct usb_device *hdev;
191 struct urb *urb; /* for interrupt polling pipe */
192
193 /* buffer for urb ... with extra space in case of babble */
194 char (*buffer)[8];
195 dma_addr_t buffer_dma; /* DMA address for buffer */
196 union {
197 struct usb_hub_status hub;
198 struct usb_port_status port;
199 } *status; /* buffer for status reports */
200
201 int error; /* last reported error */
202 int nerrors; /* track consecutive errors */
203
204 struct list_head event_list; /* hubs w/data or errs ready */
205 unsigned long event_bits[1]; /* status change bitmask */
206 unsigned long change_bits[1]; /* ports with logical connect
207 status change */
208 unsigned long busy_bits[1]; /* ports being reset */
209#if USB_MAXCHILDREN > 31 /* 8*sizeof(unsigned long) - 1 */
210#error event_bits[] is too short!
211#endif
212
213 struct usb_hub_descriptor *descriptor; /* class descriptor */
214 struct usb_tt tt; /* Transaction Translator */
215
216 u8 power_budget; /* in 2mA units; or zero */
217
218 unsigned quiescing:1;
219 unsigned activating:1;
220 unsigned resume_root_hub:1;
221
222 unsigned has_indicators:1;
223 enum hub_led_mode indicator[USB_MAXCHILDREN];
224 struct work_struct leds;
225};
226
227/* use this for low-powered root hubs */
228static inline void
229hub_set_power_budget (struct usb_device *hubdev, unsigned mA)
230{
231 struct usb_hub *hub;
232
233 hub = (struct usb_hub *)
234 usb_get_intfdata (hubdev->actconfig->interface[0]);
235 hub->power_budget = min(mA,(unsigned)500)/2;
236}
237
238#endif /* __LINUX_HUB_H */
diff --git a/drivers/usb/core/inode.c b/drivers/usb/core/inode.c
new file mode 100644
index 000000000000..d913407bcdc1
--- /dev/null
+++ b/drivers/usb/core/inode.c
@@ -0,0 +1,764 @@
1/*****************************************************************************/
2
3/*
4 * inode.c -- Inode/Dentry functions for the USB device file system.
5 *
6 * Copyright (C) 2000 Thomas Sailer (sailer@ife.ee.ethz.ch)
7 * Copyright (C) 2001,2002,2004 Greg Kroah-Hartman (greg@kroah.com)
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 *
23 * History:
24 * 0.1 04.01.2000 Created
25 * 0.2 10.12.2001 converted to use the vfs layer better
26 */
27
28/*****************************************************************************/
29
30#include <linux/config.h>
31#include <linux/module.h>
32#include <linux/fs.h>
33#include <linux/mount.h>
34#include <linux/pagemap.h>
35#include <linux/init.h>
36#include <linux/proc_fs.h>
37#include <linux/usb.h>
38#include <linux/namei.h>
39#include <linux/usbdevice_fs.h>
40#include <linux/smp_lock.h>
41#include <linux/parser.h>
42#include <asm/byteorder.h>
43#include "usb.h"
44
45static struct super_operations usbfs_ops;
46static struct file_operations default_file_operations;
47static struct inode_operations usbfs_dir_inode_operations;
48static struct vfsmount *usbfs_mount;
49static int usbfs_mount_count; /* = 0 */
50static int ignore_mount = 0;
51
52static struct dentry *devices_usbfs_dentry;
53static int num_buses; /* = 0 */
54
55static uid_t devuid; /* = 0 */
56static uid_t busuid; /* = 0 */
57static uid_t listuid; /* = 0 */
58static gid_t devgid; /* = 0 */
59static gid_t busgid; /* = 0 */
60static gid_t listgid; /* = 0 */
61static umode_t devmode = S_IWUSR | S_IRUGO;
62static umode_t busmode = S_IXUGO | S_IRUGO;
63static umode_t listmode = S_IRUGO;
64
65enum {
66 Opt_devuid, Opt_devgid, Opt_devmode,
67 Opt_busuid, Opt_busgid, Opt_busmode,
68 Opt_listuid, Opt_listgid, Opt_listmode,
69 Opt_err,
70};
71
72static match_table_t tokens = {
73 {Opt_devuid, "devuid=%u"},
74 {Opt_devgid, "devgid=%u"},
75 {Opt_devmode, "devmode=%o"},
76 {Opt_busuid, "busuid=%u"},
77 {Opt_busgid, "busgid=%u"},
78 {Opt_busmode, "busmode=%o"},
79 {Opt_listuid, "listuid=%u"},
80 {Opt_listgid, "listgid=%u"},
81 {Opt_listmode, "listmode=%o"},
82 {Opt_err, NULL}
83};
84
85static int parse_options(struct super_block *s, char *data)
86{
87 char *p;
88 int option;
89
90 /* (re)set to defaults. */
91 devuid = 0;
92 busuid = 0;
93 listuid = 0;
94 devgid = 0;
95 busgid = 0;
96 listgid = 0;
97 devmode = S_IWUSR | S_IRUGO;
98 busmode = S_IXUGO | S_IRUGO;
99 listmode = S_IRUGO;
100
101 while ((p = strsep(&data, ",")) != NULL) {
102 substring_t args[MAX_OPT_ARGS];
103 int token;
104 if (!*p)
105 continue;
106
107 token = match_token(p, tokens, args);
108 switch (token) {
109 case Opt_devuid:
110 if (match_int(&args[0], &option))
111 return -EINVAL;
112 devuid = option;
113 break;
114 case Opt_devgid:
115 if (match_int(&args[0], &option))
116 return -EINVAL;
117 devgid = option;
118 break;
119 case Opt_devmode:
120 if (match_octal(&args[0], &option))
121 return -EINVAL;
122 devmode = option & S_IRWXUGO;
123 break;
124 case Opt_busuid:
125 if (match_int(&args[0], &option))
126 return -EINVAL;
127 busuid = option;
128 break;
129 case Opt_busgid:
130 if (match_int(&args[0], &option))
131 return -EINVAL;
132 busgid = option;
133 break;
134 case Opt_busmode:
135 if (match_octal(&args[0], &option))
136 return -EINVAL;
137 busmode = option & S_IRWXUGO;
138 break;
139 case Opt_listuid:
140 if (match_int(&args[0], &option))
141 return -EINVAL;
142 listuid = option;
143 break;
144 case Opt_listgid:
145 if (match_int(&args[0], &option))
146 return -EINVAL;
147 listgid = option;
148 break;
149 case Opt_listmode:
150 if (match_octal(&args[0], &option))
151 return -EINVAL;
152 listmode = option & S_IRWXUGO;
153 break;
154 default:
155 err("usbfs: unrecognised mount option \"%s\" "
156 "or missing value\n", p);
157 return -EINVAL;
158 }
159 }
160
161 return 0;
162}
163
164static void update_special(struct dentry *special)
165{
166 special->d_inode->i_uid = listuid;
167 special->d_inode->i_gid = listgid;
168 special->d_inode->i_mode = S_IFREG | listmode;
169}
170
171static void update_dev(struct dentry *dev)
172{
173 dev->d_inode->i_uid = devuid;
174 dev->d_inode->i_gid = devgid;
175 dev->d_inode->i_mode = S_IFREG | devmode;
176}
177
178static void update_bus(struct dentry *bus)
179{
180 struct dentry *dev = NULL;
181
182 bus->d_inode->i_uid = busuid;
183 bus->d_inode->i_gid = busgid;
184 bus->d_inode->i_mode = S_IFDIR | busmode;
185
186 down(&bus->d_inode->i_sem);
187
188 list_for_each_entry(dev, &bus->d_subdirs, d_child)
189 if (dev->d_inode)
190 update_dev(dev);
191
192 up(&bus->d_inode->i_sem);
193}
194
195static void update_sb(struct super_block *sb)
196{
197 struct dentry *root = sb->s_root;
198 struct dentry *bus = NULL;
199
200 if (!root)
201 return;
202
203 down(&root->d_inode->i_sem);
204
205 list_for_each_entry(bus, &root->d_subdirs, d_child) {
206 if (bus->d_inode) {
207 switch (S_IFMT & bus->d_inode->i_mode) {
208 case S_IFDIR:
209 update_bus(bus);
210 break;
211 case S_IFREG:
212 update_special(bus);
213 break;
214 default:
215 warn("Unknown node %s mode %x found on remount!\n",bus->d_name.name,bus->d_inode->i_mode);
216 break;
217 }
218 }
219 }
220
221 up(&root->d_inode->i_sem);
222}
223
224static int remount(struct super_block *sb, int *flags, char *data)
225{
226 /* If this is not a real mount,
227 * i.e. it's a simple_pin_fs from create_special_files,
228 * then ignore it.
229 */
230 if (ignore_mount)
231 return 0;
232
233 if (parse_options(sb, data)) {
234 warn("usbfs: mount parameter error:");
235 return -EINVAL;
236 }
237
238 if (usbfs_mount && usbfs_mount->mnt_sb)
239 update_sb(usbfs_mount->mnt_sb);
240
241 return 0;
242}
243
244static struct inode *usbfs_get_inode (struct super_block *sb, int mode, dev_t dev)
245{
246 struct inode *inode = new_inode(sb);
247
248 if (inode) {
249 inode->i_mode = mode;
250 inode->i_uid = current->fsuid;
251 inode->i_gid = current->fsgid;
252 inode->i_blksize = PAGE_CACHE_SIZE;
253 inode->i_blocks = 0;
254 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
255 switch (mode & S_IFMT) {
256 default:
257 init_special_inode(inode, mode, dev);
258 break;
259 case S_IFREG:
260 inode->i_fop = &default_file_operations;
261 break;
262 case S_IFDIR:
263 inode->i_op = &usbfs_dir_inode_operations;
264 inode->i_fop = &simple_dir_operations;
265
266 /* directory inodes start off with i_nlink == 2 (for "." entry) */
267 inode->i_nlink++;
268 break;
269 }
270 }
271 return inode;
272}
273
274/* SMP-safe */
275static int usbfs_mknod (struct inode *dir, struct dentry *dentry, int mode,
276 dev_t dev)
277{
278 struct inode *inode = usbfs_get_inode(dir->i_sb, mode, dev);
279 int error = -EPERM;
280
281 if (dentry->d_inode)
282 return -EEXIST;
283
284 if (inode) {
285 d_instantiate(dentry, inode);
286 dget(dentry);
287 error = 0;
288 }
289 return error;
290}
291
292static int usbfs_mkdir (struct inode *dir, struct dentry *dentry, int mode)
293{
294 int res;
295
296 mode = (mode & (S_IRWXUGO | S_ISVTX)) | S_IFDIR;
297 res = usbfs_mknod (dir, dentry, mode, 0);
298 if (!res)
299 dir->i_nlink++;
300 return res;
301}
302
303static int usbfs_create (struct inode *dir, struct dentry *dentry, int mode)
304{
305 mode = (mode & S_IALLUGO) | S_IFREG;
306 return usbfs_mknod (dir, dentry, mode, 0);
307}
308
309static inline int usbfs_positive (struct dentry *dentry)
310{
311 return dentry->d_inode && !d_unhashed(dentry);
312}
313
314static int usbfs_empty (struct dentry *dentry)
315{
316 struct list_head *list;
317
318 spin_lock(&dcache_lock);
319
320 list_for_each(list, &dentry->d_subdirs) {
321 struct dentry *de = list_entry(list, struct dentry, d_child);
322 if (usbfs_positive(de)) {
323 spin_unlock(&dcache_lock);
324 return 0;
325 }
326 }
327
328 spin_unlock(&dcache_lock);
329 return 1;
330}
331
332static int usbfs_unlink (struct inode *dir, struct dentry *dentry)
333{
334 struct inode *inode = dentry->d_inode;
335 down(&inode->i_sem);
336 dentry->d_inode->i_nlink--;
337 dput(dentry);
338 up(&inode->i_sem);
339 d_delete(dentry);
340 return 0;
341}
342
343static int usbfs_rmdir(struct inode *dir, struct dentry *dentry)
344{
345 int error = -ENOTEMPTY;
346 struct inode * inode = dentry->d_inode;
347
348 down(&inode->i_sem);
349 dentry_unhash(dentry);
350 if (usbfs_empty(dentry)) {
351 dentry->d_inode->i_nlink -= 2;
352 dput(dentry);
353 inode->i_flags |= S_DEAD;
354 dir->i_nlink--;
355 error = 0;
356 }
357 up(&inode->i_sem);
358 if (!error)
359 d_delete(dentry);
360 dput(dentry);
361 return error;
362}
363
364
365/* default file operations */
366static ssize_t default_read_file (struct file *file, char __user *buf,
367 size_t count, loff_t *ppos)
368{
369 return 0;
370}
371
372static ssize_t default_write_file (struct file *file, const char __user *buf,
373 size_t count, loff_t *ppos)
374{
375 return count;
376}
377
378static loff_t default_file_lseek (struct file *file, loff_t offset, int orig)
379{
380 loff_t retval = -EINVAL;
381
382 down(&file->f_dentry->d_inode->i_sem);
383 switch(orig) {
384 case 0:
385 if (offset > 0) {
386 file->f_pos = offset;
387 retval = file->f_pos;
388 }
389 break;
390 case 1:
391 if ((offset + file->f_pos) > 0) {
392 file->f_pos += offset;
393 retval = file->f_pos;
394 }
395 break;
396 default:
397 break;
398 }
399 up(&file->f_dentry->d_inode->i_sem);
400 return retval;
401}
402
403static int default_open (struct inode *inode, struct file *file)
404{
405 if (inode->u.generic_ip)
406 file->private_data = inode->u.generic_ip;
407
408 return 0;
409}
410
411static struct file_operations default_file_operations = {
412 .read = default_read_file,
413 .write = default_write_file,
414 .open = default_open,
415 .llseek = default_file_lseek,
416};
417
418static struct inode_operations usbfs_dir_inode_operations = {
419 .lookup = simple_lookup,
420};
421
422static struct super_operations usbfs_ops = {
423 .statfs = simple_statfs,
424 .drop_inode = generic_delete_inode,
425 .remount_fs = remount,
426};
427
428static int usbfs_fill_super(struct super_block *sb, void *data, int silent)
429{
430 struct inode *inode;
431 struct dentry *root;
432
433 sb->s_blocksize = PAGE_CACHE_SIZE;
434 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
435 sb->s_magic = USBDEVICE_SUPER_MAGIC;
436 sb->s_op = &usbfs_ops;
437 sb->s_time_gran = 1;
438 inode = usbfs_get_inode(sb, S_IFDIR | 0755, 0);
439
440 if (!inode) {
441 dbg("%s: could not get inode!",__FUNCTION__);
442 return -ENOMEM;
443 }
444
445 root = d_alloc_root(inode);
446 if (!root) {
447 dbg("%s: could not get root dentry!",__FUNCTION__);
448 iput(inode);
449 return -ENOMEM;
450 }
451 sb->s_root = root;
452 return 0;
453}
454
455static struct dentry * get_dentry(struct dentry *parent, const char *name)
456{
457 struct qstr qstr;
458
459 qstr.name = name;
460 qstr.len = strlen(name);
461 qstr.hash = full_name_hash(name,qstr.len);
462 return lookup_hash(&qstr,parent);
463}
464
465
466/*
467 * fs_create_by_name - create a file, given a name
468 * @name: name of file
469 * @mode: type of file
470 * @parent: dentry of directory to create it in
471 * @dentry: resulting dentry of file
472 *
473 * This function handles both regular files and directories.
474 */
475static int fs_create_by_name (const char *name, mode_t mode,
476 struct dentry *parent, struct dentry **dentry)
477{
478 int error = 0;
479
480 /* If the parent is not specified, we create it in the root.
481 * We need the root dentry to do this, which is in the super
482 * block. A pointer to that is in the struct vfsmount that we
483 * have around.
484 */
485 if (!parent ) {
486 if (usbfs_mount && usbfs_mount->mnt_sb) {
487 parent = usbfs_mount->mnt_sb->s_root;
488 }
489 }
490
491 if (!parent) {
492 dbg("Ah! can not find a parent!");
493 return -EFAULT;
494 }
495
496 *dentry = NULL;
497 down(&parent->d_inode->i_sem);
498 *dentry = get_dentry (parent, name);
499 if (!IS_ERR(dentry)) {
500 if ((mode & S_IFMT) == S_IFDIR)
501 error = usbfs_mkdir (parent->d_inode, *dentry, mode);
502 else
503 error = usbfs_create (parent->d_inode, *dentry, mode);
504 } else
505 error = PTR_ERR(dentry);
506 up(&parent->d_inode->i_sem);
507
508 return error;
509}
510
511static struct dentry *fs_create_file (const char *name, mode_t mode,
512 struct dentry *parent, void *data,
513 struct file_operations *fops,
514 uid_t uid, gid_t gid)
515{
516 struct dentry *dentry;
517 int error;
518
519 dbg("creating file '%s'",name);
520
521 error = fs_create_by_name (name, mode, parent, &dentry);
522 if (error) {
523 dentry = NULL;
524 } else {
525 if (dentry->d_inode) {
526 if (data)
527 dentry->d_inode->u.generic_ip = data;
528 if (fops)
529 dentry->d_inode->i_fop = fops;
530 dentry->d_inode->i_uid = uid;
531 dentry->d_inode->i_gid = gid;
532 }
533 }
534
535 return dentry;
536}
537
538static void fs_remove_file (struct dentry *dentry)
539{
540 struct dentry *parent = dentry->d_parent;
541
542 if (!parent || !parent->d_inode)
543 return;
544
545 down(&parent->d_inode->i_sem);
546 if (usbfs_positive(dentry)) {
547 if (dentry->d_inode) {
548 if (S_ISDIR(dentry->d_inode->i_mode))
549 usbfs_rmdir(parent->d_inode, dentry);
550 else
551 usbfs_unlink(parent->d_inode, dentry);
552 dput(dentry);
553 }
554 }
555 up(&parent->d_inode->i_sem);
556}
557
558/* --------------------------------------------------------------------- */
559
560static struct super_block *usb_get_sb(struct file_system_type *fs_type,
561 int flags, const char *dev_name, void *data)
562{
563 return get_sb_single(fs_type, flags, data, usbfs_fill_super);
564}
565
566static struct file_system_type usb_fs_type = {
567 .owner = THIS_MODULE,
568 .name = "usbfs",
569 .get_sb = usb_get_sb,
570 .kill_sb = kill_litter_super,
571};
572
573/* --------------------------------------------------------------------- */
574
575static int create_special_files (void)
576{
577 struct dentry *parent;
578 int retval;
579
580 /* the simple_pin_fs calls will call remount with no options
581 * without this flag that would overwrite the real mount options (if any)
582 */
583 ignore_mount = 1;
584
585 /* create the devices special file */
586 retval = simple_pin_fs("usbfs", &usbfs_mount, &usbfs_mount_count);
587 if (retval) {
588 err ("Unable to get usbfs mount");
589 goto exit;
590 }
591
592 ignore_mount = 0;
593
594 parent = usbfs_mount->mnt_sb->s_root;
595 devices_usbfs_dentry = fs_create_file ("devices",
596 listmode | S_IFREG, parent,
597 NULL, &usbfs_devices_fops,
598 listuid, listgid);
599 if (devices_usbfs_dentry == NULL) {
600 err ("Unable to create devices usbfs file");
601 retval = -ENODEV;
602 goto error_clean_mounts;
603 }
604
605 goto exit;
606
607error_clean_mounts:
608 simple_release_fs(&usbfs_mount, &usbfs_mount_count);
609exit:
610 return retval;
611}
612
613static void remove_special_files (void)
614{
615 if (devices_usbfs_dentry)
616 fs_remove_file (devices_usbfs_dentry);
617 devices_usbfs_dentry = NULL;
618 simple_release_fs(&usbfs_mount, &usbfs_mount_count);
619}
620
621void usbfs_update_special (void)
622{
623 struct inode *inode;
624
625 if (devices_usbfs_dentry) {
626 inode = devices_usbfs_dentry->d_inode;
627 if (inode)
628 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
629 }
630}
631
632void usbfs_add_bus(struct usb_bus *bus)
633{
634 struct dentry *parent;
635 char name[8];
636 int retval;
637
638 /* create the special files if this is the first bus added */
639 if (num_buses == 0) {
640 retval = create_special_files();
641 if (retval)
642 return;
643 }
644 ++num_buses;
645
646 sprintf (name, "%03d", bus->busnum);
647
648 parent = usbfs_mount->mnt_sb->s_root;
649 bus->usbfs_dentry = fs_create_file (name, busmode | S_IFDIR, parent,
650 bus, NULL, busuid, busgid);
651 if (bus->usbfs_dentry == NULL) {
652 err ("error creating usbfs bus entry");
653 return;
654 }
655
656 usbfs_update_special();
657 usbfs_conn_disc_event();
658}
659
660void usbfs_remove_bus(struct usb_bus *bus)
661{
662 if (bus->usbfs_dentry) {
663 fs_remove_file (bus->usbfs_dentry);
664 bus->usbfs_dentry = NULL;
665 }
666
667 --num_buses;
668 if (num_buses <= 0) {
669 remove_special_files();
670 num_buses = 0;
671 }
672
673 usbfs_update_special();
674 usbfs_conn_disc_event();
675}
676
677void usbfs_add_device(struct usb_device *dev)
678{
679 char name[8];
680 int i;
681 int i_size;
682
683 sprintf (name, "%03d", dev->devnum);
684 dev->usbfs_dentry = fs_create_file (name, devmode | S_IFREG,
685 dev->bus->usbfs_dentry, dev,
686 &usbfs_device_file_operations,
687 devuid, devgid);
688 if (dev->usbfs_dentry == NULL) {
689 err ("error creating usbfs device entry");
690 return;
691 }
692
693 /* Set the size of the device's file to be
694 * equal to the size of the device descriptors. */
695 i_size = sizeof (struct usb_device_descriptor);
696 for (i = 0; i < dev->descriptor.bNumConfigurations; ++i) {
697 struct usb_config_descriptor *config =
698 (struct usb_config_descriptor *)dev->rawdescriptors[i];
699 i_size += le16_to_cpu(config->wTotalLength);
700 }
701 if (dev->usbfs_dentry->d_inode)
702 dev->usbfs_dentry->d_inode->i_size = i_size;
703
704 usbfs_update_special();
705 usbfs_conn_disc_event();
706}
707
708void usbfs_remove_device(struct usb_device *dev)
709{
710 struct dev_state *ds;
711 struct siginfo sinfo;
712
713 if (dev->usbfs_dentry) {
714 fs_remove_file (dev->usbfs_dentry);
715 dev->usbfs_dentry = NULL;
716 }
717 while (!list_empty(&dev->filelist)) {
718 ds = list_entry(dev->filelist.next, struct dev_state, list);
719 wake_up_all(&ds->wait);
720 list_del_init(&ds->list);
721 if (ds->discsignr) {
722 sinfo.si_signo = SIGPIPE;
723 sinfo.si_errno = EPIPE;
724 sinfo.si_code = SI_ASYNCIO;
725 sinfo.si_addr = ds->disccontext;
726 send_sig_info(ds->discsignr, &sinfo, ds->disctask);
727 }
728 }
729 usbfs_update_special();
730 usbfs_conn_disc_event();
731}
732
733/* --------------------------------------------------------------------- */
734
735static struct proc_dir_entry *usbdir = NULL;
736
737int __init usbfs_init(void)
738{
739 int retval;
740
741 retval = usb_register(&usbfs_driver);
742 if (retval)
743 return retval;
744
745 retval = register_filesystem(&usb_fs_type);
746 if (retval) {
747 usb_deregister(&usbfs_driver);
748 return retval;
749 }
750
751 /* create mount point for usbfs */
752 usbdir = proc_mkdir("usb", proc_bus);
753
754 return 0;
755}
756
757void usbfs_cleanup(void)
758{
759 usb_deregister(&usbfs_driver);
760 unregister_filesystem(&usb_fs_type);
761 if (usbdir)
762 remove_proc_entry("usb", proc_bus);
763}
764
diff --git a/drivers/usb/core/message.c b/drivers/usb/core/message.c
new file mode 100644
index 000000000000..40bdb38e7bcb
--- /dev/null
+++ b/drivers/usb/core/message.c
@@ -0,0 +1,1480 @@
1/*
2 * message.c - synchronous message handling
3 */
4
5#include <linux/config.h>
6
7#ifdef CONFIG_USB_DEBUG
8 #define DEBUG
9#else
10 #undef DEBUG
11#endif
12
13#include <linux/pci.h> /* for scatterlist macros */
14#include <linux/usb.h>
15#include <linux/module.h>
16#include <linux/slab.h>
17#include <linux/init.h>
18#include <linux/mm.h>
19#include <linux/timer.h>
20#include <linux/ctype.h>
21#include <linux/device.h>
22#include <asm/byteorder.h>
23
24#include "hcd.h" /* for usbcore internals */
25#include "usb.h"
26
27static void usb_api_blocking_completion(struct urb *urb, struct pt_regs *regs)
28{
29 complete((struct completion *)urb->context);
30}
31
32
33static void timeout_kill(unsigned long data)
34{
35 struct urb *urb = (struct urb *) data;
36
37 usb_unlink_urb(urb);
38}
39
40// Starts urb and waits for completion or timeout
41// note that this call is NOT interruptible, while
42// many device driver i/o requests should be interruptible
43static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
44{
45 struct completion done;
46 struct timer_list timer;
47 int status;
48
49 init_completion(&done);
50 urb->context = &done;
51 urb->transfer_flags |= URB_ASYNC_UNLINK;
52 urb->actual_length = 0;
53 status = usb_submit_urb(urb, GFP_NOIO);
54
55 if (status == 0) {
56 if (timeout > 0) {
57 init_timer(&timer);
58 timer.expires = jiffies + msecs_to_jiffies(timeout);
59 timer.data = (unsigned long)urb;
60 timer.function = timeout_kill;
61 /* grr. timeout _should_ include submit delays. */
62 add_timer(&timer);
63 }
64 wait_for_completion(&done);
65 status = urb->status;
66 /* note: HCDs return ETIMEDOUT for other reasons too */
67 if (status == -ECONNRESET) {
68 dev_dbg(&urb->dev->dev,
69 "%s timed out on ep%d%s len=%d/%d\n",
70 current->comm,
71 usb_pipeendpoint(urb->pipe),
72 usb_pipein(urb->pipe) ? "in" : "out",
73 urb->actual_length,
74 urb->transfer_buffer_length
75 );
76 if (urb->actual_length > 0)
77 status = 0;
78 else
79 status = -ETIMEDOUT;
80 }
81 if (timeout > 0)
82 del_timer_sync(&timer);
83 }
84
85 if (actual_length)
86 *actual_length = urb->actual_length;
87 usb_free_urb(urb);
88 return status;
89}
90
91/*-------------------------------------------------------------------*/
92// returns status (negative) or length (positive)
93static int usb_internal_control_msg(struct usb_device *usb_dev,
94 unsigned int pipe,
95 struct usb_ctrlrequest *cmd,
96 void *data, int len, int timeout)
97{
98 struct urb *urb;
99 int retv;
100 int length;
101
102 urb = usb_alloc_urb(0, GFP_NOIO);
103 if (!urb)
104 return -ENOMEM;
105
106 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
107 len, usb_api_blocking_completion, NULL);
108
109 retv = usb_start_wait_urb(urb, timeout, &length);
110 if (retv < 0)
111 return retv;
112 else
113 return length;
114}
115
116/**
117 * usb_control_msg - Builds a control urb, sends it off and waits for completion
118 * @dev: pointer to the usb device to send the message to
119 * @pipe: endpoint "pipe" to send the message to
120 * @request: USB message request value
121 * @requesttype: USB message request type value
122 * @value: USB message value
123 * @index: USB message index value
124 * @data: pointer to the data to send
125 * @size: length in bytes of the data to send
126 * @timeout: time in msecs to wait for the message to complete before
127 * timing out (if 0 the wait is forever)
128 * Context: !in_interrupt ()
129 *
130 * This function sends a simple control message to a specified endpoint
131 * and waits for the message to complete, or timeout.
132 *
133 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
134 *
135 * Don't use this function from within an interrupt context, like a
136 * bottom half handler. If you need an asynchronous message, or need to send
137 * a message from within interrupt context, use usb_submit_urb()
138 * If a thread in your driver uses this call, make sure your disconnect()
139 * method can wait for it to complete. Since you don't have a handle on
140 * the URB used, you can't cancel the request.
141 */
142int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
143 __u16 value, __u16 index, void *data, __u16 size, int timeout)
144{
145 struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
146 int ret;
147
148 if (!dr)
149 return -ENOMEM;
150
151 dr->bRequestType= requesttype;
152 dr->bRequest = request;
153 dr->wValue = cpu_to_le16p(&value);
154 dr->wIndex = cpu_to_le16p(&index);
155 dr->wLength = cpu_to_le16p(&size);
156
157 //dbg("usb_control_msg");
158
159 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
160
161 kfree(dr);
162
163 return ret;
164}
165
166
167/**
168 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
169 * @usb_dev: pointer to the usb device to send the message to
170 * @pipe: endpoint "pipe" to send the message to
171 * @data: pointer to the data to send
172 * @len: length in bytes of the data to send
173 * @actual_length: pointer to a location to put the actual length transferred in bytes
174 * @timeout: time in msecs to wait for the message to complete before
175 * timing out (if 0 the wait is forever)
176 * Context: !in_interrupt ()
177 *
178 * This function sends a simple bulk message to a specified endpoint
179 * and waits for the message to complete, or timeout.
180 *
181 * If successful, it returns 0, otherwise a negative error number.
182 * The number of actual bytes transferred will be stored in the
183 * actual_length paramater.
184 *
185 * Don't use this function from within an interrupt context, like a
186 * bottom half handler. If you need an asynchronous message, or need to
187 * send a message from within interrupt context, use usb_submit_urb()
188 * If a thread in your driver uses this call, make sure your disconnect()
189 * method can wait for it to complete. Since you don't have a handle on
190 * the URB used, you can't cancel the request.
191 */
192int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
193 void *data, int len, int *actual_length, int timeout)
194{
195 struct urb *urb;
196
197 if (len < 0)
198 return -EINVAL;
199
200 urb=usb_alloc_urb(0, GFP_KERNEL);
201 if (!urb)
202 return -ENOMEM;
203
204 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
205 usb_api_blocking_completion, NULL);
206
207 return usb_start_wait_urb(urb, timeout, actual_length);
208}
209
210/*-------------------------------------------------------------------*/
211
212static void sg_clean (struct usb_sg_request *io)
213{
214 if (io->urbs) {
215 while (io->entries--)
216 usb_free_urb (io->urbs [io->entries]);
217 kfree (io->urbs);
218 io->urbs = NULL;
219 }
220 if (io->dev->dev.dma_mask != NULL)
221 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
222 io->dev = NULL;
223}
224
225static void sg_complete (struct urb *urb, struct pt_regs *regs)
226{
227 struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
228
229 spin_lock (&io->lock);
230
231 /* In 2.5 we require hcds' endpoint queues not to progress after fault
232 * reports, until the completion callback (this!) returns. That lets
233 * device driver code (like this routine) unlink queued urbs first,
234 * if it needs to, since the HC won't work on them at all. So it's
235 * not possible for page N+1 to overwrite page N, and so on.
236 *
237 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
238 * complete before the HCD can get requests away from hardware,
239 * though never during cleanup after a hard fault.
240 */
241 if (io->status
242 && (io->status != -ECONNRESET
243 || urb->status != -ECONNRESET)
244 && urb->actual_length) {
245 dev_err (io->dev->bus->controller,
246 "dev %s ep%d%s scatterlist error %d/%d\n",
247 io->dev->devpath,
248 usb_pipeendpoint (urb->pipe),
249 usb_pipein (urb->pipe) ? "in" : "out",
250 urb->status, io->status);
251 // BUG ();
252 }
253
254 if (io->status == 0 && urb->status && urb->status != -ECONNRESET) {
255 int i, found, status;
256
257 io->status = urb->status;
258
259 /* the previous urbs, and this one, completed already.
260 * unlink pending urbs so they won't rx/tx bad data.
261 * careful: unlink can sometimes be synchronous...
262 */
263 spin_unlock (&io->lock);
264 for (i = 0, found = 0; i < io->entries; i++) {
265 if (!io->urbs [i] || !io->urbs [i]->dev)
266 continue;
267 if (found) {
268 status = usb_unlink_urb (io->urbs [i]);
269 if (status != -EINPROGRESS && status != -EBUSY)
270 dev_err (&io->dev->dev,
271 "%s, unlink --> %d\n",
272 __FUNCTION__, status);
273 } else if (urb == io->urbs [i])
274 found = 1;
275 }
276 spin_lock (&io->lock);
277 }
278 urb->dev = NULL;
279
280 /* on the last completion, signal usb_sg_wait() */
281 io->bytes += urb->actual_length;
282 io->count--;
283 if (!io->count)
284 complete (&io->complete);
285
286 spin_unlock (&io->lock);
287}
288
289
290/**
291 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
292 * @io: request block being initialized. until usb_sg_wait() returns,
293 * treat this as a pointer to an opaque block of memory,
294 * @dev: the usb device that will send or receive the data
295 * @pipe: endpoint "pipe" used to transfer the data
296 * @period: polling rate for interrupt endpoints, in frames or
297 * (for high speed endpoints) microframes; ignored for bulk
298 * @sg: scatterlist entries
299 * @nents: how many entries in the scatterlist
300 * @length: how many bytes to send from the scatterlist, or zero to
301 * send every byte identified in the list.
302 * @mem_flags: SLAB_* flags affecting memory allocations in this call
303 *
304 * Returns zero for success, else a negative errno value. This initializes a
305 * scatter/gather request, allocating resources such as I/O mappings and urb
306 * memory (except maybe memory used by USB controller drivers).
307 *
308 * The request must be issued using usb_sg_wait(), which waits for the I/O to
309 * complete (or to be canceled) and then cleans up all resources allocated by
310 * usb_sg_init().
311 *
312 * The request may be canceled with usb_sg_cancel(), either before or after
313 * usb_sg_wait() is called.
314 */
315int usb_sg_init (
316 struct usb_sg_request *io,
317 struct usb_device *dev,
318 unsigned pipe,
319 unsigned period,
320 struct scatterlist *sg,
321 int nents,
322 size_t length,
323 int mem_flags
324)
325{
326 int i;
327 int urb_flags;
328 int dma;
329
330 if (!io || !dev || !sg
331 || usb_pipecontrol (pipe)
332 || usb_pipeisoc (pipe)
333 || nents <= 0)
334 return -EINVAL;
335
336 spin_lock_init (&io->lock);
337 io->dev = dev;
338 io->pipe = pipe;
339 io->sg = sg;
340 io->nents = nents;
341
342 /* not all host controllers use DMA (like the mainstream pci ones);
343 * they can use PIO (sl811) or be software over another transport.
344 */
345 dma = (dev->dev.dma_mask != NULL);
346 if (dma)
347 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
348 else
349 io->entries = nents;
350
351 /* initialize all the urbs we'll use */
352 if (io->entries <= 0)
353 return io->entries;
354
355 io->count = io->entries;
356 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
357 if (!io->urbs)
358 goto nomem;
359
360 urb_flags = URB_ASYNC_UNLINK | URB_NO_TRANSFER_DMA_MAP
361 | URB_NO_INTERRUPT;
362 if (usb_pipein (pipe))
363 urb_flags |= URB_SHORT_NOT_OK;
364
365 for (i = 0; i < io->entries; i++) {
366 unsigned len;
367
368 io->urbs [i] = usb_alloc_urb (0, mem_flags);
369 if (!io->urbs [i]) {
370 io->entries = i;
371 goto nomem;
372 }
373
374 io->urbs [i]->dev = NULL;
375 io->urbs [i]->pipe = pipe;
376 io->urbs [i]->interval = period;
377 io->urbs [i]->transfer_flags = urb_flags;
378
379 io->urbs [i]->complete = sg_complete;
380 io->urbs [i]->context = io;
381 io->urbs [i]->status = -EINPROGRESS;
382 io->urbs [i]->actual_length = 0;
383
384 if (dma) {
385 /* hc may use _only_ transfer_dma */
386 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
387 len = sg_dma_len (sg + i);
388 } else {
389 /* hc may use _only_ transfer_buffer */
390 io->urbs [i]->transfer_buffer =
391 page_address (sg [i].page) + sg [i].offset;
392 len = sg [i].length;
393 }
394
395 if (length) {
396 len = min_t (unsigned, len, length);
397 length -= len;
398 if (length == 0)
399 io->entries = i + 1;
400 }
401 io->urbs [i]->transfer_buffer_length = len;
402 }
403 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
404
405 /* transaction state */
406 io->status = 0;
407 io->bytes = 0;
408 init_completion (&io->complete);
409 return 0;
410
411nomem:
412 sg_clean (io);
413 return -ENOMEM;
414}
415
416
417/**
418 * usb_sg_wait - synchronously execute scatter/gather request
419 * @io: request block handle, as initialized with usb_sg_init().
420 * some fields become accessible when this call returns.
421 * Context: !in_interrupt ()
422 *
423 * This function blocks until the specified I/O operation completes. It
424 * leverages the grouping of the related I/O requests to get good transfer
425 * rates, by queueing the requests. At higher speeds, such queuing can
426 * significantly improve USB throughput.
427 *
428 * There are three kinds of completion for this function.
429 * (1) success, where io->status is zero. The number of io->bytes
430 * transferred is as requested.
431 * (2) error, where io->status is a negative errno value. The number
432 * of io->bytes transferred before the error is usually less
433 * than requested, and can be nonzero.
434 * (3) cancelation, a type of error with status -ECONNRESET that
435 * is initiated by usb_sg_cancel().
436 *
437 * When this function returns, all memory allocated through usb_sg_init() or
438 * this call will have been freed. The request block parameter may still be
439 * passed to usb_sg_cancel(), or it may be freed. It could also be
440 * reinitialized and then reused.
441 *
442 * Data Transfer Rates:
443 *
444 * Bulk transfers are valid for full or high speed endpoints.
445 * The best full speed data rate is 19 packets of 64 bytes each
446 * per frame, or 1216 bytes per millisecond.
447 * The best high speed data rate is 13 packets of 512 bytes each
448 * per microframe, or 52 KBytes per millisecond.
449 *
450 * The reason to use interrupt transfers through this API would most likely
451 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
452 * could be transferred. That capability is less useful for low or full
453 * speed interrupt endpoints, which allow at most one packet per millisecond,
454 * of at most 8 or 64 bytes (respectively).
455 */
456void usb_sg_wait (struct usb_sg_request *io)
457{
458 int i, entries = io->entries;
459
460 /* queue the urbs. */
461 spin_lock_irq (&io->lock);
462 for (i = 0; i < entries && !io->status; i++) {
463 int retval;
464
465 io->urbs [i]->dev = io->dev;
466 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
467
468 /* after we submit, let completions or cancelations fire;
469 * we handshake using io->status.
470 */
471 spin_unlock_irq (&io->lock);
472 switch (retval) {
473 /* maybe we retrying will recover */
474 case -ENXIO: // hc didn't queue this one
475 case -EAGAIN:
476 case -ENOMEM:
477 io->urbs[i]->dev = NULL;
478 retval = 0;
479 i--;
480 yield ();
481 break;
482
483 /* no error? continue immediately.
484 *
485 * NOTE: to work better with UHCI (4K I/O buffer may
486 * need 3K of TDs) it may be good to limit how many
487 * URBs are queued at once; N milliseconds?
488 */
489 case 0:
490 cpu_relax ();
491 break;
492
493 /* fail any uncompleted urbs */
494 default:
495 io->urbs [i]->dev = NULL;
496 io->urbs [i]->status = retval;
497 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
498 __FUNCTION__, retval);
499 usb_sg_cancel (io);
500 }
501 spin_lock_irq (&io->lock);
502 if (retval && (io->status == 0 || io->status == -ECONNRESET))
503 io->status = retval;
504 }
505 io->count -= entries - i;
506 if (io->count == 0)
507 complete (&io->complete);
508 spin_unlock_irq (&io->lock);
509
510 /* OK, yes, this could be packaged as non-blocking.
511 * So could the submit loop above ... but it's easier to
512 * solve neither problem than to solve both!
513 */
514 wait_for_completion (&io->complete);
515
516 sg_clean (io);
517}
518
519/**
520 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
521 * @io: request block, initialized with usb_sg_init()
522 *
523 * This stops a request after it has been started by usb_sg_wait().
524 * It can also prevents one initialized by usb_sg_init() from starting,
525 * so that call just frees resources allocated to the request.
526 */
527void usb_sg_cancel (struct usb_sg_request *io)
528{
529 unsigned long flags;
530
531 spin_lock_irqsave (&io->lock, flags);
532
533 /* shut everything down, if it didn't already */
534 if (!io->status) {
535 int i;
536
537 io->status = -ECONNRESET;
538 spin_unlock (&io->lock);
539 for (i = 0; i < io->entries; i++) {
540 int retval;
541
542 if (!io->urbs [i]->dev)
543 continue;
544 retval = usb_unlink_urb (io->urbs [i]);
545 if (retval != -EINPROGRESS && retval != -EBUSY)
546 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
547 __FUNCTION__, retval);
548 }
549 spin_lock (&io->lock);
550 }
551 spin_unlock_irqrestore (&io->lock, flags);
552}
553
554/*-------------------------------------------------------------------*/
555
556/**
557 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
558 * @dev: the device whose descriptor is being retrieved
559 * @type: the descriptor type (USB_DT_*)
560 * @index: the number of the descriptor
561 * @buf: where to put the descriptor
562 * @size: how big is "buf"?
563 * Context: !in_interrupt ()
564 *
565 * Gets a USB descriptor. Convenience functions exist to simplify
566 * getting some types of descriptors. Use
567 * usb_get_string() or usb_string() for USB_DT_STRING.
568 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
569 * are part of the device structure.
570 * In addition to a number of USB-standard descriptors, some
571 * devices also use class-specific or vendor-specific descriptors.
572 *
573 * This call is synchronous, and may not be used in an interrupt context.
574 *
575 * Returns the number of bytes received on success, or else the status code
576 * returned by the underlying usb_control_msg() call.
577 */
578int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
579{
580 int i;
581 int result;
582
583 memset(buf,0,size); // Make sure we parse really received data
584
585 for (i = 0; i < 3; ++i) {
586 /* retry on length 0 or stall; some devices are flakey */
587 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
588 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
589 (type << 8) + index, 0, buf, size,
590 USB_CTRL_GET_TIMEOUT);
591 if (result == 0 || result == -EPIPE)
592 continue;
593 if (result > 1 && ((u8 *)buf)[1] != type) {
594 result = -EPROTO;
595 continue;
596 }
597 break;
598 }
599 return result;
600}
601
602/**
603 * usb_get_string - gets a string descriptor
604 * @dev: the device whose string descriptor is being retrieved
605 * @langid: code for language chosen (from string descriptor zero)
606 * @index: the number of the descriptor
607 * @buf: where to put the string
608 * @size: how big is "buf"?
609 * Context: !in_interrupt ()
610 *
611 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
612 * in little-endian byte order).
613 * The usb_string() function will often be a convenient way to turn
614 * these strings into kernel-printable form.
615 *
616 * Strings may be referenced in device, configuration, interface, or other
617 * descriptors, and could also be used in vendor-specific ways.
618 *
619 * This call is synchronous, and may not be used in an interrupt context.
620 *
621 * Returns the number of bytes received on success, or else the status code
622 * returned by the underlying usb_control_msg() call.
623 */
624int usb_get_string(struct usb_device *dev, unsigned short langid,
625 unsigned char index, void *buf, int size)
626{
627 int i;
628 int result;
629
630 for (i = 0; i < 3; ++i) {
631 /* retry on length 0 or stall; some devices are flakey */
632 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
633 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
634 (USB_DT_STRING << 8) + index, langid, buf, size,
635 USB_CTRL_GET_TIMEOUT);
636 if (!(result == 0 || result == -EPIPE))
637 break;
638 }
639 return result;
640}
641
642static void usb_try_string_workarounds(unsigned char *buf, int *length)
643{
644 int newlength, oldlength = *length;
645
646 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
647 if (!isprint(buf[newlength]) || buf[newlength + 1])
648 break;
649
650 if (newlength > 2) {
651 buf[0] = newlength;
652 *length = newlength;
653 }
654}
655
656static int usb_string_sub(struct usb_device *dev, unsigned int langid,
657 unsigned int index, unsigned char *buf)
658{
659 int rc;
660
661 /* Try to read the string descriptor by asking for the maximum
662 * possible number of bytes */
663 rc = usb_get_string(dev, langid, index, buf, 255);
664
665 /* If that failed try to read the descriptor length, then
666 * ask for just that many bytes */
667 if (rc < 2) {
668 rc = usb_get_string(dev, langid, index, buf, 2);
669 if (rc == 2)
670 rc = usb_get_string(dev, langid, index, buf, buf[0]);
671 }
672
673 if (rc >= 2) {
674 if (!buf[0] && !buf[1])
675 usb_try_string_workarounds(buf, &rc);
676
677 /* There might be extra junk at the end of the descriptor */
678 if (buf[0] < rc)
679 rc = buf[0];
680
681 rc = rc - (rc & 1); /* force a multiple of two */
682 }
683
684 if (rc < 2)
685 rc = (rc < 0 ? rc : -EINVAL);
686
687 return rc;
688}
689
690/**
691 * usb_string - returns ISO 8859-1 version of a string descriptor
692 * @dev: the device whose string descriptor is being retrieved
693 * @index: the number of the descriptor
694 * @buf: where to put the string
695 * @size: how big is "buf"?
696 * Context: !in_interrupt ()
697 *
698 * This converts the UTF-16LE encoded strings returned by devices, from
699 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
700 * that are more usable in most kernel contexts. Note that all characters
701 * in the chosen descriptor that can't be encoded using ISO-8859-1
702 * are converted to the question mark ("?") character, and this function
703 * chooses strings in the first language supported by the device.
704 *
705 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
706 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
707 * and is appropriate for use many uses of English and several other
708 * Western European languages. (But it doesn't include the "Euro" symbol.)
709 *
710 * This call is synchronous, and may not be used in an interrupt context.
711 *
712 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
713 */
714int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
715{
716 unsigned char *tbuf;
717 int err;
718 unsigned int u, idx;
719
720 if (dev->state == USB_STATE_SUSPENDED)
721 return -EHOSTUNREACH;
722 if (size <= 0 || !buf || !index)
723 return -EINVAL;
724 buf[0] = 0;
725 tbuf = kmalloc(256, GFP_KERNEL);
726 if (!tbuf)
727 return -ENOMEM;
728
729 /* get langid for strings if it's not yet known */
730 if (!dev->have_langid) {
731 err = usb_string_sub(dev, 0, 0, tbuf);
732 if (err < 0) {
733 dev_err (&dev->dev,
734 "string descriptor 0 read error: %d\n",
735 err);
736 goto errout;
737 } else if (err < 4) {
738 dev_err (&dev->dev, "string descriptor 0 too short\n");
739 err = -EINVAL;
740 goto errout;
741 } else {
742 dev->have_langid = -1;
743 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
744 /* always use the first langid listed */
745 dev_dbg (&dev->dev, "default language 0x%04x\n",
746 dev->string_langid);
747 }
748 }
749
750 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
751 if (err < 0)
752 goto errout;
753
754 size--; /* leave room for trailing NULL char in output buffer */
755 for (idx = 0, u = 2; u < err; u += 2) {
756 if (idx >= size)
757 break;
758 if (tbuf[u+1]) /* high byte */
759 buf[idx++] = '?'; /* non ISO-8859-1 character */
760 else
761 buf[idx++] = tbuf[u];
762 }
763 buf[idx] = 0;
764 err = idx;
765
766 if (tbuf[1] != USB_DT_STRING)
767 dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
768
769 errout:
770 kfree(tbuf);
771 return err;
772}
773
774/*
775 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
776 * @dev: the device whose device descriptor is being updated
777 * @size: how much of the descriptor to read
778 * Context: !in_interrupt ()
779 *
780 * Updates the copy of the device descriptor stored in the device structure,
781 * which dedicates space for this purpose. Note that several fields are
782 * converted to the host CPU's byte order: the USB version (bcdUSB), and
783 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
784 * That lets device drivers compare against non-byteswapped constants.
785 *
786 * Not exported, only for use by the core. If drivers really want to read
787 * the device descriptor directly, they can call usb_get_descriptor() with
788 * type = USB_DT_DEVICE and index = 0.
789 *
790 * This call is synchronous, and may not be used in an interrupt context.
791 *
792 * Returns the number of bytes received on success, or else the status code
793 * returned by the underlying usb_control_msg() call.
794 */
795int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
796{
797 struct usb_device_descriptor *desc;
798 int ret;
799
800 if (size > sizeof(*desc))
801 return -EINVAL;
802 desc = kmalloc(sizeof(*desc), GFP_NOIO);
803 if (!desc)
804 return -ENOMEM;
805
806 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
807 if (ret >= 0)
808 memcpy(&dev->descriptor, desc, size);
809 kfree(desc);
810 return ret;
811}
812
813/**
814 * usb_get_status - issues a GET_STATUS call
815 * @dev: the device whose status is being checked
816 * @type: USB_RECIP_*; for device, interface, or endpoint
817 * @target: zero (for device), else interface or endpoint number
818 * @data: pointer to two bytes of bitmap data
819 * Context: !in_interrupt ()
820 *
821 * Returns device, interface, or endpoint status. Normally only of
822 * interest to see if the device is self powered, or has enabled the
823 * remote wakeup facility; or whether a bulk or interrupt endpoint
824 * is halted ("stalled").
825 *
826 * Bits in these status bitmaps are set using the SET_FEATURE request,
827 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
828 * function should be used to clear halt ("stall") status.
829 *
830 * This call is synchronous, and may not be used in an interrupt context.
831 *
832 * Returns the number of bytes received on success, or else the status code
833 * returned by the underlying usb_control_msg() call.
834 */
835int usb_get_status(struct usb_device *dev, int type, int target, void *data)
836{
837 int ret;
838 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
839
840 if (!status)
841 return -ENOMEM;
842
843 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
844 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
845 sizeof(*status), USB_CTRL_GET_TIMEOUT);
846
847 *(u16 *)data = *status;
848 kfree(status);
849 return ret;
850}
851
852/**
853 * usb_clear_halt - tells device to clear endpoint halt/stall condition
854 * @dev: device whose endpoint is halted
855 * @pipe: endpoint "pipe" being cleared
856 * Context: !in_interrupt ()
857 *
858 * This is used to clear halt conditions for bulk and interrupt endpoints,
859 * as reported by URB completion status. Endpoints that are halted are
860 * sometimes referred to as being "stalled". Such endpoints are unable
861 * to transmit or receive data until the halt status is cleared. Any URBs
862 * queued for such an endpoint should normally be unlinked by the driver
863 * before clearing the halt condition, as described in sections 5.7.5
864 * and 5.8.5 of the USB 2.0 spec.
865 *
866 * Note that control and isochronous endpoints don't halt, although control
867 * endpoints report "protocol stall" (for unsupported requests) using the
868 * same status code used to report a true stall.
869 *
870 * This call is synchronous, and may not be used in an interrupt context.
871 *
872 * Returns zero on success, or else the status code returned by the
873 * underlying usb_control_msg() call.
874 */
875int usb_clear_halt(struct usb_device *dev, int pipe)
876{
877 int result;
878 int endp = usb_pipeendpoint(pipe);
879
880 if (usb_pipein (pipe))
881 endp |= USB_DIR_IN;
882
883 /* we don't care if it wasn't halted first. in fact some devices
884 * (like some ibmcam model 1 units) seem to expect hosts to make
885 * this request for iso endpoints, which can't halt!
886 */
887 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
888 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
889 USB_ENDPOINT_HALT, endp, NULL, 0,
890 USB_CTRL_SET_TIMEOUT);
891
892 /* don't un-halt or force to DATA0 except on success */
893 if (result < 0)
894 return result;
895
896 /* NOTE: seems like Microsoft and Apple don't bother verifying
897 * the clear "took", so some devices could lock up if you check...
898 * such as the Hagiwara FlashGate DUAL. So we won't bother.
899 *
900 * NOTE: make sure the logic here doesn't diverge much from
901 * the copy in usb-storage, for as long as we need two copies.
902 */
903
904 /* toggle was reset by the clear */
905 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
906
907 return 0;
908}
909
910/**
911 * usb_disable_endpoint -- Disable an endpoint by address
912 * @dev: the device whose endpoint is being disabled
913 * @epaddr: the endpoint's address. Endpoint number for output,
914 * endpoint number + USB_DIR_IN for input
915 *
916 * Deallocates hcd/hardware state for this endpoint ... and nukes all
917 * pending urbs.
918 *
919 * If the HCD hasn't registered a disable() function, this sets the
920 * endpoint's maxpacket size to 0 to prevent further submissions.
921 */
922void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
923{
924 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
925 struct usb_host_endpoint *ep;
926
927 if (!dev)
928 return;
929
930 if (usb_endpoint_out(epaddr)) {
931 ep = dev->ep_out[epnum];
932 dev->ep_out[epnum] = NULL;
933 } else {
934 ep = dev->ep_in[epnum];
935 dev->ep_in[epnum] = NULL;
936 }
937 if (ep && dev->bus && dev->bus->op && dev->bus->op->disable)
938 dev->bus->op->disable(dev, ep);
939}
940
941/**
942 * usb_disable_interface -- Disable all endpoints for an interface
943 * @dev: the device whose interface is being disabled
944 * @intf: pointer to the interface descriptor
945 *
946 * Disables all the endpoints for the interface's current altsetting.
947 */
948void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
949{
950 struct usb_host_interface *alt = intf->cur_altsetting;
951 int i;
952
953 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
954 usb_disable_endpoint(dev,
955 alt->endpoint[i].desc.bEndpointAddress);
956 }
957}
958
959/*
960 * usb_disable_device - Disable all the endpoints for a USB device
961 * @dev: the device whose endpoints are being disabled
962 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
963 *
964 * Disables all the device's endpoints, potentially including endpoint 0.
965 * Deallocates hcd/hardware state for the endpoints (nuking all or most
966 * pending urbs) and usbcore state for the interfaces, so that usbcore
967 * must usb_set_configuration() before any interfaces could be used.
968 */
969void usb_disable_device(struct usb_device *dev, int skip_ep0)
970{
971 int i;
972
973 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
974 skip_ep0 ? "non-ep0" : "all");
975 for (i = skip_ep0; i < 16; ++i) {
976 usb_disable_endpoint(dev, i);
977 usb_disable_endpoint(dev, i + USB_DIR_IN);
978 }
979 dev->toggle[0] = dev->toggle[1] = 0;
980
981 /* getting rid of interfaces will disconnect
982 * any drivers bound to them (a key side effect)
983 */
984 if (dev->actconfig) {
985 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
986 struct usb_interface *interface;
987
988 /* remove this interface */
989 interface = dev->actconfig->interface[i];
990 dev_dbg (&dev->dev, "unregistering interface %s\n",
991 interface->dev.bus_id);
992 usb_remove_sysfs_intf_files(interface);
993 kfree(interface->cur_altsetting->string);
994 interface->cur_altsetting->string = NULL;
995 device_del (&interface->dev);
996 }
997
998 /* Now that the interfaces are unbound, nobody should
999 * try to access them.
1000 */
1001 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1002 put_device (&dev->actconfig->interface[i]->dev);
1003 dev->actconfig->interface[i] = NULL;
1004 }
1005 dev->actconfig = NULL;
1006 if (dev->state == USB_STATE_CONFIGURED)
1007 usb_set_device_state(dev, USB_STATE_ADDRESS);
1008 }
1009}
1010
1011
1012/*
1013 * usb_enable_endpoint - Enable an endpoint for USB communications
1014 * @dev: the device whose interface is being enabled
1015 * @ep: the endpoint
1016 *
1017 * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
1018 * For control endpoints, both the input and output sides are handled.
1019 */
1020static void
1021usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
1022{
1023 unsigned int epaddr = ep->desc.bEndpointAddress;
1024 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1025 int is_control;
1026
1027 is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1028 == USB_ENDPOINT_XFER_CONTROL);
1029 if (usb_endpoint_out(epaddr) || is_control) {
1030 usb_settoggle(dev, epnum, 1, 0);
1031 dev->ep_out[epnum] = ep;
1032 }
1033 if (!usb_endpoint_out(epaddr) || is_control) {
1034 usb_settoggle(dev, epnum, 0, 0);
1035 dev->ep_in[epnum] = ep;
1036 }
1037}
1038
1039/*
1040 * usb_enable_interface - Enable all the endpoints for an interface
1041 * @dev: the device whose interface is being enabled
1042 * @intf: pointer to the interface descriptor
1043 *
1044 * Enables all the endpoints for the interface's current altsetting.
1045 */
1046static void usb_enable_interface(struct usb_device *dev,
1047 struct usb_interface *intf)
1048{
1049 struct usb_host_interface *alt = intf->cur_altsetting;
1050 int i;
1051
1052 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1053 usb_enable_endpoint(dev, &alt->endpoint[i]);
1054}
1055
1056/**
1057 * usb_set_interface - Makes a particular alternate setting be current
1058 * @dev: the device whose interface is being updated
1059 * @interface: the interface being updated
1060 * @alternate: the setting being chosen.
1061 * Context: !in_interrupt ()
1062 *
1063 * This is used to enable data transfers on interfaces that may not
1064 * be enabled by default. Not all devices support such configurability.
1065 * Only the driver bound to an interface may change its setting.
1066 *
1067 * Within any given configuration, each interface may have several
1068 * alternative settings. These are often used to control levels of
1069 * bandwidth consumption. For example, the default setting for a high
1070 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1071 * while interrupt transfers of up to 3KBytes per microframe are legal.
1072 * Also, isochronous endpoints may never be part of an
1073 * interface's default setting. To access such bandwidth, alternate
1074 * interface settings must be made current.
1075 *
1076 * Note that in the Linux USB subsystem, bandwidth associated with
1077 * an endpoint in a given alternate setting is not reserved until an URB
1078 * is submitted that needs that bandwidth. Some other operating systems
1079 * allocate bandwidth early, when a configuration is chosen.
1080 *
1081 * This call is synchronous, and may not be used in an interrupt context.
1082 * Also, drivers must not change altsettings while urbs are scheduled for
1083 * endpoints in that interface; all such urbs must first be completed
1084 * (perhaps forced by unlinking).
1085 *
1086 * Returns zero on success, or else the status code returned by the
1087 * underlying usb_control_msg() call.
1088 */
1089int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1090{
1091 struct usb_interface *iface;
1092 struct usb_host_interface *alt;
1093 int ret;
1094 int manual = 0;
1095
1096 if (dev->state == USB_STATE_SUSPENDED)
1097 return -EHOSTUNREACH;
1098
1099 iface = usb_ifnum_to_if(dev, interface);
1100 if (!iface) {
1101 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1102 interface);
1103 return -EINVAL;
1104 }
1105
1106 alt = usb_altnum_to_altsetting(iface, alternate);
1107 if (!alt) {
1108 warn("selecting invalid altsetting %d", alternate);
1109 return -EINVAL;
1110 }
1111
1112 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1113 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1114 alternate, interface, NULL, 0, 5000);
1115
1116 /* 9.4.10 says devices don't need this and are free to STALL the
1117 * request if the interface only has one alternate setting.
1118 */
1119 if (ret == -EPIPE && iface->num_altsetting == 1) {
1120 dev_dbg(&dev->dev,
1121 "manual set_interface for iface %d, alt %d\n",
1122 interface, alternate);
1123 manual = 1;
1124 } else if (ret < 0)
1125 return ret;
1126
1127 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1128 * when they implement async or easily-killable versions of this or
1129 * other "should-be-internal" functions (like clear_halt).
1130 * should hcd+usbcore postprocess control requests?
1131 */
1132
1133 /* prevent submissions using previous endpoint settings */
1134 usb_disable_interface(dev, iface);
1135
1136 /* 9.1.1.5 says:
1137 *
1138 * Configuring a device or changing an alternate setting
1139 * causes all of the status and configuration values
1140 * associated with endpoints in the affected interfaces to
1141 * be set to their default values. This includes setting
1142 * the data toggle of any endpoint using data toggles to
1143 * the value DATA0.
1144 *
1145 * Some devices take this too literally and don't reset the data
1146 * toggles if the new altsetting is the same as the old one (the
1147 * command isn't "changing" an alternate setting). We will manually
1148 * reset the toggles when the new and old altsettings are the same.
1149 * Most devices won't need this, but fortunately it doesn't happen
1150 * often.
1151 */
1152 if (iface->cur_altsetting == alt)
1153 manual = 1;
1154 iface->cur_altsetting = alt;
1155
1156 /* If the interface only has one altsetting and the device didn't
1157 * accept the request (or whenever the old altsetting is the same
1158 * as the new one), we attempt to carry out the equivalent action
1159 * by manually clearing the HALT feature for each endpoint in the
1160 * new altsetting.
1161 */
1162 if (manual) {
1163 int i;
1164
1165 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1166 unsigned int epaddr =
1167 alt->endpoint[i].desc.bEndpointAddress;
1168 unsigned int pipe =
1169 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
1170 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1171
1172 usb_clear_halt(dev, pipe);
1173 }
1174 }
1175
1176 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1177 *
1178 * Note:
1179 * Despite EP0 is always present in all interfaces/AS, the list of
1180 * endpoints from the descriptor does not contain EP0. Due to its
1181 * omnipresence one might expect EP0 being considered "affected" by
1182 * any SetInterface request and hence assume toggles need to be reset.
1183 * However, EP0 toggles are re-synced for every individual transfer
1184 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1185 * (Likewise, EP0 never "halts" on well designed devices.)
1186 */
1187 usb_enable_interface(dev, iface);
1188
1189 return 0;
1190}
1191
1192/**
1193 * usb_reset_configuration - lightweight device reset
1194 * @dev: the device whose configuration is being reset
1195 *
1196 * This issues a standard SET_CONFIGURATION request to the device using
1197 * the current configuration. The effect is to reset most USB-related
1198 * state in the device, including interface altsettings (reset to zero),
1199 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1200 * endpoints). Other usbcore state is unchanged, including bindings of
1201 * usb device drivers to interfaces.
1202 *
1203 * Because this affects multiple interfaces, avoid using this with composite
1204 * (multi-interface) devices. Instead, the driver for each interface may
1205 * use usb_set_interface() on the interfaces it claims. Resetting the whole
1206 * configuration would affect other drivers' interfaces.
1207 *
1208 * The caller must own the device lock.
1209 *
1210 * Returns zero on success, else a negative error code.
1211 */
1212int usb_reset_configuration(struct usb_device *dev)
1213{
1214 int i, retval;
1215 struct usb_host_config *config;
1216
1217 if (dev->state == USB_STATE_SUSPENDED)
1218 return -EHOSTUNREACH;
1219
1220 /* caller must have locked the device and must own
1221 * the usb bus readlock (so driver bindings are stable);
1222 * calls during probe() are fine
1223 */
1224
1225 for (i = 1; i < 16; ++i) {
1226 usb_disable_endpoint(dev, i);
1227 usb_disable_endpoint(dev, i + USB_DIR_IN);
1228 }
1229
1230 config = dev->actconfig;
1231 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1232 USB_REQ_SET_CONFIGURATION, 0,
1233 config->desc.bConfigurationValue, 0,
1234 NULL, 0, USB_CTRL_SET_TIMEOUT);
1235 if (retval < 0) {
1236 usb_set_device_state(dev, USB_STATE_ADDRESS);
1237 return retval;
1238 }
1239
1240 dev->toggle[0] = dev->toggle[1] = 0;
1241
1242 /* re-init hc/hcd interface/endpoint state */
1243 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1244 struct usb_interface *intf = config->interface[i];
1245 struct usb_host_interface *alt;
1246
1247 alt = usb_altnum_to_altsetting(intf, 0);
1248
1249 /* No altsetting 0? We'll assume the first altsetting.
1250 * We could use a GetInterface call, but if a device is
1251 * so non-compliant that it doesn't have altsetting 0
1252 * then I wouldn't trust its reply anyway.
1253 */
1254 if (!alt)
1255 alt = &intf->altsetting[0];
1256
1257 intf->cur_altsetting = alt;
1258 usb_enable_interface(dev, intf);
1259 }
1260 return 0;
1261}
1262
1263static void release_interface(struct device *dev)
1264{
1265 struct usb_interface *intf = to_usb_interface(dev);
1266 struct usb_interface_cache *intfc =
1267 altsetting_to_usb_interface_cache(intf->altsetting);
1268
1269 kref_put(&intfc->ref, usb_release_interface_cache);
1270 kfree(intf);
1271}
1272
1273/*
1274 * usb_set_configuration - Makes a particular device setting be current
1275 * @dev: the device whose configuration is being updated
1276 * @configuration: the configuration being chosen.
1277 * Context: !in_interrupt(), caller owns the device lock
1278 *
1279 * This is used to enable non-default device modes. Not all devices
1280 * use this kind of configurability; many devices only have one
1281 * configuration.
1282 *
1283 * USB device configurations may affect Linux interoperability,
1284 * power consumption and the functionality available. For example,
1285 * the default configuration is limited to using 100mA of bus power,
1286 * so that when certain device functionality requires more power,
1287 * and the device is bus powered, that functionality should be in some
1288 * non-default device configuration. Other device modes may also be
1289 * reflected as configuration options, such as whether two ISDN
1290 * channels are available independently; and choosing between open
1291 * standard device protocols (like CDC) or proprietary ones.
1292 *
1293 * Note that USB has an additional level of device configurability,
1294 * associated with interfaces. That configurability is accessed using
1295 * usb_set_interface().
1296 *
1297 * This call is synchronous. The calling context must be able to sleep,
1298 * must own the device lock, and must not hold the driver model's USB
1299 * bus rwsem; usb device driver probe() methods cannot use this routine.
1300 *
1301 * Returns zero on success, or else the status code returned by the
1302 * underlying call that failed. On succesful completion, each interface
1303 * in the original device configuration has been destroyed, and each one
1304 * in the new configuration has been probed by all relevant usb device
1305 * drivers currently known to the kernel.
1306 */
1307int usb_set_configuration(struct usb_device *dev, int configuration)
1308{
1309 int i, ret;
1310 struct usb_host_config *cp = NULL;
1311 struct usb_interface **new_interfaces = NULL;
1312 int n, nintf;
1313
1314 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1315 if (dev->config[i].desc.bConfigurationValue == configuration) {
1316 cp = &dev->config[i];
1317 break;
1318 }
1319 }
1320 if ((!cp && configuration != 0))
1321 return -EINVAL;
1322
1323 /* The USB spec says configuration 0 means unconfigured.
1324 * But if a device includes a configuration numbered 0,
1325 * we will accept it as a correctly configured state.
1326 */
1327 if (cp && configuration == 0)
1328 dev_warn(&dev->dev, "config 0 descriptor??\n");
1329
1330 if (dev->state == USB_STATE_SUSPENDED)
1331 return -EHOSTUNREACH;
1332
1333 /* Allocate memory for new interfaces before doing anything else,
1334 * so that if we run out then nothing will have changed. */
1335 n = nintf = 0;
1336 if (cp) {
1337 nintf = cp->desc.bNumInterfaces;
1338 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1339 GFP_KERNEL);
1340 if (!new_interfaces) {
1341 dev_err(&dev->dev, "Out of memory");
1342 return -ENOMEM;
1343 }
1344
1345 for (; n < nintf; ++n) {
1346 new_interfaces[n] = kmalloc(
1347 sizeof(struct usb_interface),
1348 GFP_KERNEL);
1349 if (!new_interfaces[n]) {
1350 dev_err(&dev->dev, "Out of memory");
1351 ret = -ENOMEM;
1352free_interfaces:
1353 while (--n >= 0)
1354 kfree(new_interfaces[n]);
1355 kfree(new_interfaces);
1356 return ret;
1357 }
1358 }
1359 }
1360
1361 /* if it's already configured, clear out old state first.
1362 * getting rid of old interfaces means unbinding their drivers.
1363 */
1364 if (dev->state != USB_STATE_ADDRESS)
1365 usb_disable_device (dev, 1); // Skip ep0
1366
1367 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1368 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1369 NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0)
1370 goto free_interfaces;
1371
1372 dev->actconfig = cp;
1373 if (!cp)
1374 usb_set_device_state(dev, USB_STATE_ADDRESS);
1375 else {
1376 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1377
1378 /* Initialize the new interface structures and the
1379 * hc/hcd/usbcore interface/endpoint state.
1380 */
1381 for (i = 0; i < nintf; ++i) {
1382 struct usb_interface_cache *intfc;
1383 struct usb_interface *intf;
1384 struct usb_host_interface *alt;
1385
1386 cp->interface[i] = intf = new_interfaces[i];
1387 memset(intf, 0, sizeof(*intf));
1388 intfc = cp->intf_cache[i];
1389 intf->altsetting = intfc->altsetting;
1390 intf->num_altsetting = intfc->num_altsetting;
1391 kref_get(&intfc->ref);
1392
1393 alt = usb_altnum_to_altsetting(intf, 0);
1394
1395 /* No altsetting 0? We'll assume the first altsetting.
1396 * We could use a GetInterface call, but if a device is
1397 * so non-compliant that it doesn't have altsetting 0
1398 * then I wouldn't trust its reply anyway.
1399 */
1400 if (!alt)
1401 alt = &intf->altsetting[0];
1402
1403 intf->cur_altsetting = alt;
1404 usb_enable_interface(dev, intf);
1405 intf->dev.parent = &dev->dev;
1406 intf->dev.driver = NULL;
1407 intf->dev.bus = &usb_bus_type;
1408 intf->dev.dma_mask = dev->dev.dma_mask;
1409 intf->dev.release = release_interface;
1410 device_initialize (&intf->dev);
1411 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1412 dev->bus->busnum, dev->devpath,
1413 configuration,
1414 alt->desc.bInterfaceNumber);
1415 }
1416 kfree(new_interfaces);
1417
1418 if ((cp->desc.iConfiguration) &&
1419 (cp->string == NULL)) {
1420 cp->string = kmalloc(256, GFP_KERNEL);
1421 if (cp->string)
1422 usb_string(dev, cp->desc.iConfiguration, cp->string, 256);
1423 }
1424
1425 /* Now that all the interfaces are set up, register them
1426 * to trigger binding of drivers to interfaces. probe()
1427 * routines may install different altsettings and may
1428 * claim() any interfaces not yet bound. Many class drivers
1429 * need that: CDC, audio, video, etc.
1430 */
1431 for (i = 0; i < nintf; ++i) {
1432 struct usb_interface *intf = cp->interface[i];
1433 struct usb_interface_descriptor *desc;
1434
1435 desc = &intf->altsetting [0].desc;
1436 dev_dbg (&dev->dev,
1437 "adding %s (config #%d, interface %d)\n",
1438 intf->dev.bus_id, configuration,
1439 desc->bInterfaceNumber);
1440 ret = device_add (&intf->dev);
1441 if (ret != 0) {
1442 dev_err(&dev->dev,
1443 "device_add(%s) --> %d\n",
1444 intf->dev.bus_id,
1445 ret);
1446 continue;
1447 }
1448 if ((intf->cur_altsetting->desc.iInterface) &&
1449 (intf->cur_altsetting->string == NULL)) {
1450 intf->cur_altsetting->string = kmalloc(256, GFP_KERNEL);
1451 if (intf->cur_altsetting->string)
1452 usb_string(dev, intf->cur_altsetting->desc.iInterface,
1453 intf->cur_altsetting->string, 256);
1454 }
1455 usb_create_sysfs_intf_files (intf);
1456 }
1457 }
1458
1459 return ret;
1460}
1461
1462// synchronous request completion model
1463EXPORT_SYMBOL(usb_control_msg);
1464EXPORT_SYMBOL(usb_bulk_msg);
1465
1466EXPORT_SYMBOL(usb_sg_init);
1467EXPORT_SYMBOL(usb_sg_cancel);
1468EXPORT_SYMBOL(usb_sg_wait);
1469
1470// synchronous control message convenience routines
1471EXPORT_SYMBOL(usb_get_descriptor);
1472EXPORT_SYMBOL(usb_get_status);
1473EXPORT_SYMBOL(usb_get_string);
1474EXPORT_SYMBOL(usb_string);
1475
1476// synchronous calls that also maintain usbcore state
1477EXPORT_SYMBOL(usb_clear_halt);
1478EXPORT_SYMBOL(usb_reset_configuration);
1479EXPORT_SYMBOL(usb_set_interface);
1480
diff --git a/drivers/usb/core/otg_whitelist.h b/drivers/usb/core/otg_whitelist.h
new file mode 100644
index 000000000000..627a5a2fc9cf
--- /dev/null
+++ b/drivers/usb/core/otg_whitelist.h
@@ -0,0 +1,112 @@
1/*
2 * drivers/usb/core/otg_whitelist.h
3 *
4 * Copyright (C) 2004 Texas Instruments
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 */
11
12/*
13 * This OTG Whitelist is the OTG "Targeted Peripheral List". It should
14 * mostly use of USB_DEVICE() or USB_DEVICE_VER() entries..
15 *
16 * YOU _SHOULD_ CHANGE THIS LIST TO MATCH YOUR PRODUCT AND ITS TESTING!
17 */
18
19static struct usb_device_id whitelist_table [] = {
20
21/* hubs are optional in OTG, but very handy ... */
22{ USB_DEVICE_INFO(USB_CLASS_HUB, 0, 0), },
23{ USB_DEVICE_INFO(USB_CLASS_HUB, 0, 1), },
24
25#ifdef CONFIG_USB_PRINTER /* ignoring nonstatic linkage! */
26/* FIXME actually, printers are NOT supposed to use device classes;
27 * they're supposed to use interface classes...
28 */
29{ USB_DEVICE_INFO(7, 1, 1) },
30{ USB_DEVICE_INFO(7, 1, 2) },
31{ USB_DEVICE_INFO(7, 1, 3) },
32#endif
33
34#ifdef CONFIG_USB_CDCETHER
35/* Linux-USB CDC Ethernet gadget */
36{ USB_DEVICE(0x0525, 0xa4a1), },
37/* Linux-USB CDC Ethernet + RNDIS gadget */
38{ USB_DEVICE(0x0525, 0xa4a2), },
39#endif
40
41#if defined(CONFIG_USB_TEST) || defined(CONFIG_USB_TEST_MODULE)
42/* gadget zero, for testing */
43{ USB_DEVICE(0x0525, 0xa4a0), },
44#endif
45
46{ } /* Terminating entry */
47};
48
49static int is_targeted(struct usb_device *dev)
50{
51 struct usb_device_id *id = whitelist_table;
52
53 /* possible in developer configs only! */
54 if (!dev->bus->otg_port)
55 return 1;
56
57 /* HNP test device is _never_ targeted (see OTG spec 6.6.6) */
58 if ((le16_to_cpu(dev->descriptor.idVendor) == 0x1a0a &&
59 le16_to_cpu(dev->descriptor.idProduct) == 0xbadd))
60 return 0;
61
62 /* NOTE: can't use usb_match_id() since interface caches
63 * aren't set up yet. this is cut/paste from that code.
64 */
65 for (id = whitelist_table; id->match_flags; id++) {
66 if ((id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) &&
67 id->idVendor != le16_to_cpu(dev->descriptor.idVendor))
68 continue;
69
70 if ((id->match_flags & USB_DEVICE_ID_MATCH_PRODUCT) &&
71 id->idProduct != le16_to_cpu(dev->descriptor.idProduct))
72 continue;
73
74 /* No need to test id->bcdDevice_lo != 0, since 0 is never
75 greater than any unsigned number. */
76 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_LO) &&
77 (id->bcdDevice_lo > le16_to_cpu(dev->descriptor.bcdDevice)))
78 continue;
79
80 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_HI) &&
81 (id->bcdDevice_hi < le16_to_cpu(dev->descriptor.bcdDevice)))
82 continue;
83
84 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_CLASS) &&
85 (id->bDeviceClass != dev->descriptor.bDeviceClass))
86 continue;
87
88 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_SUBCLASS) &&
89 (id->bDeviceSubClass!= dev->descriptor.bDeviceSubClass))
90 continue;
91
92 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_PROTOCOL) &&
93 (id->bDeviceProtocol != dev->descriptor.bDeviceProtocol))
94 continue;
95
96 return 1;
97 }
98
99 /* add other match criteria here ... */
100
101
102 /* OTG MESSAGE: report errors here, customize to match your product */
103 dev_err(&dev->dev, "device v%04x p%04x is not supported\n",
104 le16_to_cpu(dev->descriptor.idVendor),
105 le16_to_cpu(dev->descriptor.idProduct));
106#ifdef CONFIG_USB_OTG_WHITELIST
107 return 0;
108#else
109 return 1;
110#endif
111}
112
diff --git a/drivers/usb/core/sysfs.c b/drivers/usb/core/sysfs.c
new file mode 100644
index 000000000000..ec9b3bde8ae5
--- /dev/null
+++ b/drivers/usb/core/sysfs.c
@@ -0,0 +1,318 @@
1/*
2 * drivers/usb/core/sysfs.c
3 *
4 * (C) Copyright 2002 David Brownell
5 * (C) Copyright 2002,2004 Greg Kroah-Hartman
6 * (C) Copyright 2002,2004 IBM Corp.
7 *
8 * All of the sysfs file attributes for usb devices and interfaces.
9 *
10 */
11
12
13#include <linux/config.h>
14#include <linux/kernel.h>
15
16#ifdef CONFIG_USB_DEBUG
17 #define DEBUG
18#else
19 #undef DEBUG
20#endif
21#include <linux/usb.h>
22
23#include "usb.h"
24
25/* Active configuration fields */
26#define usb_actconfig_show(field, multiplier, format_string) \
27static ssize_t show_##field (struct device *dev, char *buf) \
28{ \
29 struct usb_device *udev; \
30 struct usb_host_config *actconfig; \
31 \
32 udev = to_usb_device (dev); \
33 actconfig = udev->actconfig; \
34 if (actconfig) \
35 return sprintf (buf, format_string, \
36 actconfig->desc.field * multiplier); \
37 else \
38 return 0; \
39} \
40
41#define usb_actconfig_attr(field, multiplier, format_string) \
42usb_actconfig_show(field, multiplier, format_string) \
43static DEVICE_ATTR(field, S_IRUGO, show_##field, NULL);
44
45usb_actconfig_attr (bNumInterfaces, 1, "%2d\n")
46usb_actconfig_attr (bmAttributes, 1, "%2x\n")
47usb_actconfig_attr (bMaxPower, 2, "%3dmA\n")
48
49static ssize_t show_configuration_string(struct device *dev, char *buf)
50{
51 struct usb_device *udev;
52 struct usb_host_config *actconfig;
53 int len;
54
55 udev = to_usb_device (dev);
56 actconfig = udev->actconfig;
57 if ((!actconfig) || (!actconfig->string))
58 return 0;
59 len = sprintf(buf, actconfig->string, PAGE_SIZE);
60 if (len < 0)
61 return 0;
62 buf[len] = '\n';
63 buf[len+1] = 0;
64 return len+1;
65}
66static DEVICE_ATTR(configuration, S_IRUGO, show_configuration_string, NULL);
67
68/* configuration value is always present, and r/w */
69usb_actconfig_show(bConfigurationValue, 1, "%u\n");
70
71static ssize_t
72set_bConfigurationValue (struct device *dev, const char *buf, size_t count)
73{
74 struct usb_device *udev = udev = to_usb_device (dev);
75 int config, value;
76
77 if (sscanf (buf, "%u", &config) != 1 || config > 255)
78 return -EINVAL;
79 usb_lock_device(udev);
80 value = usb_set_configuration (udev, config);
81 usb_unlock_device(udev);
82 return (value < 0) ? value : count;
83}
84
85static DEVICE_ATTR(bConfigurationValue, S_IRUGO | S_IWUSR,
86 show_bConfigurationValue, set_bConfigurationValue);
87
88/* String fields */
89#define usb_string_attr(name) \
90static ssize_t show_##name(struct device *dev, char *buf) \
91{ \
92 struct usb_device *udev; \
93 int len; \
94 \
95 udev = to_usb_device (dev); \
96 len = snprintf(buf, 256, "%s", udev->name); \
97 if (len < 0) \
98 return 0; \
99 buf[len] = '\n'; \
100 buf[len+1] = 0; \
101 return len+1; \
102} \
103static DEVICE_ATTR(name, S_IRUGO, show_##name, NULL);
104
105usb_string_attr(product);
106usb_string_attr(manufacturer);
107usb_string_attr(serial);
108
109static ssize_t
110show_speed (struct device *dev, char *buf)
111{
112 struct usb_device *udev;
113 char *speed;
114
115 udev = to_usb_device (dev);
116
117 switch (udev->speed) {
118 case USB_SPEED_LOW:
119 speed = "1.5";
120 break;
121 case USB_SPEED_UNKNOWN:
122 case USB_SPEED_FULL:
123 speed = "12";
124 break;
125 case USB_SPEED_HIGH:
126 speed = "480";
127 break;
128 default:
129 speed = "unknown";
130 }
131 return sprintf (buf, "%s\n", speed);
132}
133static DEVICE_ATTR(speed, S_IRUGO, show_speed, NULL);
134
135static ssize_t
136show_devnum (struct device *dev, char *buf)
137{
138 struct usb_device *udev;
139
140 udev = to_usb_device (dev);
141 return sprintf (buf, "%d\n", udev->devnum);
142}
143static DEVICE_ATTR(devnum, S_IRUGO, show_devnum, NULL);
144
145static ssize_t
146show_version (struct device *dev, char *buf)
147{
148 struct usb_device *udev;
149 u16 bcdUSB;
150
151 udev = to_usb_device(dev);
152 bcdUSB = le16_to_cpu(udev->descriptor.bcdUSB);
153 return sprintf(buf, "%2x.%02x\n", bcdUSB >> 8, bcdUSB & 0xff);
154}
155static DEVICE_ATTR(version, S_IRUGO, show_version, NULL);
156
157static ssize_t
158show_maxchild (struct device *dev, char *buf)
159{
160 struct usb_device *udev;
161
162 udev = to_usb_device (dev);
163 return sprintf (buf, "%d\n", udev->maxchild);
164}
165static DEVICE_ATTR(maxchild, S_IRUGO, show_maxchild, NULL);
166
167/* Descriptor fields */
168#define usb_descriptor_attr_le16(field, format_string) \
169static ssize_t \
170show_##field (struct device *dev, char *buf) \
171{ \
172 struct usb_device *udev; \
173 \
174 udev = to_usb_device (dev); \
175 return sprintf (buf, format_string, \
176 le16_to_cpu(udev->descriptor.field)); \
177} \
178static DEVICE_ATTR(field, S_IRUGO, show_##field, NULL);
179
180usb_descriptor_attr_le16(idVendor, "%04x\n")
181usb_descriptor_attr_le16(idProduct, "%04x\n")
182usb_descriptor_attr_le16(bcdDevice, "%04x\n")
183
184#define usb_descriptor_attr(field, format_string) \
185static ssize_t \
186show_##field (struct device *dev, char *buf) \
187{ \
188 struct usb_device *udev; \
189 \
190 udev = to_usb_device (dev); \
191 return sprintf (buf, format_string, udev->descriptor.field); \
192} \
193static DEVICE_ATTR(field, S_IRUGO, show_##field, NULL);
194
195usb_descriptor_attr (bDeviceClass, "%02x\n")
196usb_descriptor_attr (bDeviceSubClass, "%02x\n")
197usb_descriptor_attr (bDeviceProtocol, "%02x\n")
198usb_descriptor_attr (bNumConfigurations, "%d\n")
199
200static struct attribute *dev_attrs[] = {
201 /* current configuration's attributes */
202 &dev_attr_bNumInterfaces.attr,
203 &dev_attr_bConfigurationValue.attr,
204 &dev_attr_bmAttributes.attr,
205 &dev_attr_bMaxPower.attr,
206 /* device attributes */
207 &dev_attr_idVendor.attr,
208 &dev_attr_idProduct.attr,
209 &dev_attr_bcdDevice.attr,
210 &dev_attr_bDeviceClass.attr,
211 &dev_attr_bDeviceSubClass.attr,
212 &dev_attr_bDeviceProtocol.attr,
213 &dev_attr_bNumConfigurations.attr,
214 &dev_attr_speed.attr,
215 &dev_attr_devnum.attr,
216 &dev_attr_version.attr,
217 &dev_attr_maxchild.attr,
218 NULL,
219};
220static struct attribute_group dev_attr_grp = {
221 .attrs = dev_attrs,
222};
223
224void usb_create_sysfs_dev_files (struct usb_device *udev)
225{
226 struct device *dev = &udev->dev;
227
228 sysfs_create_group(&dev->kobj, &dev_attr_grp);
229
230 if (udev->manufacturer)
231 device_create_file (dev, &dev_attr_manufacturer);
232 if (udev->product)
233 device_create_file (dev, &dev_attr_product);
234 if (udev->serial)
235 device_create_file (dev, &dev_attr_serial);
236 device_create_file (dev, &dev_attr_configuration);
237}
238
239void usb_remove_sysfs_dev_files (struct usb_device *udev)
240{
241 struct device *dev = &udev->dev;
242
243 sysfs_remove_group(&dev->kobj, &dev_attr_grp);
244
245 if (udev->descriptor.iManufacturer)
246 device_remove_file(dev, &dev_attr_manufacturer);
247 if (udev->descriptor.iProduct)
248 device_remove_file(dev, &dev_attr_product);
249 if (udev->descriptor.iSerialNumber)
250 device_remove_file(dev, &dev_attr_serial);
251 device_remove_file (dev, &dev_attr_configuration);
252}
253
254/* Interface fields */
255#define usb_intf_attr(field, format_string) \
256static ssize_t \
257show_##field (struct device *dev, char *buf) \
258{ \
259 struct usb_interface *intf = to_usb_interface (dev); \
260 \
261 return sprintf (buf, format_string, intf->cur_altsetting->desc.field); \
262} \
263static DEVICE_ATTR(field, S_IRUGO, show_##field, NULL);
264
265usb_intf_attr (bInterfaceNumber, "%02x\n")
266usb_intf_attr (bAlternateSetting, "%2d\n")
267usb_intf_attr (bNumEndpoints, "%02x\n")
268usb_intf_attr (bInterfaceClass, "%02x\n")
269usb_intf_attr (bInterfaceSubClass, "%02x\n")
270usb_intf_attr (bInterfaceProtocol, "%02x\n")
271
272static ssize_t show_interface_string(struct device *dev, char *buf)
273{
274 struct usb_interface *intf;
275 struct usb_device *udev;
276 int len;
277
278 intf = to_usb_interface (dev);
279 udev = interface_to_usbdev (intf);
280 len = snprintf(buf, 256, "%s", intf->cur_altsetting->string);
281 if (len < 0)
282 return 0;
283 buf[len] = '\n';
284 buf[len+1] = 0;
285 return len+1;
286}
287static DEVICE_ATTR(interface, S_IRUGO, show_interface_string, NULL);
288
289static struct attribute *intf_attrs[] = {
290 &dev_attr_bInterfaceNumber.attr,
291 &dev_attr_bAlternateSetting.attr,
292 &dev_attr_bNumEndpoints.attr,
293 &dev_attr_bInterfaceClass.attr,
294 &dev_attr_bInterfaceSubClass.attr,
295 &dev_attr_bInterfaceProtocol.attr,
296 NULL,
297};
298static struct attribute_group intf_attr_grp = {
299 .attrs = intf_attrs,
300};
301
302void usb_create_sysfs_intf_files (struct usb_interface *intf)
303{
304 sysfs_create_group(&intf->dev.kobj, &intf_attr_grp);
305
306 if (intf->cur_altsetting->string)
307 device_create_file(&intf->dev, &dev_attr_interface);
308
309}
310
311void usb_remove_sysfs_intf_files (struct usb_interface *intf)
312{
313 sysfs_remove_group(&intf->dev.kobj, &intf_attr_grp);
314
315 if (intf->cur_altsetting->string)
316 device_remove_file(&intf->dev, &dev_attr_interface);
317
318}
diff --git a/drivers/usb/core/urb.c b/drivers/usb/core/urb.c
new file mode 100644
index 000000000000..dc838f81742c
--- /dev/null
+++ b/drivers/usb/core/urb.c
@@ -0,0 +1,511 @@
1#include <linux/config.h>
2#include <linux/module.h>
3#include <linux/string.h>
4#include <linux/bitops.h>
5#include <linux/slab.h>
6#include <linux/init.h>
7
8#ifdef CONFIG_USB_DEBUG
9 #define DEBUG
10#else
11 #undef DEBUG
12#endif
13#include <linux/usb.h>
14#include "hcd.h"
15
16#define to_urb(d) container_of(d, struct urb, kref)
17
18static void urb_destroy(struct kref *kref)
19{
20 struct urb *urb = to_urb(kref);
21 kfree(urb);
22}
23
24/**
25 * usb_init_urb - initializes a urb so that it can be used by a USB driver
26 * @urb: pointer to the urb to initialize
27 *
28 * Initializes a urb so that the USB subsystem can use it properly.
29 *
30 * If a urb is created with a call to usb_alloc_urb() it is not
31 * necessary to call this function. Only use this if you allocate the
32 * space for a struct urb on your own. If you call this function, be
33 * careful when freeing the memory for your urb that it is no longer in
34 * use by the USB core.
35 *
36 * Only use this function if you _really_ understand what you are doing.
37 */
38void usb_init_urb(struct urb *urb)
39{
40 if (urb) {
41 memset(urb, 0, sizeof(*urb));
42 kref_init(&urb->kref);
43 spin_lock_init(&urb->lock);
44 }
45}
46
47/**
48 * usb_alloc_urb - creates a new urb for a USB driver to use
49 * @iso_packets: number of iso packets for this urb
50 * @mem_flags: the type of memory to allocate, see kmalloc() for a list of
51 * valid options for this.
52 *
53 * Creates an urb for the USB driver to use, initializes a few internal
54 * structures, incrementes the usage counter, and returns a pointer to it.
55 *
56 * If no memory is available, NULL is returned.
57 *
58 * If the driver want to use this urb for interrupt, control, or bulk
59 * endpoints, pass '0' as the number of iso packets.
60 *
61 * The driver must call usb_free_urb() when it is finished with the urb.
62 */
63struct urb *usb_alloc_urb(int iso_packets, int mem_flags)
64{
65 struct urb *urb;
66
67 urb = (struct urb *)kmalloc(sizeof(struct urb) +
68 iso_packets * sizeof(struct usb_iso_packet_descriptor),
69 mem_flags);
70 if (!urb) {
71 err("alloc_urb: kmalloc failed");
72 return NULL;
73 }
74 usb_init_urb(urb);
75 return urb;
76}
77
78/**
79 * usb_free_urb - frees the memory used by a urb when all users of it are finished
80 * @urb: pointer to the urb to free, may be NULL
81 *
82 * Must be called when a user of a urb is finished with it. When the last user
83 * of the urb calls this function, the memory of the urb is freed.
84 *
85 * Note: The transfer buffer associated with the urb is not freed, that must be
86 * done elsewhere.
87 */
88void usb_free_urb(struct urb *urb)
89{
90 if (urb)
91 kref_put(&urb->kref, urb_destroy);
92}
93
94/**
95 * usb_get_urb - increments the reference count of the urb
96 * @urb: pointer to the urb to modify, may be NULL
97 *
98 * This must be called whenever a urb is transferred from a device driver to a
99 * host controller driver. This allows proper reference counting to happen
100 * for urbs.
101 *
102 * A pointer to the urb with the incremented reference counter is returned.
103 */
104struct urb * usb_get_urb(struct urb *urb)
105{
106 if (urb)
107 kref_get(&urb->kref);
108 return urb;
109}
110
111
112/*-------------------------------------------------------------------*/
113
114/**
115 * usb_submit_urb - issue an asynchronous transfer request for an endpoint
116 * @urb: pointer to the urb describing the request
117 * @mem_flags: the type of memory to allocate, see kmalloc() for a list
118 * of valid options for this.
119 *
120 * This submits a transfer request, and transfers control of the URB
121 * describing that request to the USB subsystem. Request completion will
122 * be indicated later, asynchronously, by calling the completion handler.
123 * The three types of completion are success, error, and unlink
124 * (a software-induced fault, also called "request cancelation").
125 *
126 * URBs may be submitted in interrupt context.
127 *
128 * The caller must have correctly initialized the URB before submitting
129 * it. Functions such as usb_fill_bulk_urb() and usb_fill_control_urb() are
130 * available to ensure that most fields are correctly initialized, for
131 * the particular kind of transfer, although they will not initialize
132 * any transfer flags.
133 *
134 * Successful submissions return 0; otherwise this routine returns a
135 * negative error number. If the submission is successful, the complete()
136 * callback from the URB will be called exactly once, when the USB core and
137 * Host Controller Driver (HCD) are finished with the URB. When the completion
138 * function is called, control of the URB is returned to the device
139 * driver which issued the request. The completion handler may then
140 * immediately free or reuse that URB.
141 *
142 * With few exceptions, USB device drivers should never access URB fields
143 * provided by usbcore or the HCD until its complete() is called.
144 * The exceptions relate to periodic transfer scheduling. For both
145 * interrupt and isochronous urbs, as part of successful URB submission
146 * urb->interval is modified to reflect the actual transfer period used
147 * (normally some power of two units). And for isochronous urbs,
148 * urb->start_frame is modified to reflect when the URB's transfers were
149 * scheduled to start. Not all isochronous transfer scheduling policies
150 * will work, but most host controller drivers should easily handle ISO
151 * queues going from now until 10-200 msec into the future.
152 *
153 * For control endpoints, the synchronous usb_control_msg() call is
154 * often used (in non-interrupt context) instead of this call.
155 * That is often used through convenience wrappers, for the requests
156 * that are standardized in the USB 2.0 specification. For bulk
157 * endpoints, a synchronous usb_bulk_msg() call is available.
158 *
159 * Request Queuing:
160 *
161 * URBs may be submitted to endpoints before previous ones complete, to
162 * minimize the impact of interrupt latencies and system overhead on data
163 * throughput. With that queuing policy, an endpoint's queue would never
164 * be empty. This is required for continuous isochronous data streams,
165 * and may also be required for some kinds of interrupt transfers. Such
166 * queuing also maximizes bandwidth utilization by letting USB controllers
167 * start work on later requests before driver software has finished the
168 * completion processing for earlier (successful) requests.
169 *
170 * As of Linux 2.6, all USB endpoint transfer queues support depths greater
171 * than one. This was previously a HCD-specific behavior, except for ISO
172 * transfers. Non-isochronous endpoint queues are inactive during cleanup
173 * after faults (transfer errors or cancelation).
174 *
175 * Reserved Bandwidth Transfers:
176 *
177 * Periodic transfers (interrupt or isochronous) are performed repeatedly,
178 * using the interval specified in the urb. Submitting the first urb to
179 * the endpoint reserves the bandwidth necessary to make those transfers.
180 * If the USB subsystem can't allocate sufficient bandwidth to perform
181 * the periodic request, submitting such a periodic request should fail.
182 *
183 * Device drivers must explicitly request that repetition, by ensuring that
184 * some URB is always on the endpoint's queue (except possibly for short
185 * periods during completion callacks). When there is no longer an urb
186 * queued, the endpoint's bandwidth reservation is canceled. This means
187 * drivers can use their completion handlers to ensure they keep bandwidth
188 * they need, by reinitializing and resubmitting the just-completed urb
189 * until the driver longer needs that periodic bandwidth.
190 *
191 * Memory Flags:
192 *
193 * The general rules for how to decide which mem_flags to use
194 * are the same as for kmalloc. There are four
195 * different possible values; GFP_KERNEL, GFP_NOFS, GFP_NOIO and
196 * GFP_ATOMIC.
197 *
198 * GFP_NOFS is not ever used, as it has not been implemented yet.
199 *
200 * GFP_ATOMIC is used when
201 * (a) you are inside a completion handler, an interrupt, bottom half,
202 * tasklet or timer, or
203 * (b) you are holding a spinlock or rwlock (does not apply to
204 * semaphores), or
205 * (c) current->state != TASK_RUNNING, this is the case only after
206 * you've changed it.
207 *
208 * GFP_NOIO is used in the block io path and error handling of storage
209 * devices.
210 *
211 * All other situations use GFP_KERNEL.
212 *
213 * Some more specific rules for mem_flags can be inferred, such as
214 * (1) start_xmit, timeout, and receive methods of network drivers must
215 * use GFP_ATOMIC (they are called with a spinlock held);
216 * (2) queuecommand methods of scsi drivers must use GFP_ATOMIC (also
217 * called with a spinlock held);
218 * (3) If you use a kernel thread with a network driver you must use
219 * GFP_NOIO, unless (b) or (c) apply;
220 * (4) after you have done a down() you can use GFP_KERNEL, unless (b) or (c)
221 * apply or your are in a storage driver's block io path;
222 * (5) USB probe and disconnect can use GFP_KERNEL unless (b) or (c) apply; and
223 * (6) changing firmware on a running storage or net device uses
224 * GFP_NOIO, unless b) or c) apply
225 *
226 */
227int usb_submit_urb(struct urb *urb, int mem_flags)
228{
229 int pipe, temp, max;
230 struct usb_device *dev;
231 struct usb_operations *op;
232 int is_out;
233
234 if (!urb || urb->hcpriv || !urb->complete)
235 return -EINVAL;
236 if (!(dev = urb->dev) ||
237 (dev->state < USB_STATE_DEFAULT) ||
238 (!dev->bus) || (dev->devnum <= 0))
239 return -ENODEV;
240 if (dev->state == USB_STATE_SUSPENDED)
241 return -EHOSTUNREACH;
242 if (!(op = dev->bus->op) || !op->submit_urb)
243 return -ENODEV;
244
245 urb->status = -EINPROGRESS;
246 urb->actual_length = 0;
247 urb->bandwidth = 0;
248
249 /* Lots of sanity checks, so HCDs can rely on clean data
250 * and don't need to duplicate tests
251 */
252 pipe = urb->pipe;
253 temp = usb_pipetype (pipe);
254 is_out = usb_pipeout (pipe);
255
256 if (!usb_pipecontrol (pipe) && dev->state < USB_STATE_CONFIGURED)
257 return -ENODEV;
258
259 /* FIXME there should be a sharable lock protecting us against
260 * config/altsetting changes and disconnects, kicking in here.
261 * (here == before maxpacket, and eventually endpoint type,
262 * checks get made.)
263 */
264
265 max = usb_maxpacket (dev, pipe, is_out);
266 if (max <= 0) {
267 dev_dbg(&dev->dev,
268 "bogus endpoint ep%d%s in %s (bad maxpacket %d)\n",
269 usb_pipeendpoint (pipe), is_out ? "out" : "in",
270 __FUNCTION__, max);
271 return -EMSGSIZE;
272 }
273
274 /* periodic transfers limit size per frame/uframe,
275 * but drivers only control those sizes for ISO.
276 * while we're checking, initialize return status.
277 */
278 if (temp == PIPE_ISOCHRONOUS) {
279 int n, len;
280
281 /* "high bandwidth" mode, 1-3 packets/uframe? */
282 if (dev->speed == USB_SPEED_HIGH) {
283 int mult = 1 + ((max >> 11) & 0x03);
284 max &= 0x07ff;
285 max *= mult;
286 }
287
288 if (urb->number_of_packets <= 0)
289 return -EINVAL;
290 for (n = 0; n < urb->number_of_packets; n++) {
291 len = urb->iso_frame_desc [n].length;
292 if (len < 0 || len > max)
293 return -EMSGSIZE;
294 urb->iso_frame_desc [n].status = -EXDEV;
295 urb->iso_frame_desc [n].actual_length = 0;
296 }
297 }
298
299 /* the I/O buffer must be mapped/unmapped, except when length=0 */
300 if (urb->transfer_buffer_length < 0)
301 return -EMSGSIZE;
302
303#ifdef DEBUG
304 /* stuff that drivers shouldn't do, but which shouldn't
305 * cause problems in HCDs if they get it wrong.
306 */
307 {
308 unsigned int orig_flags = urb->transfer_flags;
309 unsigned int allowed;
310
311 /* enforce simple/standard policy */
312 allowed = URB_ASYNC_UNLINK; // affects later unlinks
313 allowed |= (URB_NO_TRANSFER_DMA_MAP | URB_NO_SETUP_DMA_MAP);
314 allowed |= URB_NO_INTERRUPT;
315 switch (temp) {
316 case PIPE_BULK:
317 if (is_out)
318 allowed |= URB_ZERO_PACKET;
319 /* FALLTHROUGH */
320 case PIPE_CONTROL:
321 allowed |= URB_NO_FSBR; /* only affects UHCI */
322 /* FALLTHROUGH */
323 default: /* all non-iso endpoints */
324 if (!is_out)
325 allowed |= URB_SHORT_NOT_OK;
326 break;
327 case PIPE_ISOCHRONOUS:
328 allowed |= URB_ISO_ASAP;
329 break;
330 }
331 urb->transfer_flags &= allowed;
332
333 /* fail if submitter gave bogus flags */
334 if (urb->transfer_flags != orig_flags) {
335 err ("BOGUS urb flags, %x --> %x",
336 orig_flags, urb->transfer_flags);
337 return -EINVAL;
338 }
339 }
340#endif
341 /*
342 * Force periodic transfer intervals to be legal values that are
343 * a power of two (so HCDs don't need to).
344 *
345 * FIXME want bus->{intr,iso}_sched_horizon values here. Each HC
346 * supports different values... this uses EHCI/UHCI defaults (and
347 * EHCI can use smaller non-default values).
348 */
349 switch (temp) {
350 case PIPE_ISOCHRONOUS:
351 case PIPE_INTERRUPT:
352 /* too small? */
353 if (urb->interval <= 0)
354 return -EINVAL;
355 /* too big? */
356 switch (dev->speed) {
357 case USB_SPEED_HIGH: /* units are microframes */
358 // NOTE usb handles 2^15
359 if (urb->interval > (1024 * 8))
360 urb->interval = 1024 * 8;
361 temp = 1024 * 8;
362 break;
363 case USB_SPEED_FULL: /* units are frames/msec */
364 case USB_SPEED_LOW:
365 if (temp == PIPE_INTERRUPT) {
366 if (urb->interval > 255)
367 return -EINVAL;
368 // NOTE ohci only handles up to 32
369 temp = 128;
370 } else {
371 if (urb->interval > 1024)
372 urb->interval = 1024;
373 // NOTE usb and ohci handle up to 2^15
374 temp = 1024;
375 }
376 break;
377 default:
378 return -EINVAL;
379 }
380 /* power of two? */
381 while (temp > urb->interval)
382 temp >>= 1;
383 urb->interval = temp;
384 }
385
386 return op->submit_urb (urb, mem_flags);
387}
388
389/*-------------------------------------------------------------------*/
390
391/**
392 * usb_unlink_urb - abort/cancel a transfer request for an endpoint
393 * @urb: pointer to urb describing a previously submitted request,
394 * may be NULL
395 *
396 * This routine cancels an in-progress request. URBs complete only
397 * once per submission, and may be canceled only once per submission.
398 * Successful cancelation means the requests's completion handler will
399 * be called with a status code indicating that the request has been
400 * canceled (rather than any other code) and will quickly be removed
401 * from host controller data structures.
402 *
403 * In the past, clearing the URB_ASYNC_UNLINK transfer flag for the
404 * URB indicated that the request was synchronous. This usage is now
405 * deprecated; if the flag is clear the call will be forwarded to
406 * usb_kill_urb() and the return value will be 0. In the future, drivers
407 * should call usb_kill_urb() directly for synchronous unlinking.
408 *
409 * When the URB_ASYNC_UNLINK transfer flag for the URB is set, this
410 * request is asynchronous. Success is indicated by returning -EINPROGRESS,
411 * at which time the URB will normally have been unlinked but not yet
412 * given back to the device driver. When it is called, the completion
413 * function will see urb->status == -ECONNRESET. Failure is indicated
414 * by any other return value. Unlinking will fail when the URB is not
415 * currently "linked" (i.e., it was never submitted, or it was unlinked
416 * before, or the hardware is already finished with it), even if the
417 * completion handler has not yet run.
418 *
419 * Unlinking and Endpoint Queues:
420 *
421 * Host Controller Drivers (HCDs) place all the URBs for a particular
422 * endpoint in a queue. Normally the queue advances as the controller
423 * hardware processes each request. But when an URB terminates with any
424 * fault (such as an error, or being unlinked) its queue stops, at least
425 * until that URB's completion routine returns. It is guaranteed that
426 * the queue will not restart until all its unlinked URBs have been fully
427 * retired, with their completion routines run, even if that's not until
428 * some time after the original completion handler returns.
429 *
430 * This means that USB device drivers can safely build deep queues for
431 * large or complex transfers, and clean them up reliably after any sort
432 * of aborted transfer by unlinking all pending URBs at the first fault.
433 *
434 * Note that an URB terminating early because a short packet was received
435 * will count as an error if and only if the URB_SHORT_NOT_OK flag is set.
436 * Also, that all unlinks performed in any URB completion handler must
437 * be asynchronous.
438 *
439 * Queues for isochronous endpoints are treated differently, because they
440 * advance at fixed rates. Such queues do not stop when an URB is unlinked.
441 * An unlinked URB may leave a gap in the stream of packets. It is undefined
442 * whether such gaps can be filled in.
443 *
444 * When a control URB terminates with an error, it is likely that the
445 * status stage of the transfer will not take place, even if it is merely
446 * a soft error resulting from a short-packet with URB_SHORT_NOT_OK set.
447 */
448int usb_unlink_urb(struct urb *urb)
449{
450 if (!urb)
451 return -EINVAL;
452 if (!(urb->transfer_flags & URB_ASYNC_UNLINK)) {
453#ifdef CONFIG_DEBUG_KERNEL
454 if (printk_ratelimit()) {
455 printk(KERN_NOTICE "usb_unlink_urb() is deprecated for "
456 "synchronous unlinks. Use usb_kill_urb() instead.\n");
457 WARN_ON(1);
458 }
459#endif
460 usb_kill_urb(urb);
461 return 0;
462 }
463 if (!(urb->dev && urb->dev->bus && urb->dev->bus->op))
464 return -ENODEV;
465 return urb->dev->bus->op->unlink_urb(urb, -ECONNRESET);
466}
467
468/**
469 * usb_kill_urb - cancel a transfer request and wait for it to finish
470 * @urb: pointer to URB describing a previously submitted request,
471 * may be NULL
472 *
473 * This routine cancels an in-progress request. It is guaranteed that
474 * upon return all completion handlers will have finished and the URB
475 * will be totally idle and available for reuse. These features make
476 * this an ideal way to stop I/O in a disconnect() callback or close()
477 * function. If the request has not already finished or been unlinked
478 * the completion handler will see urb->status == -ENOENT.
479 *
480 * While the routine is running, attempts to resubmit the URB will fail
481 * with error -EPERM. Thus even if the URB's completion handler always
482 * tries to resubmit, it will not succeed and the URB will become idle.
483 *
484 * This routine may not be used in an interrupt context (such as a bottom
485 * half or a completion handler), or when holding a spinlock, or in other
486 * situations where the caller can't schedule().
487 */
488void usb_kill_urb(struct urb *urb)
489{
490 if (!(urb && urb->dev && urb->dev->bus && urb->dev->bus->op))
491 return;
492 spin_lock_irq(&urb->lock);
493 ++urb->reject;
494 spin_unlock_irq(&urb->lock);
495
496 urb->dev->bus->op->unlink_urb(urb, -ENOENT);
497 wait_event(usb_kill_urb_queue, atomic_read(&urb->use_count) == 0);
498
499 spin_lock_irq(&urb->lock);
500 --urb->reject;
501 spin_unlock_irq(&urb->lock);
502}
503
504EXPORT_SYMBOL(usb_init_urb);
505EXPORT_SYMBOL(usb_alloc_urb);
506EXPORT_SYMBOL(usb_free_urb);
507EXPORT_SYMBOL(usb_get_urb);
508EXPORT_SYMBOL(usb_submit_urb);
509EXPORT_SYMBOL(usb_unlink_urb);
510EXPORT_SYMBOL(usb_kill_urb);
511
diff --git a/drivers/usb/core/usb.c b/drivers/usb/core/usb.c
new file mode 100644
index 000000000000..f0534ee06490
--- /dev/null
+++ b/drivers/usb/core/usb.c
@@ -0,0 +1,1573 @@
1/*
2 * drivers/usb/usb.c
3 *
4 * (C) Copyright Linus Torvalds 1999
5 * (C) Copyright Johannes Erdfelt 1999-2001
6 * (C) Copyright Andreas Gal 1999
7 * (C) Copyright Gregory P. Smith 1999
8 * (C) Copyright Deti Fliegl 1999 (new USB architecture)
9 * (C) Copyright Randy Dunlap 2000
10 * (C) Copyright David Brownell 2000-2004
11 * (C) Copyright Yggdrasil Computing, Inc. 2000
12 * (usb_device_id matching changes by Adam J. Richter)
13 * (C) Copyright Greg Kroah-Hartman 2002-2003
14 *
15 * NOTE! This is not actually a driver at all, rather this is
16 * just a collection of helper routines that implement the
17 * generic USB things that the real drivers can use..
18 *
19 * Think of this as a "USB library" rather than anything else.
20 * It should be considered a slave, with no callbacks. Callbacks
21 * are evil.
22 */
23
24#include <linux/config.h>
25
26#ifdef CONFIG_USB_DEBUG
27 #define DEBUG
28#else
29 #undef DEBUG
30#endif
31
32#include <linux/module.h>
33#include <linux/string.h>
34#include <linux/bitops.h>
35#include <linux/slab.h>
36#include <linux/interrupt.h> /* for in_interrupt() */
37#include <linux/kmod.h>
38#include <linux/init.h>
39#include <linux/spinlock.h>
40#include <linux/errno.h>
41#include <linux/smp_lock.h>
42#include <linux/rwsem.h>
43#include <linux/usb.h>
44
45#include <asm/io.h>
46#include <asm/scatterlist.h>
47#include <linux/mm.h>
48#include <linux/dma-mapping.h>
49
50#include "hcd.h"
51#include "usb.h"
52
53extern int usb_hub_init(void);
54extern void usb_hub_cleanup(void);
55extern int usb_major_init(void);
56extern void usb_major_cleanup(void);
57extern int usb_host_init(void);
58extern void usb_host_cleanup(void);
59
60
61const char *usbcore_name = "usbcore";
62
63static int nousb; /* Disable USB when built into kernel image */
64 /* Not honored on modular build */
65
66static DECLARE_RWSEM(usb_all_devices_rwsem);
67
68
69static int generic_probe (struct device *dev)
70{
71 return 0;
72}
73static int generic_remove (struct device *dev)
74{
75 return 0;
76}
77
78static struct device_driver usb_generic_driver = {
79 .owner = THIS_MODULE,
80 .name = "usb",
81 .bus = &usb_bus_type,
82 .probe = generic_probe,
83 .remove = generic_remove,
84};
85
86static int usb_generic_driver_data;
87
88/* called from driver core with usb_bus_type.subsys writelock */
89static int usb_probe_interface(struct device *dev)
90{
91 struct usb_interface * intf = to_usb_interface(dev);
92 struct usb_driver * driver = to_usb_driver(dev->driver);
93 const struct usb_device_id *id;
94 int error = -ENODEV;
95
96 dev_dbg(dev, "%s\n", __FUNCTION__);
97
98 if (!driver->probe)
99 return error;
100 /* FIXME we'd much prefer to just resume it ... */
101 if (interface_to_usbdev(intf)->state == USB_STATE_SUSPENDED)
102 return -EHOSTUNREACH;
103
104 id = usb_match_id (intf, driver->id_table);
105 if (id) {
106 dev_dbg (dev, "%s - got id\n", __FUNCTION__);
107 intf->condition = USB_INTERFACE_BINDING;
108 error = driver->probe (intf, id);
109 intf->condition = error ? USB_INTERFACE_UNBOUND :
110 USB_INTERFACE_BOUND;
111 }
112
113 return error;
114}
115
116/* called from driver core with usb_bus_type.subsys writelock */
117static int usb_unbind_interface(struct device *dev)
118{
119 struct usb_interface *intf = to_usb_interface(dev);
120 struct usb_driver *driver = to_usb_driver(intf->dev.driver);
121
122 intf->condition = USB_INTERFACE_UNBINDING;
123
124 /* release all urbs for this interface */
125 usb_disable_interface(interface_to_usbdev(intf), intf);
126
127 if (driver && driver->disconnect)
128 driver->disconnect(intf);
129
130 /* reset other interface state */
131 usb_set_interface(interface_to_usbdev(intf),
132 intf->altsetting[0].desc.bInterfaceNumber,
133 0);
134 usb_set_intfdata(intf, NULL);
135 intf->condition = USB_INTERFACE_UNBOUND;
136
137 return 0;
138}
139
140/**
141 * usb_register - register a USB driver
142 * @new_driver: USB operations for the driver
143 *
144 * Registers a USB driver with the USB core. The list of unattached
145 * interfaces will be rescanned whenever a new driver is added, allowing
146 * the new driver to attach to any recognized devices.
147 * Returns a negative error code on failure and 0 on success.
148 *
149 * NOTE: if you want your driver to use the USB major number, you must call
150 * usb_register_dev() to enable that functionality. This function no longer
151 * takes care of that.
152 */
153int usb_register(struct usb_driver *new_driver)
154{
155 int retval = 0;
156
157 if (nousb)
158 return -ENODEV;
159
160 new_driver->driver.name = (char *)new_driver->name;
161 new_driver->driver.bus = &usb_bus_type;
162 new_driver->driver.probe = usb_probe_interface;
163 new_driver->driver.remove = usb_unbind_interface;
164 new_driver->driver.owner = new_driver->owner;
165
166 usb_lock_all_devices();
167 retval = driver_register(&new_driver->driver);
168 usb_unlock_all_devices();
169
170 if (!retval) {
171 pr_info("%s: registered new driver %s\n",
172 usbcore_name, new_driver->name);
173 usbfs_update_special();
174 } else {
175 printk(KERN_ERR "%s: error %d registering driver %s\n",
176 usbcore_name, retval, new_driver->name);
177 }
178
179 return retval;
180}
181
182/**
183 * usb_deregister - unregister a USB driver
184 * @driver: USB operations of the driver to unregister
185 * Context: must be able to sleep
186 *
187 * Unlinks the specified driver from the internal USB driver list.
188 *
189 * NOTE: If you called usb_register_dev(), you still need to call
190 * usb_deregister_dev() to clean up your driver's allocated minor numbers,
191 * this * call will no longer do it for you.
192 */
193void usb_deregister(struct usb_driver *driver)
194{
195 pr_info("%s: deregistering driver %s\n", usbcore_name, driver->name);
196
197 usb_lock_all_devices();
198 driver_unregister (&driver->driver);
199 usb_unlock_all_devices();
200
201 usbfs_update_special();
202}
203
204/**
205 * usb_ifnum_to_if - get the interface object with a given interface number
206 * @dev: the device whose current configuration is considered
207 * @ifnum: the desired interface
208 *
209 * This walks the device descriptor for the currently active configuration
210 * and returns a pointer to the interface with that particular interface
211 * number, or null.
212 *
213 * Note that configuration descriptors are not required to assign interface
214 * numbers sequentially, so that it would be incorrect to assume that
215 * the first interface in that descriptor corresponds to interface zero.
216 * This routine helps device drivers avoid such mistakes.
217 * However, you should make sure that you do the right thing with any
218 * alternate settings available for this interfaces.
219 *
220 * Don't call this function unless you are bound to one of the interfaces
221 * on this device or you have locked the device!
222 */
223struct usb_interface *usb_ifnum_to_if(struct usb_device *dev, unsigned ifnum)
224{
225 struct usb_host_config *config = dev->actconfig;
226 int i;
227
228 if (!config)
229 return NULL;
230 for (i = 0; i < config->desc.bNumInterfaces; i++)
231 if (config->interface[i]->altsetting[0]
232 .desc.bInterfaceNumber == ifnum)
233 return config->interface[i];
234
235 return NULL;
236}
237
238/**
239 * usb_altnum_to_altsetting - get the altsetting structure with a given
240 * alternate setting number.
241 * @intf: the interface containing the altsetting in question
242 * @altnum: the desired alternate setting number
243 *
244 * This searches the altsetting array of the specified interface for
245 * an entry with the correct bAlternateSetting value and returns a pointer
246 * to that entry, or null.
247 *
248 * Note that altsettings need not be stored sequentially by number, so
249 * it would be incorrect to assume that the first altsetting entry in
250 * the array corresponds to altsetting zero. This routine helps device
251 * drivers avoid such mistakes.
252 *
253 * Don't call this function unless you are bound to the intf interface
254 * or you have locked the device!
255 */
256struct usb_host_interface *usb_altnum_to_altsetting(struct usb_interface *intf,
257 unsigned int altnum)
258{
259 int i;
260
261 for (i = 0; i < intf->num_altsetting; i++) {
262 if (intf->altsetting[i].desc.bAlternateSetting == altnum)
263 return &intf->altsetting[i];
264 }
265 return NULL;
266}
267
268/**
269 * usb_driver_claim_interface - bind a driver to an interface
270 * @driver: the driver to be bound
271 * @iface: the interface to which it will be bound; must be in the
272 * usb device's active configuration
273 * @priv: driver data associated with that interface
274 *
275 * This is used by usb device drivers that need to claim more than one
276 * interface on a device when probing (audio and acm are current examples).
277 * No device driver should directly modify internal usb_interface or
278 * usb_device structure members.
279 *
280 * Few drivers should need to use this routine, since the most natural
281 * way to bind to an interface is to return the private data from
282 * the driver's probe() method.
283 *
284 * Callers must own the device lock and the driver model's usb_bus_type.subsys
285 * writelock. So driver probe() entries don't need extra locking,
286 * but other call contexts may need to explicitly claim those locks.
287 */
288int usb_driver_claim_interface(struct usb_driver *driver,
289 struct usb_interface *iface, void* priv)
290{
291 struct device *dev = &iface->dev;
292
293 if (dev->driver)
294 return -EBUSY;
295
296 dev->driver = &driver->driver;
297 usb_set_intfdata(iface, priv);
298 iface->condition = USB_INTERFACE_BOUND;
299
300 /* if interface was already added, bind now; else let
301 * the future device_add() bind it, bypassing probe()
302 */
303 if (!list_empty (&dev->bus_list))
304 device_bind_driver(dev);
305
306 return 0;
307}
308
309/**
310 * usb_driver_release_interface - unbind a driver from an interface
311 * @driver: the driver to be unbound
312 * @iface: the interface from which it will be unbound
313 *
314 * This can be used by drivers to release an interface without waiting
315 * for their disconnect() methods to be called. In typical cases this
316 * also causes the driver disconnect() method to be called.
317 *
318 * This call is synchronous, and may not be used in an interrupt context.
319 * Callers must own the device lock and the driver model's usb_bus_type.subsys
320 * writelock. So driver disconnect() entries don't need extra locking,
321 * but other call contexts may need to explicitly claim those locks.
322 */
323void usb_driver_release_interface(struct usb_driver *driver,
324 struct usb_interface *iface)
325{
326 struct device *dev = &iface->dev;
327
328 /* this should never happen, don't release something that's not ours */
329 if (!dev->driver || dev->driver != &driver->driver)
330 return;
331
332 /* don't disconnect from disconnect(), or before dev_add() */
333 if (!list_empty (&dev->driver_list) && !list_empty (&dev->bus_list))
334 device_release_driver(dev);
335
336 dev->driver = NULL;
337 usb_set_intfdata(iface, NULL);
338 iface->condition = USB_INTERFACE_UNBOUND;
339}
340
341/**
342 * usb_match_id - find first usb_device_id matching device or interface
343 * @interface: the interface of interest
344 * @id: array of usb_device_id structures, terminated by zero entry
345 *
346 * usb_match_id searches an array of usb_device_id's and returns
347 * the first one matching the device or interface, or null.
348 * This is used when binding (or rebinding) a driver to an interface.
349 * Most USB device drivers will use this indirectly, through the usb core,
350 * but some layered driver frameworks use it directly.
351 * These device tables are exported with MODULE_DEVICE_TABLE, through
352 * modutils and "modules.usbmap", to support the driver loading
353 * functionality of USB hotplugging.
354 *
355 * What Matches:
356 *
357 * The "match_flags" element in a usb_device_id controls which
358 * members are used. If the corresponding bit is set, the
359 * value in the device_id must match its corresponding member
360 * in the device or interface descriptor, or else the device_id
361 * does not match.
362 *
363 * "driver_info" is normally used only by device drivers,
364 * but you can create a wildcard "matches anything" usb_device_id
365 * as a driver's "modules.usbmap" entry if you provide an id with
366 * only a nonzero "driver_info" field. If you do this, the USB device
367 * driver's probe() routine should use additional intelligence to
368 * decide whether to bind to the specified interface.
369 *
370 * What Makes Good usb_device_id Tables:
371 *
372 * The match algorithm is very simple, so that intelligence in
373 * driver selection must come from smart driver id records.
374 * Unless you have good reasons to use another selection policy,
375 * provide match elements only in related groups, and order match
376 * specifiers from specific to general. Use the macros provided
377 * for that purpose if you can.
378 *
379 * The most specific match specifiers use device descriptor
380 * data. These are commonly used with product-specific matches;
381 * the USB_DEVICE macro lets you provide vendor and product IDs,
382 * and you can also match against ranges of product revisions.
383 * These are widely used for devices with application or vendor
384 * specific bDeviceClass values.
385 *
386 * Matches based on device class/subclass/protocol specifications
387 * are slightly more general; use the USB_DEVICE_INFO macro, or
388 * its siblings. These are used with single-function devices
389 * where bDeviceClass doesn't specify that each interface has
390 * its own class.
391 *
392 * Matches based on interface class/subclass/protocol are the
393 * most general; they let drivers bind to any interface on a
394 * multiple-function device. Use the USB_INTERFACE_INFO
395 * macro, or its siblings, to match class-per-interface style
396 * devices (as recorded in bDeviceClass).
397 *
398 * Within those groups, remember that not all combinations are
399 * meaningful. For example, don't give a product version range
400 * without vendor and product IDs; or specify a protocol without
401 * its associated class and subclass.
402 */
403const struct usb_device_id *
404usb_match_id(struct usb_interface *interface, const struct usb_device_id *id)
405{
406 struct usb_host_interface *intf;
407 struct usb_device *dev;
408
409 /* proc_connectinfo in devio.c may call us with id == NULL. */
410 if (id == NULL)
411 return NULL;
412
413 intf = interface->cur_altsetting;
414 dev = interface_to_usbdev(interface);
415
416 /* It is important to check that id->driver_info is nonzero,
417 since an entry that is all zeroes except for a nonzero
418 id->driver_info is the way to create an entry that
419 indicates that the driver want to examine every
420 device and interface. */
421 for (; id->idVendor || id->bDeviceClass || id->bInterfaceClass ||
422 id->driver_info; id++) {
423
424 if ((id->match_flags & USB_DEVICE_ID_MATCH_VENDOR) &&
425 id->idVendor != le16_to_cpu(dev->descriptor.idVendor))
426 continue;
427
428 if ((id->match_flags & USB_DEVICE_ID_MATCH_PRODUCT) &&
429 id->idProduct != le16_to_cpu(dev->descriptor.idProduct))
430 continue;
431
432 /* No need to test id->bcdDevice_lo != 0, since 0 is never
433 greater than any unsigned number. */
434 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_LO) &&
435 (id->bcdDevice_lo > le16_to_cpu(dev->descriptor.bcdDevice)))
436 continue;
437
438 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_HI) &&
439 (id->bcdDevice_hi < le16_to_cpu(dev->descriptor.bcdDevice)))
440 continue;
441
442 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_CLASS) &&
443 (id->bDeviceClass != dev->descriptor.bDeviceClass))
444 continue;
445
446 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_SUBCLASS) &&
447 (id->bDeviceSubClass!= dev->descriptor.bDeviceSubClass))
448 continue;
449
450 if ((id->match_flags & USB_DEVICE_ID_MATCH_DEV_PROTOCOL) &&
451 (id->bDeviceProtocol != dev->descriptor.bDeviceProtocol))
452 continue;
453
454 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_CLASS) &&
455 (id->bInterfaceClass != intf->desc.bInterfaceClass))
456 continue;
457
458 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_SUBCLASS) &&
459 (id->bInterfaceSubClass != intf->desc.bInterfaceSubClass))
460 continue;
461
462 if ((id->match_flags & USB_DEVICE_ID_MATCH_INT_PROTOCOL) &&
463 (id->bInterfaceProtocol != intf->desc.bInterfaceProtocol))
464 continue;
465
466 return id;
467 }
468
469 return NULL;
470}
471
472/**
473 * usb_find_interface - find usb_interface pointer for driver and device
474 * @drv: the driver whose current configuration is considered
475 * @minor: the minor number of the desired device
476 *
477 * This walks the driver device list and returns a pointer to the interface
478 * with the matching minor. Note, this only works for devices that share the
479 * USB major number.
480 */
481struct usb_interface *usb_find_interface(struct usb_driver *drv, int minor)
482{
483 struct list_head *entry;
484 struct device *dev;
485 struct usb_interface *intf;
486
487 list_for_each(entry, &drv->driver.devices) {
488 dev = container_of(entry, struct device, driver_list);
489
490 /* can't look at usb devices, only interfaces */
491 if (dev->driver == &usb_generic_driver)
492 continue;
493
494 intf = to_usb_interface(dev);
495 if (intf->minor == -1)
496 continue;
497 if (intf->minor == minor)
498 return intf;
499 }
500
501 /* no device found that matches */
502 return NULL;
503}
504
505static int usb_device_match (struct device *dev, struct device_driver *drv)
506{
507 struct usb_interface *intf;
508 struct usb_driver *usb_drv;
509 const struct usb_device_id *id;
510
511 /* check for generic driver, which we don't match any device with */
512 if (drv == &usb_generic_driver)
513 return 0;
514
515 intf = to_usb_interface(dev);
516 usb_drv = to_usb_driver(drv);
517
518 id = usb_match_id (intf, usb_drv->id_table);
519 if (id)
520 return 1;
521
522 return 0;
523}
524
525
526#ifdef CONFIG_HOTPLUG
527
528/*
529 * USB hotplugging invokes what /proc/sys/kernel/hotplug says
530 * (normally /sbin/hotplug) when USB devices get added or removed.
531 *
532 * This invokes a user mode policy agent, typically helping to load driver
533 * or other modules, configure the device, and more. Drivers can provide
534 * a MODULE_DEVICE_TABLE to help with module loading subtasks.
535 *
536 * We're called either from khubd (the typical case) or from root hub
537 * (init, kapmd, modprobe, rmmod, etc), but the agents need to handle
538 * delays in event delivery. Use sysfs (and DEVPATH) to make sure the
539 * device (and this configuration!) are still present.
540 */
541static int usb_hotplug (struct device *dev, char **envp, int num_envp,
542 char *buffer, int buffer_size)
543{
544 struct usb_interface *intf;
545 struct usb_device *usb_dev;
546 int i = 0;
547 int length = 0;
548
549 if (!dev)
550 return -ENODEV;
551
552 /* driver is often null here; dev_dbg() would oops */
553 pr_debug ("usb %s: hotplug\n", dev->bus_id);
554
555 /* Must check driver_data here, as on remove driver is always NULL */
556 if ((dev->driver == &usb_generic_driver) ||
557 (dev->driver_data == &usb_generic_driver_data))
558 return 0;
559
560 intf = to_usb_interface(dev);
561 usb_dev = interface_to_usbdev (intf);
562
563 if (usb_dev->devnum < 0) {
564 pr_debug ("usb %s: already deleted?\n", dev->bus_id);
565 return -ENODEV;
566 }
567 if (!usb_dev->bus) {
568 pr_debug ("usb %s: bus removed?\n", dev->bus_id);
569 return -ENODEV;
570 }
571
572#ifdef CONFIG_USB_DEVICEFS
573 /* If this is available, userspace programs can directly read
574 * all the device descriptors we don't tell them about. Or
575 * even act as usermode drivers.
576 *
577 * FIXME reduce hardwired intelligence here
578 */
579 if (add_hotplug_env_var(envp, num_envp, &i,
580 buffer, buffer_size, &length,
581 "DEVICE=/proc/bus/usb/%03d/%03d",
582 usb_dev->bus->busnum, usb_dev->devnum))
583 return -ENOMEM;
584#endif
585
586 /* per-device configurations are common */
587 if (add_hotplug_env_var(envp, num_envp, &i,
588 buffer, buffer_size, &length,
589 "PRODUCT=%x/%x/%x",
590 le16_to_cpu(usb_dev->descriptor.idVendor),
591 le16_to_cpu(usb_dev->descriptor.idProduct),
592 le16_to_cpu(usb_dev->descriptor.bcdDevice)))
593 return -ENOMEM;
594
595 /* class-based driver binding models */
596 if (add_hotplug_env_var(envp, num_envp, &i,
597 buffer, buffer_size, &length,
598 "TYPE=%d/%d/%d",
599 usb_dev->descriptor.bDeviceClass,
600 usb_dev->descriptor.bDeviceSubClass,
601 usb_dev->descriptor.bDeviceProtocol))
602 return -ENOMEM;
603
604 if (usb_dev->descriptor.bDeviceClass == 0) {
605 struct usb_host_interface *alt = intf->cur_altsetting;
606
607 /* 2.4 only exposed interface zero. in 2.5, hotplug
608 * agents are called for all interfaces, and can use
609 * $DEVPATH/bInterfaceNumber if necessary.
610 */
611 if (add_hotplug_env_var(envp, num_envp, &i,
612 buffer, buffer_size, &length,
613 "INTERFACE=%d/%d/%d",
614 alt->desc.bInterfaceClass,
615 alt->desc.bInterfaceSubClass,
616 alt->desc.bInterfaceProtocol))
617 return -ENOMEM;
618
619 if (add_hotplug_env_var(envp, num_envp, &i,
620 buffer, buffer_size, &length,
621 "MODALIAS=usb:v%04Xp%04Xdl%04Xdh%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X",
622 le16_to_cpu(usb_dev->descriptor.idVendor),
623 le16_to_cpu(usb_dev->descriptor.idProduct),
624 le16_to_cpu(usb_dev->descriptor.bcdDevice),
625 le16_to_cpu(usb_dev->descriptor.bcdDevice),
626 usb_dev->descriptor.bDeviceClass,
627 usb_dev->descriptor.bDeviceSubClass,
628 usb_dev->descriptor.bDeviceProtocol,
629 alt->desc.bInterfaceClass,
630 alt->desc.bInterfaceSubClass,
631 alt->desc.bInterfaceProtocol))
632 return -ENOMEM;
633 } else {
634 if (add_hotplug_env_var(envp, num_envp, &i,
635 buffer, buffer_size, &length,
636 "MODALIAS=usb:v%04Xp%04Xdl%04Xdh%04Xdc%02Xdsc%02Xdp%02Xic*isc*ip*",
637 le16_to_cpu(usb_dev->descriptor.idVendor),
638 le16_to_cpu(usb_dev->descriptor.idProduct),
639 le16_to_cpu(usb_dev->descriptor.bcdDevice),
640 le16_to_cpu(usb_dev->descriptor.bcdDevice),
641 usb_dev->descriptor.bDeviceClass,
642 usb_dev->descriptor.bDeviceSubClass,
643 usb_dev->descriptor.bDeviceProtocol))
644 return -ENOMEM;
645 }
646
647 envp[i] = NULL;
648
649 return 0;
650}
651
652#else
653
654static int usb_hotplug (struct device *dev, char **envp,
655 int num_envp, char *buffer, int buffer_size)
656{
657 return -ENODEV;
658}
659
660#endif /* CONFIG_HOTPLUG */
661
662/**
663 * usb_release_dev - free a usb device structure when all users of it are finished.
664 * @dev: device that's been disconnected
665 *
666 * Will be called only by the device core when all users of this usb device are
667 * done.
668 */
669static void usb_release_dev(struct device *dev)
670{
671 struct usb_device *udev;
672
673 udev = to_usb_device(dev);
674
675 usb_destroy_configuration(udev);
676 usb_bus_put(udev->bus);
677 kfree(udev->product);
678 kfree(udev->manufacturer);
679 kfree(udev->serial);
680 kfree(udev);
681}
682
683/**
684 * usb_alloc_dev - usb device constructor (usbcore-internal)
685 * @parent: hub to which device is connected; null to allocate a root hub
686 * @bus: bus used to access the device
687 * @port1: one-based index of port; ignored for root hubs
688 * Context: !in_interrupt ()
689 *
690 * Only hub drivers (including virtual root hub drivers for host
691 * controllers) should ever call this.
692 *
693 * This call may not be used in a non-sleeping context.
694 */
695struct usb_device *
696usb_alloc_dev(struct usb_device *parent, struct usb_bus *bus, unsigned port1)
697{
698 struct usb_device *dev;
699
700 dev = kmalloc(sizeof(*dev), GFP_KERNEL);
701 if (!dev)
702 return NULL;
703
704 memset(dev, 0, sizeof(*dev));
705
706 bus = usb_bus_get(bus);
707 if (!bus) {
708 kfree(dev);
709 return NULL;
710 }
711
712 device_initialize(&dev->dev);
713 dev->dev.bus = &usb_bus_type;
714 dev->dev.dma_mask = bus->controller->dma_mask;
715 dev->dev.driver_data = &usb_generic_driver_data;
716 dev->dev.driver = &usb_generic_driver;
717 dev->dev.release = usb_release_dev;
718 dev->state = USB_STATE_ATTACHED;
719
720 INIT_LIST_HEAD(&dev->ep0.urb_list);
721 dev->ep0.desc.bLength = USB_DT_ENDPOINT_SIZE;
722 dev->ep0.desc.bDescriptorType = USB_DT_ENDPOINT;
723 /* ep0 maxpacket comes later, from device descriptor */
724 dev->ep_in[0] = dev->ep_out[0] = &dev->ep0;
725
726 /* Save readable and stable topology id, distinguishing devices
727 * by location for diagnostics, tools, driver model, etc. The
728 * string is a path along hub ports, from the root. Each device's
729 * dev->devpath will be stable until USB is re-cabled, and hubs
730 * are often labeled with these port numbers. The bus_id isn't
731 * as stable: bus->busnum changes easily from modprobe order,
732 * cardbus or pci hotplugging, and so on.
733 */
734 if (unlikely (!parent)) {
735 dev->devpath [0] = '0';
736
737 dev->dev.parent = bus->controller;
738 sprintf (&dev->dev.bus_id[0], "usb%d", bus->busnum);
739 } else {
740 /* match any labeling on the hubs; it's one-based */
741 if (parent->devpath [0] == '0')
742 snprintf (dev->devpath, sizeof dev->devpath,
743 "%d", port1);
744 else
745 snprintf (dev->devpath, sizeof dev->devpath,
746 "%s.%d", parent->devpath, port1);
747
748 dev->dev.parent = &parent->dev;
749 sprintf (&dev->dev.bus_id[0], "%d-%s",
750 bus->busnum, dev->devpath);
751
752 /* hub driver sets up TT records */
753 }
754
755 dev->bus = bus;
756 dev->parent = parent;
757 INIT_LIST_HEAD(&dev->filelist);
758
759 init_MUTEX(&dev->serialize);
760
761 return dev;
762}
763
764/**
765 * usb_get_dev - increments the reference count of the usb device structure
766 * @dev: the device being referenced
767 *
768 * Each live reference to a device should be refcounted.
769 *
770 * Drivers for USB interfaces should normally record such references in
771 * their probe() methods, when they bind to an interface, and release
772 * them by calling usb_put_dev(), in their disconnect() methods.
773 *
774 * A pointer to the device with the incremented reference counter is returned.
775 */
776struct usb_device *usb_get_dev(struct usb_device *dev)
777{
778 if (dev)
779 get_device(&dev->dev);
780 return dev;
781}
782
783/**
784 * usb_put_dev - release a use of the usb device structure
785 * @dev: device that's been disconnected
786 *
787 * Must be called when a user of a device is finished with it. When the last
788 * user of the device calls this function, the memory of the device is freed.
789 */
790void usb_put_dev(struct usb_device *dev)
791{
792 if (dev)
793 put_device(&dev->dev);
794}
795
796/**
797 * usb_get_intf - increments the reference count of the usb interface structure
798 * @intf: the interface being referenced
799 *
800 * Each live reference to a interface must be refcounted.
801 *
802 * Drivers for USB interfaces should normally record such references in
803 * their probe() methods, when they bind to an interface, and release
804 * them by calling usb_put_intf(), in their disconnect() methods.
805 *
806 * A pointer to the interface with the incremented reference counter is
807 * returned.
808 */
809struct usb_interface *usb_get_intf(struct usb_interface *intf)
810{
811 if (intf)
812 get_device(&intf->dev);
813 return intf;
814}
815
816/**
817 * usb_put_intf - release a use of the usb interface structure
818 * @intf: interface that's been decremented
819 *
820 * Must be called when a user of an interface is finished with it. When the
821 * last user of the interface calls this function, the memory of the interface
822 * is freed.
823 */
824void usb_put_intf(struct usb_interface *intf)
825{
826 if (intf)
827 put_device(&intf->dev);
828}
829
830
831/* USB device locking
832 *
833 * Although locking USB devices should be straightforward, it is
834 * complicated by the way the driver-model core works. When a new USB
835 * driver is registered or unregistered, the core will automatically
836 * probe or disconnect all matching interfaces on all USB devices while
837 * holding the USB subsystem writelock. There's no good way for us to
838 * tell which devices will be used or to lock them beforehand; our only
839 * option is to effectively lock all the USB devices.
840 *
841 * We do that by using a private rw-semaphore, usb_all_devices_rwsem.
842 * When locking an individual device you must first acquire the rwsem's
843 * readlock. When a driver is registered or unregistered the writelock
844 * must be held. These actions are encapsulated in the subroutines
845 * below, so all a driver needs to do is call usb_lock_device() and
846 * usb_unlock_device().
847 *
848 * Complications arise when several devices are to be locked at the same
849 * time. Only hub-aware drivers that are part of usbcore ever have to
850 * do this; nobody else needs to worry about it. The problem is that
851 * usb_lock_device() must not be called to lock a second device since it
852 * would acquire the rwsem's readlock reentrantly, leading to deadlock if
853 * another thread was waiting for the writelock. The solution is simple:
854 *
855 * When locking more than one device, call usb_lock_device()
856 * to lock the first one. Lock the others by calling
857 * down(&udev->serialize) directly.
858 *
859 * When unlocking multiple devices, use up(&udev->serialize)
860 * to unlock all but the last one. Unlock the last one by
861 * calling usb_unlock_device().
862 *
863 * When locking both a device and its parent, always lock the
864 * the parent first.
865 */
866
867/**
868 * usb_lock_device - acquire the lock for a usb device structure
869 * @udev: device that's being locked
870 *
871 * Use this routine when you don't hold any other device locks;
872 * to acquire nested inner locks call down(&udev->serialize) directly.
873 * This is necessary for proper interaction with usb_lock_all_devices().
874 */
875void usb_lock_device(struct usb_device *udev)
876{
877 down_read(&usb_all_devices_rwsem);
878 down(&udev->serialize);
879}
880
881/**
882 * usb_trylock_device - attempt to acquire the lock for a usb device structure
883 * @udev: device that's being locked
884 *
885 * Don't use this routine if you already hold a device lock;
886 * use down_trylock(&udev->serialize) instead.
887 * This is necessary for proper interaction with usb_lock_all_devices().
888 *
889 * Returns 1 if successful, 0 if contention.
890 */
891int usb_trylock_device(struct usb_device *udev)
892{
893 if (!down_read_trylock(&usb_all_devices_rwsem))
894 return 0;
895 if (down_trylock(&udev->serialize)) {
896 up_read(&usb_all_devices_rwsem);
897 return 0;
898 }
899 return 1;
900}
901
902/**
903 * usb_lock_device_for_reset - cautiously acquire the lock for a
904 * usb device structure
905 * @udev: device that's being locked
906 * @iface: interface bound to the driver making the request (optional)
907 *
908 * Attempts to acquire the device lock, but fails if the device is
909 * NOTATTACHED or SUSPENDED, or if iface is specified and the interface
910 * is neither BINDING nor BOUND. Rather than sleeping to wait for the
911 * lock, the routine polls repeatedly. This is to prevent deadlock with
912 * disconnect; in some drivers (such as usb-storage) the disconnect()
913 * callback will block waiting for a device reset to complete.
914 *
915 * Returns a negative error code for failure, otherwise 1 or 0 to indicate
916 * that the device will or will not have to be unlocked. (0 can be
917 * returned when an interface is given and is BINDING, because in that
918 * case the driver already owns the device lock.)
919 */
920int usb_lock_device_for_reset(struct usb_device *udev,
921 struct usb_interface *iface)
922{
923 if (udev->state == USB_STATE_NOTATTACHED)
924 return -ENODEV;
925 if (udev->state == USB_STATE_SUSPENDED)
926 return -EHOSTUNREACH;
927 if (iface) {
928 switch (iface->condition) {
929 case USB_INTERFACE_BINDING:
930 return 0;
931 case USB_INTERFACE_BOUND:
932 break;
933 default:
934 return -EINTR;
935 }
936 }
937
938 while (!usb_trylock_device(udev)) {
939 msleep(15);
940 if (udev->state == USB_STATE_NOTATTACHED)
941 return -ENODEV;
942 if (udev->state == USB_STATE_SUSPENDED)
943 return -EHOSTUNREACH;
944 if (iface && iface->condition != USB_INTERFACE_BOUND)
945 return -EINTR;
946 }
947 return 1;
948}
949
950/**
951 * usb_unlock_device - release the lock for a usb device structure
952 * @udev: device that's being unlocked
953 *
954 * Use this routine when releasing the only device lock you hold;
955 * to release inner nested locks call up(&udev->serialize) directly.
956 * This is necessary for proper interaction with usb_lock_all_devices().
957 */
958void usb_unlock_device(struct usb_device *udev)
959{
960 up(&udev->serialize);
961 up_read(&usb_all_devices_rwsem);
962}
963
964/**
965 * usb_lock_all_devices - acquire the lock for all usb device structures
966 *
967 * This is necessary when registering a new driver or probing a bus,
968 * since the driver-model core may try to use any usb_device.
969 */
970void usb_lock_all_devices(void)
971{
972 down_write(&usb_all_devices_rwsem);
973}
974
975/**
976 * usb_unlock_all_devices - release the lock for all usb device structures
977 */
978void usb_unlock_all_devices(void)
979{
980 up_write(&usb_all_devices_rwsem);
981}
982
983
984static struct usb_device *match_device(struct usb_device *dev,
985 u16 vendor_id, u16 product_id)
986{
987 struct usb_device *ret_dev = NULL;
988 int child;
989
990 dev_dbg(&dev->dev, "check for vendor %04x, product %04x ...\n",
991 le16_to_cpu(dev->descriptor.idVendor),
992 le16_to_cpu(dev->descriptor.idProduct));
993
994 /* see if this device matches */
995 if ((vendor_id == le16_to_cpu(dev->descriptor.idVendor)) &&
996 (product_id == le16_to_cpu(dev->descriptor.idProduct))) {
997 dev_dbg (&dev->dev, "matched this device!\n");
998 ret_dev = usb_get_dev(dev);
999 goto exit;
1000 }
1001
1002 /* look through all of the children of this device */
1003 for (child = 0; child < dev->maxchild; ++child) {
1004 if (dev->children[child]) {
1005 down(&dev->children[child]->serialize);
1006 ret_dev = match_device(dev->children[child],
1007 vendor_id, product_id);
1008 up(&dev->children[child]->serialize);
1009 if (ret_dev)
1010 goto exit;
1011 }
1012 }
1013exit:
1014 return ret_dev;
1015}
1016
1017/**
1018 * usb_find_device - find a specific usb device in the system
1019 * @vendor_id: the vendor id of the device to find
1020 * @product_id: the product id of the device to find
1021 *
1022 * Returns a pointer to a struct usb_device if such a specified usb
1023 * device is present in the system currently. The usage count of the
1024 * device will be incremented if a device is found. Make sure to call
1025 * usb_put_dev() when the caller is finished with the device.
1026 *
1027 * If a device with the specified vendor and product id is not found,
1028 * NULL is returned.
1029 */
1030struct usb_device *usb_find_device(u16 vendor_id, u16 product_id)
1031{
1032 struct list_head *buslist;
1033 struct usb_bus *bus;
1034 struct usb_device *dev = NULL;
1035
1036 down(&usb_bus_list_lock);
1037 for (buslist = usb_bus_list.next;
1038 buslist != &usb_bus_list;
1039 buslist = buslist->next) {
1040 bus = container_of(buslist, struct usb_bus, bus_list);
1041 if (!bus->root_hub)
1042 continue;
1043 usb_lock_device(bus->root_hub);
1044 dev = match_device(bus->root_hub, vendor_id, product_id);
1045 usb_unlock_device(bus->root_hub);
1046 if (dev)
1047 goto exit;
1048 }
1049exit:
1050 up(&usb_bus_list_lock);
1051 return dev;
1052}
1053
1054/**
1055 * usb_get_current_frame_number - return current bus frame number
1056 * @dev: the device whose bus is being queried
1057 *
1058 * Returns the current frame number for the USB host controller
1059 * used with the given USB device. This can be used when scheduling
1060 * isochronous requests.
1061 *
1062 * Note that different kinds of host controller have different
1063 * "scheduling horizons". While one type might support scheduling only
1064 * 32 frames into the future, others could support scheduling up to
1065 * 1024 frames into the future.
1066 */
1067int usb_get_current_frame_number(struct usb_device *dev)
1068{
1069 return dev->bus->op->get_frame_number (dev);
1070}
1071
1072/*-------------------------------------------------------------------*/
1073/*
1074 * __usb_get_extra_descriptor() finds a descriptor of specific type in the
1075 * extra field of the interface and endpoint descriptor structs.
1076 */
1077
1078int __usb_get_extra_descriptor(char *buffer, unsigned size,
1079 unsigned char type, void **ptr)
1080{
1081 struct usb_descriptor_header *header;
1082
1083 while (size >= sizeof(struct usb_descriptor_header)) {
1084 header = (struct usb_descriptor_header *)buffer;
1085
1086 if (header->bLength < 2) {
1087 printk(KERN_ERR
1088 "%s: bogus descriptor, type %d length %d\n",
1089 usbcore_name,
1090 header->bDescriptorType,
1091 header->bLength);
1092 return -1;
1093 }
1094
1095 if (header->bDescriptorType == type) {
1096 *ptr = header;
1097 return 0;
1098 }
1099
1100 buffer += header->bLength;
1101 size -= header->bLength;
1102 }
1103 return -1;
1104}
1105
1106/**
1107 * usb_buffer_alloc - allocate dma-consistent buffer for URB_NO_xxx_DMA_MAP
1108 * @dev: device the buffer will be used with
1109 * @size: requested buffer size
1110 * @mem_flags: affect whether allocation may block
1111 * @dma: used to return DMA address of buffer
1112 *
1113 * Return value is either null (indicating no buffer could be allocated), or
1114 * the cpu-space pointer to a buffer that may be used to perform DMA to the
1115 * specified device. Such cpu-space buffers are returned along with the DMA
1116 * address (through the pointer provided).
1117 *
1118 * These buffers are used with URB_NO_xxx_DMA_MAP set in urb->transfer_flags
1119 * to avoid behaviors like using "DMA bounce buffers", or tying down I/O
1120 * mapping hardware for long idle periods. The implementation varies between
1121 * platforms, depending on details of how DMA will work to this device.
1122 * Using these buffers also helps prevent cacheline sharing problems on
1123 * architectures where CPU caches are not DMA-coherent.
1124 *
1125 * When the buffer is no longer used, free it with usb_buffer_free().
1126 */
1127void *usb_buffer_alloc (
1128 struct usb_device *dev,
1129 size_t size,
1130 int mem_flags,
1131 dma_addr_t *dma
1132)
1133{
1134 if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_alloc)
1135 return NULL;
1136 return dev->bus->op->buffer_alloc (dev->bus, size, mem_flags, dma);
1137}
1138
1139/**
1140 * usb_buffer_free - free memory allocated with usb_buffer_alloc()
1141 * @dev: device the buffer was used with
1142 * @size: requested buffer size
1143 * @addr: CPU address of buffer
1144 * @dma: DMA address of buffer
1145 *
1146 * This reclaims an I/O buffer, letting it be reused. The memory must have
1147 * been allocated using usb_buffer_alloc(), and the parameters must match
1148 * those provided in that allocation request.
1149 */
1150void usb_buffer_free (
1151 struct usb_device *dev,
1152 size_t size,
1153 void *addr,
1154 dma_addr_t dma
1155)
1156{
1157 if (!dev || !dev->bus || !dev->bus->op || !dev->bus->op->buffer_free)
1158 return;
1159 dev->bus->op->buffer_free (dev->bus, size, addr, dma);
1160}
1161
1162/**
1163 * usb_buffer_map - create DMA mapping(s) for an urb
1164 * @urb: urb whose transfer_buffer/setup_packet will be mapped
1165 *
1166 * Return value is either null (indicating no buffer could be mapped), or
1167 * the parameter. URB_NO_TRANSFER_DMA_MAP and URB_NO_SETUP_DMA_MAP are
1168 * added to urb->transfer_flags if the operation succeeds. If the device
1169 * is connected to this system through a non-DMA controller, this operation
1170 * always succeeds.
1171 *
1172 * This call would normally be used for an urb which is reused, perhaps
1173 * as the target of a large periodic transfer, with usb_buffer_dmasync()
1174 * calls to synchronize memory and dma state.
1175 *
1176 * Reverse the effect of this call with usb_buffer_unmap().
1177 */
1178#if 0
1179struct urb *usb_buffer_map (struct urb *urb)
1180{
1181 struct usb_bus *bus;
1182 struct device *controller;
1183
1184 if (!urb
1185 || !urb->dev
1186 || !(bus = urb->dev->bus)
1187 || !(controller = bus->controller))
1188 return NULL;
1189
1190 if (controller->dma_mask) {
1191 urb->transfer_dma = dma_map_single (controller,
1192 urb->transfer_buffer, urb->transfer_buffer_length,
1193 usb_pipein (urb->pipe)
1194 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1195 if (usb_pipecontrol (urb->pipe))
1196 urb->setup_dma = dma_map_single (controller,
1197 urb->setup_packet,
1198 sizeof (struct usb_ctrlrequest),
1199 DMA_TO_DEVICE);
1200 // FIXME generic api broken like pci, can't report errors
1201 // if (urb->transfer_dma == DMA_ADDR_INVALID) return 0;
1202 } else
1203 urb->transfer_dma = ~0;
1204 urb->transfer_flags |= (URB_NO_TRANSFER_DMA_MAP
1205 | URB_NO_SETUP_DMA_MAP);
1206 return urb;
1207}
1208#endif /* 0 */
1209
1210/* XXX DISABLED, no users currently. If you wish to re-enable this
1211 * XXX please determine whether the sync is to transfer ownership of
1212 * XXX the buffer from device to cpu or vice verse, and thusly use the
1213 * XXX appropriate _for_{cpu,device}() method. -DaveM
1214 */
1215#if 0
1216
1217/**
1218 * usb_buffer_dmasync - synchronize DMA and CPU view of buffer(s)
1219 * @urb: urb whose transfer_buffer/setup_packet will be synchronized
1220 */
1221void usb_buffer_dmasync (struct urb *urb)
1222{
1223 struct usb_bus *bus;
1224 struct device *controller;
1225
1226 if (!urb
1227 || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1228 || !urb->dev
1229 || !(bus = urb->dev->bus)
1230 || !(controller = bus->controller))
1231 return;
1232
1233 if (controller->dma_mask) {
1234 dma_sync_single (controller,
1235 urb->transfer_dma, urb->transfer_buffer_length,
1236 usb_pipein (urb->pipe)
1237 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1238 if (usb_pipecontrol (urb->pipe))
1239 dma_sync_single (controller,
1240 urb->setup_dma,
1241 sizeof (struct usb_ctrlrequest),
1242 DMA_TO_DEVICE);
1243 }
1244}
1245#endif
1246
1247/**
1248 * usb_buffer_unmap - free DMA mapping(s) for an urb
1249 * @urb: urb whose transfer_buffer will be unmapped
1250 *
1251 * Reverses the effect of usb_buffer_map().
1252 */
1253#if 0
1254void usb_buffer_unmap (struct urb *urb)
1255{
1256 struct usb_bus *bus;
1257 struct device *controller;
1258
1259 if (!urb
1260 || !(urb->transfer_flags & URB_NO_TRANSFER_DMA_MAP)
1261 || !urb->dev
1262 || !(bus = urb->dev->bus)
1263 || !(controller = bus->controller))
1264 return;
1265
1266 if (controller->dma_mask) {
1267 dma_unmap_single (controller,
1268 urb->transfer_dma, urb->transfer_buffer_length,
1269 usb_pipein (urb->pipe)
1270 ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1271 if (usb_pipecontrol (urb->pipe))
1272 dma_unmap_single (controller,
1273 urb->setup_dma,
1274 sizeof (struct usb_ctrlrequest),
1275 DMA_TO_DEVICE);
1276 }
1277 urb->transfer_flags &= ~(URB_NO_TRANSFER_DMA_MAP
1278 | URB_NO_SETUP_DMA_MAP);
1279}
1280#endif /* 0 */
1281
1282/**
1283 * usb_buffer_map_sg - create scatterlist DMA mapping(s) for an endpoint
1284 * @dev: device to which the scatterlist will be mapped
1285 * @pipe: endpoint defining the mapping direction
1286 * @sg: the scatterlist to map
1287 * @nents: the number of entries in the scatterlist
1288 *
1289 * Return value is either < 0 (indicating no buffers could be mapped), or
1290 * the number of DMA mapping array entries in the scatterlist.
1291 *
1292 * The caller is responsible for placing the resulting DMA addresses from
1293 * the scatterlist into URB transfer buffer pointers, and for setting the
1294 * URB_NO_TRANSFER_DMA_MAP transfer flag in each of those URBs.
1295 *
1296 * Top I/O rates come from queuing URBs, instead of waiting for each one
1297 * to complete before starting the next I/O. This is particularly easy
1298 * to do with scatterlists. Just allocate and submit one URB for each DMA
1299 * mapping entry returned, stopping on the first error or when all succeed.
1300 * Better yet, use the usb_sg_*() calls, which do that (and more) for you.
1301 *
1302 * This call would normally be used when translating scatterlist requests,
1303 * rather than usb_buffer_map(), since on some hardware (with IOMMUs) it
1304 * may be able to coalesce mappings for improved I/O efficiency.
1305 *
1306 * Reverse the effect of this call with usb_buffer_unmap_sg().
1307 */
1308int usb_buffer_map_sg (struct usb_device *dev, unsigned pipe,
1309 struct scatterlist *sg, int nents)
1310{
1311 struct usb_bus *bus;
1312 struct device *controller;
1313
1314 if (!dev
1315 || usb_pipecontrol (pipe)
1316 || !(bus = dev->bus)
1317 || !(controller = bus->controller)
1318 || !controller->dma_mask)
1319 return -1;
1320
1321 // FIXME generic api broken like pci, can't report errors
1322 return dma_map_sg (controller, sg, nents,
1323 usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1324}
1325
1326/* XXX DISABLED, no users currently. If you wish to re-enable this
1327 * XXX please determine whether the sync is to transfer ownership of
1328 * XXX the buffer from device to cpu or vice verse, and thusly use the
1329 * XXX appropriate _for_{cpu,device}() method. -DaveM
1330 */
1331#if 0
1332
1333/**
1334 * usb_buffer_dmasync_sg - synchronize DMA and CPU view of scatterlist buffer(s)
1335 * @dev: device to which the scatterlist will be mapped
1336 * @pipe: endpoint defining the mapping direction
1337 * @sg: the scatterlist to synchronize
1338 * @n_hw_ents: the positive return value from usb_buffer_map_sg
1339 *
1340 * Use this when you are re-using a scatterlist's data buffers for
1341 * another USB request.
1342 */
1343void usb_buffer_dmasync_sg (struct usb_device *dev, unsigned pipe,
1344 struct scatterlist *sg, int n_hw_ents)
1345{
1346 struct usb_bus *bus;
1347 struct device *controller;
1348
1349 if (!dev
1350 || !(bus = dev->bus)
1351 || !(controller = bus->controller)
1352 || !controller->dma_mask)
1353 return;
1354
1355 dma_sync_sg (controller, sg, n_hw_ents,
1356 usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1357}
1358#endif
1359
1360/**
1361 * usb_buffer_unmap_sg - free DMA mapping(s) for a scatterlist
1362 * @dev: device to which the scatterlist will be mapped
1363 * @pipe: endpoint defining the mapping direction
1364 * @sg: the scatterlist to unmap
1365 * @n_hw_ents: the positive return value from usb_buffer_map_sg
1366 *
1367 * Reverses the effect of usb_buffer_map_sg().
1368 */
1369void usb_buffer_unmap_sg (struct usb_device *dev, unsigned pipe,
1370 struct scatterlist *sg, int n_hw_ents)
1371{
1372 struct usb_bus *bus;
1373 struct device *controller;
1374
1375 if (!dev
1376 || !(bus = dev->bus)
1377 || !(controller = bus->controller)
1378 || !controller->dma_mask)
1379 return;
1380
1381 dma_unmap_sg (controller, sg, n_hw_ents,
1382 usb_pipein (pipe) ? DMA_FROM_DEVICE : DMA_TO_DEVICE);
1383}
1384
1385static int usb_generic_suspend(struct device *dev, u32 state)
1386{
1387 struct usb_interface *intf;
1388 struct usb_driver *driver;
1389
1390 if (dev->driver == &usb_generic_driver)
1391 return usb_suspend_device (to_usb_device(dev), state);
1392
1393 if ((dev->driver == NULL) ||
1394 (dev->driver_data == &usb_generic_driver_data))
1395 return 0;
1396
1397 intf = to_usb_interface(dev);
1398 driver = to_usb_driver(dev->driver);
1399
1400 /* there's only one USB suspend state */
1401 if (intf->dev.power.power_state)
1402 return 0;
1403
1404 if (driver->suspend)
1405 return driver->suspend(intf, state);
1406 return 0;
1407}
1408
1409static int usb_generic_resume(struct device *dev)
1410{
1411 struct usb_interface *intf;
1412 struct usb_driver *driver;
1413
1414 /* devices resume through their hub */
1415 if (dev->driver == &usb_generic_driver)
1416 return usb_resume_device (to_usb_device(dev));
1417
1418 if ((dev->driver == NULL) ||
1419 (dev->driver_data == &usb_generic_driver_data))
1420 return 0;
1421
1422 intf = to_usb_interface(dev);
1423 driver = to_usb_driver(dev->driver);
1424
1425 if (driver->resume)
1426 return driver->resume(intf);
1427 return 0;
1428}
1429
1430struct bus_type usb_bus_type = {
1431 .name = "usb",
1432 .match = usb_device_match,
1433 .hotplug = usb_hotplug,
1434 .suspend = usb_generic_suspend,
1435 .resume = usb_generic_resume,
1436};
1437
1438#ifndef MODULE
1439
1440static int __init usb_setup_disable(char *str)
1441{
1442 nousb = 1;
1443 return 1;
1444}
1445
1446/* format to disable USB on kernel command line is: nousb */
1447__setup("nousb", usb_setup_disable);
1448
1449#endif
1450
1451/*
1452 * for external read access to <nousb>
1453 */
1454int usb_disabled(void)
1455{
1456 return nousb;
1457}
1458
1459/*
1460 * Init
1461 */
1462static int __init usb_init(void)
1463{
1464 int retval;
1465 if (nousb) {
1466 pr_info ("%s: USB support disabled\n", usbcore_name);
1467 return 0;
1468 }
1469
1470 retval = bus_register(&usb_bus_type);
1471 if (retval)
1472 goto out;
1473 retval = usb_host_init();
1474 if (retval)
1475 goto host_init_failed;
1476 retval = usb_major_init();
1477 if (retval)
1478 goto major_init_failed;
1479 retval = usbfs_init();
1480 if (retval)
1481 goto fs_init_failed;
1482 retval = usb_hub_init();
1483 if (retval)
1484 goto hub_init_failed;
1485
1486 retval = driver_register(&usb_generic_driver);
1487 if (!retval)
1488 goto out;
1489
1490 usb_hub_cleanup();
1491hub_init_failed:
1492 usbfs_cleanup();
1493fs_init_failed:
1494 usb_major_cleanup();
1495major_init_failed:
1496 usb_host_cleanup();
1497host_init_failed:
1498 bus_unregister(&usb_bus_type);
1499out:
1500 return retval;
1501}
1502
1503/*
1504 * Cleanup
1505 */
1506static void __exit usb_exit(void)
1507{
1508 /* This will matter if shutdown/reboot does exitcalls. */
1509 if (nousb)
1510 return;
1511
1512 driver_unregister(&usb_generic_driver);
1513 usb_major_cleanup();
1514 usbfs_cleanup();
1515 usb_hub_cleanup();
1516 usb_host_cleanup();
1517 bus_unregister(&usb_bus_type);
1518}
1519
1520subsys_initcall(usb_init);
1521module_exit(usb_exit);
1522
1523/*
1524 * USB may be built into the kernel or be built as modules.
1525 * These symbols are exported for device (or host controller)
1526 * driver modules to use.
1527 */
1528
1529EXPORT_SYMBOL(usb_register);
1530EXPORT_SYMBOL(usb_deregister);
1531EXPORT_SYMBOL(usb_disabled);
1532
1533EXPORT_SYMBOL(usb_alloc_dev);
1534EXPORT_SYMBOL(usb_put_dev);
1535EXPORT_SYMBOL(usb_get_dev);
1536EXPORT_SYMBOL(usb_hub_tt_clear_buffer);
1537
1538EXPORT_SYMBOL(usb_lock_device);
1539EXPORT_SYMBOL(usb_trylock_device);
1540EXPORT_SYMBOL(usb_lock_device_for_reset);
1541EXPORT_SYMBOL(usb_unlock_device);
1542
1543EXPORT_SYMBOL(usb_driver_claim_interface);
1544EXPORT_SYMBOL(usb_driver_release_interface);
1545EXPORT_SYMBOL(usb_match_id);
1546EXPORT_SYMBOL(usb_find_interface);
1547EXPORT_SYMBOL(usb_ifnum_to_if);
1548EXPORT_SYMBOL(usb_altnum_to_altsetting);
1549
1550EXPORT_SYMBOL(usb_reset_device);
1551EXPORT_SYMBOL(usb_disconnect);
1552
1553EXPORT_SYMBOL(__usb_get_extra_descriptor);
1554
1555EXPORT_SYMBOL(usb_find_device);
1556EXPORT_SYMBOL(usb_get_current_frame_number);
1557
1558EXPORT_SYMBOL (usb_buffer_alloc);
1559EXPORT_SYMBOL (usb_buffer_free);
1560
1561#if 0
1562EXPORT_SYMBOL (usb_buffer_map);
1563EXPORT_SYMBOL (usb_buffer_dmasync);
1564EXPORT_SYMBOL (usb_buffer_unmap);
1565#endif
1566
1567EXPORT_SYMBOL (usb_buffer_map_sg);
1568#if 0
1569EXPORT_SYMBOL (usb_buffer_dmasync_sg);
1570#endif
1571EXPORT_SYMBOL (usb_buffer_unmap_sg);
1572
1573MODULE_LICENSE("GPL");
diff --git a/drivers/usb/core/usb.h b/drivers/usb/core/usb.h
new file mode 100644
index 000000000000..4c33eee52001
--- /dev/null
+++ b/drivers/usb/core/usb.h
@@ -0,0 +1,46 @@
1/* Functions local to drivers/usb/core/ */
2
3extern void usb_create_sysfs_dev_files (struct usb_device *dev);
4extern void usb_remove_sysfs_dev_files (struct usb_device *dev);
5extern void usb_create_sysfs_intf_files (struct usb_interface *intf);
6extern void usb_remove_sysfs_intf_files (struct usb_interface *intf);
7
8extern void usb_disable_endpoint (struct usb_device *dev, unsigned int epaddr);
9extern void usb_disable_interface (struct usb_device *dev,
10 struct usb_interface *intf);
11extern void usb_release_interface_cache(struct kref *ref);
12extern void usb_disable_device (struct usb_device *dev, int skip_ep0);
13
14extern int usb_get_device_descriptor(struct usb_device *dev,
15 unsigned int size);
16extern int usb_set_configuration(struct usb_device *dev, int configuration);
17
18extern void usb_lock_all_devices(void);
19extern void usb_unlock_all_devices(void);
20
21extern void usb_kick_khubd(struct usb_device *dev);
22extern void usb_resume_root_hub(struct usb_device *dev);
23
24/* for labeling diagnostics */
25extern const char *usbcore_name;
26
27/* usbfs stuff */
28extern struct usb_driver usbfs_driver;
29extern struct file_operations usbfs_devices_fops;
30extern struct file_operations usbfs_device_file_operations;
31extern void usbfs_conn_disc_event(void);
32
33struct dev_state {
34 struct list_head list; /* state list */
35 struct usb_device *dev;
36 struct file *file;
37 spinlock_t lock; /* protects the async urb lists */
38 struct list_head async_pending;
39 struct list_head async_completed;
40 wait_queue_head_t wait; /* wake up if a request completed */
41 unsigned int discsignr;
42 struct task_struct *disctask;
43 void __user *disccontext;
44 unsigned long ifclaimed;
45};
46