Merge with Linux 2.6.0-test1.
[linux-2.6/linux-mips.git] / drivers / usb / core / message.c
blob839cbe6132f684a3278fbe374f2a090daf6498f1
1 /*
2 * message.c - synchronous message handling
3 */
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 <asm/byteorder.h>
13 #include "hcd.h" /* for usbcore internals */
15 struct usb_api_data {
16 wait_queue_head_t wqh;
17 int done;
20 static void usb_api_blocking_completion(struct urb *urb, struct pt_regs *regs)
22 struct usb_api_data *awd = (struct usb_api_data *)urb->context;
24 awd->done = 1;
25 wmb();
26 wake_up(&awd->wqh);
29 // Starts urb and waits for completion or timeout
30 static int usb_start_wait_urb(struct urb *urb, int timeout, int* actual_length)
32 DECLARE_WAITQUEUE(wait, current);
33 struct usb_api_data awd;
34 int status;
36 init_waitqueue_head(&awd.wqh);
37 awd.done = 0;
39 set_current_state(TASK_UNINTERRUPTIBLE);
40 add_wait_queue(&awd.wqh, &wait);
42 urb->context = &awd;
43 status = usb_submit_urb(urb, GFP_ATOMIC);
44 if (status) {
45 // something went wrong
46 usb_free_urb(urb);
47 set_current_state(TASK_RUNNING);
48 remove_wait_queue(&awd.wqh, &wait);
49 return status;
52 while (timeout && !awd.done)
54 timeout = schedule_timeout(timeout);
55 set_current_state(TASK_UNINTERRUPTIBLE);
56 rmb();
59 set_current_state(TASK_RUNNING);
60 remove_wait_queue(&awd.wqh, &wait);
62 if (!timeout && !awd.done) {
63 if (urb->status != -EINPROGRESS) { /* No callback?!! */
64 printk(KERN_ERR "usb: raced timeout, "
65 "pipe 0x%x status %d time left %d\n",
66 urb->pipe, urb->status, timeout);
67 status = urb->status;
68 } else {
69 warn("usb_control/bulk_msg: timeout");
70 usb_unlink_urb(urb); // remove urb safely
71 status = -ETIMEDOUT;
73 } else
74 status = urb->status;
76 if (actual_length)
77 *actual_length = urb->actual_length;
79 usb_free_urb(urb);
80 return status;
83 /*-------------------------------------------------------------------*/
84 // returns status (negative) or length (positive)
85 int usb_internal_control_msg(struct usb_device *usb_dev, unsigned int pipe,
86 struct usb_ctrlrequest *cmd, void *data, int len, int timeout)
88 struct urb *urb;
89 int retv;
90 int length;
92 urb = usb_alloc_urb(0, GFP_NOIO);
93 if (!urb)
94 return -ENOMEM;
96 usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char*)cmd, data, len,
97 usb_api_blocking_completion, 0);
99 retv = usb_start_wait_urb(urb, timeout, &length);
100 if (retv < 0)
101 return retv;
102 else
103 return length;
107 * usb_control_msg - Builds a control urb, sends it off and waits for completion
108 * @dev: pointer to the usb device to send the message to
109 * @pipe: endpoint "pipe" to send the message to
110 * @request: USB message request value
111 * @requesttype: USB message request type value
112 * @value: USB message value
113 * @index: USB message index value
114 * @data: pointer to the data to send
115 * @size: length in bytes of the data to send
116 * @timeout: time in jiffies to wait for the message to complete before
117 * timing out (if 0 the wait is forever)
118 * Context: !in_interrupt ()
120 * This function sends a simple control message to a specified endpoint
121 * and waits for the message to complete, or timeout.
123 * If successful, it returns the number of bytes transferred, otherwise a negative error number.
125 * Don't use this function from within an interrupt context, like a
126 * bottom half handler. If you need an asynchronous message, or need to send
127 * a message from within interrupt context, use usb_submit_urb()
128 * If a thread in your driver uses this call, make sure your disconnect()
129 * method can wait for it to complete. Since you don't have a handle on
130 * the URB used, you can't cancel the request.
132 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
133 __u16 value, __u16 index, void *data, __u16 size, int timeout)
135 struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
136 int ret;
138 if (!dr)
139 return -ENOMEM;
141 dr->bRequestType= requesttype;
142 dr->bRequest = request;
143 dr->wValue = cpu_to_le16p(&value);
144 dr->wIndex = cpu_to_le16p(&index);
145 dr->wLength = cpu_to_le16p(&size);
147 //dbg("usb_control_msg");
149 ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
151 kfree(dr);
153 return ret;
158 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
159 * @usb_dev: pointer to the usb device to send the message to
160 * @pipe: endpoint "pipe" to send the message to
161 * @data: pointer to the data to send
162 * @len: length in bytes of the data to send
163 * @actual_length: pointer to a location to put the actual length transferred in bytes
164 * @timeout: time in jiffies to wait for the message to complete before
165 * timing out (if 0 the wait is forever)
166 * Context: !in_interrupt ()
168 * This function sends a simple bulk message to a specified endpoint
169 * and waits for the message to complete, or timeout.
171 * If successful, it returns 0, otherwise a negative error number.
172 * The number of actual bytes transferred will be stored in the
173 * actual_length paramater.
175 * Don't use this function from within an interrupt context, like a
176 * bottom half handler. If you need an asynchronous message, or need to
177 * send a message from within interrupt context, use usb_submit_urb()
178 * If a thread in your driver uses this call, make sure your disconnect()
179 * method can wait for it to complete. Since you don't have a handle on
180 * the URB used, you can't cancel the request.
182 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
183 void *data, int len, int *actual_length, int timeout)
185 struct urb *urb;
187 if (len < 0)
188 return -EINVAL;
190 urb=usb_alloc_urb(0, GFP_KERNEL);
191 if (!urb)
192 return -ENOMEM;
194 usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
195 usb_api_blocking_completion, 0);
197 return usb_start_wait_urb(urb,timeout,actual_length);
200 /*-------------------------------------------------------------------*/
202 static void sg_clean (struct usb_sg_request *io)
204 if (io->urbs) {
205 while (io->entries--)
206 usb_free_urb (io->urbs [io->entries]);
207 kfree (io->urbs);
208 io->urbs = 0;
210 if (io->dev->dev.dma_mask != 0)
211 usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
212 io->dev = 0;
215 static void sg_complete (struct urb *urb, struct pt_regs *regs)
217 struct usb_sg_request *io = (struct usb_sg_request *) urb->context;
218 unsigned long flags;
220 spin_lock_irqsave (&io->lock, flags);
222 /* In 2.5 we require hcds' endpoint queues not to progress after fault
223 * reports, until the completion callback (this!) returns. That lets
224 * device driver code (like this routine) unlink queued urbs first,
225 * if it needs to, since the HC won't work on them at all. So it's
226 * not possible for page N+1 to overwrite page N, and so on.
228 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
229 * complete before the HCD can get requests away from hardware,
230 * though never during cleanup after a hard fault.
232 if (io->status
233 && (io->status != -ECONNRESET
234 || urb->status != -ECONNRESET)
235 && urb->actual_length) {
236 dev_err (io->dev->bus->controller,
237 "dev %s ep%d%s scatterlist error %d/%d\n",
238 io->dev->devpath,
239 usb_pipeendpoint (urb->pipe),
240 usb_pipein (urb->pipe) ? "in" : "out",
241 urb->status, io->status);
242 // BUG ();
245 if (urb->status && urb->status != -ECONNRESET) {
246 int i, found, status;
248 io->status = urb->status;
250 /* the previous urbs, and this one, completed already.
251 * unlink the later ones so they won't rx/tx bad data,
253 * FIXME don't bother unlinking urbs that haven't yet been
254 * submitted; those non-error cases shouldn't be syslogged
256 for (i = 0, found = 0; i < io->entries; i++) {
257 if (found) {
258 status = usb_unlink_urb (io->urbs [i]);
259 if (status && status != -EINPROGRESS)
260 err ("sg_complete, unlink --> %d",
261 status);
262 } else if (urb == io->urbs [i])
263 found = 1;
267 /* on the last completion, signal usb_sg_wait() */
268 io->bytes += urb->actual_length;
269 io->count--;
270 if (!io->count)
271 complete (&io->complete);
273 spin_unlock_irqrestore (&io->lock, flags);
278 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
279 * @io: request block being initialized. until usb_sg_wait() returns,
280 * treat this as a pointer to an opaque block of memory,
281 * @dev: the usb device that will send or receive the data
282 * @pipe: endpoint "pipe" used to transfer the data
283 * @period: polling rate for interrupt endpoints, in frames or
284 * (for high speed endpoints) microframes; ignored for bulk
285 * @sg: scatterlist entries
286 * @nents: how many entries in the scatterlist
287 * @length: how many bytes to send from the scatterlist, or zero to
288 * send every byte identified in the list.
289 * @mem_flags: SLAB_* flags affecting memory allocations in this call
291 * Returns zero for success, else a negative errno value. This initializes a
292 * scatter/gather request, allocating resources such as I/O mappings and urb
293 * memory (except maybe memory used by USB controller drivers).
295 * The request must be issued using usb_sg_wait(), which waits for the I/O to
296 * complete (or to be canceled) and then cleans up all resources allocated by
297 * usb_sg_init().
299 * The request may be canceled with usb_sg_cancel(), either before or after
300 * usb_sg_wait() is called.
302 int usb_sg_init (
303 struct usb_sg_request *io,
304 struct usb_device *dev,
305 unsigned pipe,
306 unsigned period,
307 struct scatterlist *sg,
308 int nents,
309 size_t length,
310 int mem_flags
313 int i;
314 int urb_flags;
315 int dma;
317 if (!io || !dev || !sg
318 || usb_pipecontrol (pipe)
319 || usb_pipeisoc (pipe)
320 || nents <= 0)
321 return -EINVAL;
323 spin_lock_init (&io->lock);
324 io->dev = dev;
325 io->pipe = pipe;
326 io->sg = sg;
327 io->nents = nents;
329 /* not all host controllers use DMA (like the mainstream pci ones);
330 * they can use PIO (sl811) or be software over another transport.
332 dma = (dev->dev.dma_mask != 0);
333 if (dma)
334 io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
335 else
336 io->entries = nents;
338 /* initialize all the urbs we'll use */
339 if (io->entries <= 0)
340 return io->entries;
342 io->count = 0;
343 io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
344 if (!io->urbs)
345 goto nomem;
347 urb_flags = URB_ASYNC_UNLINK | URB_NO_TRANSFER_DMA_MAP
348 | URB_NO_INTERRUPT;
349 if (usb_pipein (pipe))
350 urb_flags |= URB_SHORT_NOT_OK;
352 for (i = 0; i < io->entries; i++, io->count = i) {
353 unsigned len;
355 io->urbs [i] = usb_alloc_urb (0, mem_flags);
356 if (!io->urbs [i]) {
357 io->entries = i;
358 goto nomem;
361 io->urbs [i]->dev = dev;
362 io->urbs [i]->pipe = pipe;
363 io->urbs [i]->interval = period;
364 io->urbs [i]->transfer_flags = urb_flags;
366 io->urbs [i]->complete = sg_complete;
367 io->urbs [i]->context = io;
368 io->urbs [i]->status = -EINPROGRESS;
369 io->urbs [i]->actual_length = 0;
371 if (dma) {
372 /* hc may use _only_ transfer_dma */
373 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
374 len = sg_dma_len (sg + i);
375 } else {
376 /* hc may use _only_ transfer_buffer */
377 io->urbs [i]->transfer_buffer =
378 page_address (sg [i].page) + sg [i].offset;
379 len = sg [i].length;
382 if (length) {
383 len = min_t (unsigned, len, length);
384 length -= len;
385 if (length == 0)
386 io->entries = i + 1;
388 io->urbs [i]->transfer_buffer_length = len;
390 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
392 /* transaction state */
393 io->status = 0;
394 io->bytes = 0;
395 init_completion (&io->complete);
396 return 0;
398 nomem:
399 sg_clean (io);
400 return -ENOMEM;
405 * usb_sg_wait - synchronously execute scatter/gather request
406 * @io: request block handle, as initialized with usb_sg_init().
407 * some fields become accessible when this call returns.
408 * Context: !in_interrupt ()
410 * This function blocks until the specified I/O operation completes. It
411 * leverages the grouping of the related I/O requests to get good transfer
412 * rates, by queueing the requests. At higher speeds, such queuing can
413 * significantly improve USB throughput.
415 * There are three kinds of completion for this function.
416 * (1) success, where io->status is zero. The number of io->bytes
417 * transferred is as requested.
418 * (2) error, where io->status is a negative errno value. The number
419 * of io->bytes transferred before the error is usually less
420 * than requested, and can be nonzero.
421 * (3) cancelation, a type of error with status -ECONNRESET that
422 * is initiated by usb_sg_cancel().
424 * When this function returns, all memory allocated through usb_sg_init() or
425 * this call will have been freed. The request block parameter may still be
426 * passed to usb_sg_cancel(), or it may be freed. It could also be
427 * reinitialized and then reused.
429 * Data Transfer Rates:
431 * Bulk transfers are valid for full or high speed endpoints.
432 * The best full speed data rate is 19 packets of 64 bytes each
433 * per frame, or 1216 bytes per millisecond.
434 * The best high speed data rate is 13 packets of 512 bytes each
435 * per microframe, or 52 KBytes per millisecond.
437 * The reason to use interrupt transfers through this API would most likely
438 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
439 * could be transferred. That capability is less useful for low or full
440 * speed interrupt endpoints, which allow at most one packet per millisecond,
441 * of at most 8 or 64 bytes (respectively).
443 void usb_sg_wait (struct usb_sg_request *io)
445 int i;
446 unsigned long flags;
448 /* queue the urbs. */
449 spin_lock_irqsave (&io->lock, flags);
450 for (i = 0; i < io->entries && !io->status; i++) {
451 int retval;
453 retval = usb_submit_urb (io->urbs [i], SLAB_ATOMIC);
455 /* after we submit, let completions or cancelations fire;
456 * we handshake using io->status.
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 retval = 0;
465 i--;
466 // FIXME: should it usb_sg_cancel() on INTERRUPT?
467 yield ();
468 break;
470 /* no error? continue immediately.
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?
476 case 0:
477 cpu_relax ();
478 break;
480 /* fail any uncompleted urbs */
481 default:
482 io->urbs [i]->status = retval;
483 dbg ("usb_sg_msg, submit --> %d", retval);
484 usb_sg_cancel (io);
486 spin_lock_irqsave (&io->lock, flags);
487 if (retval && io->status == -ECONNRESET)
488 io->status = retval;
490 spin_unlock_irqrestore (&io->lock, flags);
492 /* OK, yes, this could be packaged as non-blocking.
493 * So could the submit loop above ... but it's easier to
494 * solve neither problem than to solve both!
496 wait_for_completion (&io->complete);
498 sg_clean (io);
502 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
503 * @io: request block, initialized with usb_sg_init()
505 * This stops a request after it has been started by usb_sg_wait().
506 * It can also prevents one initialized by usb_sg_init() from starting,
507 * so that call just frees resources allocated to the request.
509 void usb_sg_cancel (struct usb_sg_request *io)
511 unsigned long flags;
513 spin_lock_irqsave (&io->lock, flags);
515 /* shut everything down, if it didn't already */
516 if (!io->status) {
517 int i;
519 io->status = -ECONNRESET;
520 for (i = 0; i < io->entries; i++) {
521 int retval;
523 if (!io->urbs [i]->dev)
524 continue;
525 retval = usb_unlink_urb (io->urbs [i]);
526 if (retval && retval != -EINPROGRESS)
527 warn ("usb_sg_cancel, unlink --> %d", retval);
528 // FIXME don't warn on "not yet submitted" error
531 spin_unlock_irqrestore (&io->lock, flags);
534 /*-------------------------------------------------------------------*/
537 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
538 * @dev: the device whose descriptor is being retrieved
539 * @type: the descriptor type (USB_DT_*)
540 * @index: the number of the descriptor
541 * @buf: where to put the descriptor
542 * @size: how big is "buf"?
543 * Context: !in_interrupt ()
545 * Gets a USB descriptor. Convenience functions exist to simplify
546 * getting some types of descriptors. Use
547 * usb_get_device_descriptor() for USB_DT_DEVICE,
548 * and usb_get_string() or usb_string() for USB_DT_STRING.
549 * Configuration descriptors (USB_DT_CONFIG) are part of the device
550 * structure, at least for the current configuration.
551 * In addition to a number of USB-standard descriptors, some
552 * devices also use class-specific or vendor-specific descriptors.
554 * This call is synchronous, and may not be used in an interrupt context.
556 * Returns the number of bytes received on success, or else the status code
557 * returned by the underlying usb_control_msg() call.
559 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
561 int i = 5;
562 int result;
564 memset(buf,0,size); // Make sure we parse really received data
566 while (i--) {
567 /* retries if the returned length was 0; flakey device */
568 if ((result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
569 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
570 (type << 8) + index, 0, buf, size,
571 HZ * USB_CTRL_GET_TIMEOUT)) > 0
572 || result == -EPIPE)
573 break;
575 return result;
579 * usb_get_string - gets a string descriptor
580 * @dev: the device whose string descriptor is being retrieved
581 * @langid: code for language chosen (from string descriptor zero)
582 * @index: the number of the descriptor
583 * @buf: where to put the string
584 * @size: how big is "buf"?
585 * Context: !in_interrupt ()
587 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
588 * in little-endian byte order).
589 * The usb_string() function will often be a convenient way to turn
590 * these strings into kernel-printable form.
592 * Strings may be referenced in device, configuration, interface, or other
593 * descriptors, and could also be used in vendor-specific ways.
595 * This call is synchronous, and may not be used in an interrupt context.
597 * Returns the number of bytes received on success, or else the status code
598 * returned by the underlying usb_control_msg() call.
600 int usb_get_string(struct usb_device *dev, unsigned short langid, unsigned char index, void *buf, int size)
602 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
603 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
604 (USB_DT_STRING << 8) + index, langid, buf, size,
605 HZ * USB_CTRL_GET_TIMEOUT);
609 * usb_get_device_descriptor - (re)reads the device descriptor
610 * @dev: the device whose device descriptor is being updated
611 * Context: !in_interrupt ()
613 * Updates the copy of the device descriptor stored in the device structure,
614 * which dedicates space for this purpose. Note that several fields are
615 * converted to the host CPU's byte order: the USB version (bcdUSB), and
616 * vendors product and version fields (idVendor, idProduct, and bcdDevice).
617 * That lets device drivers compare against non-byteswapped constants.
619 * There's normally no need to use this call, although some devices
620 * will change their descriptors after events like updating firmware.
622 * This call is synchronous, and may not be used in an interrupt context.
624 * Returns the number of bytes received on success, or else the status code
625 * returned by the underlying usb_control_msg() call.
627 int usb_get_device_descriptor(struct usb_device *dev)
629 int ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, &dev->descriptor,
630 sizeof(dev->descriptor));
631 if (ret >= 0) {
632 le16_to_cpus(&dev->descriptor.bcdUSB);
633 le16_to_cpus(&dev->descriptor.idVendor);
634 le16_to_cpus(&dev->descriptor.idProduct);
635 le16_to_cpus(&dev->descriptor.bcdDevice);
637 return ret;
641 * usb_get_status - issues a GET_STATUS call
642 * @dev: the device whose status is being checked
643 * @type: USB_RECIP_*; for device, interface, or endpoint
644 * @target: zero (for device), else interface or endpoint number
645 * @data: pointer to two bytes of bitmap data
646 * Context: !in_interrupt ()
648 * Returns device, interface, or endpoint status. Normally only of
649 * interest to see if the device is self powered, or has enabled the
650 * remote wakeup facility; or whether a bulk or interrupt endpoint
651 * is halted ("stalled").
653 * Bits in these status bitmaps are set using the SET_FEATURE request,
654 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
655 * function should be used to clear halt ("stall") status.
657 * This call is synchronous, and may not be used in an interrupt context.
659 * Returns the number of bytes received on success, or else the status code
660 * returned by the underlying usb_control_msg() call.
662 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
664 return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
665 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, data, 2,
666 HZ * USB_CTRL_GET_TIMEOUT);
670 // hub-only!! ... and only exported for reset/reinit path.
671 // otherwise used internally, when setting up a config
672 void usb_set_maxpacket(struct usb_device *dev)
674 int i, b;
676 /* NOTE: affects all endpoints _except_ ep0 */
677 for (i=0; i<dev->actconfig->desc.bNumInterfaces; i++) {
678 struct usb_interface *ifp = dev->actconfig->interface + i;
679 struct usb_host_interface *as = ifp->altsetting + ifp->act_altsetting;
680 struct usb_host_endpoint *ep = as->endpoint;
681 int e;
683 for (e=0; e<as->desc.bNumEndpoints; e++) {
684 struct usb_endpoint_descriptor *d;
685 d = &ep [e].desc;
686 b = d->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
687 if ((d->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
688 USB_ENDPOINT_XFER_CONTROL) { /* Control => bidirectional */
689 dev->epmaxpacketout[b] = d->wMaxPacketSize;
690 dev->epmaxpacketin [b] = d->wMaxPacketSize;
692 else if (usb_endpoint_out(d->bEndpointAddress)) {
693 if (d->wMaxPacketSize > dev->epmaxpacketout[b])
694 dev->epmaxpacketout[b] = d->wMaxPacketSize;
696 else {
697 if (d->wMaxPacketSize > dev->epmaxpacketin [b])
698 dev->epmaxpacketin [b] = d->wMaxPacketSize;
705 * usb_clear_halt - tells device to clear endpoint halt/stall condition
706 * @dev: device whose endpoint is halted
707 * @pipe: endpoint "pipe" being cleared
708 * Context: !in_interrupt ()
710 * This is used to clear halt conditions for bulk and interrupt endpoints,
711 * as reported by URB completion status. Endpoints that are halted are
712 * sometimes referred to as being "stalled". Such endpoints are unable
713 * to transmit or receive data until the halt status is cleared. Any URBs
714 * queued for such an endpoint should normally be unlinked by the driver
715 * before clearing the halt condition, as described in sections 5.7.5
716 * and 5.8.5 of the USB 2.0 spec.
718 * Note that control and isochronous endpoints don't halt, although control
719 * endpoints report "protocol stall" (for unsupported requests) using the
720 * same status code used to report a true stall.
722 * This call is synchronous, and may not be used in an interrupt context.
724 * Returns zero on success, or else the status code returned by the
725 * underlying usb_control_msg() call.
727 int usb_clear_halt(struct usb_device *dev, int pipe)
729 int result;
730 int endp = usb_pipeendpoint(pipe);
732 if (usb_pipein (pipe))
733 endp |= USB_DIR_IN;
735 /* we don't care if it wasn't halted first. in fact some devices
736 * (like some ibmcam model 1 units) seem to expect hosts to make
737 * this request for iso endpoints, which can't halt!
739 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
740 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT, 0, endp, NULL, 0,
741 HZ * USB_CTRL_SET_TIMEOUT);
743 /* don't un-halt or force to DATA0 except on success */
744 if (result < 0)
745 return result;
747 /* NOTE: seems like Microsoft and Apple don't bother verifying
748 * the clear "took", so some devices could lock up if you check...
749 * such as the Hagiwara FlashGate DUAL. So we won't bother.
751 * NOTE: make sure the logic here doesn't diverge much from
752 * the copy in usb-storage, for as long as we need two copies.
755 /* toggle was reset by the clear, then ep was reactivated */
756 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
757 usb_endpoint_running(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe));
759 return 0;
763 * usb_set_interface - Makes a particular alternate setting be current
764 * @dev: the device whose interface is being updated
765 * @interface: the interface being updated
766 * @alternate: the setting being chosen.
767 * Context: !in_interrupt ()
769 * This is used to enable data transfers on interfaces that may not
770 * be enabled by default. Not all devices support such configurability.
771 * Only the driver bound to an interface may change its setting.
773 * Within any given configuration, each interface may have several
774 * alternative settings. These are often used to control levels of
775 * bandwidth consumption. For example, the default setting for a high
776 * speed interrupt endpoint may not send more than 64 bytes per microframe,
777 * while interrupt transfers of up to 3KBytes per microframe are legal.
778 * Also, isochronous endpoints may never be part of an
779 * interface's default setting. To access such bandwidth, alternate
780 * interface settings must be made current.
782 * Note that in the Linux USB subsystem, bandwidth associated with
783 * an endpoint in a given alternate setting is not reserved until an URB
784 * is submitted that needs that bandwidth. Some other operating systems
785 * allocate bandwidth early, when a configuration is chosen.
787 * This call is synchronous, and may not be used in an interrupt context.
788 * Also, drivers must not change altsettings while urbs are scheduled for
789 * endpoints in that interface; all such urbs must first be completed
790 * (perhaps forced by unlinking).
792 * Returns zero on success, or else the status code returned by the
793 * underlying usb_control_msg() call.
795 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
797 struct usb_interface *iface;
798 struct usb_host_interface *iface_as;
799 int i, ret;
800 void (*disable)(struct usb_device *, int) = dev->bus->op->disable;
802 iface = usb_ifnum_to_if(dev, interface);
803 if (!iface) {
804 warn("selecting invalid interface %d", interface);
805 return -EINVAL;
808 /* 9.4.10 says devices don't need this, if the interface
809 only has one alternate setting */
810 if (iface->num_altsetting == 1) {
811 dbg("ignoring set_interface for dev %d, iface %d, alt %d",
812 dev->devnum, interface, alternate);
813 return 0;
816 if (alternate < 0 || alternate >= iface->num_altsetting)
817 return -EINVAL;
819 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
820 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
821 iface->altsetting[alternate]
822 .desc.bAlternateSetting,
823 interface, NULL, 0, HZ * 5)) < 0)
824 return ret;
826 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
827 * when they implement async or easily-killable versions of this or
828 * other "should-be-internal" functions (like clear_halt).
829 * should hcd+usbcore postprocess control requests?
832 /* prevent submissions using previous endpoint settings */
833 iface_as = iface->altsetting + iface->act_altsetting;
834 for (i = 0; i < iface_as->desc.bNumEndpoints; i++) {
835 u8 ep = iface_as->endpoint [i].desc.bEndpointAddress;
836 int out = !(ep & USB_DIR_IN);
838 /* clear out hcd state, then usbcore state */
839 if (disable)
840 disable (dev, ep);
841 ep &= USB_ENDPOINT_NUMBER_MASK;
842 (out ? dev->epmaxpacketout : dev->epmaxpacketin ) [ep] = 0;
844 iface->act_altsetting = alternate;
846 /* 9.1.1.5: reset toggles for all endpoints affected by this iface-as
848 * Note:
849 * Despite EP0 is always present in all interfaces/AS, the list of
850 * endpoints from the descriptor does not contain EP0. Due to its
851 * omnipresence one might expect EP0 being considered "affected" by
852 * any SetInterface request and hence assume toggles need to be reset.
853 * However, EP0 toggles are re-synced for every individual transfer
854 * during the SETUP stage - hence EP0 toggles are "don't care" here.
855 * (Likewise, EP0 never "halts" on well designed devices.)
858 iface_as = &iface->altsetting[alternate];
859 for (i = 0; i < iface_as->desc.bNumEndpoints; i++) {
860 u8 ep = iface_as->endpoint[i].desc.bEndpointAddress;
861 int out = !(ep & USB_DIR_IN);
863 ep &= USB_ENDPOINT_NUMBER_MASK;
864 usb_settoggle (dev, ep, out, 0);
865 (out ? dev->epmaxpacketout : dev->epmaxpacketin) [ep]
866 = iface_as->endpoint [i].desc.wMaxPacketSize;
867 usb_endpoint_running (dev, ep, out);
870 return 0;
874 * usb_set_configuration - Makes a particular device setting be current
875 * @dev: the device whose configuration is being updated
876 * @configuration: the configuration being chosen.
877 * Context: !in_interrupt ()
879 * This is used to enable non-default device modes. Not all devices
880 * support this kind of configurability. By default, configuration
881 * zero is selected after enumeration; many devices only have a single
882 * configuration.
884 * USB devices may support one or more configurations, which affect
885 * power consumption and the functionality available. For example,
886 * the default configuration is limited to using 100mA of bus power,
887 * so that when certain device functionality requires more power,
888 * and the device is bus powered, that functionality will be in some
889 * non-default device configuration. Other device modes may also be
890 * reflected as configuration options, such as whether two ISDN
891 * channels are presented as independent 64Kb/s interfaces or as one
892 * bonded 128Kb/s interface.
894 * Note that USB has an additional level of device configurability,
895 * associated with interfaces. That configurability is accessed using
896 * usb_set_interface().
898 * This call is synchronous, and may not be used in an interrupt context.
900 * Returns zero on success, or else the status code returned by the
901 * underlying usb_control_msg() call.
903 int usb_set_configuration(struct usb_device *dev, int configuration)
905 int i, ret;
906 struct usb_host_config *cp = NULL;
907 void (*disable)(struct usb_device *, int) = dev->bus->op->disable;
909 for (i=0; i<dev->descriptor.bNumConfigurations; i++) {
910 if (dev->config[i].desc.bConfigurationValue == configuration) {
911 cp = &dev->config[i];
912 break;
915 if ((!cp && configuration != 0) || (cp && configuration == 0)) {
916 warn("selecting invalid configuration %d", configuration);
917 return -EINVAL;
920 /* if it's already configured, clear out old state first. */
921 if (dev->state != USB_STATE_ADDRESS && disable) {
922 for (i = 1 /* skip ep0 */; i < 15; i++) {
923 disable (dev, i);
924 disable (dev, USB_DIR_IN | i);
927 dev->toggle[0] = dev->toggle[1] = 0;
928 dev->halted[0] = dev->halted[1] = 0;
929 dev->state = USB_STATE_ADDRESS;
931 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
932 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
933 NULL, 0, HZ * USB_CTRL_SET_TIMEOUT)) < 0)
934 return ret;
935 if (configuration)
936 dev->state = USB_STATE_CONFIGURED;
937 dev->actconfig = cp;
939 /* reset more hc/hcd endpoint state */
940 usb_set_maxpacket(dev);
942 return 0;
947 * usb_string - returns ISO 8859-1 version of a string descriptor
948 * @dev: the device whose string descriptor is being retrieved
949 * @index: the number of the descriptor
950 * @buf: where to put the string
951 * @size: how big is "buf"?
952 * Context: !in_interrupt ()
954 * This converts the UTF-16LE encoded strings returned by devices, from
955 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
956 * that are more usable in most kernel contexts. Note that all characters
957 * in the chosen descriptor that can't be encoded using ISO-8859-1
958 * are converted to the question mark ("?") character, and this function
959 * chooses strings in the first language supported by the device.
961 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
962 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
963 * and is appropriate for use many uses of English and several other
964 * Western European languages. (But it doesn't include the "Euro" symbol.)
966 * This call is synchronous, and may not be used in an interrupt context.
968 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
970 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
972 unsigned char *tbuf;
973 int err, len;
974 unsigned int u, idx;
976 if (size <= 0 || !buf || !index)
977 return -EINVAL;
978 buf[0] = 0;
979 tbuf = kmalloc(256, GFP_KERNEL);
980 if (!tbuf)
981 return -ENOMEM;
983 /* get langid for strings if it's not yet known */
984 if (!dev->have_langid) {
985 err = usb_get_string(dev, 0, 0, tbuf, 4);
986 if (err < 0) {
987 err("error getting string descriptor 0 (error=%d)", err);
988 goto errout;
989 } else if (err < 4 || tbuf[0] < 4) {
990 err("string descriptor 0 too short");
991 err = -EINVAL;
992 goto errout;
993 } else {
994 dev->have_langid = -1;
995 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
996 /* always use the first langid listed */
997 dbg("USB device number %d default language ID 0x%x",
998 dev->devnum, dev->string_langid);
1003 * ask for the length of the string
1006 err = usb_get_string(dev, dev->string_langid, index, tbuf, 2);
1007 if(err<2)
1008 goto errout;
1009 len=tbuf[0];
1011 err = usb_get_string(dev, dev->string_langid, index, tbuf, len);
1012 if (err < 0)
1013 goto errout;
1015 size--; /* leave room for trailing NULL char in output buffer */
1016 for (idx = 0, u = 2; u < err; u += 2) {
1017 if (idx >= size)
1018 break;
1019 if (tbuf[u+1]) /* high byte */
1020 buf[idx++] = '?'; /* non ISO-8859-1 character */
1021 else
1022 buf[idx++] = tbuf[u];
1024 buf[idx] = 0;
1025 err = idx;
1027 errout:
1028 kfree(tbuf);
1029 return err;
1032 // synchronous request completion model
1033 EXPORT_SYMBOL(usb_control_msg);
1034 EXPORT_SYMBOL(usb_bulk_msg);
1036 EXPORT_SYMBOL(usb_sg_init);
1037 EXPORT_SYMBOL(usb_sg_cancel);
1038 EXPORT_SYMBOL(usb_sg_wait);
1040 // synchronous control message convenience routines
1041 EXPORT_SYMBOL(usb_get_descriptor);
1042 EXPORT_SYMBOL(usb_get_device_descriptor);
1043 EXPORT_SYMBOL(usb_get_status);
1044 EXPORT_SYMBOL(usb_get_string);
1045 EXPORT_SYMBOL(usb_string);
1046 EXPORT_SYMBOL(usb_clear_halt);
1047 EXPORT_SYMBOL(usb_set_configuration);
1048 EXPORT_SYMBOL(usb_set_interface);