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