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