blob: 530e854961ce99785291b399d92253151c626d9e [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,
Alan Stern8d062b92007-04-23 17:30:32 -0400226 usb_api_blocking_completion, NULL,
227 ep->desc.bInterval);
Alan Sternd09d36a2005-09-26 16:22:45 -0400228 } 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;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700407
Tony Lindgren35d07fd2007-03-31 18:15:43 -0700408 /*
409 * Some systems need to revert to PIO when DMA is temporarily
410 * unavailable. For their sakes, both transfer_buffer and
411 * transfer_dma are set when possible. However this can only
412 * work on systems without HIGHMEM, since DMA buffers located
413 * in high memory are not directly addressable by the CPU for
414 * PIO ... so when HIGHMEM is in use, transfer_buffer is NULL
415 * to prevent stale pointers and to help spot bugs.
416 */
Linus Torvalds1da177e2005-04-16 15:20:36 -0700417 if (dma) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700418 io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
419 len = sg_dma_len (sg + i);
Tony Lindgren35d07fd2007-03-31 18:15:43 -0700420#ifdef CONFIG_HIGHMEM
421 io->urbs[i]->transfer_buffer = NULL;
422#else
423 io->urbs[i]->transfer_buffer =
424 page_address(sg[i].page) + sg[i].offset;
425#endif
Linus Torvalds1da177e2005-04-16 15:20:36 -0700426 } else {
427 /* hc may use _only_ transfer_buffer */
428 io->urbs [i]->transfer_buffer =
429 page_address (sg [i].page) + sg [i].offset;
430 len = sg [i].length;
431 }
432
433 if (length) {
434 len = min_t (unsigned, len, length);
435 length -= len;
436 if (length == 0)
437 io->entries = i + 1;
438 }
439 io->urbs [i]->transfer_buffer_length = len;
440 }
441 io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
442
443 /* transaction state */
444 io->status = 0;
445 io->bytes = 0;
446 init_completion (&io->complete);
447 return 0;
448
449nomem:
450 sg_clean (io);
451 return -ENOMEM;
452}
453
454
455/**
456 * usb_sg_wait - synchronously execute scatter/gather request
457 * @io: request block handle, as initialized with usb_sg_init().
458 * some fields become accessible when this call returns.
459 * Context: !in_interrupt ()
460 *
461 * This function blocks until the specified I/O operation completes. It
462 * leverages the grouping of the related I/O requests to get good transfer
463 * rates, by queueing the requests. At higher speeds, such queuing can
464 * significantly improve USB throughput.
465 *
466 * There are three kinds of completion for this function.
467 * (1) success, where io->status is zero. The number of io->bytes
468 * transferred is as requested.
469 * (2) error, where io->status is a negative errno value. The number
470 * of io->bytes transferred before the error is usually less
471 * than requested, and can be nonzero.
Steven Cole093cf722005-05-03 19:07:24 -0600472 * (3) cancellation, a type of error with status -ECONNRESET that
Linus Torvalds1da177e2005-04-16 15:20:36 -0700473 * is initiated by usb_sg_cancel().
474 *
475 * When this function returns, all memory allocated through usb_sg_init() or
476 * this call will have been freed. The request block parameter may still be
477 * passed to usb_sg_cancel(), or it may be freed. It could also be
478 * reinitialized and then reused.
479 *
480 * Data Transfer Rates:
481 *
482 * Bulk transfers are valid for full or high speed endpoints.
483 * The best full speed data rate is 19 packets of 64 bytes each
484 * per frame, or 1216 bytes per millisecond.
485 * The best high speed data rate is 13 packets of 512 bytes each
486 * per microframe, or 52 KBytes per millisecond.
487 *
488 * The reason to use interrupt transfers through this API would most likely
489 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
490 * could be transferred. That capability is less useful for low or full
491 * speed interrupt endpoints, which allow at most one packet per millisecond,
492 * of at most 8 or 64 bytes (respectively).
493 */
494void usb_sg_wait (struct usb_sg_request *io)
495{
496 int i, entries = io->entries;
497
498 /* queue the urbs. */
499 spin_lock_irq (&io->lock);
Alan Stern8ccef0d2007-06-21 16:26:46 -0400500 i = 0;
501 while (i < entries && !io->status) {
Linus Torvalds1da177e2005-04-16 15:20:36 -0700502 int retval;
503
504 io->urbs [i]->dev = io->dev;
Christoph Lameter54e6ecb2006-12-06 20:33:16 -0800505 retval = usb_submit_urb (io->urbs [i], GFP_ATOMIC);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700506
507 /* after we submit, let completions or cancelations fire;
508 * we handshake using io->status.
509 */
510 spin_unlock_irq (&io->lock);
511 switch (retval) {
512 /* maybe we retrying will recover */
513 case -ENXIO: // hc didn't queue this one
514 case -EAGAIN:
515 case -ENOMEM:
516 io->urbs[i]->dev = NULL;
517 retval = 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700518 yield ();
519 break;
520
521 /* no error? continue immediately.
522 *
523 * NOTE: to work better with UHCI (4K I/O buffer may
524 * need 3K of TDs) it may be good to limit how many
525 * URBs are queued at once; N milliseconds?
526 */
527 case 0:
Alan Stern8ccef0d2007-06-21 16:26:46 -0400528 ++i;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700529 cpu_relax ();
530 break;
531
532 /* fail any uncompleted urbs */
533 default:
534 io->urbs [i]->dev = NULL;
535 io->urbs [i]->status = retval;
536 dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
537 __FUNCTION__, retval);
538 usb_sg_cancel (io);
539 }
540 spin_lock_irq (&io->lock);
541 if (retval && (io->status == 0 || io->status == -ECONNRESET))
542 io->status = retval;
543 }
544 io->count -= entries - i;
545 if (io->count == 0)
546 complete (&io->complete);
547 spin_unlock_irq (&io->lock);
548
549 /* OK, yes, this could be packaged as non-blocking.
550 * So could the submit loop above ... but it's easier to
551 * solve neither problem than to solve both!
552 */
553 wait_for_completion (&io->complete);
554
555 sg_clean (io);
556}
557
558/**
559 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
560 * @io: request block, initialized with usb_sg_init()
561 *
562 * This stops a request after it has been started by usb_sg_wait().
563 * It can also prevents one initialized by usb_sg_init() from starting,
564 * so that call just frees resources allocated to the request.
565 */
566void usb_sg_cancel (struct usb_sg_request *io)
567{
568 unsigned long flags;
569
570 spin_lock_irqsave (&io->lock, flags);
571
572 /* shut everything down, if it didn't already */
573 if (!io->status) {
574 int i;
575
576 io->status = -ECONNRESET;
577 spin_unlock (&io->lock);
578 for (i = 0; i < io->entries; i++) {
579 int retval;
580
581 if (!io->urbs [i]->dev)
582 continue;
583 retval = usb_unlink_urb (io->urbs [i]);
584 if (retval != -EINPROGRESS && retval != -EBUSY)
585 dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
586 __FUNCTION__, retval);
587 }
588 spin_lock (&io->lock);
589 }
590 spin_unlock_irqrestore (&io->lock, flags);
591}
592
593/*-------------------------------------------------------------------*/
594
595/**
596 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
597 * @dev: the device whose descriptor is being retrieved
598 * @type: the descriptor type (USB_DT_*)
599 * @index: the number of the descriptor
600 * @buf: where to put the descriptor
601 * @size: how big is "buf"?
602 * Context: !in_interrupt ()
603 *
604 * Gets a USB descriptor. Convenience functions exist to simplify
605 * getting some types of descriptors. Use
606 * usb_get_string() or usb_string() for USB_DT_STRING.
607 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
608 * are part of the device structure.
609 * In addition to a number of USB-standard descriptors, some
610 * devices also use class-specific or vendor-specific descriptors.
611 *
612 * This call is synchronous, and may not be used in an interrupt context.
613 *
614 * Returns the number of bytes received on success, or else the status code
615 * returned by the underlying usb_control_msg() call.
616 */
617int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
618{
619 int i;
620 int result;
621
622 memset(buf,0,size); // Make sure we parse really received data
623
624 for (i = 0; i < 3; ++i) {
625 /* retry on length 0 or stall; some devices are flakey */
626 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
627 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
628 (type << 8) + index, 0, buf, size,
629 USB_CTRL_GET_TIMEOUT);
630 if (result == 0 || result == -EPIPE)
631 continue;
632 if (result > 1 && ((u8 *)buf)[1] != type) {
633 result = -EPROTO;
634 continue;
635 }
636 break;
637 }
638 return result;
639}
640
641/**
642 * usb_get_string - gets a string descriptor
643 * @dev: the device whose string descriptor is being retrieved
644 * @langid: code for language chosen (from string descriptor zero)
645 * @index: the number of the descriptor
646 * @buf: where to put the string
647 * @size: how big is "buf"?
648 * Context: !in_interrupt ()
649 *
650 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
651 * in little-endian byte order).
652 * The usb_string() function will often be a convenient way to turn
653 * these strings into kernel-printable form.
654 *
655 * Strings may be referenced in device, configuration, interface, or other
656 * descriptors, and could also be used in vendor-specific ways.
657 *
658 * This call is synchronous, and may not be used in an interrupt context.
659 *
660 * Returns the number of bytes received on success, or else the status code
661 * returned by the underlying usb_control_msg() call.
662 */
Adrian Bunke266a122005-11-08 21:05:43 +0100663static int usb_get_string(struct usb_device *dev, unsigned short langid,
664 unsigned char index, void *buf, int size)
Linus Torvalds1da177e2005-04-16 15:20:36 -0700665{
666 int i;
667 int result;
668
669 for (i = 0; i < 3; ++i) {
670 /* retry on length 0 or stall; some devices are flakey */
671 result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
672 USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
673 (USB_DT_STRING << 8) + index, langid, buf, size,
674 USB_CTRL_GET_TIMEOUT);
675 if (!(result == 0 || result == -EPIPE))
676 break;
677 }
678 return result;
679}
680
681static void usb_try_string_workarounds(unsigned char *buf, int *length)
682{
683 int newlength, oldlength = *length;
684
685 for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
686 if (!isprint(buf[newlength]) || buf[newlength + 1])
687 break;
688
689 if (newlength > 2) {
690 buf[0] = newlength;
691 *length = newlength;
692 }
693}
694
695static int usb_string_sub(struct usb_device *dev, unsigned int langid,
696 unsigned int index, unsigned char *buf)
697{
698 int rc;
699
700 /* Try to read the string descriptor by asking for the maximum
701 * possible number of bytes */
Oliver Neukum7ceec1f2007-01-26 14:26:21 +0100702 if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
703 rc = -EIO;
704 else
705 rc = usb_get_string(dev, langid, index, buf, 255);
Linus Torvalds1da177e2005-04-16 15:20:36 -0700706
707 /* If that failed try to read the descriptor length, then
708 * ask for just that many bytes */
709 if (rc < 2) {
710 rc = usb_get_string(dev, langid, index, buf, 2);
711 if (rc == 2)
712 rc = usb_get_string(dev, langid, index, buf, buf[0]);
713 }
714
715 if (rc >= 2) {
716 if (!buf[0] && !buf[1])
717 usb_try_string_workarounds(buf, &rc);
718
719 /* There might be extra junk at the end of the descriptor */
720 if (buf[0] < rc)
721 rc = buf[0];
722
723 rc = rc - (rc & 1); /* force a multiple of two */
724 }
725
726 if (rc < 2)
727 rc = (rc < 0 ? rc : -EINVAL);
728
729 return rc;
730}
731
732/**
733 * usb_string - returns ISO 8859-1 version of a string descriptor
734 * @dev: the device whose string descriptor is being retrieved
735 * @index: the number of the descriptor
736 * @buf: where to put the string
737 * @size: how big is "buf"?
738 * Context: !in_interrupt ()
739 *
740 * This converts the UTF-16LE encoded strings returned by devices, from
741 * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
742 * that are more usable in most kernel contexts. Note that all characters
743 * in the chosen descriptor that can't be encoded using ISO-8859-1
744 * are converted to the question mark ("?") character, and this function
745 * chooses strings in the first language supported by the device.
746 *
747 * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
748 * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
749 * and is appropriate for use many uses of English and several other
750 * Western European languages. (But it doesn't include the "Euro" symbol.)
751 *
752 * This call is synchronous, and may not be used in an interrupt context.
753 *
754 * Returns length of the string (>= 0) or usb_control_msg status (< 0).
755 */
756int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
757{
758 unsigned char *tbuf;
759 int err;
760 unsigned int u, idx;
761
762 if (dev->state == USB_STATE_SUSPENDED)
763 return -EHOSTUNREACH;
764 if (size <= 0 || !buf || !index)
765 return -EINVAL;
766 buf[0] = 0;
767 tbuf = kmalloc(256, GFP_KERNEL);
768 if (!tbuf)
769 return -ENOMEM;
770
771 /* get langid for strings if it's not yet known */
772 if (!dev->have_langid) {
773 err = usb_string_sub(dev, 0, 0, tbuf);
774 if (err < 0) {
775 dev_err (&dev->dev,
776 "string descriptor 0 read error: %d\n",
777 err);
778 goto errout;
779 } else if (err < 4) {
780 dev_err (&dev->dev, "string descriptor 0 too short\n");
781 err = -EINVAL;
782 goto errout;
783 } else {
Alan Sternce361582006-11-20 11:12:22 -0500784 dev->have_langid = 1;
Linus Torvalds1da177e2005-04-16 15:20:36 -0700785 dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
786 /* always use the first langid listed */
787 dev_dbg (&dev->dev, "default language 0x%04x\n",
788 dev->string_langid);
789 }
790 }
791
792 err = usb_string_sub(dev, dev->string_langid, index, tbuf);
793 if (err < 0)
794 goto errout;
795
796 size--; /* leave room for trailing NULL char in output buffer */
797 for (idx = 0, u = 2; u < err; u += 2) {
798 if (idx >= size)
799 break;
800 if (tbuf[u+1]) /* high byte */
801 buf[idx++] = '?'; /* non ISO-8859-1 character */
802 else
803 buf[idx++] = tbuf[u];
804 }
805 buf[idx] = 0;
806 err = idx;
807
808 if (tbuf[1] != USB_DT_STRING)
809 dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
810
811 errout:
812 kfree(tbuf);
813 return err;
814}
815
Alan Stern4f62efe2005-10-24 16:24:14 -0400816/**
817 * usb_cache_string - read a string descriptor and cache it for later use
818 * @udev: the device whose string descriptor is being read
819 * @index: the descriptor index
820 *
821 * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
822 * or NULL if the index is 0 or the string could not be read.
823 */
824char *usb_cache_string(struct usb_device *udev, int index)
825{
826 char *buf;
827 char *smallbuf = NULL;
828 int len;
829
830 if (index > 0 && (buf = kmalloc(256, GFP_KERNEL)) != NULL) {
831 if ((len = usb_string(udev, index, buf, 256)) > 0) {
832 if ((smallbuf = kmalloc(++len, GFP_KERNEL)) == NULL)
833 return buf;
834 memcpy(smallbuf, buf, len);
835 }
836 kfree(buf);
837 }
838 return smallbuf;
839}
840
Linus Torvalds1da177e2005-04-16 15:20:36 -0700841/*
842 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
843 * @dev: the device whose device descriptor is being updated
844 * @size: how much of the descriptor to read
845 * Context: !in_interrupt ()
846 *
847 * Updates the copy of the device descriptor stored in the device structure,
Laurent Pinchart6ab16a92006-11-07 10:16:25 +0100848 * which dedicates space for this purpose.
Linus Torvalds1da177e2005-04-16 15:20:36 -0700849 *
850 * Not exported, only for use by the core. If drivers really want to read
851 * the device descriptor directly, they can call usb_get_descriptor() with
852 * type = USB_DT_DEVICE and index = 0.
853 *
854 * This call is synchronous, and may not be used in an interrupt context.
855 *
856 * Returns the number of bytes received on success, or else the status code
857 * returned by the underlying usb_control_msg() call.
858 */
859int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
860{
861 struct usb_device_descriptor *desc;
862 int ret;
863
864 if (size > sizeof(*desc))
865 return -EINVAL;
866 desc = kmalloc(sizeof(*desc), GFP_NOIO);
867 if (!desc)
868 return -ENOMEM;
869
870 ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
871 if (ret >= 0)
872 memcpy(&dev->descriptor, desc, size);
873 kfree(desc);
874 return ret;
875}
876
877/**
878 * usb_get_status - issues a GET_STATUS call
879 * @dev: the device whose status is being checked
880 * @type: USB_RECIP_*; for device, interface, or endpoint
881 * @target: zero (for device), else interface or endpoint number
882 * @data: pointer to two bytes of bitmap data
883 * Context: !in_interrupt ()
884 *
885 * Returns device, interface, or endpoint status. Normally only of
886 * interest to see if the device is self powered, or has enabled the
887 * remote wakeup facility; or whether a bulk or interrupt endpoint
888 * is halted ("stalled").
889 *
890 * Bits in these status bitmaps are set using the SET_FEATURE request,
891 * and cleared using the CLEAR_FEATURE request. The usb_clear_halt()
892 * function should be used to clear halt ("stall") status.
893 *
894 * This call is synchronous, and may not be used in an interrupt context.
895 *
896 * Returns the number of bytes received on success, or else the status code
897 * returned by the underlying usb_control_msg() call.
898 */
899int usb_get_status(struct usb_device *dev, int type, int target, void *data)
900{
901 int ret;
902 u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
903
904 if (!status)
905 return -ENOMEM;
906
907 ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
908 USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
909 sizeof(*status), USB_CTRL_GET_TIMEOUT);
910
911 *(u16 *)data = *status;
912 kfree(status);
913 return ret;
914}
915
916/**
917 * usb_clear_halt - tells device to clear endpoint halt/stall condition
918 * @dev: device whose endpoint is halted
919 * @pipe: endpoint "pipe" being cleared
920 * Context: !in_interrupt ()
921 *
922 * This is used to clear halt conditions for bulk and interrupt endpoints,
923 * as reported by URB completion status. Endpoints that are halted are
924 * sometimes referred to as being "stalled". Such endpoints are unable
925 * to transmit or receive data until the halt status is cleared. Any URBs
926 * queued for such an endpoint should normally be unlinked by the driver
927 * before clearing the halt condition, as described in sections 5.7.5
928 * and 5.8.5 of the USB 2.0 spec.
929 *
930 * Note that control and isochronous endpoints don't halt, although control
931 * endpoints report "protocol stall" (for unsupported requests) using the
932 * same status code used to report a true stall.
933 *
934 * This call is synchronous, and may not be used in an interrupt context.
935 *
936 * Returns zero on success, or else the status code returned by the
937 * underlying usb_control_msg() call.
938 */
939int usb_clear_halt(struct usb_device *dev, int pipe)
940{
941 int result;
942 int endp = usb_pipeendpoint(pipe);
943
944 if (usb_pipein (pipe))
945 endp |= USB_DIR_IN;
946
947 /* we don't care if it wasn't halted first. in fact some devices
948 * (like some ibmcam model 1 units) seem to expect hosts to make
949 * this request for iso endpoints, which can't halt!
950 */
951 result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
952 USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
953 USB_ENDPOINT_HALT, endp, NULL, 0,
954 USB_CTRL_SET_TIMEOUT);
955
956 /* don't un-halt or force to DATA0 except on success */
957 if (result < 0)
958 return result;
959
960 /* NOTE: seems like Microsoft and Apple don't bother verifying
961 * the clear "took", so some devices could lock up if you check...
962 * such as the Hagiwara FlashGate DUAL. So we won't bother.
963 *
964 * NOTE: make sure the logic here doesn't diverge much from
965 * the copy in usb-storage, for as long as we need two copies.
966 */
967
968 /* toggle was reset by the clear */
969 usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
970
971 return 0;
972}
973
974/**
975 * usb_disable_endpoint -- Disable an endpoint by address
976 * @dev: the device whose endpoint is being disabled
977 * @epaddr: the endpoint's address. Endpoint number for output,
978 * endpoint number + USB_DIR_IN for input
979 *
980 * Deallocates hcd/hardware state for this endpoint ... and nukes all
981 * pending urbs.
982 *
983 * If the HCD hasn't registered a disable() function, this sets the
984 * endpoint's maxpacket size to 0 to prevent further submissions.
985 */
986void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
987{
988 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
989 struct usb_host_endpoint *ep;
990
991 if (!dev)
992 return;
993
994 if (usb_endpoint_out(epaddr)) {
995 ep = dev->ep_out[epnum];
996 dev->ep_out[epnum] = NULL;
997 } else {
998 ep = dev->ep_in[epnum];
999 dev->ep_in[epnum] = NULL;
1000 }
Alan Sterna6d2bb92006-08-30 11:27:36 -04001001 if (ep && dev->bus)
1002 usb_hcd_endpoint_disable(dev, ep);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001003}
1004
1005/**
1006 * usb_disable_interface -- Disable all endpoints for an interface
1007 * @dev: the device whose interface is being disabled
1008 * @intf: pointer to the interface descriptor
1009 *
1010 * Disables all the endpoints for the interface's current altsetting.
1011 */
1012void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
1013{
1014 struct usb_host_interface *alt = intf->cur_altsetting;
1015 int i;
1016
1017 for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1018 usb_disable_endpoint(dev,
1019 alt->endpoint[i].desc.bEndpointAddress);
1020 }
1021}
1022
1023/*
1024 * usb_disable_device - Disable all the endpoints for a USB device
1025 * @dev: the device whose endpoints are being disabled
1026 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1027 *
1028 * Disables all the device's endpoints, potentially including endpoint 0.
1029 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1030 * pending urbs) and usbcore state for the interfaces, so that usbcore
1031 * must usb_set_configuration() before any interfaces could be used.
1032 */
1033void usb_disable_device(struct usb_device *dev, int skip_ep0)
1034{
1035 int i;
1036
1037 dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
1038 skip_ep0 ? "non-ep0" : "all");
1039 for (i = skip_ep0; i < 16; ++i) {
1040 usb_disable_endpoint(dev, i);
1041 usb_disable_endpoint(dev, i + USB_DIR_IN);
1042 }
1043 dev->toggle[0] = dev->toggle[1] = 0;
1044
1045 /* getting rid of interfaces will disconnect
1046 * any drivers bound to them (a key side effect)
1047 */
1048 if (dev->actconfig) {
1049 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1050 struct usb_interface *interface;
1051
Alan Stern86d30742005-07-29 12:17:16 -07001052 /* remove this interface if it has been registered */
Linus Torvalds1da177e2005-04-16 15:20:36 -07001053 interface = dev->actconfig->interface[i];
Daniel Ritzd305ef52005-09-22 00:47:24 -07001054 if (!device_is_registered(&interface->dev))
Alan Stern86d30742005-07-29 12:17:16 -07001055 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001056 dev_dbg (&dev->dev, "unregistering interface %s\n",
1057 interface->dev.bus_id);
1058 usb_remove_sysfs_intf_files(interface);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001059 device_del (&interface->dev);
1060 }
1061
1062 /* Now that the interfaces are unbound, nobody should
1063 * try to access them.
1064 */
1065 for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1066 put_device (&dev->actconfig->interface[i]->dev);
1067 dev->actconfig->interface[i] = NULL;
1068 }
1069 dev->actconfig = NULL;
1070 if (dev->state == USB_STATE_CONFIGURED)
1071 usb_set_device_state(dev, USB_STATE_ADDRESS);
1072 }
1073}
1074
1075
1076/*
1077 * usb_enable_endpoint - Enable an endpoint for USB communications
1078 * @dev: the device whose interface is being enabled
1079 * @ep: the endpoint
1080 *
1081 * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
1082 * For control endpoints, both the input and output sides are handled.
1083 */
1084static void
1085usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
1086{
1087 unsigned int epaddr = ep->desc.bEndpointAddress;
1088 unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1089 int is_control;
1090
1091 is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1092 == USB_ENDPOINT_XFER_CONTROL);
1093 if (usb_endpoint_out(epaddr) || is_control) {
1094 usb_settoggle(dev, epnum, 1, 0);
1095 dev->ep_out[epnum] = ep;
1096 }
1097 if (!usb_endpoint_out(epaddr) || is_control) {
1098 usb_settoggle(dev, epnum, 0, 0);
1099 dev->ep_in[epnum] = ep;
1100 }
1101}
1102
1103/*
1104 * usb_enable_interface - Enable all the endpoints for an interface
1105 * @dev: the device whose interface is being enabled
1106 * @intf: pointer to the interface descriptor
1107 *
1108 * Enables all the endpoints for the interface's current altsetting.
1109 */
1110static void usb_enable_interface(struct usb_device *dev,
1111 struct usb_interface *intf)
1112{
1113 struct usb_host_interface *alt = intf->cur_altsetting;
1114 int i;
1115
1116 for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1117 usb_enable_endpoint(dev, &alt->endpoint[i]);
1118}
1119
1120/**
1121 * usb_set_interface - Makes a particular alternate setting be current
1122 * @dev: the device whose interface is being updated
1123 * @interface: the interface being updated
1124 * @alternate: the setting being chosen.
1125 * Context: !in_interrupt ()
1126 *
1127 * This is used to enable data transfers on interfaces that may not
1128 * be enabled by default. Not all devices support such configurability.
1129 * Only the driver bound to an interface may change its setting.
1130 *
1131 * Within any given configuration, each interface may have several
1132 * alternative settings. These are often used to control levels of
1133 * bandwidth consumption. For example, the default setting for a high
1134 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1135 * while interrupt transfers of up to 3KBytes per microframe are legal.
1136 * Also, isochronous endpoints may never be part of an
1137 * interface's default setting. To access such bandwidth, alternate
1138 * interface settings must be made current.
1139 *
1140 * Note that in the Linux USB subsystem, bandwidth associated with
1141 * an endpoint in a given alternate setting is not reserved until an URB
1142 * is submitted that needs that bandwidth. Some other operating systems
1143 * allocate bandwidth early, when a configuration is chosen.
1144 *
1145 * This call is synchronous, and may not be used in an interrupt context.
1146 * Also, drivers must not change altsettings while urbs are scheduled for
1147 * endpoints in that interface; all such urbs must first be completed
1148 * (perhaps forced by unlinking).
1149 *
1150 * Returns zero on success, or else the status code returned by the
1151 * underlying usb_control_msg() call.
1152 */
1153int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1154{
1155 struct usb_interface *iface;
1156 struct usb_host_interface *alt;
1157 int ret;
1158 int manual = 0;
1159
1160 if (dev->state == USB_STATE_SUSPENDED)
1161 return -EHOSTUNREACH;
1162
1163 iface = usb_ifnum_to_if(dev, interface);
1164 if (!iface) {
1165 dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1166 interface);
1167 return -EINVAL;
1168 }
1169
1170 alt = usb_altnum_to_altsetting(iface, alternate);
1171 if (!alt) {
1172 warn("selecting invalid altsetting %d", alternate);
1173 return -EINVAL;
1174 }
1175
1176 ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1177 USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1178 alternate, interface, NULL, 0, 5000);
1179
1180 /* 9.4.10 says devices don't need this and are free to STALL the
1181 * request if the interface only has one alternate setting.
1182 */
1183 if (ret == -EPIPE && iface->num_altsetting == 1) {
1184 dev_dbg(&dev->dev,
1185 "manual set_interface for iface %d, alt %d\n",
1186 interface, alternate);
1187 manual = 1;
1188 } else if (ret < 0)
1189 return ret;
1190
1191 /* FIXME drivers shouldn't need to replicate/bugfix the logic here
1192 * when they implement async or easily-killable versions of this or
1193 * other "should-be-internal" functions (like clear_halt).
1194 * should hcd+usbcore postprocess control requests?
1195 */
1196
1197 /* prevent submissions using previous endpoint settings */
Alan Stern0e6c8e82005-10-24 15:33:03 -04001198 if (device_is_registered(&iface->dev))
1199 usb_remove_sysfs_intf_files(iface);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001200 usb_disable_interface(dev, iface);
1201
Linus Torvalds1da177e2005-04-16 15:20:36 -07001202 iface->cur_altsetting = alt;
1203
1204 /* If the interface only has one altsetting and the device didn't
David Brownella81e7ec2005-04-18 17:39:25 -07001205 * accept the request, we attempt to carry out the equivalent action
Linus Torvalds1da177e2005-04-16 15:20:36 -07001206 * by manually clearing the HALT feature for each endpoint in the
1207 * new altsetting.
1208 */
1209 if (manual) {
1210 int i;
1211
1212 for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1213 unsigned int epaddr =
1214 alt->endpoint[i].desc.bEndpointAddress;
1215 unsigned int pipe =
1216 __create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
1217 | (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1218
1219 usb_clear_halt(dev, pipe);
1220 }
1221 }
1222
1223 /* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1224 *
1225 * Note:
1226 * Despite EP0 is always present in all interfaces/AS, the list of
1227 * endpoints from the descriptor does not contain EP0. Due to its
1228 * omnipresence one might expect EP0 being considered "affected" by
1229 * any SetInterface request and hence assume toggles need to be reset.
1230 * However, EP0 toggles are re-synced for every individual transfer
1231 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1232 * (Likewise, EP0 never "halts" on well designed devices.)
1233 */
1234 usb_enable_interface(dev, iface);
Alan Stern0e6c8e82005-10-24 15:33:03 -04001235 if (device_is_registered(&iface->dev))
1236 usb_create_sysfs_intf_files(iface);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001237
1238 return 0;
1239}
1240
1241/**
1242 * usb_reset_configuration - lightweight device reset
1243 * @dev: the device whose configuration is being reset
1244 *
1245 * This issues a standard SET_CONFIGURATION request to the device using
1246 * the current configuration. The effect is to reset most USB-related
1247 * state in the device, including interface altsettings (reset to zero),
1248 * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1249 * endpoints). Other usbcore state is unchanged, including bindings of
1250 * usb device drivers to interfaces.
1251 *
1252 * Because this affects multiple interfaces, avoid using this with composite
1253 * (multi-interface) devices. Instead, the driver for each interface may
David Brownella81e7ec2005-04-18 17:39:25 -07001254 * use usb_set_interface() on the interfaces it claims. Be careful though;
1255 * some devices don't support the SET_INTERFACE request, and others won't
1256 * reset all the interface state (notably data toggles). Resetting the whole
Linus Torvalds1da177e2005-04-16 15:20:36 -07001257 * configuration would affect other drivers' interfaces.
1258 *
1259 * The caller must own the device lock.
1260 *
1261 * Returns zero on success, else a negative error code.
1262 */
1263int usb_reset_configuration(struct usb_device *dev)
1264{
1265 int i, retval;
1266 struct usb_host_config *config;
1267
1268 if (dev->state == USB_STATE_SUSPENDED)
1269 return -EHOSTUNREACH;
1270
1271 /* caller must have locked the device and must own
1272 * the usb bus readlock (so driver bindings are stable);
1273 * calls during probe() are fine
1274 */
1275
1276 for (i = 1; i < 16; ++i) {
1277 usb_disable_endpoint(dev, i);
1278 usb_disable_endpoint(dev, i + USB_DIR_IN);
1279 }
1280
1281 config = dev->actconfig;
1282 retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1283 USB_REQ_SET_CONFIGURATION, 0,
1284 config->desc.bConfigurationValue, 0,
1285 NULL, 0, USB_CTRL_SET_TIMEOUT);
Alan Stern0e6c8e82005-10-24 15:33:03 -04001286 if (retval < 0)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001287 return retval;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001288
1289 dev->toggle[0] = dev->toggle[1] = 0;
1290
1291 /* re-init hc/hcd interface/endpoint state */
1292 for (i = 0; i < config->desc.bNumInterfaces; i++) {
1293 struct usb_interface *intf = config->interface[i];
1294 struct usb_host_interface *alt;
1295
Alan Stern0e6c8e82005-10-24 15:33:03 -04001296 if (device_is_registered(&intf->dev))
1297 usb_remove_sysfs_intf_files(intf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001298 alt = usb_altnum_to_altsetting(intf, 0);
1299
1300 /* No altsetting 0? We'll assume the first altsetting.
1301 * We could use a GetInterface call, but if a device is
1302 * so non-compliant that it doesn't have altsetting 0
1303 * then I wouldn't trust its reply anyway.
1304 */
1305 if (!alt)
1306 alt = &intf->altsetting[0];
1307
1308 intf->cur_altsetting = alt;
1309 usb_enable_interface(dev, intf);
Alan Stern0e6c8e82005-10-24 15:33:03 -04001310 if (device_is_registered(&intf->dev))
1311 usb_create_sysfs_intf_files(intf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001312 }
1313 return 0;
1314}
1315
Kay Sievers9f8b17e2007-03-13 15:59:31 +01001316void usb_release_interface(struct device *dev)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001317{
1318 struct usb_interface *intf = to_usb_interface(dev);
1319 struct usb_interface_cache *intfc =
1320 altsetting_to_usb_interface_cache(intf->altsetting);
1321
1322 kref_put(&intfc->ref, usb_release_interface_cache);
1323 kfree(intf);
1324}
1325
Kay Sievers9f8b17e2007-03-13 15:59:31 +01001326#ifdef CONFIG_HOTPLUG
1327static int usb_if_uevent(struct device *dev, char **envp, int num_envp,
1328 char *buffer, int buffer_size)
1329{
1330 struct usb_device *usb_dev;
1331 struct usb_interface *intf;
1332 struct usb_host_interface *alt;
1333 int i = 0;
1334 int length = 0;
1335
1336 if (!dev)
1337 return -ENODEV;
1338
1339 /* driver is often null here; dev_dbg() would oops */
1340 pr_debug ("usb %s: uevent\n", dev->bus_id);
1341
1342 intf = to_usb_interface(dev);
1343 usb_dev = interface_to_usbdev(intf);
1344 alt = intf->cur_altsetting;
1345
1346 if (add_uevent_var(envp, num_envp, &i,
1347 buffer, buffer_size, &length,
1348 "INTERFACE=%d/%d/%d",
1349 alt->desc.bInterfaceClass,
1350 alt->desc.bInterfaceSubClass,
1351 alt->desc.bInterfaceProtocol))
1352 return -ENOMEM;
1353
1354 if (add_uevent_var(envp, num_envp, &i,
1355 buffer, buffer_size, &length,
1356 "MODALIAS=usb:v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X",
1357 le16_to_cpu(usb_dev->descriptor.idVendor),
1358 le16_to_cpu(usb_dev->descriptor.idProduct),
1359 le16_to_cpu(usb_dev->descriptor.bcdDevice),
1360 usb_dev->descriptor.bDeviceClass,
1361 usb_dev->descriptor.bDeviceSubClass,
1362 usb_dev->descriptor.bDeviceProtocol,
1363 alt->desc.bInterfaceClass,
1364 alt->desc.bInterfaceSubClass,
1365 alt->desc.bInterfaceProtocol))
1366 return -ENOMEM;
1367
1368 envp[i] = NULL;
1369 return 0;
1370}
1371
1372#else
1373
1374static int usb_if_uevent(struct device *dev, char **envp,
1375 int num_envp, char *buffer, int buffer_size)
1376{
1377 return -ENODEV;
1378}
1379#endif /* CONFIG_HOTPLUG */
1380
1381struct device_type usb_if_device_type = {
1382 .name = "usb_interface",
1383 .release = usb_release_interface,
1384 .uevent = usb_if_uevent,
1385};
1386
Craig W. Nadler165fe972007-06-15 23:14:35 -04001387static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1388 struct usb_host_config *config,
1389 u8 inum)
1390{
1391 struct usb_interface_assoc_descriptor *retval = NULL;
1392 struct usb_interface_assoc_descriptor *intf_assoc;
1393 int first_intf;
1394 int last_intf;
1395 int i;
1396
1397 for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
1398 intf_assoc = config->intf_assoc[i];
1399 if (intf_assoc->bInterfaceCount == 0)
1400 continue;
1401
1402 first_intf = intf_assoc->bFirstInterface;
1403 last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
1404 if (inum >= first_intf && inum <= last_intf) {
1405 if (!retval)
1406 retval = intf_assoc;
1407 else
1408 dev_err(&dev->dev, "Interface #%d referenced"
1409 " by multiple IADs\n", inum);
1410 }
1411 }
1412
1413 return retval;
1414}
1415
1416
Linus Torvalds1da177e2005-04-16 15:20:36 -07001417/*
1418 * usb_set_configuration - Makes a particular device setting be current
1419 * @dev: the device whose configuration is being updated
1420 * @configuration: the configuration being chosen.
1421 * Context: !in_interrupt(), caller owns the device lock
1422 *
1423 * This is used to enable non-default device modes. Not all devices
1424 * use this kind of configurability; many devices only have one
1425 * configuration.
1426 *
Alan Stern3f141e22007-02-08 16:40:43 -05001427 * @configuration is the value of the configuration to be installed.
1428 * According to the USB spec (e.g. section 9.1.1.5), configuration values
1429 * must be non-zero; a value of zero indicates that the device in
1430 * unconfigured. However some devices erroneously use 0 as one of their
1431 * configuration values. To help manage such devices, this routine will
1432 * accept @configuration = -1 as indicating the device should be put in
1433 * an unconfigured state.
1434 *
Linus Torvalds1da177e2005-04-16 15:20:36 -07001435 * USB device configurations may affect Linux interoperability,
1436 * power consumption and the functionality available. For example,
1437 * the default configuration is limited to using 100mA of bus power,
1438 * so that when certain device functionality requires more power,
1439 * and the device is bus powered, that functionality should be in some
1440 * non-default device configuration. Other device modes may also be
1441 * reflected as configuration options, such as whether two ISDN
1442 * channels are available independently; and choosing between open
1443 * standard device protocols (like CDC) or proprietary ones.
1444 *
1445 * Note that USB has an additional level of device configurability,
1446 * associated with interfaces. That configurability is accessed using
1447 * usb_set_interface().
1448 *
1449 * This call is synchronous. The calling context must be able to sleep,
1450 * must own the device lock, and must not hold the driver model's USB
Greg Kroah-Hartman341487a82007-04-09 11:52:31 -04001451 * bus mutex; usb device driver probe() methods cannot use this routine.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001452 *
1453 * Returns zero on success, or else the status code returned by the
Steven Cole093cf722005-05-03 19:07:24 -06001454 * underlying call that failed. On successful completion, each interface
Linus Torvalds1da177e2005-04-16 15:20:36 -07001455 * in the original device configuration has been destroyed, and each one
1456 * in the new configuration has been probed by all relevant usb device
1457 * drivers currently known to the kernel.
1458 */
1459int usb_set_configuration(struct usb_device *dev, int configuration)
1460{
1461 int i, ret;
1462 struct usb_host_config *cp = NULL;
1463 struct usb_interface **new_interfaces = NULL;
1464 int n, nintf;
1465
Alan Stern3f141e22007-02-08 16:40:43 -05001466 if (configuration == -1)
1467 configuration = 0;
1468 else {
1469 for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1470 if (dev->config[i].desc.bConfigurationValue ==
1471 configuration) {
1472 cp = &dev->config[i];
1473 break;
1474 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001475 }
1476 }
1477 if ((!cp && configuration != 0))
1478 return -EINVAL;
1479
1480 /* The USB spec says configuration 0 means unconfigured.
1481 * But if a device includes a configuration numbered 0,
1482 * we will accept it as a correctly configured state.
Alan Stern3f141e22007-02-08 16:40:43 -05001483 * Use -1 if you really want to unconfigure the device.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001484 */
1485 if (cp && configuration == 0)
1486 dev_warn(&dev->dev, "config 0 descriptor??\n");
1487
Linus Torvalds1da177e2005-04-16 15:20:36 -07001488 /* Allocate memory for new interfaces before doing anything else,
1489 * so that if we run out then nothing will have changed. */
1490 n = nintf = 0;
1491 if (cp) {
1492 nintf = cp->desc.bNumInterfaces;
1493 new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1494 GFP_KERNEL);
1495 if (!new_interfaces) {
1496 dev_err(&dev->dev, "Out of memory");
1497 return -ENOMEM;
1498 }
1499
1500 for (; n < nintf; ++n) {
Alan Stern0a1ef3b2005-10-24 15:38:24 -04001501 new_interfaces[n] = kzalloc(
Linus Torvalds1da177e2005-04-16 15:20:36 -07001502 sizeof(struct usb_interface),
1503 GFP_KERNEL);
1504 if (!new_interfaces[n]) {
1505 dev_err(&dev->dev, "Out of memory");
1506 ret = -ENOMEM;
1507free_interfaces:
1508 while (--n >= 0)
1509 kfree(new_interfaces[n]);
1510 kfree(new_interfaces);
1511 return ret;
1512 }
1513 }
Alan Stern6ad07122006-06-01 13:59:16 -04001514
1515 i = dev->bus_mA - cp->desc.bMaxPower * 2;
1516 if (i < 0)
1517 dev_warn(&dev->dev, "new config #%d exceeds power "
1518 "limit by %dmA\n",
1519 configuration, -i);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001520 }
1521
Alan Stern01d883d2006-08-30 15:47:18 -04001522 /* Wake up the device so we can send it the Set-Config request */
Alan Stern94fcda12006-11-20 11:38:46 -05001523 ret = usb_autoresume_device(dev);
Alan Stern01d883d2006-08-30 15:47:18 -04001524 if (ret)
1525 goto free_interfaces;
1526
Linus Torvalds1da177e2005-04-16 15:20:36 -07001527 /* if it's already configured, clear out old state first.
1528 * getting rid of old interfaces means unbinding their drivers.
1529 */
1530 if (dev->state != USB_STATE_ADDRESS)
1531 usb_disable_device (dev, 1); // Skip ep0
1532
1533 if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1534 USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
Alan Stern6ad07122006-06-01 13:59:16 -04001535 NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0) {
1536
1537 /* All the old state is gone, so what else can we do?
1538 * The device is probably useless now anyway.
1539 */
1540 cp = NULL;
1541 }
Linus Torvalds1da177e2005-04-16 15:20:36 -07001542
1543 dev->actconfig = cp;
Alan Stern6ad07122006-06-01 13:59:16 -04001544 if (!cp) {
Linus Torvalds1da177e2005-04-16 15:20:36 -07001545 usb_set_device_state(dev, USB_STATE_ADDRESS);
Alan Stern94fcda12006-11-20 11:38:46 -05001546 usb_autosuspend_device(dev);
Alan Stern6ad07122006-06-01 13:59:16 -04001547 goto free_interfaces;
1548 }
1549 usb_set_device_state(dev, USB_STATE_CONFIGURED);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001550
Alan Stern6ad07122006-06-01 13:59:16 -04001551 /* Initialize the new interface structures and the
1552 * hc/hcd/usbcore interface/endpoint state.
1553 */
1554 for (i = 0; i < nintf; ++i) {
1555 struct usb_interface_cache *intfc;
1556 struct usb_interface *intf;
1557 struct usb_host_interface *alt;
1558
1559 cp->interface[i] = intf = new_interfaces[i];
1560 intfc = cp->intf_cache[i];
1561 intf->altsetting = intfc->altsetting;
1562 intf->num_altsetting = intfc->num_altsetting;
Craig W. Nadler165fe972007-06-15 23:14:35 -04001563 intf->intf_assoc = find_iad(dev, cp, i);
Alan Stern6ad07122006-06-01 13:59:16 -04001564 kref_get(&intfc->ref);
1565
1566 alt = usb_altnum_to_altsetting(intf, 0);
1567
1568 /* No altsetting 0? We'll assume the first altsetting.
1569 * We could use a GetInterface call, but if a device is
1570 * so non-compliant that it doesn't have altsetting 0
1571 * then I wouldn't trust its reply anyway.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001572 */
Alan Stern6ad07122006-06-01 13:59:16 -04001573 if (!alt)
1574 alt = &intf->altsetting[0];
Linus Torvalds1da177e2005-04-16 15:20:36 -07001575
Alan Stern6ad07122006-06-01 13:59:16 -04001576 intf->cur_altsetting = alt;
1577 usb_enable_interface(dev, intf);
1578 intf->dev.parent = &dev->dev;
1579 intf->dev.driver = NULL;
1580 intf->dev.bus = &usb_bus_type;
Kay Sievers9f8b17e2007-03-13 15:59:31 +01001581 intf->dev.type = &usb_if_device_type;
Alan Stern6ad07122006-06-01 13:59:16 -04001582 intf->dev.dma_mask = dev->dev.dma_mask;
Alan Stern6ad07122006-06-01 13:59:16 -04001583 device_initialize (&intf->dev);
1584 mark_quiesced(intf);
1585 sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1586 dev->bus->busnum, dev->devpath,
1587 configuration, alt->desc.bInterfaceNumber);
1588 }
1589 kfree(new_interfaces);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001590
Alan Stern6ad07122006-06-01 13:59:16 -04001591 if (cp->string == NULL)
1592 cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001593
Alan Stern6ad07122006-06-01 13:59:16 -04001594 /* Now that all the interfaces are set up, register them
1595 * to trigger binding of drivers to interfaces. probe()
1596 * routines may install different altsettings and may
1597 * claim() any interfaces not yet bound. Many class drivers
1598 * need that: CDC, audio, video, etc.
1599 */
1600 for (i = 0; i < nintf; ++i) {
1601 struct usb_interface *intf = cp->interface[i];
Linus Torvalds1da177e2005-04-16 15:20:36 -07001602
Alan Stern6ad07122006-06-01 13:59:16 -04001603 dev_dbg (&dev->dev,
1604 "adding %s (config #%d, interface %d)\n",
1605 intf->dev.bus_id, configuration,
1606 intf->cur_altsetting->desc.bInterfaceNumber);
1607 ret = device_add (&intf->dev);
1608 if (ret != 0) {
1609 dev_err(&dev->dev, "device_add(%s) --> %d\n",
1610 intf->dev.bus_id, ret);
1611 continue;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001612 }
Alan Stern6ad07122006-06-01 13:59:16 -04001613 usb_create_sysfs_intf_files (intf);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001614 }
1615
Alan Stern94fcda12006-11-20 11:38:46 -05001616 usb_autosuspend_device(dev);
Alan Stern86d30742005-07-29 12:17:16 -07001617 return 0;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001618}
1619
Alan Stern088dc272006-08-21 12:08:19 -04001620struct set_config_request {
1621 struct usb_device *udev;
1622 int config;
1623 struct work_struct work;
1624};
1625
1626/* Worker routine for usb_driver_set_configuration() */
David Howellsc4028952006-11-22 14:57:56 +00001627static void driver_set_config_work(struct work_struct *work)
Alan Stern088dc272006-08-21 12:08:19 -04001628{
David Howellsc4028952006-11-22 14:57:56 +00001629 struct set_config_request *req =
1630 container_of(work, struct set_config_request, work);
Alan Stern088dc272006-08-21 12:08:19 -04001631
1632 usb_lock_device(req->udev);
1633 usb_set_configuration(req->udev, req->config);
1634 usb_unlock_device(req->udev);
1635 usb_put_dev(req->udev);
1636 kfree(req);
1637}
1638
1639/**
1640 * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1641 * @udev: the device whose configuration is being updated
1642 * @config: the configuration being chosen.
1643 * Context: In process context, must be able to sleep
1644 *
1645 * Device interface drivers are not allowed to change device configurations.
1646 * This is because changing configurations will destroy the interface the
1647 * driver is bound to and create new ones; it would be like a floppy-disk
1648 * driver telling the computer to replace the floppy-disk drive with a
1649 * tape drive!
1650 *
1651 * Still, in certain specialized circumstances the need may arise. This
1652 * routine gets around the normal restrictions by using a work thread to
1653 * submit the change-config request.
1654 *
1655 * Returns 0 if the request was succesfully queued, error code otherwise.
1656 * The caller has no way to know whether the queued request will eventually
1657 * succeed.
1658 */
1659int usb_driver_set_configuration(struct usb_device *udev, int config)
1660{
1661 struct set_config_request *req;
1662
1663 req = kmalloc(sizeof(*req), GFP_KERNEL);
1664 if (!req)
1665 return -ENOMEM;
1666 req->udev = udev;
1667 req->config = config;
David Howellsc4028952006-11-22 14:57:56 +00001668 INIT_WORK(&req->work, driver_set_config_work);
Alan Stern088dc272006-08-21 12:08:19 -04001669
1670 usb_get_dev(udev);
Alan Stern1737bf22006-12-15 16:04:52 -05001671 schedule_work(&req->work);
Alan Stern088dc272006-08-21 12:08:19 -04001672 return 0;
1673}
1674EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
1675
Linus Torvalds1da177e2005-04-16 15:20:36 -07001676// synchronous request completion model
1677EXPORT_SYMBOL(usb_control_msg);
1678EXPORT_SYMBOL(usb_bulk_msg);
1679
1680EXPORT_SYMBOL(usb_sg_init);
1681EXPORT_SYMBOL(usb_sg_cancel);
1682EXPORT_SYMBOL(usb_sg_wait);
1683
1684// synchronous control message convenience routines
1685EXPORT_SYMBOL(usb_get_descriptor);
1686EXPORT_SYMBOL(usb_get_status);
Linus Torvalds1da177e2005-04-16 15:20:36 -07001687EXPORT_SYMBOL(usb_string);
1688
1689// synchronous calls that also maintain usbcore state
1690EXPORT_SYMBOL(usb_clear_halt);
1691EXPORT_SYMBOL(usb_reset_configuration);
1692EXPORT_SYMBOL(usb_set_interface);
1693