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