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