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