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