xref: /linux/drivers/usb/core/message.c (revision 843aef4930b9953c9ca624a990b201440304b56f)
1 /*
2  * message.c - synchronous message handling
3  */
4 
5 #include <linux/pci.h>	/* for scatterlist macros */
6 #include <linux/usb.h>
7 #include <linux/module.h>
8 #include <linux/slab.h>
9 #include <linux/init.h>
10 #include <linux/mm.h>
11 #include <linux/timer.h>
12 #include <linux/ctype.h>
13 #include <linux/device.h>
14 #include <linux/scatterlist.h>
15 #include <linux/usb/quirks.h>
16 #include <asm/byteorder.h>
17 
18 #include "hcd.h"	/* for usbcore internals */
19 #include "usb.h"
20 
21 static void cancel_async_set_config(struct usb_device *udev);
22 
23 struct api_context {
24 	struct completion	done;
25 	int			status;
26 };
27 
28 static void usb_api_blocking_completion(struct urb *urb)
29 {
30 	struct api_context *ctx = urb->context;
31 
32 	ctx->status = urb->status;
33 	complete(&ctx->done);
34 }
35 
36 
37 /*
38  * Starts urb and waits for completion or timeout. Note that this call
39  * is NOT interruptible. Many device driver i/o requests should be
40  * interruptible and therefore these drivers should implement their
41  * own interruptible routines.
42  */
43 static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
44 {
45 	struct api_context ctx;
46 	unsigned long expire;
47 	int retval;
48 
49 	init_completion(&ctx.done);
50 	urb->context = &ctx;
51 	urb->actual_length = 0;
52 	retval = usb_submit_urb(urb, GFP_NOIO);
53 	if (unlikely(retval))
54 		goto out;
55 
56 	expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
57 	if (!wait_for_completion_timeout(&ctx.done, expire)) {
58 		usb_kill_urb(urb);
59 		retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
60 
61 		dev_dbg(&urb->dev->dev,
62 			"%s timed out on ep%d%s len=%d/%d\n",
63 			current->comm,
64 			usb_endpoint_num(&urb->ep->desc),
65 			usb_urb_dir_in(urb) ? "in" : "out",
66 			urb->actual_length,
67 			urb->transfer_buffer_length);
68 	} else
69 		retval = ctx.status;
70 out:
71 	if (actual_length)
72 		*actual_length = urb->actual_length;
73 
74 	usb_free_urb(urb);
75 	return retval;
76 }
77 
78 /*-------------------------------------------------------------------*/
79 /* returns status (negative) or length (positive) */
80 static int usb_internal_control_msg(struct usb_device *usb_dev,
81 				    unsigned int pipe,
82 				    struct usb_ctrlrequest *cmd,
83 				    void *data, int len, int timeout)
84 {
85 	struct urb *urb;
86 	int retv;
87 	int length;
88 
89 	urb = usb_alloc_urb(0, GFP_NOIO);
90 	if (!urb)
91 		return -ENOMEM;
92 
93 	usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
94 			     len, usb_api_blocking_completion, NULL);
95 
96 	retv = usb_start_wait_urb(urb, timeout, &length);
97 	if (retv < 0)
98 		return retv;
99 	else
100 		return length;
101 }
102 
103 /**
104  * usb_control_msg - Builds a control urb, sends it off and waits for completion
105  * @dev: pointer to the usb device to send the message to
106  * @pipe: endpoint "pipe" to send the message to
107  * @request: USB message request value
108  * @requesttype: USB message request type value
109  * @value: USB message value
110  * @index: USB message index value
111  * @data: pointer to the data to send
112  * @size: length in bytes of the data to send
113  * @timeout: time in msecs to wait for the message to complete before timing
114  *	out (if 0 the wait is forever)
115  *
116  * Context: !in_interrupt ()
117  *
118  * This function sends a simple control message to a specified endpoint and
119  * waits for the message to complete, or timeout.
120  *
121  * If successful, it returns the number of bytes transferred, otherwise a
122  * negative error number.
123  *
124  * Don't use this function from within an interrupt context, like a bottom half
125  * handler.  If you need an asynchronous message, or need to send a message
126  * from within interrupt context, use usb_submit_urb().
127  * If a thread in your driver uses this call, make sure your disconnect()
128  * method can wait for it to complete.  Since you don't have a handle on the
129  * URB used, you can't cancel the request.
130  */
131 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
132 		    __u8 requesttype, __u16 value, __u16 index, void *data,
133 		    __u16 size, int timeout)
134 {
135 	struct usb_ctrlrequest *dr;
136 	int ret;
137 
138 	dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
139 	if (!dr)
140 		return -ENOMEM;
141 
142 	dr->bRequestType = requesttype;
143 	dr->bRequest = request;
144 	dr->wValue = cpu_to_le16(value);
145 	dr->wIndex = cpu_to_le16(index);
146 	dr->wLength = cpu_to_le16(size);
147 
148 	/* dbg("usb_control_msg"); */
149 
150 	ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
151 
152 	kfree(dr);
153 
154 	return ret;
155 }
156 EXPORT_SYMBOL_GPL(usb_control_msg);
157 
158 /**
159  * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
160  * @usb_dev: pointer to the usb device to send the message to
161  * @pipe: endpoint "pipe" to send the message to
162  * @data: pointer to the data to send
163  * @len: length in bytes of the data to send
164  * @actual_length: pointer to a location to put the actual length transferred
165  *	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  *
169  * Context: !in_interrupt ()
170  *
171  * This function sends a simple interrupt message to a specified endpoint and
172  * waits for the message to complete, or timeout.
173  *
174  * If successful, it returns 0, otherwise a negative error number.  The number
175  * of actual bytes transferred will be stored in the actual_length paramater.
176  *
177  * Don't use this function from within an interrupt context, like a bottom half
178  * handler.  If you need an asynchronous message, or need to send a message
179  * from within interrupt context, use usb_submit_urb() If a thread in your
180  * driver uses this call, make sure your disconnect() method can wait for it to
181  * complete.  Since you don't have a handle on the URB used, you can't cancel
182  * the request.
183  */
184 int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
185 		      void *data, int len, int *actual_length, int timeout)
186 {
187 	return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
188 }
189 EXPORT_SYMBOL_GPL(usb_interrupt_msg);
190 
191 /**
192  * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
193  * @usb_dev: pointer to the usb device to send the message to
194  * @pipe: endpoint "pipe" to send the message to
195  * @data: pointer to the data to send
196  * @len: length in bytes of the data to send
197  * @actual_length: pointer to a location to put the actual length transferred
198  *	in bytes
199  * @timeout: time in msecs to wait for the message to complete before
200  *	timing out (if 0 the wait is forever)
201  *
202  * Context: !in_interrupt ()
203  *
204  * This function sends a simple bulk message to a specified endpoint
205  * and waits for the message to complete, or timeout.
206  *
207  * If successful, it returns 0, otherwise a negative error number.  The number
208  * of actual bytes transferred will be stored in the actual_length paramater.
209  *
210  * Don't use this function from within an interrupt context, like a bottom half
211  * handler.  If you need an asynchronous message, or need to send a message
212  * from within interrupt context, use usb_submit_urb() If a thread in your
213  * driver uses this call, make sure your disconnect() method can wait for it to
214  * complete.  Since you don't have a handle on the URB used, you can't cancel
215  * the request.
216  *
217  * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
218  * users are forced to abuse this routine by using it to submit URBs for
219  * interrupt endpoints.  We will take the liberty of creating an interrupt URB
220  * (with the default interval) if the target is an interrupt endpoint.
221  */
222 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
223 		 void *data, int len, int *actual_length, int timeout)
224 {
225 	struct urb *urb;
226 	struct usb_host_endpoint *ep;
227 
228 	ep = (usb_pipein(pipe) ? usb_dev->ep_in : usb_dev->ep_out)
229 			[usb_pipeendpoint(pipe)];
230 	if (!ep || len < 0)
231 		return -EINVAL;
232 
233 	urb = usb_alloc_urb(0, GFP_KERNEL);
234 	if (!urb)
235 		return -ENOMEM;
236 
237 	if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
238 			USB_ENDPOINT_XFER_INT) {
239 		pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
240 		usb_fill_int_urb(urb, usb_dev, pipe, data, len,
241 				usb_api_blocking_completion, NULL,
242 				ep->desc.bInterval);
243 	} else
244 		usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
245 				usb_api_blocking_completion, NULL);
246 
247 	return usb_start_wait_urb(urb, timeout, actual_length);
248 }
249 EXPORT_SYMBOL_GPL(usb_bulk_msg);
250 
251 /*-------------------------------------------------------------------*/
252 
253 static void sg_clean(struct usb_sg_request *io)
254 {
255 	if (io->urbs) {
256 		while (io->entries--)
257 			usb_free_urb(io->urbs [io->entries]);
258 		kfree(io->urbs);
259 		io->urbs = NULL;
260 	}
261 	if (io->dev->dev.dma_mask != NULL)
262 		usb_buffer_unmap_sg(io->dev, usb_pipein(io->pipe),
263 				    io->sg, io->nents);
264 	io->dev = NULL;
265 }
266 
267 static void sg_complete(struct urb *urb)
268 {
269 	struct usb_sg_request *io = urb->context;
270 	int status = urb->status;
271 
272 	spin_lock(&io->lock);
273 
274 	/* In 2.5 we require hcds' endpoint queues not to progress after fault
275 	 * reports, until the completion callback (this!) returns.  That lets
276 	 * device driver code (like this routine) unlink queued urbs first,
277 	 * if it needs to, since the HC won't work on them at all.  So it's
278 	 * not possible for page N+1 to overwrite page N, and so on.
279 	 *
280 	 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
281 	 * complete before the HCD can get requests away from hardware,
282 	 * though never during cleanup after a hard fault.
283 	 */
284 	if (io->status
285 			&& (io->status != -ECONNRESET
286 				|| status != -ECONNRESET)
287 			&& urb->actual_length) {
288 		dev_err(io->dev->bus->controller,
289 			"dev %s ep%d%s scatterlist error %d/%d\n",
290 			io->dev->devpath,
291 			usb_endpoint_num(&urb->ep->desc),
292 			usb_urb_dir_in(urb) ? "in" : "out",
293 			status, io->status);
294 		/* BUG (); */
295 	}
296 
297 	if (io->status == 0 && status && status != -ECONNRESET) {
298 		int i, found, retval;
299 
300 		io->status = status;
301 
302 		/* the previous urbs, and this one, completed already.
303 		 * unlink pending urbs so they won't rx/tx bad data.
304 		 * careful: unlink can sometimes be synchronous...
305 		 */
306 		spin_unlock(&io->lock);
307 		for (i = 0, found = 0; i < io->entries; i++) {
308 			if (!io->urbs [i] || !io->urbs [i]->dev)
309 				continue;
310 			if (found) {
311 				retval = usb_unlink_urb(io->urbs [i]);
312 				if (retval != -EINPROGRESS &&
313 				    retval != -ENODEV &&
314 				    retval != -EBUSY)
315 					dev_err(&io->dev->dev,
316 						"%s, unlink --> %d\n",
317 						__func__, retval);
318 			} else if (urb == io->urbs [i])
319 				found = 1;
320 		}
321 		spin_lock(&io->lock);
322 	}
323 	urb->dev = NULL;
324 
325 	/* on the last completion, signal usb_sg_wait() */
326 	io->bytes += urb->actual_length;
327 	io->count--;
328 	if (!io->count)
329 		complete(&io->complete);
330 
331 	spin_unlock(&io->lock);
332 }
333 
334 
335 /**
336  * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
337  * @io: request block being initialized.  until usb_sg_wait() returns,
338  *	treat this as a pointer to an opaque block of memory,
339  * @dev: the usb device that will send or receive the data
340  * @pipe: endpoint "pipe" used to transfer the data
341  * @period: polling rate for interrupt endpoints, in frames or
342  * 	(for high speed endpoints) microframes; ignored for bulk
343  * @sg: scatterlist entries
344  * @nents: how many entries in the scatterlist
345  * @length: how many bytes to send from the scatterlist, or zero to
346  * 	send every byte identified in the list.
347  * @mem_flags: SLAB_* flags affecting memory allocations in this call
348  *
349  * Returns zero for success, else a negative errno value.  This initializes a
350  * scatter/gather request, allocating resources such as I/O mappings and urb
351  * memory (except maybe memory used by USB controller drivers).
352  *
353  * The request must be issued using usb_sg_wait(), which waits for the I/O to
354  * complete (or to be canceled) and then cleans up all resources allocated by
355  * usb_sg_init().
356  *
357  * The request may be canceled with usb_sg_cancel(), either before or after
358  * usb_sg_wait() is called.
359  */
360 int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
361 		unsigned pipe, unsigned	period, struct scatterlist *sg,
362 		int nents, size_t length, gfp_t mem_flags)
363 {
364 	int i;
365 	int urb_flags;
366 	int dma;
367 
368 	if (!io || !dev || !sg
369 			|| usb_pipecontrol(pipe)
370 			|| usb_pipeisoc(pipe)
371 			|| nents <= 0)
372 		return -EINVAL;
373 
374 	spin_lock_init(&io->lock);
375 	io->dev = dev;
376 	io->pipe = pipe;
377 	io->sg = sg;
378 	io->nents = nents;
379 
380 	/* not all host controllers use DMA (like the mainstream pci ones);
381 	 * they can use PIO (sl811) or be software over another transport.
382 	 */
383 	dma = (dev->dev.dma_mask != NULL);
384 	if (dma)
385 		io->entries = usb_buffer_map_sg(dev, usb_pipein(pipe),
386 						sg, nents);
387 	else
388 		io->entries = nents;
389 
390 	/* initialize all the urbs we'll use */
391 	if (io->entries <= 0)
392 		return io->entries;
393 
394 	io->urbs = kmalloc(io->entries * sizeof *io->urbs, mem_flags);
395 	if (!io->urbs)
396 		goto nomem;
397 
398 	urb_flags = URB_NO_INTERRUPT;
399 	if (dma)
400 		urb_flags |= URB_NO_TRANSFER_DMA_MAP;
401 	if (usb_pipein(pipe))
402 		urb_flags |= URB_SHORT_NOT_OK;
403 
404 	for_each_sg(sg, sg, io->entries, i) {
405 		unsigned len;
406 
407 		io->urbs[i] = usb_alloc_urb(0, mem_flags);
408 		if (!io->urbs[i]) {
409 			io->entries = i;
410 			goto nomem;
411 		}
412 
413 		io->urbs[i]->dev = NULL;
414 		io->urbs[i]->pipe = pipe;
415 		io->urbs[i]->interval = period;
416 		io->urbs[i]->transfer_flags = urb_flags;
417 
418 		io->urbs[i]->complete = sg_complete;
419 		io->urbs[i]->context = io;
420 
421 		/*
422 		 * Some systems need to revert to PIO when DMA is temporarily
423 		 * unavailable.  For their sakes, both transfer_buffer and
424 		 * transfer_dma are set when possible.  However this can only
425 		 * work on systems without:
426 		 *
427 		 *  - HIGHMEM, since DMA buffers located in high memory are
428 		 *    not directly addressable by the CPU for PIO;
429 		 *
430 		 *  - IOMMU, since dma_map_sg() is allowed to use an IOMMU to
431 		 *    make virtually discontiguous buffers be "dma-contiguous"
432 		 *    so that PIO and DMA need diferent numbers of URBs.
433 		 *
434 		 * So when HIGHMEM or IOMMU are in use, transfer_buffer is NULL
435 		 * to prevent stale pointers and to help spot bugs.
436 		 */
437 		if (dma) {
438 			io->urbs[i]->transfer_dma = sg_dma_address(sg);
439 			len = sg_dma_len(sg);
440 #if defined(CONFIG_HIGHMEM) || defined(CONFIG_GART_IOMMU)
441 			io->urbs[i]->transfer_buffer = NULL;
442 #else
443 			io->urbs[i]->transfer_buffer = sg_virt(sg);
444 #endif
445 		} else {
446 			/* hc may use _only_ transfer_buffer */
447 			io->urbs[i]->transfer_buffer = sg_virt(sg);
448 			len = sg->length;
449 		}
450 
451 		if (length) {
452 			len = min_t(unsigned, len, length);
453 			length -= len;
454 			if (length == 0)
455 				io->entries = i + 1;
456 		}
457 		io->urbs[i]->transfer_buffer_length = len;
458 	}
459 	io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
460 
461 	/* transaction state */
462 	io->count = io->entries;
463 	io->status = 0;
464 	io->bytes = 0;
465 	init_completion(&io->complete);
466 	return 0;
467 
468 nomem:
469 	sg_clean(io);
470 	return -ENOMEM;
471 }
472 EXPORT_SYMBOL_GPL(usb_sg_init);
473 
474 /**
475  * usb_sg_wait - synchronously execute scatter/gather request
476  * @io: request block handle, as initialized with usb_sg_init().
477  * 	some fields become accessible when this call returns.
478  * Context: !in_interrupt ()
479  *
480  * This function blocks until the specified I/O operation completes.  It
481  * leverages the grouping of the related I/O requests to get good transfer
482  * rates, by queueing the requests.  At higher speeds, such queuing can
483  * significantly improve USB throughput.
484  *
485  * There are three kinds of completion for this function.
486  * (1) success, where io->status is zero.  The number of io->bytes
487  *     transferred is as requested.
488  * (2) error, where io->status is a negative errno value.  The number
489  *     of io->bytes transferred before the error is usually less
490  *     than requested, and can be nonzero.
491  * (3) cancellation, a type of error with status -ECONNRESET that
492  *     is initiated by usb_sg_cancel().
493  *
494  * When this function returns, all memory allocated through usb_sg_init() or
495  * this call will have been freed.  The request block parameter may still be
496  * passed to usb_sg_cancel(), or it may be freed.  It could also be
497  * reinitialized and then reused.
498  *
499  * Data Transfer Rates:
500  *
501  * Bulk transfers are valid for full or high speed endpoints.
502  * The best full speed data rate is 19 packets of 64 bytes each
503  * per frame, or 1216 bytes per millisecond.
504  * The best high speed data rate is 13 packets of 512 bytes each
505  * per microframe, or 52 KBytes per millisecond.
506  *
507  * The reason to use interrupt transfers through this API would most likely
508  * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
509  * could be transferred.  That capability is less useful for low or full
510  * speed interrupt endpoints, which allow at most one packet per millisecond,
511  * of at most 8 or 64 bytes (respectively).
512  */
513 void usb_sg_wait(struct usb_sg_request *io)
514 {
515 	int i;
516 	int entries = io->entries;
517 
518 	/* queue the urbs.  */
519 	spin_lock_irq(&io->lock);
520 	i = 0;
521 	while (i < entries && !io->status) {
522 		int retval;
523 
524 		io->urbs[i]->dev = io->dev;
525 		retval = usb_submit_urb(io->urbs [i], GFP_ATOMIC);
526 
527 		/* after we submit, let completions or cancelations fire;
528 		 * we handshake using io->status.
529 		 */
530 		spin_unlock_irq(&io->lock);
531 		switch (retval) {
532 			/* maybe we retrying will recover */
533 		case -ENXIO:	/* hc didn't queue this one */
534 		case -EAGAIN:
535 		case -ENOMEM:
536 			io->urbs[i]->dev = NULL;
537 			retval = 0;
538 			yield();
539 			break;
540 
541 			/* no error? continue immediately.
542 			 *
543 			 * NOTE: to work better with UHCI (4K I/O buffer may
544 			 * need 3K of TDs) it may be good to limit how many
545 			 * URBs are queued at once; N milliseconds?
546 			 */
547 		case 0:
548 			++i;
549 			cpu_relax();
550 			break;
551 
552 			/* fail any uncompleted urbs */
553 		default:
554 			io->urbs[i]->dev = NULL;
555 			io->urbs[i]->status = retval;
556 			dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
557 				__func__, retval);
558 			usb_sg_cancel(io);
559 		}
560 		spin_lock_irq(&io->lock);
561 		if (retval && (io->status == 0 || io->status == -ECONNRESET))
562 			io->status = retval;
563 	}
564 	io->count -= entries - i;
565 	if (io->count == 0)
566 		complete(&io->complete);
567 	spin_unlock_irq(&io->lock);
568 
569 	/* OK, yes, this could be packaged as non-blocking.
570 	 * So could the submit loop above ... but it's easier to
571 	 * solve neither problem than to solve both!
572 	 */
573 	wait_for_completion(&io->complete);
574 
575 	sg_clean(io);
576 }
577 EXPORT_SYMBOL_GPL(usb_sg_wait);
578 
579 /**
580  * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
581  * @io: request block, initialized with usb_sg_init()
582  *
583  * This stops a request after it has been started by usb_sg_wait().
584  * It can also prevents one initialized by usb_sg_init() from starting,
585  * so that call just frees resources allocated to the request.
586  */
587 void usb_sg_cancel(struct usb_sg_request *io)
588 {
589 	unsigned long flags;
590 
591 	spin_lock_irqsave(&io->lock, flags);
592 
593 	/* shut everything down, if it didn't already */
594 	if (!io->status) {
595 		int i;
596 
597 		io->status = -ECONNRESET;
598 		spin_unlock(&io->lock);
599 		for (i = 0; i < io->entries; i++) {
600 			int retval;
601 
602 			if (!io->urbs [i]->dev)
603 				continue;
604 			retval = usb_unlink_urb(io->urbs [i]);
605 			if (retval != -EINPROGRESS && retval != -EBUSY)
606 				dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
607 					__func__, retval);
608 		}
609 		spin_lock(&io->lock);
610 	}
611 	spin_unlock_irqrestore(&io->lock, flags);
612 }
613 EXPORT_SYMBOL_GPL(usb_sg_cancel);
614 
615 /*-------------------------------------------------------------------*/
616 
617 /**
618  * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
619  * @dev: the device whose descriptor is being retrieved
620  * @type: the descriptor type (USB_DT_*)
621  * @index: the number of the descriptor
622  * @buf: where to put the descriptor
623  * @size: how big is "buf"?
624  * Context: !in_interrupt ()
625  *
626  * Gets a USB descriptor.  Convenience functions exist to simplify
627  * getting some types of descriptors.  Use
628  * usb_get_string() or usb_string() for USB_DT_STRING.
629  * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
630  * are part of the device structure.
631  * In addition to a number of USB-standard descriptors, some
632  * devices also use class-specific or vendor-specific descriptors.
633  *
634  * This call is synchronous, and may not be used in an interrupt context.
635  *
636  * Returns the number of bytes received on success, or else the status code
637  * returned by the underlying usb_control_msg() call.
638  */
639 int usb_get_descriptor(struct usb_device *dev, unsigned char type,
640 		       unsigned char index, void *buf, int size)
641 {
642 	int i;
643 	int result;
644 
645 	memset(buf, 0, size);	/* Make sure we parse really received data */
646 
647 	for (i = 0; i < 3; ++i) {
648 		/* retry on length 0 or error; some devices are flakey */
649 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
650 				USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
651 				(type << 8) + index, 0, buf, size,
652 				USB_CTRL_GET_TIMEOUT);
653 		if (result <= 0 && result != -ETIMEDOUT)
654 			continue;
655 		if (result > 1 && ((u8 *)buf)[1] != type) {
656 			result = -EPROTO;
657 			continue;
658 		}
659 		break;
660 	}
661 	return result;
662 }
663 EXPORT_SYMBOL_GPL(usb_get_descriptor);
664 
665 /**
666  * usb_get_string - gets a string descriptor
667  * @dev: the device whose string descriptor is being retrieved
668  * @langid: code for language chosen (from string descriptor zero)
669  * @index: the number of the descriptor
670  * @buf: where to put the string
671  * @size: how big is "buf"?
672  * Context: !in_interrupt ()
673  *
674  * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
675  * in little-endian byte order).
676  * The usb_string() function will often be a convenient way to turn
677  * these strings into kernel-printable form.
678  *
679  * Strings may be referenced in device, configuration, interface, or other
680  * descriptors, and could also be used in vendor-specific ways.
681  *
682  * This call is synchronous, and may not be used in an interrupt context.
683  *
684  * Returns the number of bytes received on success, or else the status code
685  * returned by the underlying usb_control_msg() call.
686  */
687 static int usb_get_string(struct usb_device *dev, unsigned short langid,
688 			  unsigned char index, void *buf, int size)
689 {
690 	int i;
691 	int result;
692 
693 	for (i = 0; i < 3; ++i) {
694 		/* retry on length 0 or stall; some devices are flakey */
695 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
696 			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
697 			(USB_DT_STRING << 8) + index, langid, buf, size,
698 			USB_CTRL_GET_TIMEOUT);
699 		if (!(result == 0 || result == -EPIPE))
700 			break;
701 	}
702 	return result;
703 }
704 
705 static void usb_try_string_workarounds(unsigned char *buf, int *length)
706 {
707 	int newlength, oldlength = *length;
708 
709 	for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
710 		if (!isprint(buf[newlength]) || buf[newlength + 1])
711 			break;
712 
713 	if (newlength > 2) {
714 		buf[0] = newlength;
715 		*length = newlength;
716 	}
717 }
718 
719 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
720 			  unsigned int index, unsigned char *buf)
721 {
722 	int rc;
723 
724 	/* Try to read the string descriptor by asking for the maximum
725 	 * possible number of bytes */
726 	if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
727 		rc = -EIO;
728 	else
729 		rc = usb_get_string(dev, langid, index, buf, 255);
730 
731 	/* If that failed try to read the descriptor length, then
732 	 * ask for just that many bytes */
733 	if (rc < 2) {
734 		rc = usb_get_string(dev, langid, index, buf, 2);
735 		if (rc == 2)
736 			rc = usb_get_string(dev, langid, index, buf, buf[0]);
737 	}
738 
739 	if (rc >= 2) {
740 		if (!buf[0] && !buf[1])
741 			usb_try_string_workarounds(buf, &rc);
742 
743 		/* There might be extra junk at the end of the descriptor */
744 		if (buf[0] < rc)
745 			rc = buf[0];
746 
747 		rc = rc - (rc & 1); /* force a multiple of two */
748 	}
749 
750 	if (rc < 2)
751 		rc = (rc < 0 ? rc : -EINVAL);
752 
753 	return rc;
754 }
755 
756 /**
757  * usb_string - returns ISO 8859-1 version of a string descriptor
758  * @dev: the device whose string descriptor is being retrieved
759  * @index: the number of the descriptor
760  * @buf: where to put the string
761  * @size: how big is "buf"?
762  * Context: !in_interrupt ()
763  *
764  * This converts the UTF-16LE encoded strings returned by devices, from
765  * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
766  * that are more usable in most kernel contexts.  Note that all characters
767  * in the chosen descriptor that can't be encoded using ISO-8859-1
768  * are converted to the question mark ("?") character, and this function
769  * chooses strings in the first language supported by the device.
770  *
771  * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
772  * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
773  * and is appropriate for use many uses of English and several other
774  * Western European languages.  (But it doesn't include the "Euro" symbol.)
775  *
776  * This call is synchronous, and may not be used in an interrupt context.
777  *
778  * Returns length of the string (>= 0) or usb_control_msg status (< 0).
779  */
780 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
781 {
782 	unsigned char *tbuf;
783 	int err;
784 	unsigned int u, idx;
785 
786 	if (dev->state == USB_STATE_SUSPENDED)
787 		return -EHOSTUNREACH;
788 	if (size <= 0 || !buf || !index)
789 		return -EINVAL;
790 	buf[0] = 0;
791 	tbuf = kmalloc(256, GFP_NOIO);
792 	if (!tbuf)
793 		return -ENOMEM;
794 
795 	/* get langid for strings if it's not yet known */
796 	if (!dev->have_langid) {
797 		err = usb_string_sub(dev, 0, 0, tbuf);
798 		if (err < 0) {
799 			dev_err(&dev->dev,
800 				"string descriptor 0 read error: %d\n",
801 				err);
802 			goto errout;
803 		} else if (err < 4) {
804 			dev_err(&dev->dev, "string descriptor 0 too short\n");
805 			err = -EINVAL;
806 			goto errout;
807 		} else {
808 			dev->have_langid = 1;
809 			dev->string_langid = tbuf[2] | (tbuf[3] << 8);
810 			/* always use the first langid listed */
811 			dev_dbg(&dev->dev, "default language 0x%04x\n",
812 				dev->string_langid);
813 		}
814 	}
815 
816 	err = usb_string_sub(dev, dev->string_langid, index, tbuf);
817 	if (err < 0)
818 		goto errout;
819 
820 	size--;		/* leave room for trailing NULL char in output buffer */
821 	for (idx = 0, u = 2; u < err; u += 2) {
822 		if (idx >= size)
823 			break;
824 		if (tbuf[u+1])			/* high byte */
825 			buf[idx++] = '?';  /* non ISO-8859-1 character */
826 		else
827 			buf[idx++] = tbuf[u];
828 	}
829 	buf[idx] = 0;
830 	err = idx;
831 
832 	if (tbuf[1] != USB_DT_STRING)
833 		dev_dbg(&dev->dev,
834 			"wrong descriptor type %02x for string %d (\"%s\")\n",
835 			tbuf[1], index, buf);
836 
837  errout:
838 	kfree(tbuf);
839 	return err;
840 }
841 EXPORT_SYMBOL_GPL(usb_string);
842 
843 /**
844  * usb_cache_string - read a string descriptor and cache it for later use
845  * @udev: the device whose string descriptor is being read
846  * @index: the descriptor index
847  *
848  * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
849  * or NULL if the index is 0 or the string could not be read.
850  */
851 char *usb_cache_string(struct usb_device *udev, int index)
852 {
853 	char *buf;
854 	char *smallbuf = NULL;
855 	int len;
856 
857 	if (index <= 0)
858 		return NULL;
859 
860 	buf = kmalloc(256, GFP_KERNEL);
861 	if (buf) {
862 		len = usb_string(udev, index, buf, 256);
863 		if (len > 0) {
864 			smallbuf = kmalloc(++len, GFP_KERNEL);
865 			if (!smallbuf)
866 				return buf;
867 			memcpy(smallbuf, buf, len);
868 		}
869 		kfree(buf);
870 	}
871 	return smallbuf;
872 }
873 
874 /*
875  * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
876  * @dev: the device whose device descriptor is being updated
877  * @size: how much of the descriptor to read
878  * Context: !in_interrupt ()
879  *
880  * Updates the copy of the device descriptor stored in the device structure,
881  * which dedicates space for this purpose.
882  *
883  * Not exported, only for use by the core.  If drivers really want to read
884  * the device descriptor directly, they can call usb_get_descriptor() with
885  * type = USB_DT_DEVICE and index = 0.
886  *
887  * This call is synchronous, and may not be used in an interrupt context.
888  *
889  * Returns the number of bytes received on success, or else the status code
890  * returned by the underlying usb_control_msg() call.
891  */
892 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
893 {
894 	struct usb_device_descriptor *desc;
895 	int ret;
896 
897 	if (size > sizeof(*desc))
898 		return -EINVAL;
899 	desc = kmalloc(sizeof(*desc), GFP_NOIO);
900 	if (!desc)
901 		return -ENOMEM;
902 
903 	ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
904 	if (ret >= 0)
905 		memcpy(&dev->descriptor, desc, size);
906 	kfree(desc);
907 	return ret;
908 }
909 
910 /**
911  * usb_get_status - issues a GET_STATUS call
912  * @dev: the device whose status is being checked
913  * @type: USB_RECIP_*; for device, interface, or endpoint
914  * @target: zero (for device), else interface or endpoint number
915  * @data: pointer to two bytes of bitmap data
916  * Context: !in_interrupt ()
917  *
918  * Returns device, interface, or endpoint status.  Normally only of
919  * interest to see if the device is self powered, or has enabled the
920  * remote wakeup facility; or whether a bulk or interrupt endpoint
921  * is halted ("stalled").
922  *
923  * Bits in these status bitmaps are set using the SET_FEATURE request,
924  * and cleared using the CLEAR_FEATURE request.  The usb_clear_halt()
925  * function should be used to clear halt ("stall") status.
926  *
927  * This call is synchronous, and may not be used in an interrupt context.
928  *
929  * Returns the number of bytes received on success, or else the status code
930  * returned by the underlying usb_control_msg() call.
931  */
932 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
933 {
934 	int ret;
935 	u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
936 
937 	if (!status)
938 		return -ENOMEM;
939 
940 	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
941 		USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
942 		sizeof(*status), USB_CTRL_GET_TIMEOUT);
943 
944 	*(u16 *)data = *status;
945 	kfree(status);
946 	return ret;
947 }
948 EXPORT_SYMBOL_GPL(usb_get_status);
949 
950 /**
951  * usb_clear_halt - tells device to clear endpoint halt/stall condition
952  * @dev: device whose endpoint is halted
953  * @pipe: endpoint "pipe" being cleared
954  * Context: !in_interrupt ()
955  *
956  * This is used to clear halt conditions for bulk and interrupt endpoints,
957  * as reported by URB completion status.  Endpoints that are halted are
958  * sometimes referred to as being "stalled".  Such endpoints are unable
959  * to transmit or receive data until the halt status is cleared.  Any URBs
960  * queued for such an endpoint should normally be unlinked by the driver
961  * before clearing the halt condition, as described in sections 5.7.5
962  * and 5.8.5 of the USB 2.0 spec.
963  *
964  * Note that control and isochronous endpoints don't halt, although control
965  * endpoints report "protocol stall" (for unsupported requests) using the
966  * same status code used to report a true stall.
967  *
968  * This call is synchronous, and may not be used in an interrupt context.
969  *
970  * Returns zero on success, or else the status code returned by the
971  * underlying usb_control_msg() call.
972  */
973 int usb_clear_halt(struct usb_device *dev, int pipe)
974 {
975 	int result;
976 	int endp = usb_pipeendpoint(pipe);
977 
978 	if (usb_pipein(pipe))
979 		endp |= USB_DIR_IN;
980 
981 	/* we don't care if it wasn't halted first. in fact some devices
982 	 * (like some ibmcam model 1 units) seem to expect hosts to make
983 	 * this request for iso endpoints, which can't halt!
984 	 */
985 	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
986 		USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
987 		USB_ENDPOINT_HALT, endp, NULL, 0,
988 		USB_CTRL_SET_TIMEOUT);
989 
990 	/* don't un-halt or force to DATA0 except on success */
991 	if (result < 0)
992 		return result;
993 
994 	/* NOTE:  seems like Microsoft and Apple don't bother verifying
995 	 * the clear "took", so some devices could lock up if you check...
996 	 * such as the Hagiwara FlashGate DUAL.  So we won't bother.
997 	 *
998 	 * NOTE:  make sure the logic here doesn't diverge much from
999 	 * the copy in usb-storage, for as long as we need two copies.
1000 	 */
1001 
1002 	/* toggle was reset by the clear */
1003 	usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
1004 
1005 	return 0;
1006 }
1007 EXPORT_SYMBOL_GPL(usb_clear_halt);
1008 
1009 static int create_intf_ep_devs(struct usb_interface *intf)
1010 {
1011 	struct usb_device *udev = interface_to_usbdev(intf);
1012 	struct usb_host_interface *alt = intf->cur_altsetting;
1013 	int i;
1014 
1015 	if (intf->ep_devs_created || intf->unregistering)
1016 		return 0;
1017 
1018 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1019 		(void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
1020 	intf->ep_devs_created = 1;
1021 	return 0;
1022 }
1023 
1024 static void remove_intf_ep_devs(struct usb_interface *intf)
1025 {
1026 	struct usb_host_interface *alt = intf->cur_altsetting;
1027 	int i;
1028 
1029 	if (!intf->ep_devs_created)
1030 		return;
1031 
1032 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1033 		usb_remove_ep_devs(&alt->endpoint[i]);
1034 	intf->ep_devs_created = 0;
1035 }
1036 
1037 /**
1038  * usb_disable_endpoint -- Disable an endpoint by address
1039  * @dev: the device whose endpoint is being disabled
1040  * @epaddr: the endpoint's address.  Endpoint number for output,
1041  *	endpoint number + USB_DIR_IN for input
1042  *
1043  * Deallocates hcd/hardware state for this endpoint ... and nukes all
1044  * pending urbs.
1045  *
1046  * If the HCD hasn't registered a disable() function, this sets the
1047  * endpoint's maxpacket size to 0 to prevent further submissions.
1048  */
1049 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
1050 {
1051 	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1052 	struct usb_host_endpoint *ep;
1053 
1054 	if (!dev)
1055 		return;
1056 
1057 	if (usb_endpoint_out(epaddr)) {
1058 		ep = dev->ep_out[epnum];
1059 		dev->ep_out[epnum] = NULL;
1060 	} else {
1061 		ep = dev->ep_in[epnum];
1062 		dev->ep_in[epnum] = NULL;
1063 	}
1064 	if (ep) {
1065 		ep->enabled = 0;
1066 		usb_hcd_flush_endpoint(dev, ep);
1067 		usb_hcd_disable_endpoint(dev, ep);
1068 	}
1069 }
1070 
1071 /**
1072  * usb_disable_interface -- Disable all endpoints for an interface
1073  * @dev: the device whose interface is being disabled
1074  * @intf: pointer to the interface descriptor
1075  *
1076  * Disables all the endpoints for the interface's current altsetting.
1077  */
1078 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
1079 {
1080 	struct usb_host_interface *alt = intf->cur_altsetting;
1081 	int i;
1082 
1083 	for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1084 		usb_disable_endpoint(dev,
1085 				alt->endpoint[i].desc.bEndpointAddress);
1086 	}
1087 }
1088 
1089 /**
1090  * usb_disable_device - Disable all the endpoints for a USB device
1091  * @dev: the device whose endpoints are being disabled
1092  * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1093  *
1094  * Disables all the device's endpoints, potentially including endpoint 0.
1095  * Deallocates hcd/hardware state for the endpoints (nuking all or most
1096  * pending urbs) and usbcore state for the interfaces, so that usbcore
1097  * must usb_set_configuration() before any interfaces could be used.
1098  */
1099 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1100 {
1101 	int i;
1102 
1103 	dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
1104 		skip_ep0 ? "non-ep0" : "all");
1105 	for (i = skip_ep0; i < 16; ++i) {
1106 		usb_disable_endpoint(dev, i);
1107 		usb_disable_endpoint(dev, i + USB_DIR_IN);
1108 	}
1109 	dev->toggle[0] = dev->toggle[1] = 0;
1110 
1111 	/* getting rid of interfaces will disconnect
1112 	 * any drivers bound to them (a key side effect)
1113 	 */
1114 	if (dev->actconfig) {
1115 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1116 			struct usb_interface	*interface;
1117 
1118 			/* remove this interface if it has been registered */
1119 			interface = dev->actconfig->interface[i];
1120 			if (!device_is_registered(&interface->dev))
1121 				continue;
1122 			dev_dbg(&dev->dev, "unregistering interface %s\n",
1123 				dev_name(&interface->dev));
1124 			interface->unregistering = 1;
1125 			remove_intf_ep_devs(interface);
1126 			device_del(&interface->dev);
1127 		}
1128 
1129 		/* Now that the interfaces are unbound, nobody should
1130 		 * try to access them.
1131 		 */
1132 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1133 			put_device(&dev->actconfig->interface[i]->dev);
1134 			dev->actconfig->interface[i] = NULL;
1135 		}
1136 		dev->actconfig = NULL;
1137 		if (dev->state == USB_STATE_CONFIGURED)
1138 			usb_set_device_state(dev, USB_STATE_ADDRESS);
1139 	}
1140 }
1141 
1142 /**
1143  * usb_enable_endpoint - Enable an endpoint for USB communications
1144  * @dev: the device whose interface is being enabled
1145  * @ep: the endpoint
1146  * @reset_toggle: flag to set the endpoint's toggle back to 0
1147  *
1148  * Resets the endpoint toggle if asked, and sets dev->ep_{in,out} pointers.
1149  * For control endpoints, both the input and output sides are handled.
1150  */
1151 void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
1152 		bool reset_toggle)
1153 {
1154 	int epnum = usb_endpoint_num(&ep->desc);
1155 	int is_out = usb_endpoint_dir_out(&ep->desc);
1156 	int is_control = usb_endpoint_xfer_control(&ep->desc);
1157 
1158 	if (is_out || is_control) {
1159 		if (reset_toggle)
1160 			usb_settoggle(dev, epnum, 1, 0);
1161 		dev->ep_out[epnum] = ep;
1162 	}
1163 	if (!is_out || is_control) {
1164 		if (reset_toggle)
1165 			usb_settoggle(dev, epnum, 0, 0);
1166 		dev->ep_in[epnum] = ep;
1167 	}
1168 	ep->enabled = 1;
1169 }
1170 
1171 /**
1172  * usb_enable_interface - Enable all the endpoints for an interface
1173  * @dev: the device whose interface is being enabled
1174  * @intf: pointer to the interface descriptor
1175  * @reset_toggles: flag to set the endpoints' toggles back to 0
1176  *
1177  * Enables all the endpoints for the interface's current altsetting.
1178  */
1179 void usb_enable_interface(struct usb_device *dev,
1180 		struct usb_interface *intf, bool reset_toggles)
1181 {
1182 	struct usb_host_interface *alt = intf->cur_altsetting;
1183 	int i;
1184 
1185 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1186 		usb_enable_endpoint(dev, &alt->endpoint[i], reset_toggles);
1187 }
1188 
1189 /**
1190  * usb_set_interface - Makes a particular alternate setting be current
1191  * @dev: the device whose interface is being updated
1192  * @interface: the interface being updated
1193  * @alternate: the setting being chosen.
1194  * Context: !in_interrupt ()
1195  *
1196  * This is used to enable data transfers on interfaces that may not
1197  * be enabled by default.  Not all devices support such configurability.
1198  * Only the driver bound to an interface may change its setting.
1199  *
1200  * Within any given configuration, each interface may have several
1201  * alternative settings.  These are often used to control levels of
1202  * bandwidth consumption.  For example, the default setting for a high
1203  * speed interrupt endpoint may not send more than 64 bytes per microframe,
1204  * while interrupt transfers of up to 3KBytes per microframe are legal.
1205  * Also, isochronous endpoints may never be part of an
1206  * interface's default setting.  To access such bandwidth, alternate
1207  * interface settings must be made current.
1208  *
1209  * Note that in the Linux USB subsystem, bandwidth associated with
1210  * an endpoint in a given alternate setting is not reserved until an URB
1211  * is submitted that needs that bandwidth.  Some other operating systems
1212  * allocate bandwidth early, when a configuration is chosen.
1213  *
1214  * This call is synchronous, and may not be used in an interrupt context.
1215  * Also, drivers must not change altsettings while urbs are scheduled for
1216  * endpoints in that interface; all such urbs must first be completed
1217  * (perhaps forced by unlinking).
1218  *
1219  * Returns zero on success, or else the status code returned by the
1220  * underlying usb_control_msg() call.
1221  */
1222 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1223 {
1224 	struct usb_interface *iface;
1225 	struct usb_host_interface *alt;
1226 	int ret;
1227 	int manual = 0;
1228 	unsigned int epaddr;
1229 	unsigned int pipe;
1230 
1231 	if (dev->state == USB_STATE_SUSPENDED)
1232 		return -EHOSTUNREACH;
1233 
1234 	iface = usb_ifnum_to_if(dev, interface);
1235 	if (!iface) {
1236 		dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1237 			interface);
1238 		return -EINVAL;
1239 	}
1240 
1241 	alt = usb_altnum_to_altsetting(iface, alternate);
1242 	if (!alt) {
1243 		dev_warn(&dev->dev, "selecting invalid altsetting %d",
1244 			 alternate);
1245 		return -EINVAL;
1246 	}
1247 
1248 	if (dev->quirks & USB_QUIRK_NO_SET_INTF)
1249 		ret = -EPIPE;
1250 	else
1251 		ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1252 				   USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1253 				   alternate, interface, NULL, 0, 5000);
1254 
1255 	/* 9.4.10 says devices don't need this and are free to STALL the
1256 	 * request if the interface only has one alternate setting.
1257 	 */
1258 	if (ret == -EPIPE && iface->num_altsetting == 1) {
1259 		dev_dbg(&dev->dev,
1260 			"manual set_interface for iface %d, alt %d\n",
1261 			interface, alternate);
1262 		manual = 1;
1263 	} else if (ret < 0)
1264 		return ret;
1265 
1266 	/* FIXME drivers shouldn't need to replicate/bugfix the logic here
1267 	 * when they implement async or easily-killable versions of this or
1268 	 * other "should-be-internal" functions (like clear_halt).
1269 	 * should hcd+usbcore postprocess control requests?
1270 	 */
1271 
1272 	/* prevent submissions using previous endpoint settings */
1273 	if (iface->cur_altsetting != alt) {
1274 		remove_intf_ep_devs(iface);
1275 		usb_remove_sysfs_intf_files(iface);
1276 	}
1277 	usb_disable_interface(dev, iface);
1278 
1279 	iface->cur_altsetting = alt;
1280 
1281 	/* If the interface only has one altsetting and the device didn't
1282 	 * accept the request, we attempt to carry out the equivalent action
1283 	 * by manually clearing the HALT feature for each endpoint in the
1284 	 * new altsetting.
1285 	 */
1286 	if (manual) {
1287 		int i;
1288 
1289 		for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1290 			epaddr = alt->endpoint[i].desc.bEndpointAddress;
1291 			pipe = __create_pipe(dev,
1292 					USB_ENDPOINT_NUMBER_MASK & epaddr) |
1293 					(usb_endpoint_out(epaddr) ?
1294 					USB_DIR_OUT : USB_DIR_IN);
1295 
1296 			usb_clear_halt(dev, pipe);
1297 		}
1298 	}
1299 
1300 	/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1301 	 *
1302 	 * Note:
1303 	 * Despite EP0 is always present in all interfaces/AS, the list of
1304 	 * endpoints from the descriptor does not contain EP0. Due to its
1305 	 * omnipresence one might expect EP0 being considered "affected" by
1306 	 * any SetInterface request and hence assume toggles need to be reset.
1307 	 * However, EP0 toggles are re-synced for every individual transfer
1308 	 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1309 	 * (Likewise, EP0 never "halts" on well designed devices.)
1310 	 */
1311 	usb_enable_interface(dev, iface, true);
1312 	if (device_is_registered(&iface->dev)) {
1313 		usb_create_sysfs_intf_files(iface);
1314 		create_intf_ep_devs(iface);
1315 	}
1316 	return 0;
1317 }
1318 EXPORT_SYMBOL_GPL(usb_set_interface);
1319 
1320 /**
1321  * usb_reset_configuration - lightweight device reset
1322  * @dev: the device whose configuration is being reset
1323  *
1324  * This issues a standard SET_CONFIGURATION request to the device using
1325  * the current configuration.  The effect is to reset most USB-related
1326  * state in the device, including interface altsettings (reset to zero),
1327  * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1328  * endpoints).  Other usbcore state is unchanged, including bindings of
1329  * usb device drivers to interfaces.
1330  *
1331  * Because this affects multiple interfaces, avoid using this with composite
1332  * (multi-interface) devices.  Instead, the driver for each interface may
1333  * use usb_set_interface() on the interfaces it claims.  Be careful though;
1334  * some devices don't support the SET_INTERFACE request, and others won't
1335  * reset all the interface state (notably data toggles).  Resetting the whole
1336  * configuration would affect other drivers' interfaces.
1337  *
1338  * The caller must own the device lock.
1339  *
1340  * Returns zero on success, else a negative error code.
1341  */
1342 int usb_reset_configuration(struct usb_device *dev)
1343 {
1344 	int			i, retval;
1345 	struct usb_host_config	*config;
1346 
1347 	if (dev->state == USB_STATE_SUSPENDED)
1348 		return -EHOSTUNREACH;
1349 
1350 	/* caller must have locked the device and must own
1351 	 * the usb bus readlock (so driver bindings are stable);
1352 	 * calls during probe() are fine
1353 	 */
1354 
1355 	for (i = 1; i < 16; ++i) {
1356 		usb_disable_endpoint(dev, i);
1357 		usb_disable_endpoint(dev, i + USB_DIR_IN);
1358 	}
1359 
1360 	config = dev->actconfig;
1361 	retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1362 			USB_REQ_SET_CONFIGURATION, 0,
1363 			config->desc.bConfigurationValue, 0,
1364 			NULL, 0, USB_CTRL_SET_TIMEOUT);
1365 	if (retval < 0)
1366 		return retval;
1367 
1368 	dev->toggle[0] = dev->toggle[1] = 0;
1369 
1370 	/* re-init hc/hcd interface/endpoint state */
1371 	for (i = 0; i < config->desc.bNumInterfaces; i++) {
1372 		struct usb_interface *intf = config->interface[i];
1373 		struct usb_host_interface *alt;
1374 
1375 		alt = usb_altnum_to_altsetting(intf, 0);
1376 
1377 		/* No altsetting 0?  We'll assume the first altsetting.
1378 		 * We could use a GetInterface call, but if a device is
1379 		 * so non-compliant that it doesn't have altsetting 0
1380 		 * then I wouldn't trust its reply anyway.
1381 		 */
1382 		if (!alt)
1383 			alt = &intf->altsetting[0];
1384 
1385 		if (alt != intf->cur_altsetting) {
1386 			remove_intf_ep_devs(intf);
1387 			usb_remove_sysfs_intf_files(intf);
1388 		}
1389 		intf->cur_altsetting = alt;
1390 		usb_enable_interface(dev, intf, true);
1391 		if (device_is_registered(&intf->dev)) {
1392 			usb_create_sysfs_intf_files(intf);
1393 			create_intf_ep_devs(intf);
1394 		}
1395 	}
1396 	return 0;
1397 }
1398 EXPORT_SYMBOL_GPL(usb_reset_configuration);
1399 
1400 static void usb_release_interface(struct device *dev)
1401 {
1402 	struct usb_interface *intf = to_usb_interface(dev);
1403 	struct usb_interface_cache *intfc =
1404 			altsetting_to_usb_interface_cache(intf->altsetting);
1405 
1406 	kref_put(&intfc->ref, usb_release_interface_cache);
1407 	kfree(intf);
1408 }
1409 
1410 #ifdef	CONFIG_HOTPLUG
1411 static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1412 {
1413 	struct usb_device *usb_dev;
1414 	struct usb_interface *intf;
1415 	struct usb_host_interface *alt;
1416 
1417 	intf = to_usb_interface(dev);
1418 	usb_dev = interface_to_usbdev(intf);
1419 	alt = intf->cur_altsetting;
1420 
1421 	if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
1422 		   alt->desc.bInterfaceClass,
1423 		   alt->desc.bInterfaceSubClass,
1424 		   alt->desc.bInterfaceProtocol))
1425 		return -ENOMEM;
1426 
1427 	if (add_uevent_var(env,
1428 		   "MODALIAS=usb:"
1429 		   "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X",
1430 		   le16_to_cpu(usb_dev->descriptor.idVendor),
1431 		   le16_to_cpu(usb_dev->descriptor.idProduct),
1432 		   le16_to_cpu(usb_dev->descriptor.bcdDevice),
1433 		   usb_dev->descriptor.bDeviceClass,
1434 		   usb_dev->descriptor.bDeviceSubClass,
1435 		   usb_dev->descriptor.bDeviceProtocol,
1436 		   alt->desc.bInterfaceClass,
1437 		   alt->desc.bInterfaceSubClass,
1438 		   alt->desc.bInterfaceProtocol))
1439 		return -ENOMEM;
1440 
1441 	return 0;
1442 }
1443 
1444 #else
1445 
1446 static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1447 {
1448 	return -ENODEV;
1449 }
1450 #endif	/* CONFIG_HOTPLUG */
1451 
1452 struct device_type usb_if_device_type = {
1453 	.name =		"usb_interface",
1454 	.release =	usb_release_interface,
1455 	.uevent =	usb_if_uevent,
1456 };
1457 
1458 static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1459 						struct usb_host_config *config,
1460 						u8 inum)
1461 {
1462 	struct usb_interface_assoc_descriptor *retval = NULL;
1463 	struct usb_interface_assoc_descriptor *intf_assoc;
1464 	int first_intf;
1465 	int last_intf;
1466 	int i;
1467 
1468 	for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
1469 		intf_assoc = config->intf_assoc[i];
1470 		if (intf_assoc->bInterfaceCount == 0)
1471 			continue;
1472 
1473 		first_intf = intf_assoc->bFirstInterface;
1474 		last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
1475 		if (inum >= first_intf && inum <= last_intf) {
1476 			if (!retval)
1477 				retval = intf_assoc;
1478 			else
1479 				dev_err(&dev->dev, "Interface #%d referenced"
1480 					" by multiple IADs\n", inum);
1481 		}
1482 	}
1483 
1484 	return retval;
1485 }
1486 
1487 
1488 /*
1489  * Internal function to queue a device reset
1490  *
1491  * This is initialized into the workstruct in 'struct
1492  * usb_device->reset_ws' that is launched by
1493  * message.c:usb_set_configuration() when initializing each 'struct
1494  * usb_interface'.
1495  *
1496  * It is safe to get the USB device without reference counts because
1497  * the life cycle of @iface is bound to the life cycle of @udev. Then,
1498  * this function will be ran only if @iface is alive (and before
1499  * freeing it any scheduled instances of it will have been cancelled).
1500  *
1501  * We need to set a flag (usb_dev->reset_running) because when we call
1502  * the reset, the interfaces might be unbound. The current interface
1503  * cannot try to remove the queued work as it would cause a deadlock
1504  * (you cannot remove your work from within your executing
1505  * workqueue). This flag lets it know, so that
1506  * usb_cancel_queued_reset() doesn't try to do it.
1507  *
1508  * See usb_queue_reset_device() for more details
1509  */
1510 void __usb_queue_reset_device(struct work_struct *ws)
1511 {
1512 	int rc;
1513 	struct usb_interface *iface =
1514 		container_of(ws, struct usb_interface, reset_ws);
1515 	struct usb_device *udev = interface_to_usbdev(iface);
1516 
1517 	rc = usb_lock_device_for_reset(udev, iface);
1518 	if (rc >= 0) {
1519 		iface->reset_running = 1;
1520 		usb_reset_device(udev);
1521 		iface->reset_running = 0;
1522 		usb_unlock_device(udev);
1523 	}
1524 }
1525 
1526 
1527 /*
1528  * usb_set_configuration - Makes a particular device setting be current
1529  * @dev: the device whose configuration is being updated
1530  * @configuration: the configuration being chosen.
1531  * Context: !in_interrupt(), caller owns the device lock
1532  *
1533  * This is used to enable non-default device modes.  Not all devices
1534  * use this kind of configurability; many devices only have one
1535  * configuration.
1536  *
1537  * @configuration is the value of the configuration to be installed.
1538  * According to the USB spec (e.g. section 9.1.1.5), configuration values
1539  * must be non-zero; a value of zero indicates that the device in
1540  * unconfigured.  However some devices erroneously use 0 as one of their
1541  * configuration values.  To help manage such devices, this routine will
1542  * accept @configuration = -1 as indicating the device should be put in
1543  * an unconfigured state.
1544  *
1545  * USB device configurations may affect Linux interoperability,
1546  * power consumption and the functionality available.  For example,
1547  * the default configuration is limited to using 100mA of bus power,
1548  * so that when certain device functionality requires more power,
1549  * and the device is bus powered, that functionality should be in some
1550  * non-default device configuration.  Other device modes may also be
1551  * reflected as configuration options, such as whether two ISDN
1552  * channels are available independently; and choosing between open
1553  * standard device protocols (like CDC) or proprietary ones.
1554  *
1555  * Note that a non-authorized device (dev->authorized == 0) will only
1556  * be put in unconfigured mode.
1557  *
1558  * Note that USB has an additional level of device configurability,
1559  * associated with interfaces.  That configurability is accessed using
1560  * usb_set_interface().
1561  *
1562  * This call is synchronous. The calling context must be able to sleep,
1563  * must own the device lock, and must not hold the driver model's USB
1564  * bus mutex; usb interface driver probe() methods cannot use this routine.
1565  *
1566  * Returns zero on success, or else the status code returned by the
1567  * underlying call that failed.  On successful completion, each interface
1568  * in the original device configuration has been destroyed, and each one
1569  * in the new configuration has been probed by all relevant usb device
1570  * drivers currently known to the kernel.
1571  */
1572 int usb_set_configuration(struct usb_device *dev, int configuration)
1573 {
1574 	int i, ret;
1575 	struct usb_host_config *cp = NULL;
1576 	struct usb_interface **new_interfaces = NULL;
1577 	int n, nintf;
1578 
1579 	if (dev->authorized == 0 || configuration == -1)
1580 		configuration = 0;
1581 	else {
1582 		for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1583 			if (dev->config[i].desc.bConfigurationValue ==
1584 					configuration) {
1585 				cp = &dev->config[i];
1586 				break;
1587 			}
1588 		}
1589 	}
1590 	if ((!cp && configuration != 0))
1591 		return -EINVAL;
1592 
1593 	/* The USB spec says configuration 0 means unconfigured.
1594 	 * But if a device includes a configuration numbered 0,
1595 	 * we will accept it as a correctly configured state.
1596 	 * Use -1 if you really want to unconfigure the device.
1597 	 */
1598 	if (cp && configuration == 0)
1599 		dev_warn(&dev->dev, "config 0 descriptor??\n");
1600 
1601 	/* Allocate memory for new interfaces before doing anything else,
1602 	 * so that if we run out then nothing will have changed. */
1603 	n = nintf = 0;
1604 	if (cp) {
1605 		nintf = cp->desc.bNumInterfaces;
1606 		new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1607 				GFP_KERNEL);
1608 		if (!new_interfaces) {
1609 			dev_err(&dev->dev, "Out of memory\n");
1610 			return -ENOMEM;
1611 		}
1612 
1613 		for (; n < nintf; ++n) {
1614 			new_interfaces[n] = kzalloc(
1615 					sizeof(struct usb_interface),
1616 					GFP_KERNEL);
1617 			if (!new_interfaces[n]) {
1618 				dev_err(&dev->dev, "Out of memory\n");
1619 				ret = -ENOMEM;
1620 free_interfaces:
1621 				while (--n >= 0)
1622 					kfree(new_interfaces[n]);
1623 				kfree(new_interfaces);
1624 				return ret;
1625 			}
1626 		}
1627 
1628 		i = dev->bus_mA - cp->desc.bMaxPower * 2;
1629 		if (i < 0)
1630 			dev_warn(&dev->dev, "new config #%d exceeds power "
1631 					"limit by %dmA\n",
1632 					configuration, -i);
1633 	}
1634 
1635 	/* Wake up the device so we can send it the Set-Config request */
1636 	ret = usb_autoresume_device(dev);
1637 	if (ret)
1638 		goto free_interfaces;
1639 
1640 	/* if it's already configured, clear out old state first.
1641 	 * getting rid of old interfaces means unbinding their drivers.
1642 	 */
1643 	if (dev->state != USB_STATE_ADDRESS)
1644 		usb_disable_device(dev, 1);	/* Skip ep0 */
1645 
1646 	/* Get rid of pending async Set-Config requests for this device */
1647 	cancel_async_set_config(dev);
1648 
1649 	ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1650 			      USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1651 			      NULL, 0, USB_CTRL_SET_TIMEOUT);
1652 	if (ret < 0) {
1653 		/* All the old state is gone, so what else can we do?
1654 		 * The device is probably useless now anyway.
1655 		 */
1656 		cp = NULL;
1657 	}
1658 
1659 	dev->actconfig = cp;
1660 	if (!cp) {
1661 		usb_set_device_state(dev, USB_STATE_ADDRESS);
1662 		usb_autosuspend_device(dev);
1663 		goto free_interfaces;
1664 	}
1665 	usb_set_device_state(dev, USB_STATE_CONFIGURED);
1666 
1667 	/* Initialize the new interface structures and the
1668 	 * hc/hcd/usbcore interface/endpoint state.
1669 	 */
1670 	for (i = 0; i < nintf; ++i) {
1671 		struct usb_interface_cache *intfc;
1672 		struct usb_interface *intf;
1673 		struct usb_host_interface *alt;
1674 
1675 		cp->interface[i] = intf = new_interfaces[i];
1676 		intfc = cp->intf_cache[i];
1677 		intf->altsetting = intfc->altsetting;
1678 		intf->num_altsetting = intfc->num_altsetting;
1679 		intf->intf_assoc = find_iad(dev, cp, i);
1680 		kref_get(&intfc->ref);
1681 
1682 		alt = usb_altnum_to_altsetting(intf, 0);
1683 
1684 		/* No altsetting 0?  We'll assume the first altsetting.
1685 		 * We could use a GetInterface call, but if a device is
1686 		 * so non-compliant that it doesn't have altsetting 0
1687 		 * then I wouldn't trust its reply anyway.
1688 		 */
1689 		if (!alt)
1690 			alt = &intf->altsetting[0];
1691 
1692 		intf->cur_altsetting = alt;
1693 		usb_enable_interface(dev, intf, true);
1694 		intf->dev.parent = &dev->dev;
1695 		intf->dev.driver = NULL;
1696 		intf->dev.bus = &usb_bus_type;
1697 		intf->dev.type = &usb_if_device_type;
1698 		intf->dev.groups = usb_interface_groups;
1699 		intf->dev.dma_mask = dev->dev.dma_mask;
1700 		INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
1701 		device_initialize(&intf->dev);
1702 		mark_quiesced(intf);
1703 		dev_set_name(&intf->dev, "%d-%s:%d.%d",
1704 			dev->bus->busnum, dev->devpath,
1705 			configuration, alt->desc.bInterfaceNumber);
1706 	}
1707 	kfree(new_interfaces);
1708 
1709 	if (cp->string == NULL)
1710 		cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
1711 
1712 	/* Now that all the interfaces are set up, register them
1713 	 * to trigger binding of drivers to interfaces.  probe()
1714 	 * routines may install different altsettings and may
1715 	 * claim() any interfaces not yet bound.  Many class drivers
1716 	 * need that: CDC, audio, video, etc.
1717 	 */
1718 	for (i = 0; i < nintf; ++i) {
1719 		struct usb_interface *intf = cp->interface[i];
1720 
1721 		dev_dbg(&dev->dev,
1722 			"adding %s (config #%d, interface %d)\n",
1723 			dev_name(&intf->dev), configuration,
1724 			intf->cur_altsetting->desc.bInterfaceNumber);
1725 		ret = device_add(&intf->dev);
1726 		if (ret != 0) {
1727 			dev_err(&dev->dev, "device_add(%s) --> %d\n",
1728 				dev_name(&intf->dev), ret);
1729 			continue;
1730 		}
1731 		create_intf_ep_devs(intf);
1732 	}
1733 
1734 	usb_autosuspend_device(dev);
1735 	return 0;
1736 }
1737 
1738 static LIST_HEAD(set_config_list);
1739 static DEFINE_SPINLOCK(set_config_lock);
1740 
1741 struct set_config_request {
1742 	struct usb_device	*udev;
1743 	int			config;
1744 	struct work_struct	work;
1745 	struct list_head	node;
1746 };
1747 
1748 /* Worker routine for usb_driver_set_configuration() */
1749 static void driver_set_config_work(struct work_struct *work)
1750 {
1751 	struct set_config_request *req =
1752 		container_of(work, struct set_config_request, work);
1753 	struct usb_device *udev = req->udev;
1754 
1755 	usb_lock_device(udev);
1756 	spin_lock(&set_config_lock);
1757 	list_del(&req->node);
1758 	spin_unlock(&set_config_lock);
1759 
1760 	if (req->config >= -1)		/* Is req still valid? */
1761 		usb_set_configuration(udev, req->config);
1762 	usb_unlock_device(udev);
1763 	usb_put_dev(udev);
1764 	kfree(req);
1765 }
1766 
1767 /* Cancel pending Set-Config requests for a device whose configuration
1768  * was just changed
1769  */
1770 static void cancel_async_set_config(struct usb_device *udev)
1771 {
1772 	struct set_config_request *req;
1773 
1774 	spin_lock(&set_config_lock);
1775 	list_for_each_entry(req, &set_config_list, node) {
1776 		if (req->udev == udev)
1777 			req->config = -999;	/* Mark as cancelled */
1778 	}
1779 	spin_unlock(&set_config_lock);
1780 }
1781 
1782 /**
1783  * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1784  * @udev: the device whose configuration is being updated
1785  * @config: the configuration being chosen.
1786  * Context: In process context, must be able to sleep
1787  *
1788  * Device interface drivers are not allowed to change device configurations.
1789  * This is because changing configurations will destroy the interface the
1790  * driver is bound to and create new ones; it would be like a floppy-disk
1791  * driver telling the computer to replace the floppy-disk drive with a
1792  * tape drive!
1793  *
1794  * Still, in certain specialized circumstances the need may arise.  This
1795  * routine gets around the normal restrictions by using a work thread to
1796  * submit the change-config request.
1797  *
1798  * Returns 0 if the request was succesfully queued, error code otherwise.
1799  * The caller has no way to know whether the queued request will eventually
1800  * succeed.
1801  */
1802 int usb_driver_set_configuration(struct usb_device *udev, int config)
1803 {
1804 	struct set_config_request *req;
1805 
1806 	req = kmalloc(sizeof(*req), GFP_KERNEL);
1807 	if (!req)
1808 		return -ENOMEM;
1809 	req->udev = udev;
1810 	req->config = config;
1811 	INIT_WORK(&req->work, driver_set_config_work);
1812 
1813 	spin_lock(&set_config_lock);
1814 	list_add(&req->node, &set_config_list);
1815 	spin_unlock(&set_config_lock);
1816 
1817 	usb_get_dev(udev);
1818 	schedule_work(&req->work);
1819 	return 0;
1820 }
1821 EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
1822