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