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