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