]> git.proxmox.com Git - mirror_ubuntu-artful-kernel.git/blob - drivers/usb/core/message.c
Pull bugzilla-5737 into release branch
[mirror_ubuntu-artful-kernel.git] / drivers / usb / core / message.c
1 /*
2 * message.c - synchronous message handling
3 */
4
5 #include <linux/config.h>
6 #include <linux/pci.h> /* for scatterlist macros */
7 #include <linux/usb.h>
8 #include <linux/module.h>
9 #include <linux/slab.h>
10 #include <linux/init.h>
11 #include <linux/mm.h>
12 #include <linux/timer.h>
13 #include <linux/ctype.h>
14 #include <linux/device.h>
15 #include <asm/byteorder.h>
16 #include <asm/scatterlist.h>
17
18 #include "hcd.h" /* for usbcore internals */
19 #include "usb.h"
20
21 static void usb_api_blocking_completion(struct urb *urb, struct pt_regs *regs)
22 {
23 complete((struct completion *)urb->context);
24 }
25
26
27 static void timeout_kill(unsigned long data)
28 {
29 struct urb *urb = (struct urb *) data;
30
31 usb_unlink_urb(urb);
32 }
33
34 // Starts urb and waits for completion or timeout
35 // note that this call is NOT interruptible, while
36 // many device driver i/o requests should be interruptible
37 static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
38 {
39 struct completion done;
40 struct timer_list timer;
41 int status;
42
43 init_completion(&done);
44 urb->context = &done;
45 urb->actual_length = 0;
46 status = usb_submit_urb(urb, GFP_NOIO);
47
48 if (status == 0) {
49 if (timeout > 0) {
50 init_timer(&timer);
51 timer.expires = jiffies + msecs_to_jiffies(timeout);
52 timer.data = (unsigned long)urb;
53 timer.function = timeout_kill;
54 /* grr. timeout _should_ include submit delays. */
55 add_timer(&timer);
56 }
57 wait_for_completion(&done);
58 status = urb->status;
59 /* note: HCDs return ETIMEDOUT for other reasons too */
60 if (status == -ECONNRESET) {
61 dev_dbg(&urb->dev->dev,
62 "%s timed out on ep%d%s len=%d/%d\n",
63 current->comm,
64 usb_pipeendpoint(urb->pipe),
65 usb_pipein(urb->pipe) ? "in" : "out",
66 urb->actual_length,
67 urb->transfer_buffer_length
68 );
69 if (urb->actual_length > 0)
70 status = 0;
71 else
72 status = -ETIMEDOUT;
73 }
74 if (timeout > 0)
75 del_timer_sync(&timer);
76 }
77
78 if (actual_length)
79 *actual_length = urb->actual_length;
80 usb_free_urb(urb);
81 return status;
82 }
83
84 /*-------------------------------------------------------------------*/
85 // returns status (negative) or length (positive)
86 static int usb_internal_control_msg(struct usb_device *usb_dev,
87 unsigned int pipe,
88 struct usb_ctrlrequest *cmd,
89 void *data, int len, int timeout)
90 {
91 struct urb *urb;
92 int retv;
93 int length;
94
95 urb = usb_alloc_urb(0, GFP_NOIO);
96 if (!urb)
97 return -ENOMEM;
98
99 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
100 len, usb_api_blocking_completion, NULL);
101
102 retv = usb_start_wait_urb(urb, timeout, &length);
103 if (retv < 0)
104 return retv;
105 else
106 return length;
107 }
108
109 /**
110 * usb_control_msg - Builds a control urb, sends it off and waits for completion
111 * @dev: pointer to the usb device to send the message to
112 * @pipe: endpoint "pipe" to send the message to
113 * @request: USB message request value
114 * @requesttype: USB message request type value
115 * @value: USB message value
116 * @index: USB message index value
117 * @data: pointer to the data to send
118 * @size: length in bytes of the data to send
119 * @timeout: time in msecs to wait for the message to complete before
120 * timing out (if 0 the wait is forever)
121 * Context: !in_interrupt ()
122 *
123 * This function sends a simple control message to a specified endpoint
124 * and waits for the message to complete, or timeout.
125 *
126 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
127 *
128 * Don't use this function from within an interrupt context, like a
129 * bottom half handler. If you need an asynchronous message, or need to send
130 * a message from within interrupt context, use usb_submit_urb()
131 * If a thread in your driver uses this call, make sure your disconnect()
132 * method can wait for it to complete. Since you don't have a handle on
133 * the URB used, you can't cancel the request.
134 */
135 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
136 __u16 value, __u16 index, void *data, __u16 size, int timeout)
137 {
138 struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
139 int ret;
140
141 if (!dr)
142 return -ENOMEM;
143
144 dr->bRequestType= requesttype;
145 dr->bRequest = request;
146 dr->wValue = cpu_to_le16p(&value);
147 dr->wIndex = cpu_to_le16p(&index);
148 dr->wLength = cpu_to_le16p(&size);
149
150 //dbg("usb_control_msg");
151
152 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
153
154 kfree(dr);
155
156 return ret;
157 }
158
159
160 /**
161 * usb_bulk_msg - Builds a bulk 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 in bytes
167 * @timeout: time in msecs to wait for the message to complete before
168 * timing out (if 0 the wait is forever)
169 * Context: !in_interrupt ()
170 *
171 * This function sends a simple bulk message to a specified endpoint
172 * and waits for the message to complete, or timeout.
173 *
174 * If successful, it returns 0, otherwise a negative error number.
175 * The number of actual bytes transferred will be stored in the
176 * actual_length paramater.
177 *
178 * Don't use this function from within an interrupt context, like a
179 * bottom half handler. If you need an asynchronous message, or need to
180 * send a message from within interrupt context, use usb_submit_urb()
181 * If a thread in your driver uses this call, make sure your disconnect()
182 * method can wait for it to complete. Since you don't have a handle on
183 * the URB used, you can't cancel the request.
184 *
185 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT
186 * ioctl, users are forced to abuse this routine by using it to submit
187 * URBs for interrupt endpoints. We will take the liberty of creating
188 * an interrupt URB (with the default interval) if the target is an
189 * interrupt endpoint.
190 */
191 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
192 void *data, int len, int *actual_length, int timeout)
193 {
194 struct urb *urb;
195 struct usb_host_endpoint *ep;
196
197 ep = (usb_pipein(pipe) ? usb_dev->ep_in : usb_dev->ep_out)
198 [usb_pipeendpoint(pipe)];
199 if (!ep || len < 0)
200 return -EINVAL;
201
202 urb = usb_alloc_urb(0, GFP_KERNEL);
203 if (!urb)
204 return -ENOMEM;
205
206 if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
207 USB_ENDPOINT_XFER_INT) {
208 pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
209 usb_fill_int_urb(urb, usb_dev, pipe, data, len,
210 usb_api_blocking_completion, NULL,
211 ep->desc.bInterval);
212 } else
213 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
214 usb_api_blocking_completion, NULL);
215
216 return usb_start_wait_urb(urb, timeout, actual_length);
217 }
218
219 /*-------------------------------------------------------------------*/
220
221 static void sg_clean (struct usb_sg_request *io)
222 {
223 if (io->urbs) {
224 while (io->entries--)
225 usb_free_urb (io->urbs [io->entries]);
226 kfree (io->urbs);
227 io->urbs = NULL;
228 }
229 if (io->dev->dev.dma_mask != NULL)
230 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
231 io->dev = NULL;
232 }
233
234 static void sg_complete (struct urb *urb, struct pt_regs *regs)
235 {
236 struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
237
238 spin_lock (&io->lock);
239
240 /* In 2.5 we require hcds' endpoint queues not to progress after fault
241 * reports, until the completion callback (this!) returns. That lets
242 * device driver code (like this routine) unlink queued urbs first,
243 * if it needs to, since the HC won't work on them at all. So it's
244 * not possible for page N+1 to overwrite page N, and so on.
245 *
246 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
247 * complete before the HCD can get requests away from hardware,
248 * though never during cleanup after a hard fault.
249 */
250 if (io->status
251 && (io->status != -ECONNRESET
252 || urb->status != -ECONNRESET)
253 && urb->actual_length) {
254 dev_err (io->dev->bus->controller,
255 "dev %s ep%d%s scatterlist error %d/%d\n",
256 io->dev->devpath,
257 usb_pipeendpoint (urb->pipe),
258 usb_pipein (urb->pipe) ? "in" : "out",
259 urb->status, io->status);
260 // BUG ();
261 }
262
263 if (io->status == 0 && urb->status && urb->status != -ECONNRESET) {
264 int i, found, status;
265
266 io->status = urb->status;
267
268 /* the previous urbs, and this one, completed already.
269 * unlink pending urbs so they won't rx/tx bad data.
270 * careful: unlink can sometimes be synchronous...
271 */
272 spin_unlock (&io->lock);
273 for (i = 0, found = 0; i < io->entries; i++) {
274 if (!io->urbs [i] || !io->urbs [i]->dev)
275 continue;
276 if (found) {
277 status = usb_unlink_urb (io->urbs [i]);
278 if (status != -EINPROGRESS
279 && status != -ENODEV
280 && status != -EBUSY)
281 dev_err (&io->dev->dev,
282 "%s, unlink --> %d\n",
283 __FUNCTION__, status);
284 } else if (urb == io->urbs [i])
285 found = 1;
286 }
287 spin_lock (&io->lock);
288 }
289 urb->dev = NULL;
290
291 /* on the last completion, signal usb_sg_wait() */
292 io->bytes += urb->actual_length;
293 io->count--;
294 if (!io->count)
295 complete (&io->complete);
296
297 spin_unlock (&io->lock);
298 }
299
300
301 /**
302 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
303 * @io: request block being initialized. until usb_sg_wait() returns,
304 * treat this as a pointer to an opaque block of memory,
305 * @dev: the usb device that will send or receive the data
306 * @pipe: endpoint "pipe" used to transfer the data
307 * @period: polling rate for interrupt endpoints, in frames or
308 * (for high speed endpoints) microframes; ignored for bulk
309 * @sg: scatterlist entries
310 * @nents: how many entries in the scatterlist
311 * @length: how many bytes to send from the scatterlist, or zero to
312 * send every byte identified in the list.
313 * @mem_flags: SLAB_* flags affecting memory allocations in this call
314 *
315 * Returns zero for success, else a negative errno value. This initializes a
316 * scatter/gather request, allocating resources such as I/O mappings and urb
317 * memory (except maybe memory used by USB controller drivers).
318 *
319 * The request must be issued using usb_sg_wait(), which waits for the I/O to
320 * complete (or to be canceled) and then cleans up all resources allocated by
321 * usb_sg_init().
322 *
323 * The request may be canceled with usb_sg_cancel(), either before or after
324 * usb_sg_wait() is called.
325 */
326 int usb_sg_init (
327 struct usb_sg_request *io,
328 struct usb_device *dev,
329 unsigned pipe,
330 unsigned period,
331 struct scatterlist *sg,
332 int nents,
333 size_t length,
334 gfp_t mem_flags
335 )
336 {
337 int i;
338 int urb_flags;
339 int dma;
340
341 if (!io || !dev || !sg
342 || usb_pipecontrol (pipe)
343 || usb_pipeisoc (pipe)
344 || nents <= 0)
345 return -EINVAL;
346
347 spin_lock_init (&io->lock);
348 io->dev = dev;
349 io->pipe = pipe;
350 io->sg = sg;
351 io->nents = nents;
352
353 /* not all host controllers use DMA (like the mainstream pci ones);
354 * they can use PIO (sl811) or be software over another transport.
355 */
356 dma = (dev->dev.dma_mask != NULL);
357 if (dma)
358 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
359 else
360 io->entries = nents;
361
362 /* initialize all the urbs we'll use */
363 if (io->entries <= 0)
364 return io->entries;
365
366 io->count = io->entries;
367 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
368 if (!io->urbs)
369 goto nomem;
370
371 urb_flags = URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
372 if (usb_pipein (pipe))
373 urb_flags |= URB_SHORT_NOT_OK;
374
375 for (i = 0; i < io->entries; i++) {
376 unsigned len;
377
378 io->urbs [i] = usb_alloc_urb (0, mem_flags);
379 if (!io->urbs [i]) {
380 io->entries = i;
381 goto nomem;
382 }
383
384 io->urbs [i]->dev = NULL;
385 io->urbs [i]->pipe = pipe;
386 io->urbs [i]->interval = period;
387 io->urbs [i]->transfer_flags = urb_flags;
388
389 io->urbs [i]->complete = sg_complete;
390 io->urbs [i]->context = io;
391 io->urbs [i]->status = -EINPROGRESS;
392 io->urbs [i]->actual_length = 0;
393
394 if (dma) {
395 /* hc may use _only_ transfer_dma */
396 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
397 len = sg_dma_len (sg + i);
398 } else {
399 /* hc may use _only_ transfer_buffer */
400 io->urbs [i]->transfer_buffer =
401 page_address (sg [i].page) + sg [i].offset;
402 len = sg [i].length;
403 }
404
405 if (length) {
406 len = min_t (unsigned, len, length);
407 length -= len;
408 if (length == 0)
409 io->entries = i + 1;
410 }
411 io->urbs [i]->transfer_buffer_length = len;
412 }
413 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
414
415 /* transaction state */
416 io->status = 0;
417 io->bytes = 0;
418 init_completion (&io->complete);
419 return 0;
420
421 nomem:
422 sg_clean (io);
423 return -ENOMEM;
424 }
425
426
427 /**
428 * usb_sg_wait - synchronously execute scatter/gather request
429 * @io: request block handle, as initialized with usb_sg_init().
430 * some fields become accessible when this call returns.
431 * Context: !in_interrupt ()
432 *
433 * This function blocks until the specified I/O operation completes. It
434 * leverages the grouping of the related I/O requests to get good transfer
435 * rates, by queueing the requests. At higher speeds, such queuing can
436 * significantly improve USB throughput.
437 *
438 * There are three kinds of completion for this function.
439 * (1) success, where io->status is zero. The number of io->bytes
440 * transferred is as requested.
441 * (2) error, where io->status is a negative errno value. The number
442 * of io->bytes transferred before the error is usually less
443 * than requested, and can be nonzero.
444 * (3) cancellation, a type of error with status -ECONNRESET that
445 * is initiated by usb_sg_cancel().
446 *
447 * When this function returns, all memory allocated through usb_sg_init() or
448 * this call will have been freed. The request block parameter may still be
449 * passed to usb_sg_cancel(), or it may be freed. It could also be
450 * reinitialized and then reused.
451 *
452 * Data Transfer Rates:
453 *
454 * Bulk transfers are valid for full or high speed endpoints.
455 * The best full speed data rate is 19 packets of 64 bytes each
456 * per frame, or 1216 bytes per millisecond.
457 * The best high speed data rate is 13 packets of 512 bytes each
458 * per microframe, or 52 KBytes per millisecond.
459 *
460 * The reason to use interrupt transfers through this API would most likely
461 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
462 * could be transferred. That capability is less useful for low or full
463 * speed interrupt endpoints, which allow at most one packet per millisecond,
464 * of at most 8 or 64 bytes (respectively).
465 */
466 void usb_sg_wait (struct usb_sg_request *io)
467 {
468 int i, entries = io->entries;
469
470 /* queue the urbs. */
471 spin_lock_irq (&io->lock);
472 for (i = 0; i < entries && !io->status; i++) {
473 int retval;
474
475 io->urbs [i]->dev = io->dev;
476 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
477
478 /* after we submit, let completions or cancelations fire;
479 * we handshake using io->status.
480 */
481 spin_unlock_irq (&io->lock);
482 switch (retval) {
483 /* maybe we retrying will recover */
484 case -ENXIO: // hc didn't queue this one
485 case -EAGAIN:
486 case -ENOMEM:
487 io->urbs[i]->dev = NULL;
488 retval = 0;
489 i--;
490 yield ();
491 break;
492
493 /* no error? continue immediately.
494 *
495 * NOTE: to work better with UHCI (4K I/O buffer may
496 * need 3K of TDs) it may be good to limit how many
497 * URBs are queued at once; N milliseconds?
498 */
499 case 0:
500 cpu_relax ();
501 break;
502
503 /* fail any uncompleted urbs */
504 default:
505 io->urbs [i]->dev = NULL;
506 io->urbs [i]->status = retval;
507 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
508 __FUNCTION__, retval);
509 usb_sg_cancel (io);
510 }
511 spin_lock_irq (&io->lock);
512 if (retval && (io->status == 0 || io->status == -ECONNRESET))
513 io->status = retval;
514 }
515 io->count -= entries - i;
516 if (io->count == 0)
517 complete (&io->complete);
518 spin_unlock_irq (&io->lock);
519
520 /* OK, yes, this could be packaged as non-blocking.
521 * So could the submit loop above ... but it's easier to
522 * solve neither problem than to solve both!
523 */
524 wait_for_completion (&io->complete);
525
526 sg_clean (io);
527 }
528
529 /**
530 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
531 * @io: request block, initialized with usb_sg_init()
532 *
533 * This stops a request after it has been started by usb_sg_wait().
534 * It can also prevents one initialized by usb_sg_init() from starting,
535 * so that call just frees resources allocated to the request.
536 */
537 void usb_sg_cancel (struct usb_sg_request *io)
538 {
539 unsigned long flags;
540
541 spin_lock_irqsave (&io->lock, flags);
542
543 /* shut everything down, if it didn't already */
544 if (!io->status) {
545 int i;
546
547 io->status = -ECONNRESET;
548 spin_unlock (&io->lock);
549 for (i = 0; i < io->entries; i++) {
550 int retval;
551
552 if (!io->urbs [i]->dev)
553 continue;
554 retval = usb_unlink_urb (io->urbs [i]);
555 if (retval != -EINPROGRESS && retval != -EBUSY)
556 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
557 __FUNCTION__, retval);
558 }
559 spin_lock (&io->lock);
560 }
561 spin_unlock_irqrestore (&io->lock, flags);
562 }
563
564 /*-------------------------------------------------------------------*/
565
566 /**
567 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
568 * @dev: the device whose descriptor is being retrieved
569 * @type: the descriptor type (USB_DT_*)
570 * @index: the number of the descriptor
571 * @buf: where to put the descriptor
572 * @size: how big is "buf"?
573 * Context: !in_interrupt ()
574 *
575 * Gets a USB descriptor. Convenience functions exist to simplify
576 * getting some types of descriptors. Use
577 * usb_get_string() or usb_string() for USB_DT_STRING.
578 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
579 * are part of the device structure.
580 * In addition to a number of USB-standard descriptors, some
581 * devices also use class-specific or vendor-specific descriptors.
582 *
583 * This call is synchronous, and may not be used in an interrupt context.
584 *
585 * Returns the number of bytes received on success, or else the status code
586 * returned by the underlying usb_control_msg() call.
587 */
588 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
589 {
590 int i;
591 int result;
592
593 memset(buf,0,size); // Make sure we parse really received data
594
595 for (i = 0; i < 3; ++i) {
596 /* retry on length 0 or stall; some devices are flakey */
597 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
598 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
599 (type << 8) + index, 0, buf, size,
600 USB_CTRL_GET_TIMEOUT);
601 if (result == 0 || result == -EPIPE)
602 continue;
603 if (result > 1 && ((u8 *)buf)[1] != type) {
604 result = -EPROTO;
605 continue;
606 }
607 break;
608 }
609 return result;
610 }
611
612 /**
613 * usb_get_string - gets a string descriptor
614 * @dev: the device whose string descriptor is being retrieved
615 * @langid: code for language chosen (from string descriptor zero)
616 * @index: the number of the descriptor
617 * @buf: where to put the string
618 * @size: how big is "buf"?
619 * Context: !in_interrupt ()
620 *
621 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
622 * in little-endian byte order).
623 * The usb_string() function will often be a convenient way to turn
624 * these strings into kernel-printable form.
625 *
626 * Strings may be referenced in device, configuration, interface, or other
627 * descriptors, and could also be used in vendor-specific ways.
628 *
629 * This call is synchronous, and may not be used in an interrupt context.
630 *
631 * Returns the number of bytes received on success, or else the status code
632 * returned by the underlying usb_control_msg() call.
633 */
634 static int usb_get_string(struct usb_device *dev, unsigned short langid,
635 unsigned char index, void *buf, int size)
636 {
637 int i;
638 int result;
639
640 for (i = 0; i < 3; ++i) {
641 /* retry on length 0 or stall; some devices are flakey */
642 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
643 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
644 (USB_DT_STRING << 8) + index, langid, buf, size,
645 USB_CTRL_GET_TIMEOUT);
646 if (!(result == 0 || result == -EPIPE))
647 break;
648 }
649 return result;
650 }
651
652 static void usb_try_string_workarounds(unsigned char *buf, int *length)
653 {
654 int newlength, oldlength = *length;
655
656 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
657 if (!isprint(buf[newlength]) || buf[newlength + 1])
658 break;
659
660 if (newlength > 2) {
661 buf[0] = newlength;
662 *length = newlength;
663 }
664 }
665
666 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
667 unsigned int index, unsigned char *buf)
668 {
669 int rc;
670
671 /* Try to read the string descriptor by asking for the maximum
672 * possible number of bytes */
673 rc = usb_get_string(dev, langid, index, buf, 255);
674
675 /* If that failed try to read the descriptor length, then
676 * ask for just that many bytes */
677 if (rc < 2) {
678 rc = usb_get_string(dev, langid, index, buf, 2);
679 if (rc == 2)
680 rc = usb_get_string(dev, langid, index, buf, buf[0]);
681 }
682
683 if (rc >= 2) {
684 if (!buf[0] && !buf[1])
685 usb_try_string_workarounds(buf, &rc);
686
687 /* There might be extra junk at the end of the descriptor */
688 if (buf[0] < rc)
689 rc = buf[0];
690
691 rc = rc - (rc & 1); /* force a multiple of two */
692 }
693
694 if (rc < 2)
695 rc = (rc < 0 ? rc : -EINVAL);
696
697 return rc;
698 }
699
700 /**
701 * usb_string - returns ISO 8859-1 version of a string descriptor
702 * @dev: the device whose string descriptor is being retrieved
703 * @index: the number of the descriptor
704 * @buf: where to put the string
705 * @size: how big is "buf"?
706 * Context: !in_interrupt ()
707 *
708 * This converts the UTF-16LE encoded strings returned by devices, from
709 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
710 * that are more usable in most kernel contexts. Note that all characters
711 * in the chosen descriptor that can't be encoded using ISO-8859-1
712 * are converted to the question mark ("?") character, and this function
713 * chooses strings in the first language supported by the device.
714 *
715 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
716 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
717 * and is appropriate for use many uses of English and several other
718 * Western European languages. (But it doesn't include the "Euro" symbol.)
719 *
720 * This call is synchronous, and may not be used in an interrupt context.
721 *
722 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
723 */
724 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
725 {
726 unsigned char *tbuf;
727 int err;
728 unsigned int u, idx;
729
730 if (dev->state == USB_STATE_SUSPENDED)
731 return -EHOSTUNREACH;
732 if (size <= 0 || !buf || !index)
733 return -EINVAL;
734 buf[0] = 0;
735 tbuf = kmalloc(256, GFP_KERNEL);
736 if (!tbuf)
737 return -ENOMEM;
738
739 /* get langid for strings if it's not yet known */
740 if (!dev->have_langid) {
741 err = usb_string_sub(dev, 0, 0, tbuf);
742 if (err < 0) {
743 dev_err (&dev->dev,
744 "string descriptor 0 read error: %d\n",
745 err);
746 goto errout;
747 } else if (err < 4) {
748 dev_err (&dev->dev, "string descriptor 0 too short\n");
749 err = -EINVAL;
750 goto errout;
751 } else {
752 dev->have_langid = -1;
753 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
754 /* always use the first langid listed */
755 dev_dbg (&dev->dev, "default language 0x%04x\n",
756 dev->string_langid);
757 }
758 }
759
760 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
761 if (err < 0)
762 goto errout;
763
764 size--; /* leave room for trailing NULL char in output buffer */
765 for (idx = 0, u = 2; u < err; u += 2) {
766 if (idx >= size)
767 break;
768 if (tbuf[u+1]) /* high byte */
769 buf[idx++] = '?'; /* non ISO-8859-1 character */
770 else
771 buf[idx++] = tbuf[u];
772 }
773 buf[idx] = 0;
774 err = idx;
775
776 if (tbuf[1] != USB_DT_STRING)
777 dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
778
779 errout:
780 kfree(tbuf);
781 return err;
782 }
783
784 /**
785 * usb_cache_string - read a string descriptor and cache it for later use
786 * @udev: the device whose string descriptor is being read
787 * @index: the descriptor index
788 *
789 * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
790 * or NULL if the index is 0 or the string could not be read.
791 */
792 char *usb_cache_string(struct usb_device *udev, int index)
793 {
794 char *buf;
795 char *smallbuf = NULL;
796 int len;
797
798 if (index > 0 && (buf = kmalloc(256, GFP_KERNEL)) != NULL) {
799 if ((len = usb_string(udev, index, buf, 256)) > 0) {
800 if ((smallbuf = kmalloc(++len, GFP_KERNEL)) == NULL)
801 return buf;
802 memcpy(smallbuf, buf, len);
803 }
804 kfree(buf);
805 }
806 return smallbuf;
807 }
808
809 /*
810 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
811 * @dev: the device whose device descriptor is being updated
812 * @size: how much of the descriptor to read
813 * Context: !in_interrupt ()
814 *
815 * Updates the copy of the device descriptor stored in the device structure,
816 * which dedicates space for this purpose. Note that several fields are
817 * converted to the host CPU's byte order: the USB version (bcdUSB), and
818 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
819 * That lets device drivers compare against non-byteswapped constants.
820 *
821 * Not exported, only for use by the core. If drivers really want to read
822 * the device descriptor directly, they can call usb_get_descriptor() with
823 * type = USB_DT_DEVICE and index = 0.
824 *
825 * This call is synchronous, and may not be used in an interrupt context.
826 *
827 * Returns the number of bytes received on success, or else the status code
828 * returned by the underlying usb_control_msg() call.
829 */
830 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
831 {
832 struct usb_device_descriptor *desc;
833 int ret;
834
835 if (size > sizeof(*desc))
836 return -EINVAL;
837 desc = kmalloc(sizeof(*desc), GFP_NOIO);
838 if (!desc)
839 return -ENOMEM;
840
841 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
842 if (ret >= 0)
843 memcpy(&dev->descriptor, desc, size);
844 kfree(desc);
845 return ret;
846 }
847
848 /**
849 * usb_get_status - issues a GET_STATUS call
850 * @dev: the device whose status is being checked
851 * @type: USB_RECIP_*; for device, interface, or endpoint
852 * @target: zero (for device), else interface or endpoint number
853 * @data: pointer to two bytes of bitmap data
854 * Context: !in_interrupt ()
855 *
856 * Returns device, interface, or endpoint status. Normally only of
857 * interest to see if the device is self powered, or has enabled the
858 * remote wakeup facility; or whether a bulk or interrupt endpoint
859 * is halted ("stalled").
860 *
861 * Bits in these status bitmaps are set using the SET_FEATURE request,
862 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
863 * function should be used to clear halt ("stall") status.
864 *
865 * This call is synchronous, and may not be used in an interrupt context.
866 *
867 * Returns the number of bytes received on success, or else the status code
868 * returned by the underlying usb_control_msg() call.
869 */
870 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
871 {
872 int ret;
873 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
874
875 if (!status)
876 return -ENOMEM;
877
878 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
879 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
880 sizeof(*status), USB_CTRL_GET_TIMEOUT);
881
882 *(u16 *)data = *status;
883 kfree(status);
884 return ret;
885 }
886
887 /**
888 * usb_clear_halt - tells device to clear endpoint halt/stall condition
889 * @dev: device whose endpoint is halted
890 * @pipe: endpoint "pipe" being cleared
891 * Context: !in_interrupt ()
892 *
893 * This is used to clear halt conditions for bulk and interrupt endpoints,
894 * as reported by URB completion status. Endpoints that are halted are
895 * sometimes referred to as being "stalled". Such endpoints are unable
896 * to transmit or receive data until the halt status is cleared. Any URBs
897 * queued for such an endpoint should normally be unlinked by the driver
898 * before clearing the halt condition, as described in sections 5.7.5
899 * and 5.8.5 of the USB 2.0 spec.
900 *
901 * Note that control and isochronous endpoints don't halt, although control
902 * endpoints report "protocol stall" (for unsupported requests) using the
903 * same status code used to report a true stall.
904 *
905 * This call is synchronous, and may not be used in an interrupt context.
906 *
907 * Returns zero on success, or else the status code returned by the
908 * underlying usb_control_msg() call.
909 */
910 int usb_clear_halt(struct usb_device *dev, int pipe)
911 {
912 int result;
913 int endp = usb_pipeendpoint(pipe);
914
915 if (usb_pipein (pipe))
916 endp |= USB_DIR_IN;
917
918 /* we don't care if it wasn't halted first. in fact some devices
919 * (like some ibmcam model 1 units) seem to expect hosts to make
920 * this request for iso endpoints, which can't halt!
921 */
922 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
923 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
924 USB_ENDPOINT_HALT, endp, NULL, 0,
925 USB_CTRL_SET_TIMEOUT);
926
927 /* don't un-halt or force to DATA0 except on success */
928 if (result < 0)
929 return result;
930
931 /* NOTE: seems like Microsoft and Apple don't bother verifying
932 * the clear "took", so some devices could lock up if you check...
933 * such as the Hagiwara FlashGate DUAL. So we won't bother.
934 *
935 * NOTE: make sure the logic here doesn't diverge much from
936 * the copy in usb-storage, for as long as we need two copies.
937 */
938
939 /* toggle was reset by the clear */
940 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
941
942 return 0;
943 }
944
945 /**
946 * usb_disable_endpoint -- Disable an endpoint by address
947 * @dev: the device whose endpoint is being disabled
948 * @epaddr: the endpoint's address. Endpoint number for output,
949 * endpoint number + USB_DIR_IN for input
950 *
951 * Deallocates hcd/hardware state for this endpoint ... and nukes all
952 * pending urbs.
953 *
954 * If the HCD hasn't registered a disable() function, this sets the
955 * endpoint's maxpacket size to 0 to prevent further submissions.
956 */
957 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
958 {
959 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
960 struct usb_host_endpoint *ep;
961
962 if (!dev)
963 return;
964
965 if (usb_endpoint_out(epaddr)) {
966 ep = dev->ep_out[epnum];
967 dev->ep_out[epnum] = NULL;
968 } else {
969 ep = dev->ep_in[epnum];
970 dev->ep_in[epnum] = NULL;
971 }
972 if (ep && dev->bus && dev->bus->op && dev->bus->op->disable)
973 dev->bus->op->disable(dev, ep);
974 }
975
976 /**
977 * usb_disable_interface -- Disable all endpoints for an interface
978 * @dev: the device whose interface is being disabled
979 * @intf: pointer to the interface descriptor
980 *
981 * Disables all the endpoints for the interface's current altsetting.
982 */
983 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
984 {
985 struct usb_host_interface *alt = intf->cur_altsetting;
986 int i;
987
988 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
989 usb_disable_endpoint(dev,
990 alt->endpoint[i].desc.bEndpointAddress);
991 }
992 }
993
994 /*
995 * usb_disable_device - Disable all the endpoints for a USB device
996 * @dev: the device whose endpoints are being disabled
997 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
998 *
999 * Disables all the device's endpoints, potentially including endpoint 0.
1000 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1001 * pending urbs) and usbcore state for the interfaces, so that usbcore
1002 * must usb_set_configuration() before any interfaces could be used.
1003 */
1004 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1005 {
1006 int i;
1007
1008 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
1009 skip_ep0 ? "non-ep0" : "all");
1010 for (i = skip_ep0; i < 16; ++i) {
1011 usb_disable_endpoint(dev, i);
1012 usb_disable_endpoint(dev, i + USB_DIR_IN);
1013 }
1014 dev->toggle[0] = dev->toggle[1] = 0;
1015
1016 /* getting rid of interfaces will disconnect
1017 * any drivers bound to them (a key side effect)
1018 */
1019 if (dev->actconfig) {
1020 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1021 struct usb_interface *interface;
1022
1023 /* remove this interface if it has been registered */
1024 interface = dev->actconfig->interface[i];
1025 if (!device_is_registered(&interface->dev))
1026 continue;
1027 dev_dbg (&dev->dev, "unregistering interface %s\n",
1028 interface->dev.bus_id);
1029 usb_remove_sysfs_intf_files(interface);
1030 device_del (&interface->dev);
1031 }
1032
1033 /* Now that the interfaces are unbound, nobody should
1034 * try to access them.
1035 */
1036 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1037 put_device (&dev->actconfig->interface[i]->dev);
1038 dev->actconfig->interface[i] = NULL;
1039 }
1040 dev->actconfig = NULL;
1041 if (dev->state == USB_STATE_CONFIGURED)
1042 usb_set_device_state(dev, USB_STATE_ADDRESS);
1043 }
1044 }
1045
1046
1047 /*
1048 * usb_enable_endpoint - Enable an endpoint for USB communications
1049 * @dev: the device whose interface is being enabled
1050 * @ep: the endpoint
1051 *
1052 * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
1053 * For control endpoints, both the input and output sides are handled.
1054 */
1055 static void
1056 usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
1057 {
1058 unsigned int epaddr = ep->desc.bEndpointAddress;
1059 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1060 int is_control;
1061
1062 is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1063 == USB_ENDPOINT_XFER_CONTROL);
1064 if (usb_endpoint_out(epaddr) || is_control) {
1065 usb_settoggle(dev, epnum, 1, 0);
1066 dev->ep_out[epnum] = ep;
1067 }
1068 if (!usb_endpoint_out(epaddr) || is_control) {
1069 usb_settoggle(dev, epnum, 0, 0);
1070 dev->ep_in[epnum] = ep;
1071 }
1072 }
1073
1074 /*
1075 * usb_enable_interface - Enable all the endpoints for an interface
1076 * @dev: the device whose interface is being enabled
1077 * @intf: pointer to the interface descriptor
1078 *
1079 * Enables all the endpoints for the interface's current altsetting.
1080 */
1081 static void usb_enable_interface(struct usb_device *dev,
1082 struct usb_interface *intf)
1083 {
1084 struct usb_host_interface *alt = intf->cur_altsetting;
1085 int i;
1086
1087 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1088 usb_enable_endpoint(dev, &alt->endpoint[i]);
1089 }
1090
1091 /**
1092 * usb_set_interface - Makes a particular alternate setting be current
1093 * @dev: the device whose interface is being updated
1094 * @interface: the interface being updated
1095 * @alternate: the setting being chosen.
1096 * Context: !in_interrupt ()
1097 *
1098 * This is used to enable data transfers on interfaces that may not
1099 * be enabled by default. Not all devices support such configurability.
1100 * Only the driver bound to an interface may change its setting.
1101 *
1102 * Within any given configuration, each interface may have several
1103 * alternative settings. These are often used to control levels of
1104 * bandwidth consumption. For example, the default setting for a high
1105 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1106 * while interrupt transfers of up to 3KBytes per microframe are legal.
1107 * Also, isochronous endpoints may never be part of an
1108 * interface's default setting. To access such bandwidth, alternate
1109 * interface settings must be made current.
1110 *
1111 * Note that in the Linux USB subsystem, bandwidth associated with
1112 * an endpoint in a given alternate setting is not reserved until an URB
1113 * is submitted that needs that bandwidth. Some other operating systems
1114 * allocate bandwidth early, when a configuration is chosen.
1115 *
1116 * This call is synchronous, and may not be used in an interrupt context.
1117 * Also, drivers must not change altsettings while urbs are scheduled for
1118 * endpoints in that interface; all such urbs must first be completed
1119 * (perhaps forced by unlinking).
1120 *
1121 * Returns zero on success, or else the status code returned by the
1122 * underlying usb_control_msg() call.
1123 */
1124 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1125 {
1126 struct usb_interface *iface;
1127 struct usb_host_interface *alt;
1128 int ret;
1129 int manual = 0;
1130
1131 if (dev->state == USB_STATE_SUSPENDED)
1132 return -EHOSTUNREACH;
1133
1134 iface = usb_ifnum_to_if(dev, interface);
1135 if (!iface) {
1136 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1137 interface);
1138 return -EINVAL;
1139 }
1140
1141 alt = usb_altnum_to_altsetting(iface, alternate);
1142 if (!alt) {
1143 warn("selecting invalid altsetting %d", alternate);
1144 return -EINVAL;
1145 }
1146
1147 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1148 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1149 alternate, interface, NULL, 0, 5000);
1150
1151 /* 9.4.10 says devices don't need this and are free to STALL the
1152 * request if the interface only has one alternate setting.
1153 */
1154 if (ret == -EPIPE && iface->num_altsetting == 1) {
1155 dev_dbg(&dev->dev,
1156 "manual set_interface for iface %d, alt %d\n",
1157 interface, alternate);
1158 manual = 1;
1159 } else if (ret < 0)
1160 return ret;
1161
1162 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1163 * when they implement async or easily-killable versions of this or
1164 * other "should-be-internal" functions (like clear_halt).
1165 * should hcd+usbcore postprocess control requests?
1166 */
1167
1168 /* prevent submissions using previous endpoint settings */
1169 if (device_is_registered(&iface->dev))
1170 usb_remove_sysfs_intf_files(iface);
1171 usb_disable_interface(dev, iface);
1172
1173 iface->cur_altsetting = alt;
1174
1175 /* If the interface only has one altsetting and the device didn't
1176 * accept the request, we attempt to carry out the equivalent action
1177 * by manually clearing the HALT feature for each endpoint in the
1178 * new altsetting.
1179 */
1180 if (manual) {
1181 int i;
1182
1183 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1184 unsigned int epaddr =
1185 alt->endpoint[i].desc.bEndpointAddress;
1186 unsigned int pipe =
1187 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
1188 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1189
1190 usb_clear_halt(dev, pipe);
1191 }
1192 }
1193
1194 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1195 *
1196 * Note:
1197 * Despite EP0 is always present in all interfaces/AS, the list of
1198 * endpoints from the descriptor does not contain EP0. Due to its
1199 * omnipresence one might expect EP0 being considered "affected" by
1200 * any SetInterface request and hence assume toggles need to be reset.
1201 * However, EP0 toggles are re-synced for every individual transfer
1202 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1203 * (Likewise, EP0 never "halts" on well designed devices.)
1204 */
1205 usb_enable_interface(dev, iface);
1206 if (device_is_registered(&iface->dev))
1207 usb_create_sysfs_intf_files(iface);
1208
1209 return 0;
1210 }
1211
1212 /**
1213 * usb_reset_configuration - lightweight device reset
1214 * @dev: the device whose configuration is being reset
1215 *
1216 * This issues a standard SET_CONFIGURATION request to the device using
1217 * the current configuration. The effect is to reset most USB-related
1218 * state in the device, including interface altsettings (reset to zero),
1219 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1220 * endpoints). Other usbcore state is unchanged, including bindings of
1221 * usb device drivers to interfaces.
1222 *
1223 * Because this affects multiple interfaces, avoid using this with composite
1224 * (multi-interface) devices. Instead, the driver for each interface may
1225 * use usb_set_interface() on the interfaces it claims. Be careful though;
1226 * some devices don't support the SET_INTERFACE request, and others won't
1227 * reset all the interface state (notably data toggles). Resetting the whole
1228 * configuration would affect other drivers' interfaces.
1229 *
1230 * The caller must own the device lock.
1231 *
1232 * Returns zero on success, else a negative error code.
1233 */
1234 int usb_reset_configuration(struct usb_device *dev)
1235 {
1236 int i, retval;
1237 struct usb_host_config *config;
1238
1239 if (dev->state == USB_STATE_SUSPENDED)
1240 return -EHOSTUNREACH;
1241
1242 /* caller must have locked the device and must own
1243 * the usb bus readlock (so driver bindings are stable);
1244 * calls during probe() are fine
1245 */
1246
1247 for (i = 1; i < 16; ++i) {
1248 usb_disable_endpoint(dev, i);
1249 usb_disable_endpoint(dev, i + USB_DIR_IN);
1250 }
1251
1252 config = dev->actconfig;
1253 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1254 USB_REQ_SET_CONFIGURATION, 0,
1255 config->desc.bConfigurationValue, 0,
1256 NULL, 0, USB_CTRL_SET_TIMEOUT);
1257 if (retval < 0)
1258 return retval;
1259
1260 dev->toggle[0] = dev->toggle[1] = 0;
1261
1262 /* re-init hc/hcd interface/endpoint state */
1263 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1264 struct usb_interface *intf = config->interface[i];
1265 struct usb_host_interface *alt;
1266
1267 if (device_is_registered(&intf->dev))
1268 usb_remove_sysfs_intf_files(intf);
1269 alt = usb_altnum_to_altsetting(intf, 0);
1270
1271 /* No altsetting 0? We'll assume the first altsetting.
1272 * We could use a GetInterface call, but if a device is
1273 * so non-compliant that it doesn't have altsetting 0
1274 * then I wouldn't trust its reply anyway.
1275 */
1276 if (!alt)
1277 alt = &intf->altsetting[0];
1278
1279 intf->cur_altsetting = alt;
1280 usb_enable_interface(dev, intf);
1281 if (device_is_registered(&intf->dev))
1282 usb_create_sysfs_intf_files(intf);
1283 }
1284 return 0;
1285 }
1286
1287 static void release_interface(struct device *dev)
1288 {
1289 struct usb_interface *intf = to_usb_interface(dev);
1290 struct usb_interface_cache *intfc =
1291 altsetting_to_usb_interface_cache(intf->altsetting);
1292
1293 kref_put(&intfc->ref, usb_release_interface_cache);
1294 kfree(intf);
1295 }
1296
1297 /*
1298 * usb_set_configuration - Makes a particular device setting be current
1299 * @dev: the device whose configuration is being updated
1300 * @configuration: the configuration being chosen.
1301 * Context: !in_interrupt(), caller owns the device lock
1302 *
1303 * This is used to enable non-default device modes. Not all devices
1304 * use this kind of configurability; many devices only have one
1305 * configuration.
1306 *
1307 * USB device configurations may affect Linux interoperability,
1308 * power consumption and the functionality available. For example,
1309 * the default configuration is limited to using 100mA of bus power,
1310 * so that when certain device functionality requires more power,
1311 * and the device is bus powered, that functionality should be in some
1312 * non-default device configuration. Other device modes may also be
1313 * reflected as configuration options, such as whether two ISDN
1314 * channels are available independently; and choosing between open
1315 * standard device protocols (like CDC) or proprietary ones.
1316 *
1317 * Note that USB has an additional level of device configurability,
1318 * associated with interfaces. That configurability is accessed using
1319 * usb_set_interface().
1320 *
1321 * This call is synchronous. The calling context must be able to sleep,
1322 * must own the device lock, and must not hold the driver model's USB
1323 * bus rwsem; usb device driver probe() methods cannot use this routine.
1324 *
1325 * Returns zero on success, or else the status code returned by the
1326 * underlying call that failed. On successful completion, each interface
1327 * in the original device configuration has been destroyed, and each one
1328 * in the new configuration has been probed by all relevant usb device
1329 * drivers currently known to the kernel.
1330 */
1331 int usb_set_configuration(struct usb_device *dev, int configuration)
1332 {
1333 int i, ret;
1334 struct usb_host_config *cp = NULL;
1335 struct usb_interface **new_interfaces = NULL;
1336 int n, nintf;
1337
1338 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1339 if (dev->config[i].desc.bConfigurationValue == configuration) {
1340 cp = &dev->config[i];
1341 break;
1342 }
1343 }
1344 if ((!cp && configuration != 0))
1345 return -EINVAL;
1346
1347 /* The USB spec says configuration 0 means unconfigured.
1348 * But if a device includes a configuration numbered 0,
1349 * we will accept it as a correctly configured state.
1350 */
1351 if (cp && configuration == 0)
1352 dev_warn(&dev->dev, "config 0 descriptor??\n");
1353
1354 if (dev->state == USB_STATE_SUSPENDED)
1355 return -EHOSTUNREACH;
1356
1357 /* Allocate memory for new interfaces before doing anything else,
1358 * so that if we run out then nothing will have changed. */
1359 n = nintf = 0;
1360 if (cp) {
1361 nintf = cp->desc.bNumInterfaces;
1362 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1363 GFP_KERNEL);
1364 if (!new_interfaces) {
1365 dev_err(&dev->dev, "Out of memory");
1366 return -ENOMEM;
1367 }
1368
1369 for (; n < nintf; ++n) {
1370 new_interfaces[n] = kzalloc(
1371 sizeof(struct usb_interface),
1372 GFP_KERNEL);
1373 if (!new_interfaces[n]) {
1374 dev_err(&dev->dev, "Out of memory");
1375 ret = -ENOMEM;
1376 free_interfaces:
1377 while (--n >= 0)
1378 kfree(new_interfaces[n]);
1379 kfree(new_interfaces);
1380 return ret;
1381 }
1382 }
1383 }
1384
1385 /* if it's already configured, clear out old state first.
1386 * getting rid of old interfaces means unbinding their drivers.
1387 */
1388 if (dev->state != USB_STATE_ADDRESS)
1389 usb_disable_device (dev, 1); // Skip ep0
1390
1391 if (cp) {
1392 i = dev->bus_mA - cp->desc.bMaxPower * 2;
1393 if (i < 0)
1394 dev_warn(&dev->dev, "new config #%d exceeds power "
1395 "limit by %dmA\n",
1396 configuration, -i);
1397 }
1398
1399 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1400 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1401 NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0)
1402 goto free_interfaces;
1403
1404 dev->actconfig = cp;
1405 if (!cp)
1406 usb_set_device_state(dev, USB_STATE_ADDRESS);
1407 else {
1408 usb_set_device_state(dev, USB_STATE_CONFIGURED);
1409
1410 /* Initialize the new interface structures and the
1411 * hc/hcd/usbcore interface/endpoint state.
1412 */
1413 for (i = 0; i < nintf; ++i) {
1414 struct usb_interface_cache *intfc;
1415 struct usb_interface *intf;
1416 struct usb_host_interface *alt;
1417
1418 cp->interface[i] = intf = new_interfaces[i];
1419 intfc = cp->intf_cache[i];
1420 intf->altsetting = intfc->altsetting;
1421 intf->num_altsetting = intfc->num_altsetting;
1422 kref_get(&intfc->ref);
1423
1424 alt = usb_altnum_to_altsetting(intf, 0);
1425
1426 /* No altsetting 0? We'll assume the first altsetting.
1427 * We could use a GetInterface call, but if a device is
1428 * so non-compliant that it doesn't have altsetting 0
1429 * then I wouldn't trust its reply anyway.
1430 */
1431 if (!alt)
1432 alt = &intf->altsetting[0];
1433
1434 intf->cur_altsetting = alt;
1435 usb_enable_interface(dev, intf);
1436 intf->dev.parent = &dev->dev;
1437 intf->dev.driver = NULL;
1438 intf->dev.bus = &usb_bus_type;
1439 intf->dev.dma_mask = dev->dev.dma_mask;
1440 intf->dev.release = release_interface;
1441 device_initialize (&intf->dev);
1442 mark_quiesced(intf);
1443 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1444 dev->bus->busnum, dev->devpath,
1445 configuration,
1446 alt->desc.bInterfaceNumber);
1447 }
1448 kfree(new_interfaces);
1449
1450 if (cp->string == NULL)
1451 cp->string = usb_cache_string(dev,
1452 cp->desc.iConfiguration);
1453
1454 /* Now that all the interfaces are set up, register them
1455 * to trigger binding of drivers to interfaces. probe()
1456 * routines may install different altsettings and may
1457 * claim() any interfaces not yet bound. Many class drivers
1458 * need that: CDC, audio, video, etc.
1459 */
1460 for (i = 0; i < nintf; ++i) {
1461 struct usb_interface *intf = cp->interface[i];
1462
1463 dev_dbg (&dev->dev,
1464 "adding %s (config #%d, interface %d)\n",
1465 intf->dev.bus_id, configuration,
1466 intf->cur_altsetting->desc.bInterfaceNumber);
1467 ret = device_add (&intf->dev);
1468 if (ret != 0) {
1469 dev_err(&dev->dev,
1470 "device_add(%s) --> %d\n",
1471 intf->dev.bus_id,
1472 ret);
1473 continue;
1474 }
1475 usb_create_sysfs_intf_files (intf);
1476 }
1477 }
1478
1479 return 0;
1480 }
1481
1482 // synchronous request completion model
1483 EXPORT_SYMBOL(usb_control_msg);
1484 EXPORT_SYMBOL(usb_bulk_msg);
1485
1486 EXPORT_SYMBOL(usb_sg_init);
1487 EXPORT_SYMBOL(usb_sg_cancel);
1488 EXPORT_SYMBOL(usb_sg_wait);
1489
1490 // synchronous control message convenience routines
1491 EXPORT_SYMBOL(usb_get_descriptor);
1492 EXPORT_SYMBOL(usb_get_status);
1493 EXPORT_SYMBOL(usb_string);
1494
1495 // synchronous calls that also maintain usbcore state
1496 EXPORT_SYMBOL(usb_clear_halt);
1497 EXPORT_SYMBOL(usb_reset_configuration);
1498 EXPORT_SYMBOL(usb_set_interface);
1499