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