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