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