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