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