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