]> git.proxmox.com Git - mirror_ubuntu-eoan-kernel.git/blame - drivers/usb/core/message.c
USB: host: ohci-at91: fix non static symbol warning
[mirror_ubuntu-eoan-kernel.git] / drivers / usb / core / message.c
CommitLineData
1da177e4
LT
1/*
2 * message.c - synchronous message handling
3 */
4
1da177e4
LT
5#include <linux/pci.h> /* for scatterlist macros */
6#include <linux/usb.h>
7#include <linux/module.h>
8#include <linux/slab.h>
1da177e4
LT
9#include <linux/mm.h>
10#include <linux/timer.h>
11#include <linux/ctype.h>
a853a3d4 12#include <linux/nls.h>
1da177e4 13#include <linux/device.h>
11763609 14#include <linux/scatterlist.h>
e4c6fb77 15#include <linux/usb/cdc.h>
7ceec1f1 16#include <linux/usb/quirks.h>
27729aad 17#include <linux/usb/hcd.h> /* for usbcore internals */
1da177e4
LT
18#include <asm/byteorder.h>
19
1da177e4
LT
20#include "usb.h"
21
df718962
AS
22static void cancel_async_set_config(struct usb_device *udev);
23
67f5dde3
AS
24struct api_context {
25 struct completion done;
26 int status;
27};
28
7d12e780 29static void usb_api_blocking_completion(struct urb *urb)
1da177e4 30{
67f5dde3
AS
31 struct api_context *ctx = urb->context;
32
33 ctx->status = urb->status;
34 complete(&ctx->done);
1da177e4
LT
35}
36
37
ecdc0a59
FBH
38/*
39 * Starts urb and waits for completion or timeout. Note that this call
40 * is NOT interruptible. Many device driver i/o requests should be
41 * interruptible and therefore these drivers should implement their
42 * own interruptible routines.
43 */
44static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
3e35bf39 45{
67f5dde3 46 struct api_context ctx;
ecdc0a59 47 unsigned long expire;
3fc3e826 48 int retval;
1da177e4 49
67f5dde3
AS
50 init_completion(&ctx.done);
51 urb->context = &ctx;
1da177e4 52 urb->actual_length = 0;
3fc3e826
GKH
53 retval = usb_submit_urb(urb, GFP_NOIO);
54 if (unlikely(retval))
ecdc0a59 55 goto out;
1da177e4 56
ecdc0a59 57 expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
67f5dde3
AS
58 if (!wait_for_completion_timeout(&ctx.done, expire)) {
59 usb_kill_urb(urb);
60 retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
ecdc0a59
FBH
61
62 dev_dbg(&urb->dev->dev,
71d2718f 63 "%s timed out on ep%d%s len=%u/%u\n",
ecdc0a59 64 current->comm,
5e60a161
AS
65 usb_endpoint_num(&urb->ep->desc),
66 usb_urb_dir_in(urb) ? "in" : "out",
ecdc0a59
FBH
67 urb->actual_length,
68 urb->transfer_buffer_length);
ecdc0a59 69 } else
67f5dde3 70 retval = ctx.status;
ecdc0a59 71out:
1da177e4
LT
72 if (actual_length)
73 *actual_length = urb->actual_length;
ecdc0a59 74
1da177e4 75 usb_free_urb(urb);
3fc3e826 76 return retval;
1da177e4
LT
77}
78
79/*-------------------------------------------------------------------*/
3e35bf39 80/* returns status (negative) or length (positive) */
1da177e4 81static int usb_internal_control_msg(struct usb_device *usb_dev,
3e35bf39 82 unsigned int pipe,
1da177e4
LT
83 struct usb_ctrlrequest *cmd,
84 void *data, int len, int timeout)
85{
86 struct urb *urb;
87 int retv;
88 int length;
89
90 urb = usb_alloc_urb(0, GFP_NOIO);
91 if (!urb)
92 return -ENOMEM;
3e35bf39 93
1da177e4
LT
94 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
95 len, usb_api_blocking_completion, NULL);
96
97 retv = usb_start_wait_urb(urb, timeout, &length);
98 if (retv < 0)
99 return retv;
100 else
101 return length;
102}
103
104/**
3e35bf39
GKH
105 * usb_control_msg - Builds a control urb, sends it off and waits for completion
106 * @dev: pointer to the usb device to send the message to
107 * @pipe: endpoint "pipe" to send the message to
108 * @request: USB message request value
109 * @requesttype: USB message request type value
110 * @value: USB message value
111 * @index: USB message index value
112 * @data: pointer to the data to send
113 * @size: length in bytes of the data to send
114 * @timeout: time in msecs to wait for the message to complete before timing
115 * out (if 0 the wait is forever)
116 *
117 * Context: !in_interrupt ()
118 *
119 * This function sends a simple control message to a specified endpoint and
120 * waits for the message to complete, or timeout.
121 *
3e35bf39
GKH
122 * Don't use this function from within an interrupt context, like a bottom half
123 * handler. If you need an asynchronous message, or need to send a message
124 * from within interrupt context, use usb_submit_urb().
125 * If a thread in your driver uses this call, make sure your disconnect()
126 * method can wait for it to complete. Since you don't have a handle on the
127 * URB used, you can't cancel the request.
626f090c
YB
128 *
129 * Return: If successful, the number of bytes transferred. Otherwise, a negative
130 * error number.
1da177e4 131 */
3e35bf39
GKH
132int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
133 __u8 requesttype, __u16 value, __u16 index, void *data,
134 __u16 size, int timeout)
1da177e4 135{
3e35bf39 136 struct usb_ctrlrequest *dr;
1da177e4 137 int ret;
3e35bf39
GKH
138
139 dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
1da177e4
LT
140 if (!dr)
141 return -ENOMEM;
142
3e35bf39 143 dr->bRequestType = requesttype;
1da177e4 144 dr->bRequest = request;
da2bbdcc
HH
145 dr->wValue = cpu_to_le16(value);
146 dr->wIndex = cpu_to_le16(index);
147 dr->wLength = cpu_to_le16(size);
1da177e4 148
1da177e4
LT
149 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
150
151 kfree(dr);
152
153 return ret;
154}
782e70c6 155EXPORT_SYMBOL_GPL(usb_control_msg);
1da177e4 156
782a7a63
GKH
157/**
158 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
159 * @usb_dev: pointer to the usb device to send the message to
160 * @pipe: endpoint "pipe" to send the message to
161 * @data: pointer to the data to send
162 * @len: length in bytes of the data to send
3e35bf39
GKH
163 * @actual_length: pointer to a location to put the actual length transferred
164 * in bytes
782a7a63
GKH
165 * @timeout: time in msecs to wait for the message to complete before
166 * timing out (if 0 the wait is forever)
3e35bf39 167 *
782a7a63
GKH
168 * Context: !in_interrupt ()
169 *
170 * This function sends a simple interrupt message to a specified endpoint and
171 * waits for the message to complete, or timeout.
172 *
782a7a63
GKH
173 * Don't use this function from within an interrupt context, like a bottom half
174 * handler. If you need an asynchronous message, or need to send a message
175 * from within interrupt context, use usb_submit_urb() If a thread in your
176 * driver uses this call, make sure your disconnect() method can wait for it to
177 * complete. Since you don't have a handle on the URB used, you can't cancel
178 * the request.
626f090c
YB
179 *
180 * Return:
181 * If successful, 0. Otherwise a negative error number. The number of actual
e227867f 182 * bytes transferred will be stored in the @actual_length parameter.
782a7a63
GKH
183 */
184int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
185 void *data, int len, int *actual_length, int timeout)
186{
187 return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
188}
189EXPORT_SYMBOL_GPL(usb_interrupt_msg);
190
1da177e4 191/**
3e35bf39
GKH
192 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
193 * @usb_dev: pointer to the usb device to send the message to
194 * @pipe: endpoint "pipe" to send the message to
195 * @data: pointer to the data to send
196 * @len: length in bytes of the data to send
197 * @actual_length: pointer to a location to put the actual length transferred
198 * in bytes
199 * @timeout: time in msecs to wait for the message to complete before
200 * timing out (if 0 the wait is forever)
201 *
202 * Context: !in_interrupt ()
203 *
204 * This function sends a simple bulk message to a specified endpoint
205 * and waits for the message to complete, or timeout.
206 *
3e35bf39
GKH
207 * Don't use this function from within an interrupt context, like a bottom half
208 * handler. If you need an asynchronous message, or need to send a message
209 * from within interrupt context, use usb_submit_urb() If a thread in your
210 * driver uses this call, make sure your disconnect() method can wait for it to
211 * complete. Since you don't have a handle on the URB used, you can't cancel
212 * the request.
213 *
214 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
215 * users are forced to abuse this routine by using it to submit URBs for
216 * interrupt endpoints. We will take the liberty of creating an interrupt URB
217 * (with the default interval) if the target is an interrupt endpoint.
626f090c
YB
218 *
219 * Return:
220 * If successful, 0. Otherwise a negative error number. The number of actual
025d4430 221 * bytes transferred will be stored in the @actual_length parameter.
626f090c 222 *
1da177e4 223 */
3e35bf39
GKH
224int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
225 void *data, int len, int *actual_length, int timeout)
1da177e4
LT
226{
227 struct urb *urb;
d09d36a9 228 struct usb_host_endpoint *ep;
1da177e4 229
fe54b058 230 ep = usb_pipe_endpoint(usb_dev, pipe);
d09d36a9 231 if (!ep || len < 0)
1da177e4
LT
232 return -EINVAL;
233
d09d36a9 234 urb = usb_alloc_urb(0, GFP_KERNEL);
1da177e4
LT
235 if (!urb)
236 return -ENOMEM;
237
d09d36a9
AS
238 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
239 USB_ENDPOINT_XFER_INT) {
240 pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
241 usb_fill_int_urb(urb, usb_dev, pipe, data, len,
8d062b9a
AS
242 usb_api_blocking_completion, NULL,
243 ep->desc.bInterval);
d09d36a9
AS
244 } else
245 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
246 usb_api_blocking_completion, NULL);
1da177e4
LT
247
248 return usb_start_wait_urb(urb, timeout, actual_length);
249}
782e70c6 250EXPORT_SYMBOL_GPL(usb_bulk_msg);
1da177e4
LT
251
252/*-------------------------------------------------------------------*/
253
3e35bf39 254static void sg_clean(struct usb_sg_request *io)
1da177e4
LT
255{
256 if (io->urbs) {
257 while (io->entries--)
085528e5 258 usb_free_urb(io->urbs[io->entries]);
3e35bf39 259 kfree(io->urbs);
1da177e4
LT
260 io->urbs = NULL;
261 }
1da177e4
LT
262 io->dev = NULL;
263}
264
3e35bf39 265static void sg_complete(struct urb *urb)
1da177e4 266{
3e35bf39 267 struct usb_sg_request *io = urb->context;
3fc3e826 268 int status = urb->status;
1da177e4 269
3e35bf39 270 spin_lock(&io->lock);
1da177e4
LT
271
272 /* In 2.5 we require hcds' endpoint queues not to progress after fault
273 * reports, until the completion callback (this!) returns. That lets
274 * device driver code (like this routine) unlink queued urbs first,
275 * if it needs to, since the HC won't work on them at all. So it's
276 * not possible for page N+1 to overwrite page N, and so on.
277 *
278 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
279 * complete before the HCD can get requests away from hardware,
280 * though never during cleanup after a hard fault.
281 */
282 if (io->status
283 && (io->status != -ECONNRESET
3fc3e826 284 || status != -ECONNRESET)
1da177e4 285 && urb->actual_length) {
3e35bf39 286 dev_err(io->dev->bus->controller,
1da177e4
LT
287 "dev %s ep%d%s scatterlist error %d/%d\n",
288 io->dev->devpath,
5e60a161
AS
289 usb_endpoint_num(&urb->ep->desc),
290 usb_urb_dir_in(urb) ? "in" : "out",
3fc3e826 291 status, io->status);
3e35bf39 292 /* BUG (); */
1da177e4
LT
293 }
294
3fc3e826
GKH
295 if (io->status == 0 && status && status != -ECONNRESET) {
296 int i, found, retval;
1da177e4 297
3fc3e826 298 io->status = status;
1da177e4
LT
299
300 /* the previous urbs, and this one, completed already.
301 * unlink pending urbs so they won't rx/tx bad data.
302 * careful: unlink can sometimes be synchronous...
303 */
3e35bf39 304 spin_unlock(&io->lock);
1da177e4 305 for (i = 0, found = 0; i < io->entries; i++) {
98b74b0e 306 if (!io->urbs[i])
1da177e4
LT
307 continue;
308 if (found) {
98b74b0e 309 usb_block_urb(io->urbs[i]);
085528e5 310 retval = usb_unlink_urb(io->urbs[i]);
3fc3e826
GKH
311 if (retval != -EINPROGRESS &&
312 retval != -ENODEV &&
bcf39853
AS
313 retval != -EBUSY &&
314 retval != -EIDRM)
3e35bf39 315 dev_err(&io->dev->dev,
1da177e4 316 "%s, unlink --> %d\n",
441b62c1 317 __func__, retval);
085528e5 318 } else if (urb == io->urbs[i])
1da177e4
LT
319 found = 1;
320 }
3e35bf39 321 spin_lock(&io->lock);
1da177e4 322 }
1da177e4
LT
323
324 /* on the last completion, signal usb_sg_wait() */
325 io->bytes += urb->actual_length;
326 io->count--;
327 if (!io->count)
3e35bf39 328 complete(&io->complete);
1da177e4 329
3e35bf39 330 spin_unlock(&io->lock);
1da177e4
LT
331}
332
333
334/**
335 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
336 * @io: request block being initialized. until usb_sg_wait() returns,
337 * treat this as a pointer to an opaque block of memory,
338 * @dev: the usb device that will send or receive the data
339 * @pipe: endpoint "pipe" used to transfer the data
340 * @period: polling rate for interrupt endpoints, in frames or
341 * (for high speed endpoints) microframes; ignored for bulk
342 * @sg: scatterlist entries
343 * @nents: how many entries in the scatterlist
344 * @length: how many bytes to send from the scatterlist, or zero to
345 * send every byte identified in the list.
346 * @mem_flags: SLAB_* flags affecting memory allocations in this call
347 *
626f090c
YB
348 * This initializes a scatter/gather request, allocating resources such as
349 * I/O mappings and urb memory (except maybe memory used by USB controller
350 * drivers).
1da177e4
LT
351 *
352 * The request must be issued using usb_sg_wait(), which waits for the I/O to
353 * complete (or to be canceled) and then cleans up all resources allocated by
354 * usb_sg_init().
355 *
356 * The request may be canceled with usb_sg_cancel(), either before or after
357 * usb_sg_wait() is called.
626f090c
YB
358 *
359 * Return: Zero for success, else a negative errno value.
1da177e4 360 */
3e35bf39
GKH
361int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
362 unsigned pipe, unsigned period, struct scatterlist *sg,
363 int nents, size_t length, gfp_t mem_flags)
1da177e4 364{
3e35bf39
GKH
365 int i;
366 int urb_flags;
e04748e3 367 int use_sg;
1da177e4
LT
368
369 if (!io || !dev || !sg
3e35bf39
GKH
370 || usb_pipecontrol(pipe)
371 || usb_pipeisoc(pipe)
1da177e4
LT
372 || nents <= 0)
373 return -EINVAL;
374
3e35bf39 375 spin_lock_init(&io->lock);
1da177e4
LT
376 io->dev = dev;
377 io->pipe = pipe;
1da177e4 378
4c1bd3d7 379 if (dev->bus->sg_tablesize > 0) {
e04748e3 380 use_sg = true;
0ba169af 381 io->entries = 1;
e04748e3 382 } else {
e04748e3 383 use_sg = false;
0ba169af 384 io->entries = nents;
e04748e3 385 }
0ba169af
AS
386
387 /* initialize all the urbs we'll use */
a1fefaab 388 io->urbs = kmalloc(io->entries * sizeof(*io->urbs), mem_flags);
1da177e4
LT
389 if (!io->urbs)
390 goto nomem;
391
0ba169af 392 urb_flags = URB_NO_INTERRUPT;
3e35bf39 393 if (usb_pipein(pipe))
1da177e4
LT
394 urb_flags |= URB_SHORT_NOT_OK;
395
0ba169af
AS
396 for_each_sg(sg, sg, io->entries, i) {
397 struct urb *urb;
398 unsigned len;
ff9c895f 399
0ba169af
AS
400 urb = usb_alloc_urb(0, mem_flags);
401 if (!urb) {
402 io->entries = i;
403 goto nomem;
e04748e3 404 }
0ba169af
AS
405 io->urbs[i] = urb;
406
407 urb->dev = NULL;
408 urb->pipe = pipe;
409 urb->interval = period;
410 urb->transfer_flags = urb_flags;
411 urb->complete = sg_complete;
412 urb->context = io;
413 urb->sg = sg;
414
415 if (use_sg) {
416 /* There is no single transfer buffer */
417 urb->transfer_buffer = NULL;
418 urb->num_sgs = nents;
419
420 /* A length of zero means transfer the whole sg list */
421 len = length;
422 if (len == 0) {
64d65872
AS
423 struct scatterlist *sg2;
424 int j;
425
426 for_each_sg(sg, sg2, nents, j)
427 len += sg2->length;
e04748e3 428 }
0ba169af 429 } else {
e04748e3 430 /*
ff9c895f
AS
431 * Some systems can't use DMA; they use PIO instead.
432 * For their sakes, transfer_buffer is set whenever
433 * possible.
e04748e3 434 */
ff9c895f 435 if (!PageHighMem(sg_page(sg)))
0ba169af 436 urb->transfer_buffer = sg_virt(sg);
81bf46f3 437 else
0ba169af 438 urb->transfer_buffer = NULL;
81bf46f3 439
ff9c895f 440 len = sg->length;
e04748e3 441 if (length) {
edb2b255 442 len = min_t(size_t, len, length);
e04748e3
SS
443 length -= len;
444 if (length == 0)
445 io->entries = i + 1;
446 }
1da177e4 447 }
0ba169af 448 urb->transfer_buffer_length = len;
1da177e4 449 }
0ba169af 450 io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
1da177e4
LT
451
452 /* transaction state */
580da348 453 io->count = io->entries;
1da177e4
LT
454 io->status = 0;
455 io->bytes = 0;
3e35bf39 456 init_completion(&io->complete);
1da177e4
LT
457 return 0;
458
459nomem:
3e35bf39 460 sg_clean(io);
1da177e4
LT
461 return -ENOMEM;
462}
782e70c6 463EXPORT_SYMBOL_GPL(usb_sg_init);
1da177e4
LT
464
465/**
466 * usb_sg_wait - synchronously execute scatter/gather request
467 * @io: request block handle, as initialized with usb_sg_init().
468 * some fields become accessible when this call returns.
469 * Context: !in_interrupt ()
470 *
471 * This function blocks until the specified I/O operation completes. It
472 * leverages the grouping of the related I/O requests to get good transfer
473 * rates, by queueing the requests. At higher speeds, such queuing can
474 * significantly improve USB throughput.
475 *
476 * There are three kinds of completion for this function.
477 * (1) success, where io->status is zero. The number of io->bytes
478 * transferred is as requested.
479 * (2) error, where io->status is a negative errno value. The number
480 * of io->bytes transferred before the error is usually less
481 * than requested, and can be nonzero.
093cf723 482 * (3) cancellation, a type of error with status -ECONNRESET that
1da177e4
LT
483 * is initiated by usb_sg_cancel().
484 *
485 * When this function returns, all memory allocated through usb_sg_init() or
486 * this call will have been freed. The request block parameter may still be
487 * passed to usb_sg_cancel(), or it may be freed. It could also be
488 * reinitialized and then reused.
489 *
490 * Data Transfer Rates:
491 *
492 * Bulk transfers are valid for full or high speed endpoints.
493 * The best full speed data rate is 19 packets of 64 bytes each
494 * per frame, or 1216 bytes per millisecond.
495 * The best high speed data rate is 13 packets of 512 bytes each
496 * per microframe, or 52 KBytes per millisecond.
497 *
498 * The reason to use interrupt transfers through this API would most likely
499 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
500 * could be transferred. That capability is less useful for low or full
501 * speed interrupt endpoints, which allow at most one packet per millisecond,
502 * of at most 8 or 64 bytes (respectively).
79abb1ab
SS
503 *
504 * It is not necessary to call this function to reserve bandwidth for devices
505 * under an xHCI host controller, as the bandwidth is reserved when the
506 * configuration or interface alt setting is selected.
1da177e4 507 */
3e35bf39 508void usb_sg_wait(struct usb_sg_request *io)
1da177e4 509{
3e35bf39
GKH
510 int i;
511 int entries = io->entries;
1da177e4
LT
512
513 /* queue the urbs. */
3e35bf39 514 spin_lock_irq(&io->lock);
8ccef0df
AS
515 i = 0;
516 while (i < entries && !io->status) {
3e35bf39 517 int retval;
1da177e4 518
3e35bf39 519 io->urbs[i]->dev = io->dev;
3e35bf39 520 spin_unlock_irq(&io->lock);
98b74b0e
DM
521
522 retval = usb_submit_urb(io->urbs[i], GFP_NOIO);
523
1da177e4
LT
524 switch (retval) {
525 /* maybe we retrying will recover */
3e35bf39 526 case -ENXIO: /* hc didn't queue this one */
1da177e4
LT
527 case -EAGAIN:
528 case -ENOMEM:
1da177e4 529 retval = 0;
3e35bf39 530 yield();
1da177e4
LT
531 break;
532
533 /* no error? continue immediately.
534 *
535 * NOTE: to work better with UHCI (4K I/O buffer may
536 * need 3K of TDs) it may be good to limit how many
537 * URBs are queued at once; N milliseconds?
538 */
539 case 0:
8ccef0df 540 ++i;
3e35bf39 541 cpu_relax();
1da177e4
LT
542 break;
543
544 /* fail any uncompleted urbs */
545 default:
3e35bf39
GKH
546 io->urbs[i]->status = retval;
547 dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
441b62c1 548 __func__, retval);
3e35bf39 549 usb_sg_cancel(io);
1da177e4 550 }
3e35bf39 551 spin_lock_irq(&io->lock);
1da177e4
LT
552 if (retval && (io->status == 0 || io->status == -ECONNRESET))
553 io->status = retval;
554 }
555 io->count -= entries - i;
556 if (io->count == 0)
3e35bf39
GKH
557 complete(&io->complete);
558 spin_unlock_irq(&io->lock);
1da177e4
LT
559
560 /* OK, yes, this could be packaged as non-blocking.
561 * So could the submit loop above ... but it's easier to
562 * solve neither problem than to solve both!
563 */
3e35bf39 564 wait_for_completion(&io->complete);
1da177e4 565
3e35bf39 566 sg_clean(io);
1da177e4 567}
782e70c6 568EXPORT_SYMBOL_GPL(usb_sg_wait);
1da177e4
LT
569
570/**
571 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
572 * @io: request block, initialized with usb_sg_init()
573 *
574 * This stops a request after it has been started by usb_sg_wait().
575 * It can also prevents one initialized by usb_sg_init() from starting,
576 * so that call just frees resources allocated to the request.
577 */
3e35bf39 578void usb_sg_cancel(struct usb_sg_request *io)
1da177e4 579{
3e35bf39 580 unsigned long flags;
5f2e5fb8 581 int i, retval;
1da177e4 582
3e35bf39 583 spin_lock_irqsave(&io->lock, flags);
5f2e5fb8
DM
584 if (io->status) {
585 spin_unlock_irqrestore(&io->lock, flags);
586 return;
587 }
588 /* shut everything down */
589 io->status = -ECONNRESET;
590 spin_unlock_irqrestore(&io->lock, flags);
1da177e4 591
5f2e5fb8
DM
592 for (i = io->entries - 1; i >= 0; --i) {
593 usb_block_urb(io->urbs[i]);
1da177e4 594
5f2e5fb8
DM
595 retval = usb_unlink_urb(io->urbs[i]);
596 if (retval != -EINPROGRESS
597 && retval != -ENODEV
598 && retval != -EBUSY
599 && retval != -EIDRM)
600 dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
601 __func__, retval);
1da177e4 602 }
1da177e4 603}
782e70c6 604EXPORT_SYMBOL_GPL(usb_sg_cancel);
1da177e4
LT
605
606/*-------------------------------------------------------------------*/
607
608/**
609 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
610 * @dev: the device whose descriptor is being retrieved
611 * @type: the descriptor type (USB_DT_*)
612 * @index: the number of the descriptor
613 * @buf: where to put the descriptor
614 * @size: how big is "buf"?
615 * Context: !in_interrupt ()
616 *
617 * Gets a USB descriptor. Convenience functions exist to simplify
618 * getting some types of descriptors. Use
619 * usb_get_string() or usb_string() for USB_DT_STRING.
620 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
621 * are part of the device structure.
622 * In addition to a number of USB-standard descriptors, some
623 * devices also use class-specific or vendor-specific descriptors.
624 *
625 * This call is synchronous, and may not be used in an interrupt context.
626 *
626f090c 627 * Return: The number of bytes received on success, or else the status code
1da177e4
LT
628 * returned by the underlying usb_control_msg() call.
629 */
3e35bf39
GKH
630int usb_get_descriptor(struct usb_device *dev, unsigned char type,
631 unsigned char index, void *buf, int size)
1da177e4
LT
632{
633 int i;
634 int result;
3e35bf39
GKH
635
636 memset(buf, 0, size); /* Make sure we parse really received data */
1da177e4
LT
637
638 for (i = 0; i < 3; ++i) {
c39772d8 639 /* retry on length 0 or error; some devices are flakey */
1da177e4
LT
640 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
641 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
642 (type << 8) + index, 0, buf, size,
643 USB_CTRL_GET_TIMEOUT);
c39772d8 644 if (result <= 0 && result != -ETIMEDOUT)
1da177e4
LT
645 continue;
646 if (result > 1 && ((u8 *)buf)[1] != type) {
67f5a4ba 647 result = -ENODATA;
1da177e4
LT
648 continue;
649 }
650 break;
651 }
652 return result;
653}
782e70c6 654EXPORT_SYMBOL_GPL(usb_get_descriptor);
1da177e4
LT
655
656/**
657 * usb_get_string - gets a string descriptor
658 * @dev: the device whose string descriptor is being retrieved
659 * @langid: code for language chosen (from string descriptor zero)
660 * @index: the number of the descriptor
661 * @buf: where to put the string
662 * @size: how big is "buf"?
663 * Context: !in_interrupt ()
664 *
665 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
666 * in little-endian byte order).
667 * The usb_string() function will often be a convenient way to turn
668 * these strings into kernel-printable form.
669 *
670 * Strings may be referenced in device, configuration, interface, or other
671 * descriptors, and could also be used in vendor-specific ways.
672 *
673 * This call is synchronous, and may not be used in an interrupt context.
674 *
626f090c 675 * Return: The number of bytes received on success, or else the status code
1da177e4
LT
676 * returned by the underlying usb_control_msg() call.
677 */
e266a124
AB
678static int usb_get_string(struct usb_device *dev, unsigned short langid,
679 unsigned char index, void *buf, int size)
1da177e4
LT
680{
681 int i;
682 int result;
683
684 for (i = 0; i < 3; ++i) {
685 /* retry on length 0 or stall; some devices are flakey */
686 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
687 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
688 (USB_DT_STRING << 8) + index, langid, buf, size,
689 USB_CTRL_GET_TIMEOUT);
67f5a4ba
AS
690 if (result == 0 || result == -EPIPE)
691 continue;
692 if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
693 result = -ENODATA;
694 continue;
695 }
696 break;
1da177e4
LT
697 }
698 return result;
699}
700
701static void usb_try_string_workarounds(unsigned char *buf, int *length)
702{
703 int newlength, oldlength = *length;
704
705 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
706 if (!isprint(buf[newlength]) || buf[newlength + 1])
707 break;
708
709 if (newlength > 2) {
710 buf[0] = newlength;
711 *length = newlength;
712 }
713}
714
715static int usb_string_sub(struct usb_device *dev, unsigned int langid,
3e35bf39 716 unsigned int index, unsigned char *buf)
1da177e4
LT
717{
718 int rc;
719
720 /* Try to read the string descriptor by asking for the maximum
721 * possible number of bytes */
7ceec1f1
ON
722 if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
723 rc = -EIO;
724 else
725 rc = usb_get_string(dev, langid, index, buf, 255);
1da177e4
LT
726
727 /* If that failed try to read the descriptor length, then
728 * ask for just that many bytes */
729 if (rc < 2) {
730 rc = usb_get_string(dev, langid, index, buf, 2);
731 if (rc == 2)
732 rc = usb_get_string(dev, langid, index, buf, buf[0]);
733 }
734
735 if (rc >= 2) {
736 if (!buf[0] && !buf[1])
737 usb_try_string_workarounds(buf, &rc);
738
739 /* There might be extra junk at the end of the descriptor */
740 if (buf[0] < rc)
741 rc = buf[0];
742
743 rc = rc - (rc & 1); /* force a multiple of two */
744 }
745
746 if (rc < 2)
747 rc = (rc < 0 ? rc : -EINVAL);
748
749 return rc;
750}
751
0cce2eda
DM
752static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
753{
754 int err;
755
756 if (dev->have_langid)
757 return 0;
758
759 if (dev->string_langid < 0)
760 return -EPIPE;
761
762 err = usb_string_sub(dev, 0, 0, tbuf);
763
764 /* If the string was reported but is malformed, default to english
765 * (0x0409) */
766 if (err == -ENODATA || (err > 0 && err < 4)) {
767 dev->string_langid = 0x0409;
768 dev->have_langid = 1;
769 dev_err(&dev->dev,
586af079 770 "language id specifier not provided by device, defaulting to English\n");
0cce2eda
DM
771 return 0;
772 }
773
774 /* In case of all other errors, we assume the device is not able to
775 * deal with strings at all. Set string_langid to -1 in order to
776 * prevent any string to be retrieved from the device */
777 if (err < 0) {
778 dev_err(&dev->dev, "string descriptor 0 read error: %d\n",
779 err);
780 dev->string_langid = -1;
781 return -EPIPE;
782 }
783
784 /* always use the first langid listed */
785 dev->string_langid = tbuf[2] | (tbuf[3] << 8);
786 dev->have_langid = 1;
787 dev_dbg(&dev->dev, "default language 0x%04x\n",
788 dev->string_langid);
789 return 0;
790}
791
1da177e4 792/**
a853a3d4 793 * usb_string - returns UTF-8 version of a string descriptor
1da177e4
LT
794 * @dev: the device whose string descriptor is being retrieved
795 * @index: the number of the descriptor
796 * @buf: where to put the string
797 * @size: how big is "buf"?
798 * Context: !in_interrupt ()
3e35bf39 799 *
1da177e4 800 * This converts the UTF-16LE encoded strings returned by devices, from
a853a3d4
CL
801 * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
802 * that are more usable in most kernel contexts. Note that this function
1da177e4
LT
803 * chooses strings in the first language supported by the device.
804 *
1da177e4
LT
805 * This call is synchronous, and may not be used in an interrupt context.
806 *
626f090c 807 * Return: length of the string (>= 0) or usb_control_msg status (< 0).
1da177e4
LT
808 */
809int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
810{
811 unsigned char *tbuf;
812 int err;
1da177e4
LT
813
814 if (dev->state == USB_STATE_SUSPENDED)
815 return -EHOSTUNREACH;
816 if (size <= 0 || !buf || !index)
817 return -EINVAL;
818 buf[0] = 0;
74675a58 819 tbuf = kmalloc(256, GFP_NOIO);
1da177e4
LT
820 if (!tbuf)
821 return -ENOMEM;
822
0cce2eda
DM
823 err = usb_get_langid(dev, tbuf);
824 if (err < 0)
825 goto errout;
3e35bf39 826
1da177e4
LT
827 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
828 if (err < 0)
829 goto errout;
830
831 size--; /* leave room for trailing NULL char in output buffer */
74675a58
AS
832 err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
833 UTF16_LITTLE_ENDIAN, buf, size);
a853a3d4 834 buf[err] = 0;
1da177e4
LT
835
836 if (tbuf[1] != USB_DT_STRING)
3e35bf39
GKH
837 dev_dbg(&dev->dev,
838 "wrong descriptor type %02x for string %d (\"%s\")\n",
839 tbuf[1], index, buf);
1da177e4
LT
840
841 errout:
842 kfree(tbuf);
843 return err;
844}
782e70c6 845EXPORT_SYMBOL_GPL(usb_string);
1da177e4 846
a853a3d4
CL
847/* one UTF-8-encoded 16-bit character has at most three bytes */
848#define MAX_USB_STRING_SIZE (127 * 3 + 1)
849
4f62efe6
AS
850/**
851 * usb_cache_string - read a string descriptor and cache it for later use
852 * @udev: the device whose string descriptor is being read
853 * @index: the descriptor index
854 *
626f090c
YB
855 * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
856 * or %NULL if the index is 0 or the string could not be read.
4f62efe6
AS
857 */
858char *usb_cache_string(struct usb_device *udev, int index)
859{
860 char *buf;
861 char *smallbuf = NULL;
862 int len;
863
3e35bf39
GKH
864 if (index <= 0)
865 return NULL;
866
acbe2feb 867 buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
3e35bf39 868 if (buf) {
a853a3d4 869 len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
3e35bf39 870 if (len > 0) {
acbe2feb 871 smallbuf = kmalloc(++len, GFP_NOIO);
3e35bf39 872 if (!smallbuf)
4f62efe6
AS
873 return buf;
874 memcpy(smallbuf, buf, len);
875 }
876 kfree(buf);
877 }
878 return smallbuf;
879}
880
1da177e4
LT
881/*
882 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
883 * @dev: the device whose device descriptor is being updated
884 * @size: how much of the descriptor to read
885 * Context: !in_interrupt ()
886 *
887 * Updates the copy of the device descriptor stored in the device structure,
6ab16a90 888 * which dedicates space for this purpose.
1da177e4
LT
889 *
890 * Not exported, only for use by the core. If drivers really want to read
891 * the device descriptor directly, they can call usb_get_descriptor() with
892 * type = USB_DT_DEVICE and index = 0.
893 *
894 * This call is synchronous, and may not be used in an interrupt context.
895 *
626f090c 896 * Return: The number of bytes received on success, or else the status code
1da177e4
LT
897 * returned by the underlying usb_control_msg() call.
898 */
899int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
900{
901 struct usb_device_descriptor *desc;
902 int ret;
903
904 if (size > sizeof(*desc))
905 return -EINVAL;
906 desc = kmalloc(sizeof(*desc), GFP_NOIO);
907 if (!desc)
908 return -ENOMEM;
909
910 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
3e35bf39 911 if (ret >= 0)
1da177e4
LT
912 memcpy(&dev->descriptor, desc, size);
913 kfree(desc);
914 return ret;
915}
916
917/**
918 * usb_get_status - issues a GET_STATUS call
919 * @dev: the device whose status is being checked
920 * @type: USB_RECIP_*; for device, interface, or endpoint
921 * @target: zero (for device), else interface or endpoint number
922 * @data: pointer to two bytes of bitmap data
923 * Context: !in_interrupt ()
924 *
925 * Returns device, interface, or endpoint status. Normally only of
926 * interest to see if the device is self powered, or has enabled the
927 * remote wakeup facility; or whether a bulk or interrupt endpoint
928 * is halted ("stalled").
929 *
930 * Bits in these status bitmaps are set using the SET_FEATURE request,
931 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
932 * function should be used to clear halt ("stall") status.
933 *
934 * This call is synchronous, and may not be used in an interrupt context.
935 *
15b7336e
AS
936 * Returns 0 and the status value in *@data (in host byte order) on success,
937 * or else the status code from the underlying usb_control_msg() call.
1da177e4
LT
938 */
939int usb_get_status(struct usb_device *dev, int type, int target, void *data)
940{
941 int ret;
15b7336e 942 __le16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
1da177e4
LT
943
944 if (!status)
945 return -ENOMEM;
946
947 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
948 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
949 sizeof(*status), USB_CTRL_GET_TIMEOUT);
950
15b7336e
AS
951 if (ret == 2) {
952 *(u16 *) data = le16_to_cpu(*status);
953 ret = 0;
954 } else if (ret >= 0) {
955 ret = -EIO;
956 }
1da177e4
LT
957 kfree(status);
958 return ret;
959}
782e70c6 960EXPORT_SYMBOL_GPL(usb_get_status);
1da177e4
LT
961
962/**
963 * usb_clear_halt - tells device to clear endpoint halt/stall condition
964 * @dev: device whose endpoint is halted
965 * @pipe: endpoint "pipe" being cleared
966 * Context: !in_interrupt ()
967 *
968 * This is used to clear halt conditions for bulk and interrupt endpoints,
969 * as reported by URB completion status. Endpoints that are halted are
970 * sometimes referred to as being "stalled". Such endpoints are unable
971 * to transmit or receive data until the halt status is cleared. Any URBs
972 * queued for such an endpoint should normally be unlinked by the driver
973 * before clearing the halt condition, as described in sections 5.7.5
974 * and 5.8.5 of the USB 2.0 spec.
975 *
976 * Note that control and isochronous endpoints don't halt, although control
977 * endpoints report "protocol stall" (for unsupported requests) using the
978 * same status code used to report a true stall.
979 *
980 * This call is synchronous, and may not be used in an interrupt context.
981 *
626f090c 982 * Return: Zero on success, or else the status code returned by the
1da177e4
LT
983 * underlying usb_control_msg() call.
984 */
985int usb_clear_halt(struct usb_device *dev, int pipe)
986{
987 int result;
988 int endp = usb_pipeendpoint(pipe);
3e35bf39
GKH
989
990 if (usb_pipein(pipe))
1da177e4
LT
991 endp |= USB_DIR_IN;
992
993 /* we don't care if it wasn't halted first. in fact some devices
994 * (like some ibmcam model 1 units) seem to expect hosts to make
995 * this request for iso endpoints, which can't halt!
996 */
997 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
998 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
999 USB_ENDPOINT_HALT, endp, NULL, 0,
1000 USB_CTRL_SET_TIMEOUT);
1001
1002 /* don't un-halt or force to DATA0 except on success */
1003 if (result < 0)
1004 return result;
1005
1006 /* NOTE: seems like Microsoft and Apple don't bother verifying
1007 * the clear "took", so some devices could lock up if you check...
1008 * such as the Hagiwara FlashGate DUAL. So we won't bother.
1009 *
1010 * NOTE: make sure the logic here doesn't diverge much from
1011 * the copy in usb-storage, for as long as we need two copies.
1012 */
1013
3444b26a 1014 usb_reset_endpoint(dev, endp);
1da177e4
LT
1015
1016 return 0;
1017}
782e70c6 1018EXPORT_SYMBOL_GPL(usb_clear_halt);
1da177e4 1019
3b23dd6f
AS
1020static int create_intf_ep_devs(struct usb_interface *intf)
1021{
1022 struct usb_device *udev = interface_to_usbdev(intf);
1023 struct usb_host_interface *alt = intf->cur_altsetting;
1024 int i;
1025
1026 if (intf->ep_devs_created || intf->unregistering)
1027 return 0;
1028
1029 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1030 (void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
1031 intf->ep_devs_created = 1;
1032 return 0;
1033}
1034
1035static void remove_intf_ep_devs(struct usb_interface *intf)
1036{
1037 struct usb_host_interface *alt = intf->cur_altsetting;
1038 int i;
1039
1040 if (!intf->ep_devs_created)
1041 return;
1042
1043 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1044 usb_remove_ep_devs(&alt->endpoint[i]);
1045 intf->ep_devs_created = 0;
1046}
1047
1da177e4
LT
1048/**
1049 * usb_disable_endpoint -- Disable an endpoint by address
1050 * @dev: the device whose endpoint is being disabled
1051 * @epaddr: the endpoint's address. Endpoint number for output,
1052 * endpoint number + USB_DIR_IN for input
ddeac4e7
AS
1053 * @reset_hardware: flag to erase any endpoint state stored in the
1054 * controller hardware
1da177e4 1055 *
ddeac4e7
AS
1056 * Disables the endpoint for URB submission and nukes all pending URBs.
1057 * If @reset_hardware is set then also deallocates hcd/hardware state
1058 * for the endpoint.
1da177e4 1059 */
ddeac4e7
AS
1060void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
1061 bool reset_hardware)
1da177e4
LT
1062{
1063 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1064 struct usb_host_endpoint *ep;
1065
1066 if (!dev)
1067 return;
1068
1069 if (usb_endpoint_out(epaddr)) {
1070 ep = dev->ep_out[epnum];
ddeac4e7
AS
1071 if (reset_hardware)
1072 dev->ep_out[epnum] = NULL;
1da177e4
LT
1073 } else {
1074 ep = dev->ep_in[epnum];
ddeac4e7
AS
1075 if (reset_hardware)
1076 dev->ep_in[epnum] = NULL;
1da177e4 1077 }
bdd016ba
AS
1078 if (ep) {
1079 ep->enabled = 0;
95cf82f9 1080 usb_hcd_flush_endpoint(dev, ep);
ddeac4e7
AS
1081 if (reset_hardware)
1082 usb_hcd_disable_endpoint(dev, ep);
bdd016ba 1083 }
1da177e4
LT
1084}
1085
3444b26a
DV
1086/**
1087 * usb_reset_endpoint - Reset an endpoint's state.
1088 * @dev: the device whose endpoint is to be reset
1089 * @epaddr: the endpoint's address. Endpoint number for output,
1090 * endpoint number + USB_DIR_IN for input
1091 *
1092 * Resets any host-side endpoint state such as the toggle bit,
1093 * sequence number or current window.
1094 */
1095void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
1096{
1097 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1098 struct usb_host_endpoint *ep;
1099
1100 if (usb_endpoint_out(epaddr))
1101 ep = dev->ep_out[epnum];
1102 else
1103 ep = dev->ep_in[epnum];
1104 if (ep)
1105 usb_hcd_reset_endpoint(dev, ep);
1106}
1107EXPORT_SYMBOL_GPL(usb_reset_endpoint);
1108
1109
1da177e4
LT
1110/**
1111 * usb_disable_interface -- Disable all endpoints for an interface
1112 * @dev: the device whose interface is being disabled
1113 * @intf: pointer to the interface descriptor
ddeac4e7
AS
1114 * @reset_hardware: flag to erase any endpoint state stored in the
1115 * controller hardware
1da177e4
LT
1116 *
1117 * Disables all the endpoints for the interface's current altsetting.
1118 */
ddeac4e7
AS
1119void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
1120 bool reset_hardware)
1da177e4
LT
1121{
1122 struct usb_host_interface *alt = intf->cur_altsetting;
1123 int i;
1124
1125 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1126 usb_disable_endpoint(dev,
ddeac4e7
AS
1127 alt->endpoint[i].desc.bEndpointAddress,
1128 reset_hardware);
1da177e4
LT
1129 }
1130}
1131
3e35bf39 1132/**
1da177e4
LT
1133 * usb_disable_device - Disable all the endpoints for a USB device
1134 * @dev: the device whose endpoints are being disabled
1135 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1136 *
1137 * Disables all the device's endpoints, potentially including endpoint 0.
1138 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1139 * pending urbs) and usbcore state for the interfaces, so that usbcore
1140 * must usb_set_configuration() before any interfaces could be used.
1141 */
1142void usb_disable_device(struct usb_device *dev, int skip_ep0)
1143{
1144 int i;
fccf4e86 1145 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1da177e4 1146
1da177e4
LT
1147 /* getting rid of interfaces will disconnect
1148 * any drivers bound to them (a key side effect)
1149 */
1150 if (dev->actconfig) {
ca5c485f
AS
1151 /*
1152 * FIXME: In order to avoid self-deadlock involving the
1153 * bandwidth_mutex, we have to mark all the interfaces
1154 * before unregistering any of them.
1155 */
1156 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
1157 dev->actconfig->interface[i]->unregistering = 1;
1158
1da177e4
LT
1159 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1160 struct usb_interface *interface;
1161
86d30741 1162 /* remove this interface if it has been registered */
1da177e4 1163 interface = dev->actconfig->interface[i];
d305ef5d 1164 if (!device_is_registered(&interface->dev))
86d30741 1165 continue;
3e35bf39 1166 dev_dbg(&dev->dev, "unregistering interface %s\n",
7071a3ce 1167 dev_name(&interface->dev));
3b23dd6f 1168 remove_intf_ep_devs(interface);
1a21175a 1169 device_del(&interface->dev);
1da177e4
LT
1170 }
1171
1172 /* Now that the interfaces are unbound, nobody should
1173 * try to access them.
1174 */
1175 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
3e35bf39 1176 put_device(&dev->actconfig->interface[i]->dev);
1da177e4
LT
1177 dev->actconfig->interface[i] = NULL;
1178 }
f468f7b9
SS
1179
1180 if (dev->usb2_hw_lpm_enabled == 1)
1181 usb_set_usb2_hardware_lpm(dev, 0);
24971912 1182 usb_unlocked_disable_lpm(dev);
f74631e3 1183 usb_disable_ltm(dev);
f468f7b9 1184
1da177e4
LT
1185 dev->actconfig = NULL;
1186 if (dev->state == USB_STATE_CONFIGURED)
1187 usb_set_device_state(dev, USB_STATE_ADDRESS);
1188 }
80f0cf39
AS
1189
1190 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
1191 skip_ep0 ? "non-ep0" : "all");
fccf4e86
SS
1192 if (hcd->driver->check_bandwidth) {
1193 /* First pass: Cancel URBs, leave endpoint pointers intact. */
1194 for (i = skip_ep0; i < 16; ++i) {
1195 usb_disable_endpoint(dev, i, false);
1196 usb_disable_endpoint(dev, i + USB_DIR_IN, false);
1197 }
1198 /* Remove endpoints from the host controller internal state */
8963c487 1199 mutex_lock(hcd->bandwidth_mutex);
fccf4e86 1200 usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
8963c487 1201 mutex_unlock(hcd->bandwidth_mutex);
fccf4e86
SS
1202 /* Second pass: remove endpoint pointers */
1203 }
80f0cf39
AS
1204 for (i = skip_ep0; i < 16; ++i) {
1205 usb_disable_endpoint(dev, i, true);
1206 usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1207 }
1da177e4
LT
1208}
1209
3e35bf39 1210/**
1da177e4
LT
1211 * usb_enable_endpoint - Enable an endpoint for USB communications
1212 * @dev: the device whose interface is being enabled
1213 * @ep: the endpoint
3444b26a 1214 * @reset_ep: flag to reset the endpoint state
1da177e4 1215 *
3444b26a 1216 * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
1da177e4
LT
1217 * For control endpoints, both the input and output sides are handled.
1218 */
2caf7fcd 1219void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
3444b26a 1220 bool reset_ep)
1da177e4 1221{
bdd016ba
AS
1222 int epnum = usb_endpoint_num(&ep->desc);
1223 int is_out = usb_endpoint_dir_out(&ep->desc);
1224 int is_control = usb_endpoint_xfer_control(&ep->desc);
1da177e4 1225
3444b26a
DV
1226 if (reset_ep)
1227 usb_hcd_reset_endpoint(dev, ep);
1228 if (is_out || is_control)
1da177e4 1229 dev->ep_out[epnum] = ep;
3444b26a 1230 if (!is_out || is_control)
1da177e4 1231 dev->ep_in[epnum] = ep;
bdd016ba 1232 ep->enabled = 1;
1da177e4
LT
1233}
1234
3e35bf39 1235/**
1da177e4
LT
1236 * usb_enable_interface - Enable all the endpoints for an interface
1237 * @dev: the device whose interface is being enabled
1238 * @intf: pointer to the interface descriptor
3444b26a 1239 * @reset_eps: flag to reset the endpoints' state
1da177e4
LT
1240 *
1241 * Enables all the endpoints for the interface's current altsetting.
1242 */
2caf7fcd 1243void usb_enable_interface(struct usb_device *dev,
3444b26a 1244 struct usb_interface *intf, bool reset_eps)
1da177e4
LT
1245{
1246 struct usb_host_interface *alt = intf->cur_altsetting;
1247 int i;
1248
1249 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
3444b26a 1250 usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
1da177e4
LT
1251}
1252
1253/**
1254 * usb_set_interface - Makes a particular alternate setting be current
1255 * @dev: the device whose interface is being updated
1256 * @interface: the interface being updated
1257 * @alternate: the setting being chosen.
1258 * Context: !in_interrupt ()
1259 *
1260 * This is used to enable data transfers on interfaces that may not
1261 * be enabled by default. Not all devices support such configurability.
1262 * Only the driver bound to an interface may change its setting.
1263 *
1264 * Within any given configuration, each interface may have several
1265 * alternative settings. These are often used to control levels of
1266 * bandwidth consumption. For example, the default setting for a high
1267 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1268 * while interrupt transfers of up to 3KBytes per microframe are legal.
1269 * Also, isochronous endpoints may never be part of an
1270 * interface's default setting. To access such bandwidth, alternate
1271 * interface settings must be made current.
1272 *
1273 * Note that in the Linux USB subsystem, bandwidth associated with
1274 * an endpoint in a given alternate setting is not reserved until an URB
1275 * is submitted that needs that bandwidth. Some other operating systems
1276 * allocate bandwidth early, when a configuration is chosen.
1277 *
1278 * This call is synchronous, and may not be used in an interrupt context.
1279 * Also, drivers must not change altsettings while urbs are scheduled for
1280 * endpoints in that interface; all such urbs must first be completed
1281 * (perhaps forced by unlinking).
1282 *
626f090c 1283 * Return: Zero on success, or else the status code returned by the
1da177e4
LT
1284 * underlying usb_control_msg() call.
1285 */
1286int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1287{
1288 struct usb_interface *iface;
1289 struct usb_host_interface *alt;
3f0479e0 1290 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
7a7b562d 1291 int i, ret, manual = 0;
3e35bf39
GKH
1292 unsigned int epaddr;
1293 unsigned int pipe;
1da177e4
LT
1294
1295 if (dev->state == USB_STATE_SUSPENDED)
1296 return -EHOSTUNREACH;
1297
1298 iface = usb_ifnum_to_if(dev, interface);
1299 if (!iface) {
1300 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1301 interface);
1302 return -EINVAL;
1303 }
e534c5b8
AS
1304 if (iface->unregistering)
1305 return -ENODEV;
1da177e4
LT
1306
1307 alt = usb_altnum_to_altsetting(iface, alternate);
1308 if (!alt) {
385f690b 1309 dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
3b6004f3 1310 alternate);
1da177e4
LT
1311 return -EINVAL;
1312 }
1313
3f0479e0
SS
1314 /* Make sure we have enough bandwidth for this alternate interface.
1315 * Remove the current alt setting and add the new alt setting.
1316 */
d673bfcb 1317 mutex_lock(hcd->bandwidth_mutex);
8306095f
SS
1318 /* Disable LPM, and re-enable it once the new alt setting is installed,
1319 * so that the xHCI driver can recalculate the U1/U2 timeouts.
1320 */
1321 if (usb_disable_lpm(dev)) {
1322 dev_err(&iface->dev, "%s Failed to disable LPM\n.", __func__);
1323 mutex_unlock(hcd->bandwidth_mutex);
1324 return -ENOMEM;
1325 }
7a7b562d
HG
1326 /* Changing alt-setting also frees any allocated streams */
1327 for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
1328 iface->cur_altsetting->endpoint[i].streams = 0;
1329
3f0479e0
SS
1330 ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
1331 if (ret < 0) {
1332 dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
1333 alternate);
8306095f 1334 usb_enable_lpm(dev);
d673bfcb 1335 mutex_unlock(hcd->bandwidth_mutex);
3f0479e0
SS
1336 return ret;
1337 }
1338
392e1d98
AS
1339 if (dev->quirks & USB_QUIRK_NO_SET_INTF)
1340 ret = -EPIPE;
1341 else
1342 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1da177e4
LT
1343 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1344 alternate, interface, NULL, 0, 5000);
1345
1346 /* 9.4.10 says devices don't need this and are free to STALL the
1347 * request if the interface only has one alternate setting.
1348 */
1349 if (ret == -EPIPE && iface->num_altsetting == 1) {
1350 dev_dbg(&dev->dev,
1351 "manual set_interface for iface %d, alt %d\n",
1352 interface, alternate);
1353 manual = 1;
3f0479e0
SS
1354 } else if (ret < 0) {
1355 /* Re-instate the old alt setting */
1356 usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
8306095f 1357 usb_enable_lpm(dev);
d673bfcb 1358 mutex_unlock(hcd->bandwidth_mutex);
1da177e4 1359 return ret;
3f0479e0 1360 }
d673bfcb 1361 mutex_unlock(hcd->bandwidth_mutex);
1da177e4
LT
1362
1363 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1364 * when they implement async or easily-killable versions of this or
1365 * other "should-be-internal" functions (like clear_halt).
1366 * should hcd+usbcore postprocess control requests?
1367 */
1368
1369 /* prevent submissions using previous endpoint settings */
3b23dd6f
AS
1370 if (iface->cur_altsetting != alt) {
1371 remove_intf_ep_devs(iface);
0e6c8e8d 1372 usb_remove_sysfs_intf_files(iface);
3b23dd6f 1373 }
ddeac4e7 1374 usb_disable_interface(dev, iface, true);
1da177e4 1375
1da177e4
LT
1376 iface->cur_altsetting = alt;
1377
8306095f
SS
1378 /* Now that the interface is installed, re-enable LPM. */
1379 usb_unlocked_enable_lpm(dev);
1380
1da177e4 1381 /* If the interface only has one altsetting and the device didn't
a81e7ecc 1382 * accept the request, we attempt to carry out the equivalent action
1da177e4
LT
1383 * by manually clearing the HALT feature for each endpoint in the
1384 * new altsetting.
1385 */
1386 if (manual) {
1da177e4 1387 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
3e35bf39
GKH
1388 epaddr = alt->endpoint[i].desc.bEndpointAddress;
1389 pipe = __create_pipe(dev,
1390 USB_ENDPOINT_NUMBER_MASK & epaddr) |
1391 (usb_endpoint_out(epaddr) ?
1392 USB_DIR_OUT : USB_DIR_IN);
1da177e4
LT
1393
1394 usb_clear_halt(dev, pipe);
1395 }
1396 }
1397
1398 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1399 *
1400 * Note:
1401 * Despite EP0 is always present in all interfaces/AS, the list of
1402 * endpoints from the descriptor does not contain EP0. Due to its
1403 * omnipresence one might expect EP0 being considered "affected" by
1404 * any SetInterface request and hence assume toggles need to be reset.
1405 * However, EP0 toggles are re-synced for every individual transfer
1406 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1407 * (Likewise, EP0 never "halts" on well designed devices.)
1408 */
2caf7fcd 1409 usb_enable_interface(dev, iface, true);
3b23dd6f 1410 if (device_is_registered(&iface->dev)) {
0e6c8e8d 1411 usb_create_sysfs_intf_files(iface);
3b23dd6f
AS
1412 create_intf_ep_devs(iface);
1413 }
1da177e4
LT
1414 return 0;
1415}
782e70c6 1416EXPORT_SYMBOL_GPL(usb_set_interface);
1da177e4
LT
1417
1418/**
1419 * usb_reset_configuration - lightweight device reset
1420 * @dev: the device whose configuration is being reset
1421 *
1422 * This issues a standard SET_CONFIGURATION request to the device using
1423 * the current configuration. The effect is to reset most USB-related
1424 * state in the device, including interface altsettings (reset to zero),
3444b26a 1425 * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
1da177e4
LT
1426 * endpoints). Other usbcore state is unchanged, including bindings of
1427 * usb device drivers to interfaces.
1428 *
1429 * Because this affects multiple interfaces, avoid using this with composite
1430 * (multi-interface) devices. Instead, the driver for each interface may
a81e7ecc
DB
1431 * use usb_set_interface() on the interfaces it claims. Be careful though;
1432 * some devices don't support the SET_INTERFACE request, and others won't
3444b26a 1433 * reset all the interface state (notably endpoint state). Resetting the whole
1da177e4
LT
1434 * configuration would affect other drivers' interfaces.
1435 *
1436 * The caller must own the device lock.
1437 *
626f090c 1438 * Return: Zero on success, else a negative error code.
1da177e4
LT
1439 */
1440int usb_reset_configuration(struct usb_device *dev)
1441{
1442 int i, retval;
1443 struct usb_host_config *config;
3f0479e0 1444 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1da177e4
LT
1445
1446 if (dev->state == USB_STATE_SUSPENDED)
1447 return -EHOSTUNREACH;
1448
1449 /* caller must have locked the device and must own
1450 * the usb bus readlock (so driver bindings are stable);
1451 * calls during probe() are fine
1452 */
1453
1454 for (i = 1; i < 16; ++i) {
ddeac4e7
AS
1455 usb_disable_endpoint(dev, i, true);
1456 usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1da177e4
LT
1457 }
1458
1459 config = dev->actconfig;
3f0479e0 1460 retval = 0;
d673bfcb 1461 mutex_lock(hcd->bandwidth_mutex);
8306095f
SS
1462 /* Disable LPM, and re-enable it once the configuration is reset, so
1463 * that the xHCI driver can recalculate the U1/U2 timeouts.
1464 */
1465 if (usb_disable_lpm(dev)) {
1466 dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
1467 mutex_unlock(hcd->bandwidth_mutex);
1468 return -ENOMEM;
1469 }
3f0479e0
SS
1470 /* Make sure we have enough bandwidth for each alternate setting 0 */
1471 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1472 struct usb_interface *intf = config->interface[i];
1473 struct usb_host_interface *alt;
1474
1475 alt = usb_altnum_to_altsetting(intf, 0);
1476 if (!alt)
1477 alt = &intf->altsetting[0];
1478 if (alt != intf->cur_altsetting)
1479 retval = usb_hcd_alloc_bandwidth(dev, NULL,
1480 intf->cur_altsetting, alt);
1481 if (retval < 0)
1482 break;
1483 }
1484 /* If not, reinstate the old alternate settings */
1485 if (retval < 0) {
1486reset_old_alts:
e4a3d946 1487 for (i--; i >= 0; i--) {
3f0479e0
SS
1488 struct usb_interface *intf = config->interface[i];
1489 struct usb_host_interface *alt;
1490
1491 alt = usb_altnum_to_altsetting(intf, 0);
1492 if (!alt)
1493 alt = &intf->altsetting[0];
1494 if (alt != intf->cur_altsetting)
1495 usb_hcd_alloc_bandwidth(dev, NULL,
1496 alt, intf->cur_altsetting);
1497 }
8306095f 1498 usb_enable_lpm(dev);
d673bfcb 1499 mutex_unlock(hcd->bandwidth_mutex);
3f0479e0
SS
1500 return retval;
1501 }
1da177e4
LT
1502 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1503 USB_REQ_SET_CONFIGURATION, 0,
1504 config->desc.bConfigurationValue, 0,
1505 NULL, 0, USB_CTRL_SET_TIMEOUT);
0e6c8e8d 1506 if (retval < 0)
3f0479e0 1507 goto reset_old_alts;
d673bfcb 1508 mutex_unlock(hcd->bandwidth_mutex);
1da177e4 1509
1da177e4
LT
1510 /* re-init hc/hcd interface/endpoint state */
1511 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1512 struct usb_interface *intf = config->interface[i];
1513 struct usb_host_interface *alt;
1514
1515 alt = usb_altnum_to_altsetting(intf, 0);
1516
1517 /* No altsetting 0? We'll assume the first altsetting.
1518 * We could use a GetInterface call, but if a device is
1519 * so non-compliant that it doesn't have altsetting 0
1520 * then I wouldn't trust its reply anyway.
1521 */
1522 if (!alt)
1523 alt = &intf->altsetting[0];
1524
3b23dd6f
AS
1525 if (alt != intf->cur_altsetting) {
1526 remove_intf_ep_devs(intf);
1527 usb_remove_sysfs_intf_files(intf);
1528 }
1da177e4 1529 intf->cur_altsetting = alt;
2caf7fcd 1530 usb_enable_interface(dev, intf, true);
3b23dd6f 1531 if (device_is_registered(&intf->dev)) {
0e6c8e8d 1532 usb_create_sysfs_intf_files(intf);
3b23dd6f
AS
1533 create_intf_ep_devs(intf);
1534 }
1da177e4 1535 }
8306095f
SS
1536 /* Now that the interfaces are installed, re-enable LPM. */
1537 usb_unlocked_enable_lpm(dev);
1da177e4
LT
1538 return 0;
1539}
782e70c6 1540EXPORT_SYMBOL_GPL(usb_reset_configuration);
1da177e4 1541
b0e396e3 1542static void usb_release_interface(struct device *dev)
1da177e4
LT
1543{
1544 struct usb_interface *intf = to_usb_interface(dev);
1545 struct usb_interface_cache *intfc =
1546 altsetting_to_usb_interface_cache(intf->altsetting);
1547
1548 kref_put(&intfc->ref, usb_release_interface_cache);
524134d4 1549 usb_put_dev(interface_to_usbdev(intf));
1da177e4
LT
1550 kfree(intf);
1551}
1552
b3910cef
SK
1553/*
1554 * usb_deauthorize_interface - deauthorize an USB interface
1555 *
1556 * @intf: USB interface structure
1557 */
1558void usb_deauthorize_interface(struct usb_interface *intf)
1559{
1560 struct device *dev = &intf->dev;
1561
1562 device_lock(dev->parent);
1563
1564 if (intf->authorized) {
1565 device_lock(dev);
1566 intf->authorized = 0;
1567 device_unlock(dev);
1568
1569 usb_forced_unbind_intf(intf);
1570 }
1571
1572 device_unlock(dev->parent);
1573}
1574
1575/*
1576 * usb_authorize_interface - authorize an USB interface
1577 *
1578 * @intf: USB interface structure
1579 */
1580void usb_authorize_interface(struct usb_interface *intf)
1581{
1582 struct device *dev = &intf->dev;
1583
1584 if (!intf->authorized) {
1585 device_lock(dev);
1586 intf->authorized = 1; /* authorize interface */
1587 device_unlock(dev);
1588 }
1589}
1590
7eff2e7a 1591static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
9f8b17e6
KS
1592{
1593 struct usb_device *usb_dev;
1594 struct usb_interface *intf;
1595 struct usb_host_interface *alt;
9f8b17e6 1596
9f8b17e6
KS
1597 intf = to_usb_interface(dev);
1598 usb_dev = interface_to_usbdev(intf);
1599 alt = intf->cur_altsetting;
1600
7eff2e7a 1601 if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
9f8b17e6
KS
1602 alt->desc.bInterfaceClass,
1603 alt->desc.bInterfaceSubClass,
1604 alt->desc.bInterfaceProtocol))
1605 return -ENOMEM;
1606
7eff2e7a 1607 if (add_uevent_var(env,
3e35bf39 1608 "MODALIAS=usb:"
81df2d59 1609 "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
9f8b17e6
KS
1610 le16_to_cpu(usb_dev->descriptor.idVendor),
1611 le16_to_cpu(usb_dev->descriptor.idProduct),
1612 le16_to_cpu(usb_dev->descriptor.bcdDevice),
1613 usb_dev->descriptor.bDeviceClass,
1614 usb_dev->descriptor.bDeviceSubClass,
1615 usb_dev->descriptor.bDeviceProtocol,
1616 alt->desc.bInterfaceClass,
1617 alt->desc.bInterfaceSubClass,
81df2d59
BM
1618 alt->desc.bInterfaceProtocol,
1619 alt->desc.bInterfaceNumber))
9f8b17e6
KS
1620 return -ENOMEM;
1621
9f8b17e6
KS
1622 return 0;
1623}
1624
9f8b17e6
KS
1625struct device_type usb_if_device_type = {
1626 .name = "usb_interface",
1627 .release = usb_release_interface,
1628 .uevent = usb_if_uevent,
1629};
1630
165fe97e 1631static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
3e35bf39
GKH
1632 struct usb_host_config *config,
1633 u8 inum)
165fe97e
CN
1634{
1635 struct usb_interface_assoc_descriptor *retval = NULL;
1636 struct usb_interface_assoc_descriptor *intf_assoc;
1637 int first_intf;
1638 int last_intf;
1639 int i;
1640
1641 for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
1642 intf_assoc = config->intf_assoc[i];
1643 if (intf_assoc->bInterfaceCount == 0)
1644 continue;
1645
1646 first_intf = intf_assoc->bFirstInterface;
1647 last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
1648 if (inum >= first_intf && inum <= last_intf) {
1649 if (!retval)
1650 retval = intf_assoc;
1651 else
1652 dev_err(&dev->dev, "Interface #%d referenced"
1653 " by multiple IADs\n", inum);
1654 }
1655 }
1656
1657 return retval;
1658}
1659
dc023dce
IPG
1660
1661/*
1662 * Internal function to queue a device reset
dc023dce
IPG
1663 * See usb_queue_reset_device() for more details
1664 */
09e81f3d 1665static void __usb_queue_reset_device(struct work_struct *ws)
dc023dce
IPG
1666{
1667 int rc;
1668 struct usb_interface *iface =
1669 container_of(ws, struct usb_interface, reset_ws);
1670 struct usb_device *udev = interface_to_usbdev(iface);
1671
1672 rc = usb_lock_device_for_reset(udev, iface);
1673 if (rc >= 0) {
dc023dce 1674 usb_reset_device(udev);
dc023dce
IPG
1675 usb_unlock_device(udev);
1676 }
524134d4 1677 usb_put_intf(iface); /* Undo _get_ in usb_queue_reset_device() */
dc023dce
IPG
1678}
1679
1680
1da177e4
LT
1681/*
1682 * usb_set_configuration - Makes a particular device setting be current
1683 * @dev: the device whose configuration is being updated
1684 * @configuration: the configuration being chosen.
1685 * Context: !in_interrupt(), caller owns the device lock
1686 *
1687 * This is used to enable non-default device modes. Not all devices
1688 * use this kind of configurability; many devices only have one
1689 * configuration.
1690 *
3f141e2a
AS
1691 * @configuration is the value of the configuration to be installed.
1692 * According to the USB spec (e.g. section 9.1.1.5), configuration values
1693 * must be non-zero; a value of zero indicates that the device in
1694 * unconfigured. However some devices erroneously use 0 as one of their
1695 * configuration values. To help manage such devices, this routine will
1696 * accept @configuration = -1 as indicating the device should be put in
1697 * an unconfigured state.
1698 *
1da177e4
LT
1699 * USB device configurations may affect Linux interoperability,
1700 * power consumption and the functionality available. For example,
1701 * the default configuration is limited to using 100mA of bus power,
1702 * so that when certain device functionality requires more power,
1703 * and the device is bus powered, that functionality should be in some
1704 * non-default device configuration. Other device modes may also be
1705 * reflected as configuration options, such as whether two ISDN
1706 * channels are available independently; and choosing between open
1707 * standard device protocols (like CDC) or proprietary ones.
1708 *
16bbab29
IPG
1709 * Note that a non-authorized device (dev->authorized == 0) will only
1710 * be put in unconfigured mode.
1711 *
1da177e4
LT
1712 * Note that USB has an additional level of device configurability,
1713 * associated with interfaces. That configurability is accessed using
1714 * usb_set_interface().
1715 *
1716 * This call is synchronous. The calling context must be able to sleep,
1717 * must own the device lock, and must not hold the driver model's USB
6d243e5c 1718 * bus mutex; usb interface driver probe() methods cannot use this routine.
1da177e4
LT
1719 *
1720 * Returns zero on success, or else the status code returned by the
093cf723 1721 * underlying call that failed. On successful completion, each interface
1da177e4
LT
1722 * in the original device configuration has been destroyed, and each one
1723 * in the new configuration has been probed by all relevant usb device
1724 * drivers currently known to the kernel.
1725 */
1726int usb_set_configuration(struct usb_device *dev, int configuration)
1727{
1728 int i, ret;
1729 struct usb_host_config *cp = NULL;
1730 struct usb_interface **new_interfaces = NULL;
3f0479e0 1731 struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1da177e4
LT
1732 int n, nintf;
1733
16bbab29 1734 if (dev->authorized == 0 || configuration == -1)
3f141e2a
AS
1735 configuration = 0;
1736 else {
1737 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1738 if (dev->config[i].desc.bConfigurationValue ==
1739 configuration) {
1740 cp = &dev->config[i];
1741 break;
1742 }
1da177e4
LT
1743 }
1744 }
1745 if ((!cp && configuration != 0))
1746 return -EINVAL;
1747
1748 /* The USB spec says configuration 0 means unconfigured.
1749 * But if a device includes a configuration numbered 0,
1750 * we will accept it as a correctly configured state.
3f141e2a 1751 * Use -1 if you really want to unconfigure the device.
1da177e4
LT
1752 */
1753 if (cp && configuration == 0)
1754 dev_warn(&dev->dev, "config 0 descriptor??\n");
1755
1da177e4
LT
1756 /* Allocate memory for new interfaces before doing anything else,
1757 * so that if we run out then nothing will have changed. */
1758 n = nintf = 0;
1759 if (cp) {
1760 nintf = cp->desc.bNumInterfaces;
1761 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
acbe2feb 1762 GFP_NOIO);
93fab795 1763 if (!new_interfaces)
1da177e4 1764 return -ENOMEM;
1da177e4
LT
1765
1766 for (; n < nintf; ++n) {
0a1ef3b5 1767 new_interfaces[n] = kzalloc(
1da177e4 1768 sizeof(struct usb_interface),
acbe2feb 1769 GFP_NOIO);
1da177e4 1770 if (!new_interfaces[n]) {
1da177e4
LT
1771 ret = -ENOMEM;
1772free_interfaces:
1773 while (--n >= 0)
1774 kfree(new_interfaces[n]);
1775 kfree(new_interfaces);
1776 return ret;
1777 }
1778 }
1da177e4 1779
8d8479db 1780 i = dev->bus_mA - usb_get_max_power(dev, cp);
f48219db
HS
1781 if (i < 0)
1782 dev_warn(&dev->dev, "new config #%d exceeds power "
1783 "limit by %dmA\n",
1784 configuration, -i);
1785 }
55c52718 1786
01d883d4 1787 /* Wake up the device so we can send it the Set-Config request */
94fcda1f 1788 ret = usb_autoresume_device(dev);
01d883d4
AS
1789 if (ret)
1790 goto free_interfaces;
1791
0791971b
TLSC
1792 /* if it's already configured, clear out old state first.
1793 * getting rid of old interfaces means unbinding their drivers.
1794 */
1795 if (dev->state != USB_STATE_ADDRESS)
1796 usb_disable_device(dev, 1); /* Skip ep0 */
1797
1798 /* Get rid of pending async Set-Config requests for this device */
1799 cancel_async_set_config(dev);
1800
79abb1ab
SS
1801 /* Make sure we have bandwidth (and available HCD resources) for this
1802 * configuration. Remove endpoints from the schedule if we're dropping
1803 * this configuration to set configuration 0. After this point, the
1804 * host controller will not allow submissions to dropped endpoints. If
1805 * this call fails, the device state is unchanged.
1806 */
8963c487 1807 mutex_lock(hcd->bandwidth_mutex);
8306095f
SS
1808 /* Disable LPM, and re-enable it once the new configuration is
1809 * installed, so that the xHCI driver can recalculate the U1/U2
1810 * timeouts.
1811 */
9cf65991 1812 if (dev->actconfig && usb_disable_lpm(dev)) {
8306095f
SS
1813 dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
1814 mutex_unlock(hcd->bandwidth_mutex);
c058f7ab
SK
1815 ret = -ENOMEM;
1816 goto free_interfaces;
8306095f 1817 }
3f0479e0 1818 ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
79abb1ab 1819 if (ret < 0) {
9cf65991
SS
1820 if (dev->actconfig)
1821 usb_enable_lpm(dev);
d673bfcb 1822 mutex_unlock(hcd->bandwidth_mutex);
0791971b 1823 usb_autosuspend_device(dev);
79abb1ab
SS
1824 goto free_interfaces;
1825 }
1826
36caff5d
AS
1827 /*
1828 * Initialize the new interface structures and the
6ad07129
AS
1829 * hc/hcd/usbcore interface/endpoint state.
1830 */
1831 for (i = 0; i < nintf; ++i) {
1832 struct usb_interface_cache *intfc;
1833 struct usb_interface *intf;
1834 struct usb_host_interface *alt;
1da177e4 1835
6ad07129
AS
1836 cp->interface[i] = intf = new_interfaces[i];
1837 intfc = cp->intf_cache[i];
1838 intf->altsetting = intfc->altsetting;
1839 intf->num_altsetting = intfc->num_altsetting;
6b2bd3c8 1840 intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
6ad07129 1841 kref_get(&intfc->ref);
1da177e4 1842
6ad07129
AS
1843 alt = usb_altnum_to_altsetting(intf, 0);
1844
1845 /* No altsetting 0? We'll assume the first altsetting.
1846 * We could use a GetInterface call, but if a device is
1847 * so non-compliant that it doesn't have altsetting 0
1848 * then I wouldn't trust its reply anyway.
1da177e4 1849 */
6ad07129
AS
1850 if (!alt)
1851 alt = &intf->altsetting[0];
1852
b3a3dd07
DM
1853 intf->intf_assoc =
1854 find_iad(dev, cp, alt->desc.bInterfaceNumber);
6ad07129 1855 intf->cur_altsetting = alt;
2caf7fcd 1856 usb_enable_interface(dev, intf, true);
6ad07129
AS
1857 intf->dev.parent = &dev->dev;
1858 intf->dev.driver = NULL;
1859 intf->dev.bus = &usb_bus_type;
9f8b17e6 1860 intf->dev.type = &usb_if_device_type;
2e5f10e4 1861 intf->dev.groups = usb_interface_groups;
6ad07129 1862 intf->dev.dma_mask = dev->dev.dma_mask;
dc023dce 1863 INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
0026e005 1864 intf->minor = -1;
3e35bf39 1865 device_initialize(&intf->dev);
63defa73 1866 pm_runtime_no_callbacks(&intf->dev);
0031a06e 1867 dev_set_name(&intf->dev, "%d-%s:%d.%d",
3e35bf39
GKH
1868 dev->bus->busnum, dev->devpath,
1869 configuration, alt->desc.bInterfaceNumber);
524134d4 1870 usb_get_dev(dev);
6ad07129
AS
1871 }
1872 kfree(new_interfaces);
1873
36caff5d
AS
1874 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1875 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1876 NULL, 0, USB_CTRL_SET_TIMEOUT);
1877 if (ret < 0 && cp) {
1878 /*
1879 * All the old state is gone, so what else can we do?
1880 * The device is probably useless now anyway.
1881 */
1882 usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1883 for (i = 0; i < nintf; ++i) {
1884 usb_disable_interface(dev, cp->interface[i], true);
1885 put_device(&cp->interface[i]->dev);
1886 cp->interface[i] = NULL;
1887 }
1888 cp = NULL;
1889 }
1890
1891 dev->actconfig = cp;
1892 mutex_unlock(hcd->bandwidth_mutex);
1893
1894 if (!cp) {
1895 usb_set_device_state(dev, USB_STATE_ADDRESS);
1896
1897 /* Leave LPM disabled while the device is unconfigured. */
1898 usb_autosuspend_device(dev);
1899 return ret;
1900 }
1901 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1902
1662e3a7
AS
1903 if (cp->string == NULL &&
1904 !(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
6ad07129
AS
1905 cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
1906
8306095f
SS
1907 /* Now that the interfaces are installed, re-enable LPM. */
1908 usb_unlocked_enable_lpm(dev);
f74631e3
SS
1909 /* Enable LTM if it was turned off by usb_disable_device. */
1910 usb_enable_ltm(dev);
8306095f 1911
6ad07129
AS
1912 /* Now that all the interfaces are set up, register them
1913 * to trigger binding of drivers to interfaces. probe()
1914 * routines may install different altsettings and may
1915 * claim() any interfaces not yet bound. Many class drivers
1916 * need that: CDC, audio, video, etc.
1917 */
1918 for (i = 0; i < nintf; ++i) {
1919 struct usb_interface *intf = cp->interface[i];
1920
3e35bf39 1921 dev_dbg(&dev->dev,
6ad07129 1922 "adding %s (config #%d, interface %d)\n",
7071a3ce 1923 dev_name(&intf->dev), configuration,
6ad07129 1924 intf->cur_altsetting->desc.bInterfaceNumber);
927bc916 1925 device_enable_async_suspend(&intf->dev);
3e35bf39 1926 ret = device_add(&intf->dev);
6ad07129
AS
1927 if (ret != 0) {
1928 dev_err(&dev->dev, "device_add(%s) --> %d\n",
7071a3ce 1929 dev_name(&intf->dev), ret);
6ad07129 1930 continue;
1da177e4 1931 }
3b23dd6f 1932 create_intf_ep_devs(intf);
1da177e4
LT
1933 }
1934
94fcda1f 1935 usb_autosuspend_device(dev);
86d30741 1936 return 0;
1da177e4 1937}
b7945b77 1938EXPORT_SYMBOL_GPL(usb_set_configuration);
1da177e4 1939
df718962
AS
1940static LIST_HEAD(set_config_list);
1941static DEFINE_SPINLOCK(set_config_lock);
1942
088dc270
AS
1943struct set_config_request {
1944 struct usb_device *udev;
1945 int config;
1946 struct work_struct work;
df718962 1947 struct list_head node;
088dc270
AS
1948};
1949
1950/* Worker routine for usb_driver_set_configuration() */
c4028958 1951static void driver_set_config_work(struct work_struct *work)
088dc270 1952{
c4028958
DH
1953 struct set_config_request *req =
1954 container_of(work, struct set_config_request, work);
df718962 1955 struct usb_device *udev = req->udev;
088dc270 1956
df718962
AS
1957 usb_lock_device(udev);
1958 spin_lock(&set_config_lock);
1959 list_del(&req->node);
1960 spin_unlock(&set_config_lock);
1961
1962 if (req->config >= -1) /* Is req still valid? */
1963 usb_set_configuration(udev, req->config);
1964 usb_unlock_device(udev);
1965 usb_put_dev(udev);
088dc270
AS
1966 kfree(req);
1967}
1968
df718962
AS
1969/* Cancel pending Set-Config requests for a device whose configuration
1970 * was just changed
1971 */
1972static void cancel_async_set_config(struct usb_device *udev)
1973{
1974 struct set_config_request *req;
1975
1976 spin_lock(&set_config_lock);
1977 list_for_each_entry(req, &set_config_list, node) {
1978 if (req->udev == udev)
1979 req->config = -999; /* Mark as cancelled */
1980 }
1981 spin_unlock(&set_config_lock);
1982}
1983
088dc270
AS
1984/**
1985 * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1986 * @udev: the device whose configuration is being updated
1987 * @config: the configuration being chosen.
1988 * Context: In process context, must be able to sleep
1989 *
1990 * Device interface drivers are not allowed to change device configurations.
1991 * This is because changing configurations will destroy the interface the
1992 * driver is bound to and create new ones; it would be like a floppy-disk
1993 * driver telling the computer to replace the floppy-disk drive with a
1994 * tape drive!
1995 *
1996 * Still, in certain specialized circumstances the need may arise. This
1997 * routine gets around the normal restrictions by using a work thread to
1998 * submit the change-config request.
1999 *
626f090c 2000 * Return: 0 if the request was successfully queued, error code otherwise.
088dc270
AS
2001 * The caller has no way to know whether the queued request will eventually
2002 * succeed.
2003 */
2004int usb_driver_set_configuration(struct usb_device *udev, int config)
2005{
2006 struct set_config_request *req;
2007
2008 req = kmalloc(sizeof(*req), GFP_KERNEL);
2009 if (!req)
2010 return -ENOMEM;
2011 req->udev = udev;
2012 req->config = config;
c4028958 2013 INIT_WORK(&req->work, driver_set_config_work);
088dc270 2014
df718962
AS
2015 spin_lock(&set_config_lock);
2016 list_add(&req->node, &set_config_list);
2017 spin_unlock(&set_config_lock);
2018
088dc270 2019 usb_get_dev(udev);
1737bf2c 2020 schedule_work(&req->work);
088dc270
AS
2021 return 0;
2022}
2023EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
e4c6fb77
ON
2024
2025/**
2026 * cdc_parse_cdc_header - parse the extra headers present in CDC devices
2027 * @hdr: the place to put the results of the parsing
2028 * @intf: the interface for which parsing is requested
2029 * @buffer: pointer to the extra headers to be parsed
2030 * @buflen: length of the extra headers
2031 *
2032 * This evaluates the extra headers present in CDC devices which
2033 * bind the interfaces for data and control and provide details
2034 * about the capabilities of the device.
2035 *
2036 * Return: number of descriptors parsed or -EINVAL
2037 * if the header is contradictory beyond salvage
2038 */
2039
2040int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr,
2041 struct usb_interface *intf,
2042 u8 *buffer,
2043 int buflen)
2044{
2045 /* duplicates are ignored */
2046 struct usb_cdc_union_desc *union_header = NULL;
2047
2048 /* duplicates are not tolerated */
2049 struct usb_cdc_header_desc *header = NULL;
2050 struct usb_cdc_ether_desc *ether = NULL;
2051 struct usb_cdc_mdlm_detail_desc *detail = NULL;
2052 struct usb_cdc_mdlm_desc *desc = NULL;
2053
2054 unsigned int elength;
2055 int cnt = 0;
2056
2057 memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header));
2058 hdr->phonet_magic_present = false;
2059 while (buflen > 0) {
2060 elength = buffer[0];
2061 if (!elength) {
2062 dev_err(&intf->dev, "skipping garbage byte\n");
2063 elength = 1;
2064 goto next_desc;
2065 }
2066 if (buffer[1] != USB_DT_CS_INTERFACE) {
2067 dev_err(&intf->dev, "skipping garbage\n");
2068 goto next_desc;
2069 }
2070
2071 switch (buffer[2]) {
2072 case USB_CDC_UNION_TYPE: /* we've found it */
2073 if (elength < sizeof(struct usb_cdc_union_desc))
2074 goto next_desc;
2075 if (union_header) {
2076 dev_err(&intf->dev, "More than one union descriptor, skipping ...\n");
2077 goto next_desc;
2078 }
2079 union_header = (struct usb_cdc_union_desc *)buffer;
2080 break;
2081 case USB_CDC_COUNTRY_TYPE:
2082 if (elength < sizeof(struct usb_cdc_country_functional_desc))
2083 goto next_desc;
2084 hdr->usb_cdc_country_functional_desc =
2085 (struct usb_cdc_country_functional_desc *)buffer;
2086 break;
2087 case USB_CDC_HEADER_TYPE:
2088 if (elength != sizeof(struct usb_cdc_header_desc))
2089 goto next_desc;
2090 if (header)
2091 return -EINVAL;
2092 header = (struct usb_cdc_header_desc *)buffer;
2093 break;
2094 case USB_CDC_ACM_TYPE:
2095 if (elength < sizeof(struct usb_cdc_acm_descriptor))
2096 goto next_desc;
2097 hdr->usb_cdc_acm_descriptor =
2098 (struct usb_cdc_acm_descriptor *)buffer;
2099 break;
2100 case USB_CDC_ETHERNET_TYPE:
2101 if (elength != sizeof(struct usb_cdc_ether_desc))
2102 goto next_desc;
2103 if (ether)
2104 return -EINVAL;
2105 ether = (struct usb_cdc_ether_desc *)buffer;
2106 break;
2107 case USB_CDC_CALL_MANAGEMENT_TYPE:
2108 if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor))
2109 goto next_desc;
2110 hdr->usb_cdc_call_mgmt_descriptor =
2111 (struct usb_cdc_call_mgmt_descriptor *)buffer;
2112 break;
2113 case USB_CDC_DMM_TYPE:
2114 if (elength < sizeof(struct usb_cdc_dmm_desc))
2115 goto next_desc;
2116 hdr->usb_cdc_dmm_desc =
2117 (struct usb_cdc_dmm_desc *)buffer;
2118 break;
2119 case USB_CDC_MDLM_TYPE:
2120 if (elength < sizeof(struct usb_cdc_mdlm_desc *))
2121 goto next_desc;
2122 if (desc)
2123 return -EINVAL;
2124 desc = (struct usb_cdc_mdlm_desc *)buffer;
2125 break;
2126 case USB_CDC_MDLM_DETAIL_TYPE:
2127 if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *))
2128 goto next_desc;
2129 if (detail)
2130 return -EINVAL;
2131 detail = (struct usb_cdc_mdlm_detail_desc *)buffer;
2132 break;
2133 case USB_CDC_NCM_TYPE:
2134 if (elength < sizeof(struct usb_cdc_ncm_desc))
2135 goto next_desc;
2136 hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer;
2137 break;
2138 case USB_CDC_MBIM_TYPE:
2139 if (elength < sizeof(struct usb_cdc_mbim_desc))
2140 goto next_desc;
2141
2142 hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer;
2143 break;
2144 case USB_CDC_MBIM_EXTENDED_TYPE:
2145 if (elength < sizeof(struct usb_cdc_mbim_extended_desc))
2146 break;
2147 hdr->usb_cdc_mbim_extended_desc =
2148 (struct usb_cdc_mbim_extended_desc *)buffer;
2149 break;
2150 case CDC_PHONET_MAGIC_NUMBER:
2151 hdr->phonet_magic_present = true;
2152 break;
2153 default:
2154 /*
2155 * there are LOTS more CDC descriptors that
2156 * could legitimately be found here.
2157 */
2158 dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n",
2159 buffer[2], elength);
2160 goto next_desc;
2161 }
2162 cnt++;
2163next_desc:
2164 buflen -= elength;
2165 buffer += elength;
2166 }
2167 hdr->usb_cdc_union_desc = union_header;
2168 hdr->usb_cdc_header_desc = header;
2169 hdr->usb_cdc_mdlm_detail_desc = detail;
2170 hdr->usb_cdc_mdlm_desc = desc;
2171 hdr->usb_cdc_ether_desc = ether;
2172 return cnt;
2173}
2174
2175EXPORT_SYMBOL(cdc_parse_cdc_header);