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