xref: /openbmc/linux/drivers/usb/core/message.c (revision 1491eaf9)
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/mm.h>
10 #include <linux/timer.h>
11 #include <linux/ctype.h>
12 #include <linux/nls.h>
13 #include <linux/device.h>
14 #include <linux/scatterlist.h>
15 #include <linux/usb/cdc.h>
16 #include <linux/usb/quirks.h>
17 #include <linux/usb/hcd.h>	/* for usbcore internals */
18 #include <asm/byteorder.h>
19 
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  * Don't use this function from within an interrupt context, like a bottom half
123  * handler.  If you need an asynchronous message, or need to send a message
124  * from within interrupt context, use usb_submit_urb().
125  * If a thread in your driver uses this call, make sure your disconnect()
126  * method can wait for it to complete.  Since you don't have a handle on the
127  * URB used, you can't cancel the request.
128  *
129  * Return: If successful, the number of bytes transferred. Otherwise, a negative
130  * error number.
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 	ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
150 
151 	kfree(dr);
152 
153 	return ret;
154 }
155 EXPORT_SYMBOL_GPL(usb_control_msg);
156 
157 /**
158  * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
159  * @usb_dev: pointer to the usb device to send the message to
160  * @pipe: endpoint "pipe" to send the message to
161  * @data: pointer to the data to send
162  * @len: length in bytes of the data to send
163  * @actual_length: pointer to a location to put the actual length transferred
164  *	in bytes
165  * @timeout: time in msecs to wait for the message to complete before
166  *	timing out (if 0 the wait is forever)
167  *
168  * Context: !in_interrupt ()
169  *
170  * This function sends a simple interrupt message to a specified endpoint and
171  * waits for the message to complete, or timeout.
172  *
173  * Don't use this function from within an interrupt context, like a bottom half
174  * handler.  If you need an asynchronous message, or need to send a message
175  * from within interrupt context, use usb_submit_urb() If a thread in your
176  * driver uses this call, make sure your disconnect() method can wait for it to
177  * complete.  Since you don't have a handle on the URB used, you can't cancel
178  * the request.
179  *
180  * Return:
181  * If successful, 0. Otherwise a negative error number. The number of actual
182  * bytes transferred will be stored in the @actual_length parameter.
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  * Don't use this function from within an interrupt context, like a bottom half
208  * handler.  If you need an asynchronous message, or need to send a message
209  * from within interrupt context, use usb_submit_urb() If a thread in your
210  * driver uses this call, make sure your disconnect() method can wait for it to
211  * complete.  Since you don't have a handle on the URB used, you can't cancel
212  * the request.
213  *
214  * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
215  * users are forced to abuse this routine by using it to submit URBs for
216  * interrupt endpoints.  We will take the liberty of creating an interrupt URB
217  * (with the default interval) if the target is an interrupt endpoint.
218  *
219  * Return:
220  * If successful, 0. Otherwise a negative error number. The number of actual
221  * bytes transferred will be stored in the @actual_length parameter.
222  *
223  */
224 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
225 		 void *data, int len, int *actual_length, int timeout)
226 {
227 	struct urb *urb;
228 	struct usb_host_endpoint *ep;
229 
230 	ep = usb_pipe_endpoint(usb_dev, 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 	io->dev = NULL;
263 }
264 
265 static void sg_complete(struct urb *urb)
266 {
267 	struct usb_sg_request *io = urb->context;
268 	int status = urb->status;
269 
270 	spin_lock(&io->lock);
271 
272 	/* In 2.5 we require hcds' endpoint queues not to progress after fault
273 	 * reports, until the completion callback (this!) returns.  That lets
274 	 * device driver code (like this routine) unlink queued urbs first,
275 	 * if it needs to, since the HC won't work on them at all.  So it's
276 	 * not possible for page N+1 to overwrite page N, and so on.
277 	 *
278 	 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
279 	 * complete before the HCD can get requests away from hardware,
280 	 * though never during cleanup after a hard fault.
281 	 */
282 	if (io->status
283 			&& (io->status != -ECONNRESET
284 				|| status != -ECONNRESET)
285 			&& urb->actual_length) {
286 		dev_err(io->dev->bus->controller,
287 			"dev %s ep%d%s scatterlist error %d/%d\n",
288 			io->dev->devpath,
289 			usb_endpoint_num(&urb->ep->desc),
290 			usb_urb_dir_in(urb) ? "in" : "out",
291 			status, io->status);
292 		/* BUG (); */
293 	}
294 
295 	if (io->status == 0 && status && status != -ECONNRESET) {
296 		int i, found, retval;
297 
298 		io->status = status;
299 
300 		/* the previous urbs, and this one, completed already.
301 		 * unlink pending urbs so they won't rx/tx bad data.
302 		 * careful: unlink can sometimes be synchronous...
303 		 */
304 		spin_unlock(&io->lock);
305 		for (i = 0, found = 0; i < io->entries; i++) {
306 			if (!io->urbs[i])
307 				continue;
308 			if (found) {
309 				usb_block_urb(io->urbs[i]);
310 				retval = usb_unlink_urb(io->urbs[i]);
311 				if (retval != -EINPROGRESS &&
312 				    retval != -ENODEV &&
313 				    retval != -EBUSY &&
314 				    retval != -EIDRM)
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 
324 	/* on the last completion, signal usb_sg_wait() */
325 	io->bytes += urb->actual_length;
326 	io->count--;
327 	if (!io->count)
328 		complete(&io->complete);
329 
330 	spin_unlock(&io->lock);
331 }
332 
333 
334 /**
335  * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
336  * @io: request block being initialized.  until usb_sg_wait() returns,
337  *	treat this as a pointer to an opaque block of memory,
338  * @dev: the usb device that will send or receive the data
339  * @pipe: endpoint "pipe" used to transfer the data
340  * @period: polling rate for interrupt endpoints, in frames or
341  * 	(for high speed endpoints) microframes; ignored for bulk
342  * @sg: scatterlist entries
343  * @nents: how many entries in the scatterlist
344  * @length: how many bytes to send from the scatterlist, or zero to
345  * 	send every byte identified in the list.
346  * @mem_flags: SLAB_* flags affecting memory allocations in this call
347  *
348  * This initializes a scatter/gather request, allocating resources such as
349  * I/O mappings and urb memory (except maybe memory used by USB controller
350  * drivers).
351  *
352  * The request must be issued using usb_sg_wait(), which waits for the I/O to
353  * complete (or to be canceled) and then cleans up all resources allocated by
354  * usb_sg_init().
355  *
356  * The request may be canceled with usb_sg_cancel(), either before or after
357  * usb_sg_wait() is called.
358  *
359  * Return: Zero for success, else a negative errno value.
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 use_sg;
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 
379 	if (dev->bus->sg_tablesize > 0) {
380 		use_sg = true;
381 		io->entries = 1;
382 	} else {
383 		use_sg = false;
384 		io->entries = nents;
385 	}
386 
387 	/* initialize all the urbs we'll use */
388 	io->urbs = kmalloc(io->entries * sizeof(*io->urbs), mem_flags);
389 	if (!io->urbs)
390 		goto nomem;
391 
392 	urb_flags = URB_NO_INTERRUPT;
393 	if (usb_pipein(pipe))
394 		urb_flags |= URB_SHORT_NOT_OK;
395 
396 	for_each_sg(sg, sg, io->entries, i) {
397 		struct urb *urb;
398 		unsigned len;
399 
400 		urb = usb_alloc_urb(0, mem_flags);
401 		if (!urb) {
402 			io->entries = i;
403 			goto nomem;
404 		}
405 		io->urbs[i] = urb;
406 
407 		urb->dev = NULL;
408 		urb->pipe = pipe;
409 		urb->interval = period;
410 		urb->transfer_flags = urb_flags;
411 		urb->complete = sg_complete;
412 		urb->context = io;
413 		urb->sg = sg;
414 
415 		if (use_sg) {
416 			/* There is no single transfer buffer */
417 			urb->transfer_buffer = NULL;
418 			urb->num_sgs = nents;
419 
420 			/* A length of zero means transfer the whole sg list */
421 			len = length;
422 			if (len == 0) {
423 				struct scatterlist	*sg2;
424 				int			j;
425 
426 				for_each_sg(sg, sg2, nents, j)
427 					len += sg2->length;
428 			}
429 		} else {
430 			/*
431 			 * Some systems can't use DMA; they use PIO instead.
432 			 * For their sakes, transfer_buffer is set whenever
433 			 * possible.
434 			 */
435 			if (!PageHighMem(sg_page(sg)))
436 				urb->transfer_buffer = sg_virt(sg);
437 			else
438 				urb->transfer_buffer = NULL;
439 
440 			len = sg->length;
441 			if (length) {
442 				len = min_t(size_t, len, length);
443 				length -= len;
444 				if (length == 0)
445 					io->entries = i + 1;
446 			}
447 		}
448 		urb->transfer_buffer_length = len;
449 	}
450 	io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
451 
452 	/* transaction state */
453 	io->count = io->entries;
454 	io->status = 0;
455 	io->bytes = 0;
456 	init_completion(&io->complete);
457 	return 0;
458 
459 nomem:
460 	sg_clean(io);
461 	return -ENOMEM;
462 }
463 EXPORT_SYMBOL_GPL(usb_sg_init);
464 
465 /**
466  * usb_sg_wait - synchronously execute scatter/gather request
467  * @io: request block handle, as initialized with usb_sg_init().
468  * 	some fields become accessible when this call returns.
469  * Context: !in_interrupt ()
470  *
471  * This function blocks until the specified I/O operation completes.  It
472  * leverages the grouping of the related I/O requests to get good transfer
473  * rates, by queueing the requests.  At higher speeds, such queuing can
474  * significantly improve USB throughput.
475  *
476  * There are three kinds of completion for this function.
477  * (1) success, where io->status is zero.  The number of io->bytes
478  *     transferred is as requested.
479  * (2) error, where io->status is a negative errno value.  The number
480  *     of io->bytes transferred before the error is usually less
481  *     than requested, and can be nonzero.
482  * (3) cancellation, a type of error with status -ECONNRESET that
483  *     is initiated by usb_sg_cancel().
484  *
485  * When this function returns, all memory allocated through usb_sg_init() or
486  * this call will have been freed.  The request block parameter may still be
487  * passed to usb_sg_cancel(), or it may be freed.  It could also be
488  * reinitialized and then reused.
489  *
490  * Data Transfer Rates:
491  *
492  * Bulk transfers are valid for full or high speed endpoints.
493  * The best full speed data rate is 19 packets of 64 bytes each
494  * per frame, or 1216 bytes per millisecond.
495  * The best high speed data rate is 13 packets of 512 bytes each
496  * per microframe, or 52 KBytes per millisecond.
497  *
498  * The reason to use interrupt transfers through this API would most likely
499  * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
500  * could be transferred.  That capability is less useful for low or full
501  * speed interrupt endpoints, which allow at most one packet per millisecond,
502  * of at most 8 or 64 bytes (respectively).
503  *
504  * It is not necessary to call this function to reserve bandwidth for devices
505  * under an xHCI host controller, as the bandwidth is reserved when the
506  * configuration or interface alt setting is selected.
507  */
508 void usb_sg_wait(struct usb_sg_request *io)
509 {
510 	int i;
511 	int entries = io->entries;
512 
513 	/* queue the urbs.  */
514 	spin_lock_irq(&io->lock);
515 	i = 0;
516 	while (i < entries && !io->status) {
517 		int retval;
518 
519 		io->urbs[i]->dev = io->dev;
520 		spin_unlock_irq(&io->lock);
521 
522 		retval = usb_submit_urb(io->urbs[i], GFP_NOIO);
523 
524 		switch (retval) {
525 			/* maybe we retrying will recover */
526 		case -ENXIO:	/* hc didn't queue this one */
527 		case -EAGAIN:
528 		case -ENOMEM:
529 			retval = 0;
530 			yield();
531 			break;
532 
533 			/* no error? continue immediately.
534 			 *
535 			 * NOTE: to work better with UHCI (4K I/O buffer may
536 			 * need 3K of TDs) it may be good to limit how many
537 			 * URBs are queued at once; N milliseconds?
538 			 */
539 		case 0:
540 			++i;
541 			cpu_relax();
542 			break;
543 
544 			/* fail any uncompleted urbs */
545 		default:
546 			io->urbs[i]->status = retval;
547 			dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
548 				__func__, retval);
549 			usb_sg_cancel(io);
550 		}
551 		spin_lock_irq(&io->lock);
552 		if (retval && (io->status == 0 || io->status == -ECONNRESET))
553 			io->status = retval;
554 	}
555 	io->count -= entries - i;
556 	if (io->count == 0)
557 		complete(&io->complete);
558 	spin_unlock_irq(&io->lock);
559 
560 	/* OK, yes, this could be packaged as non-blocking.
561 	 * So could the submit loop above ... but it's easier to
562 	 * solve neither problem than to solve both!
563 	 */
564 	wait_for_completion(&io->complete);
565 
566 	sg_clean(io);
567 }
568 EXPORT_SYMBOL_GPL(usb_sg_wait);
569 
570 /**
571  * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
572  * @io: request block, initialized with usb_sg_init()
573  *
574  * This stops a request after it has been started by usb_sg_wait().
575  * It can also prevents one initialized by usb_sg_init() from starting,
576  * so that call just frees resources allocated to the request.
577  */
578 void usb_sg_cancel(struct usb_sg_request *io)
579 {
580 	unsigned long flags;
581 	int i, retval;
582 
583 	spin_lock_irqsave(&io->lock, flags);
584 	if (io->status) {
585 		spin_unlock_irqrestore(&io->lock, flags);
586 		return;
587 	}
588 	/* shut everything down */
589 	io->status = -ECONNRESET;
590 	spin_unlock_irqrestore(&io->lock, flags);
591 
592 	for (i = io->entries - 1; i >= 0; --i) {
593 		usb_block_urb(io->urbs[i]);
594 
595 		retval = usb_unlink_urb(io->urbs[i]);
596 		if (retval != -EINPROGRESS
597 		    && retval != -ENODEV
598 		    && retval != -EBUSY
599 		    && retval != -EIDRM)
600 			dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
601 				 __func__, retval);
602 	}
603 }
604 EXPORT_SYMBOL_GPL(usb_sg_cancel);
605 
606 /*-------------------------------------------------------------------*/
607 
608 /**
609  * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
610  * @dev: the device whose descriptor is being retrieved
611  * @type: the descriptor type (USB_DT_*)
612  * @index: the number of the descriptor
613  * @buf: where to put the descriptor
614  * @size: how big is "buf"?
615  * Context: !in_interrupt ()
616  *
617  * Gets a USB descriptor.  Convenience functions exist to simplify
618  * getting some types of descriptors.  Use
619  * usb_get_string() or usb_string() for USB_DT_STRING.
620  * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
621  * are part of the device structure.
622  * In addition to a number of USB-standard descriptors, some
623  * devices also use class-specific or vendor-specific descriptors.
624  *
625  * This call is synchronous, and may not be used in an interrupt context.
626  *
627  * Return: The number of bytes received on success, or else the status code
628  * returned by the underlying usb_control_msg() call.
629  */
630 int usb_get_descriptor(struct usb_device *dev, unsigned char type,
631 		       unsigned char index, void *buf, int size)
632 {
633 	int i;
634 	int result;
635 
636 	memset(buf, 0, size);	/* Make sure we parse really received data */
637 
638 	for (i = 0; i < 3; ++i) {
639 		/* retry on length 0 or error; some devices are flakey */
640 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
641 				USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
642 				(type << 8) + index, 0, buf, size,
643 				USB_CTRL_GET_TIMEOUT);
644 		if (result <= 0 && result != -ETIMEDOUT)
645 			continue;
646 		if (result > 1 && ((u8 *)buf)[1] != type) {
647 			result = -ENODATA;
648 			continue;
649 		}
650 		break;
651 	}
652 	return result;
653 }
654 EXPORT_SYMBOL_GPL(usb_get_descriptor);
655 
656 /**
657  * usb_get_string - gets a string descriptor
658  * @dev: the device whose string descriptor is being retrieved
659  * @langid: code for language chosen (from string descriptor zero)
660  * @index: the number of the descriptor
661  * @buf: where to put the string
662  * @size: how big is "buf"?
663  * Context: !in_interrupt ()
664  *
665  * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
666  * in little-endian byte order).
667  * The usb_string() function will often be a convenient way to turn
668  * these strings into kernel-printable form.
669  *
670  * Strings may be referenced in device, configuration, interface, or other
671  * descriptors, and could also be used in vendor-specific ways.
672  *
673  * This call is synchronous, and may not be used in an interrupt context.
674  *
675  * Return: The number of bytes received on success, or else the status code
676  * returned by the underlying usb_control_msg() call.
677  */
678 static int usb_get_string(struct usb_device *dev, unsigned short langid,
679 			  unsigned char index, void *buf, int size)
680 {
681 	int i;
682 	int result;
683 
684 	for (i = 0; i < 3; ++i) {
685 		/* retry on length 0 or stall; some devices are flakey */
686 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
687 			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
688 			(USB_DT_STRING << 8) + index, langid, buf, size,
689 			USB_CTRL_GET_TIMEOUT);
690 		if (result == 0 || result == -EPIPE)
691 			continue;
692 		if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
693 			result = -ENODATA;
694 			continue;
695 		}
696 		break;
697 	}
698 	return result;
699 }
700 
701 static void usb_try_string_workarounds(unsigned char *buf, int *length)
702 {
703 	int newlength, oldlength = *length;
704 
705 	for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
706 		if (!isprint(buf[newlength]) || buf[newlength + 1])
707 			break;
708 
709 	if (newlength > 2) {
710 		buf[0] = newlength;
711 		*length = newlength;
712 	}
713 }
714 
715 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
716 			  unsigned int index, unsigned char *buf)
717 {
718 	int rc;
719 
720 	/* Try to read the string descriptor by asking for the maximum
721 	 * possible number of bytes */
722 	if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
723 		rc = -EIO;
724 	else
725 		rc = usb_get_string(dev, langid, index, buf, 255);
726 
727 	/* If that failed try to read the descriptor length, then
728 	 * ask for just that many bytes */
729 	if (rc < 2) {
730 		rc = usb_get_string(dev, langid, index, buf, 2);
731 		if (rc == 2)
732 			rc = usb_get_string(dev, langid, index, buf, buf[0]);
733 	}
734 
735 	if (rc >= 2) {
736 		if (!buf[0] && !buf[1])
737 			usb_try_string_workarounds(buf, &rc);
738 
739 		/* There might be extra junk at the end of the descriptor */
740 		if (buf[0] < rc)
741 			rc = buf[0];
742 
743 		rc = rc - (rc & 1); /* force a multiple of two */
744 	}
745 
746 	if (rc < 2)
747 		rc = (rc < 0 ? rc : -EINVAL);
748 
749 	return rc;
750 }
751 
752 static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
753 {
754 	int err;
755 
756 	if (dev->have_langid)
757 		return 0;
758 
759 	if (dev->string_langid < 0)
760 		return -EPIPE;
761 
762 	err = usb_string_sub(dev, 0, 0, tbuf);
763 
764 	/* If the string was reported but is malformed, default to english
765 	 * (0x0409) */
766 	if (err == -ENODATA || (err > 0 && err < 4)) {
767 		dev->string_langid = 0x0409;
768 		dev->have_langid = 1;
769 		dev_err(&dev->dev,
770 			"language id specifier not provided by device, defaulting to English\n");
771 		return 0;
772 	}
773 
774 	/* In case of all other errors, we assume the device is not able to
775 	 * deal with strings at all. Set string_langid to -1 in order to
776 	 * prevent any string to be retrieved from the device */
777 	if (err < 0) {
778 		dev_err(&dev->dev, "string descriptor 0 read error: %d\n",
779 					err);
780 		dev->string_langid = -1;
781 		return -EPIPE;
782 	}
783 
784 	/* always use the first langid listed */
785 	dev->string_langid = tbuf[2] | (tbuf[3] << 8);
786 	dev->have_langid = 1;
787 	dev_dbg(&dev->dev, "default language 0x%04x\n",
788 				dev->string_langid);
789 	return 0;
790 }
791 
792 /**
793  * usb_string - returns UTF-8 version of a string descriptor
794  * @dev: the device whose string descriptor is being retrieved
795  * @index: the number of the descriptor
796  * @buf: where to put the string
797  * @size: how big is "buf"?
798  * Context: !in_interrupt ()
799  *
800  * This converts the UTF-16LE encoded strings returned by devices, from
801  * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
802  * that are more usable in most kernel contexts.  Note that this function
803  * chooses strings in the first language supported by the device.
804  *
805  * This call is synchronous, and may not be used in an interrupt context.
806  *
807  * Return: length of the string (>= 0) or usb_control_msg status (< 0).
808  */
809 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
810 {
811 	unsigned char *tbuf;
812 	int err;
813 
814 	if (dev->state == USB_STATE_SUSPENDED)
815 		return -EHOSTUNREACH;
816 	if (size <= 0 || !buf || !index)
817 		return -EINVAL;
818 	buf[0] = 0;
819 	tbuf = kmalloc(256, GFP_NOIO);
820 	if (!tbuf)
821 		return -ENOMEM;
822 
823 	err = usb_get_langid(dev, tbuf);
824 	if (err < 0)
825 		goto errout;
826 
827 	err = usb_string_sub(dev, dev->string_langid, index, tbuf);
828 	if (err < 0)
829 		goto errout;
830 
831 	size--;		/* leave room for trailing NULL char in output buffer */
832 	err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
833 			UTF16_LITTLE_ENDIAN, buf, size);
834 	buf[err] = 0;
835 
836 	if (tbuf[1] != USB_DT_STRING)
837 		dev_dbg(&dev->dev,
838 			"wrong descriptor type %02x for string %d (\"%s\")\n",
839 			tbuf[1], index, buf);
840 
841  errout:
842 	kfree(tbuf);
843 	return err;
844 }
845 EXPORT_SYMBOL_GPL(usb_string);
846 
847 /* one UTF-8-encoded 16-bit character has at most three bytes */
848 #define MAX_USB_STRING_SIZE (127 * 3 + 1)
849 
850 /**
851  * usb_cache_string - read a string descriptor and cache it for later use
852  * @udev: the device whose string descriptor is being read
853  * @index: the descriptor index
854  *
855  * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
856  * or %NULL if the index is 0 or the string could not be read.
857  */
858 char *usb_cache_string(struct usb_device *udev, int index)
859 {
860 	char *buf;
861 	char *smallbuf = NULL;
862 	int len;
863 
864 	if (index <= 0)
865 		return NULL;
866 
867 	buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
868 	if (buf) {
869 		len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
870 		if (len > 0) {
871 			smallbuf = kmalloc(++len, GFP_NOIO);
872 			if (!smallbuf)
873 				return buf;
874 			memcpy(smallbuf, buf, len);
875 		}
876 		kfree(buf);
877 	}
878 	return smallbuf;
879 }
880 
881 /*
882  * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
883  * @dev: the device whose device descriptor is being updated
884  * @size: how much of the descriptor to read
885  * Context: !in_interrupt ()
886  *
887  * Updates the copy of the device descriptor stored in the device structure,
888  * which dedicates space for this purpose.
889  *
890  * Not exported, only for use by the core.  If drivers really want to read
891  * the device descriptor directly, they can call usb_get_descriptor() with
892  * type = USB_DT_DEVICE and index = 0.
893  *
894  * This call is synchronous, and may not be used in an interrupt context.
895  *
896  * Return: The number of bytes received on success, or else the status code
897  * returned by the underlying usb_control_msg() call.
898  */
899 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
900 {
901 	struct usb_device_descriptor *desc;
902 	int ret;
903 
904 	if (size > sizeof(*desc))
905 		return -EINVAL;
906 	desc = kmalloc(sizeof(*desc), GFP_NOIO);
907 	if (!desc)
908 		return -ENOMEM;
909 
910 	ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
911 	if (ret >= 0)
912 		memcpy(&dev->descriptor, desc, size);
913 	kfree(desc);
914 	return ret;
915 }
916 
917 /**
918  * usb_get_status - issues a GET_STATUS call
919  * @dev: the device whose status is being checked
920  * @type: USB_RECIP_*; for device, interface, or endpoint
921  * @target: zero (for device), else interface or endpoint number
922  * @data: pointer to two bytes of bitmap data
923  * Context: !in_interrupt ()
924  *
925  * Returns device, interface, or endpoint status.  Normally only of
926  * interest to see if the device is self powered, or has enabled the
927  * remote wakeup facility; or whether a bulk or interrupt endpoint
928  * is halted ("stalled").
929  *
930  * Bits in these status bitmaps are set using the SET_FEATURE request,
931  * and cleared using the CLEAR_FEATURE request.  The usb_clear_halt()
932  * function should be used to clear halt ("stall") status.
933  *
934  * This call is synchronous, and may not be used in an interrupt context.
935  *
936  * Returns 0 and the status value in *@data (in host byte order) on success,
937  * or else the status code from the underlying usb_control_msg() call.
938  */
939 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
940 {
941 	int ret;
942 	__le16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
943 
944 	if (!status)
945 		return -ENOMEM;
946 
947 	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
948 		USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
949 		sizeof(*status), USB_CTRL_GET_TIMEOUT);
950 
951 	if (ret == 2) {
952 		*(u16 *) data = le16_to_cpu(*status);
953 		ret = 0;
954 	} else if (ret >= 0) {
955 		ret = -EIO;
956 	}
957 	kfree(status);
958 	return ret;
959 }
960 EXPORT_SYMBOL_GPL(usb_get_status);
961 
962 /**
963  * usb_clear_halt - tells device to clear endpoint halt/stall condition
964  * @dev: device whose endpoint is halted
965  * @pipe: endpoint "pipe" being cleared
966  * Context: !in_interrupt ()
967  *
968  * This is used to clear halt conditions for bulk and interrupt endpoints,
969  * as reported by URB completion status.  Endpoints that are halted are
970  * sometimes referred to as being "stalled".  Such endpoints are unable
971  * to transmit or receive data until the halt status is cleared.  Any URBs
972  * queued for such an endpoint should normally be unlinked by the driver
973  * before clearing the halt condition, as described in sections 5.7.5
974  * and 5.8.5 of the USB 2.0 spec.
975  *
976  * Note that control and isochronous endpoints don't halt, although control
977  * endpoints report "protocol stall" (for unsupported requests) using the
978  * same status code used to report a true stall.
979  *
980  * This call is synchronous, and may not be used in an interrupt context.
981  *
982  * Return: Zero on success, or else the status code returned by the
983  * underlying usb_control_msg() call.
984  */
985 int usb_clear_halt(struct usb_device *dev, int pipe)
986 {
987 	int result;
988 	int endp = usb_pipeendpoint(pipe);
989 
990 	if (usb_pipein(pipe))
991 		endp |= USB_DIR_IN;
992 
993 	/* we don't care if it wasn't halted first. in fact some devices
994 	 * (like some ibmcam model 1 units) seem to expect hosts to make
995 	 * this request for iso endpoints, which can't halt!
996 	 */
997 	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
998 		USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
999 		USB_ENDPOINT_HALT, endp, NULL, 0,
1000 		USB_CTRL_SET_TIMEOUT);
1001 
1002 	/* don't un-halt or force to DATA0 except on success */
1003 	if (result < 0)
1004 		return result;
1005 
1006 	/* NOTE:  seems like Microsoft and Apple don't bother verifying
1007 	 * the clear "took", so some devices could lock up if you check...
1008 	 * such as the Hagiwara FlashGate DUAL.  So we won't bother.
1009 	 *
1010 	 * NOTE:  make sure the logic here doesn't diverge much from
1011 	 * the copy in usb-storage, for as long as we need two copies.
1012 	 */
1013 
1014 	usb_reset_endpoint(dev, endp);
1015 
1016 	return 0;
1017 }
1018 EXPORT_SYMBOL_GPL(usb_clear_halt);
1019 
1020 static int create_intf_ep_devs(struct usb_interface *intf)
1021 {
1022 	struct usb_device *udev = interface_to_usbdev(intf);
1023 	struct usb_host_interface *alt = intf->cur_altsetting;
1024 	int i;
1025 
1026 	if (intf->ep_devs_created || intf->unregistering)
1027 		return 0;
1028 
1029 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1030 		(void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
1031 	intf->ep_devs_created = 1;
1032 	return 0;
1033 }
1034 
1035 static void remove_intf_ep_devs(struct usb_interface *intf)
1036 {
1037 	struct usb_host_interface *alt = intf->cur_altsetting;
1038 	int i;
1039 
1040 	if (!intf->ep_devs_created)
1041 		return;
1042 
1043 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1044 		usb_remove_ep_devs(&alt->endpoint[i]);
1045 	intf->ep_devs_created = 0;
1046 }
1047 
1048 /**
1049  * usb_disable_endpoint -- Disable an endpoint by address
1050  * @dev: the device whose endpoint is being disabled
1051  * @epaddr: the endpoint's address.  Endpoint number for output,
1052  *	endpoint number + USB_DIR_IN for input
1053  * @reset_hardware: flag to erase any endpoint state stored in the
1054  *	controller hardware
1055  *
1056  * Disables the endpoint for URB submission and nukes all pending URBs.
1057  * If @reset_hardware is set then also deallocates hcd/hardware state
1058  * for the endpoint.
1059  */
1060 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
1061 		bool reset_hardware)
1062 {
1063 	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1064 	struct usb_host_endpoint *ep;
1065 
1066 	if (!dev)
1067 		return;
1068 
1069 	if (usb_endpoint_out(epaddr)) {
1070 		ep = dev->ep_out[epnum];
1071 		if (reset_hardware)
1072 			dev->ep_out[epnum] = NULL;
1073 	} else {
1074 		ep = dev->ep_in[epnum];
1075 		if (reset_hardware)
1076 			dev->ep_in[epnum] = NULL;
1077 	}
1078 	if (ep) {
1079 		ep->enabled = 0;
1080 		usb_hcd_flush_endpoint(dev, ep);
1081 		if (reset_hardware)
1082 			usb_hcd_disable_endpoint(dev, ep);
1083 	}
1084 }
1085 
1086 /**
1087  * usb_reset_endpoint - Reset an endpoint's state.
1088  * @dev: the device whose endpoint is to be reset
1089  * @epaddr: the endpoint's address.  Endpoint number for output,
1090  *	endpoint number + USB_DIR_IN for input
1091  *
1092  * Resets any host-side endpoint state such as the toggle bit,
1093  * sequence number or current window.
1094  */
1095 void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
1096 {
1097 	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1098 	struct usb_host_endpoint *ep;
1099 
1100 	if (usb_endpoint_out(epaddr))
1101 		ep = dev->ep_out[epnum];
1102 	else
1103 		ep = dev->ep_in[epnum];
1104 	if (ep)
1105 		usb_hcd_reset_endpoint(dev, ep);
1106 }
1107 EXPORT_SYMBOL_GPL(usb_reset_endpoint);
1108 
1109 
1110 /**
1111  * usb_disable_interface -- Disable all endpoints for an interface
1112  * @dev: the device whose interface is being disabled
1113  * @intf: pointer to the interface descriptor
1114  * @reset_hardware: flag to erase any endpoint state stored in the
1115  *	controller hardware
1116  *
1117  * Disables all the endpoints for the interface's current altsetting.
1118  */
1119 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
1120 		bool reset_hardware)
1121 {
1122 	struct usb_host_interface *alt = intf->cur_altsetting;
1123 	int i;
1124 
1125 	for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1126 		usb_disable_endpoint(dev,
1127 				alt->endpoint[i].desc.bEndpointAddress,
1128 				reset_hardware);
1129 	}
1130 }
1131 
1132 /**
1133  * usb_disable_device - Disable all the endpoints for a USB device
1134  * @dev: the device whose endpoints are being disabled
1135  * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1136  *
1137  * Disables all the device's endpoints, potentially including endpoint 0.
1138  * Deallocates hcd/hardware state for the endpoints (nuking all or most
1139  * pending urbs) and usbcore state for the interfaces, so that usbcore
1140  * must usb_set_configuration() before any interfaces could be used.
1141  */
1142 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1143 {
1144 	int i;
1145 	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1146 
1147 	/* getting rid of interfaces will disconnect
1148 	 * any drivers bound to them (a key side effect)
1149 	 */
1150 	if (dev->actconfig) {
1151 		/*
1152 		 * FIXME: In order to avoid self-deadlock involving the
1153 		 * bandwidth_mutex, we have to mark all the interfaces
1154 		 * before unregistering any of them.
1155 		 */
1156 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
1157 			dev->actconfig->interface[i]->unregistering = 1;
1158 
1159 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1160 			struct usb_interface	*interface;
1161 
1162 			/* remove this interface if it has been registered */
1163 			interface = dev->actconfig->interface[i];
1164 			if (!device_is_registered(&interface->dev))
1165 				continue;
1166 			dev_dbg(&dev->dev, "unregistering interface %s\n",
1167 				dev_name(&interface->dev));
1168 			remove_intf_ep_devs(interface);
1169 			device_del(&interface->dev);
1170 		}
1171 
1172 		/* Now that the interfaces are unbound, nobody should
1173 		 * try to access them.
1174 		 */
1175 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1176 			put_device(&dev->actconfig->interface[i]->dev);
1177 			dev->actconfig->interface[i] = NULL;
1178 		}
1179 
1180 		if (dev->usb2_hw_lpm_enabled == 1)
1181 			usb_set_usb2_hardware_lpm(dev, 0);
1182 		usb_unlocked_disable_lpm(dev);
1183 		usb_disable_ltm(dev);
1184 
1185 		dev->actconfig = NULL;
1186 		if (dev->state == USB_STATE_CONFIGURED)
1187 			usb_set_device_state(dev, USB_STATE_ADDRESS);
1188 	}
1189 
1190 	dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
1191 		skip_ep0 ? "non-ep0" : "all");
1192 	if (hcd->driver->check_bandwidth) {
1193 		/* First pass: Cancel URBs, leave endpoint pointers intact. */
1194 		for (i = skip_ep0; i < 16; ++i) {
1195 			usb_disable_endpoint(dev, i, false);
1196 			usb_disable_endpoint(dev, i + USB_DIR_IN, false);
1197 		}
1198 		/* Remove endpoints from the host controller internal state */
1199 		mutex_lock(hcd->bandwidth_mutex);
1200 		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1201 		mutex_unlock(hcd->bandwidth_mutex);
1202 		/* Second pass: remove endpoint pointers */
1203 	}
1204 	for (i = skip_ep0; i < 16; ++i) {
1205 		usb_disable_endpoint(dev, i, true);
1206 		usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1207 	}
1208 }
1209 
1210 /**
1211  * usb_enable_endpoint - Enable an endpoint for USB communications
1212  * @dev: the device whose interface is being enabled
1213  * @ep: the endpoint
1214  * @reset_ep: flag to reset the endpoint state
1215  *
1216  * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
1217  * For control endpoints, both the input and output sides are handled.
1218  */
1219 void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
1220 		bool reset_ep)
1221 {
1222 	int epnum = usb_endpoint_num(&ep->desc);
1223 	int is_out = usb_endpoint_dir_out(&ep->desc);
1224 	int is_control = usb_endpoint_xfer_control(&ep->desc);
1225 
1226 	if (reset_ep)
1227 		usb_hcd_reset_endpoint(dev, ep);
1228 	if (is_out || is_control)
1229 		dev->ep_out[epnum] = ep;
1230 	if (!is_out || is_control)
1231 		dev->ep_in[epnum] = ep;
1232 	ep->enabled = 1;
1233 }
1234 
1235 /**
1236  * usb_enable_interface - Enable all the endpoints for an interface
1237  * @dev: the device whose interface is being enabled
1238  * @intf: pointer to the interface descriptor
1239  * @reset_eps: flag to reset the endpoints' state
1240  *
1241  * Enables all the endpoints for the interface's current altsetting.
1242  */
1243 void usb_enable_interface(struct usb_device *dev,
1244 		struct usb_interface *intf, bool reset_eps)
1245 {
1246 	struct usb_host_interface *alt = intf->cur_altsetting;
1247 	int i;
1248 
1249 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1250 		usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
1251 }
1252 
1253 /**
1254  * usb_set_interface - Makes a particular alternate setting be current
1255  * @dev: the device whose interface is being updated
1256  * @interface: the interface being updated
1257  * @alternate: the setting being chosen.
1258  * Context: !in_interrupt ()
1259  *
1260  * This is used to enable data transfers on interfaces that may not
1261  * be enabled by default.  Not all devices support such configurability.
1262  * Only the driver bound to an interface may change its setting.
1263  *
1264  * Within any given configuration, each interface may have several
1265  * alternative settings.  These are often used to control levels of
1266  * bandwidth consumption.  For example, the default setting for a high
1267  * speed interrupt endpoint may not send more than 64 bytes per microframe,
1268  * while interrupt transfers of up to 3KBytes per microframe are legal.
1269  * Also, isochronous endpoints may never be part of an
1270  * interface's default setting.  To access such bandwidth, alternate
1271  * interface settings must be made current.
1272  *
1273  * Note that in the Linux USB subsystem, bandwidth associated with
1274  * an endpoint in a given alternate setting is not reserved until an URB
1275  * is submitted that needs that bandwidth.  Some other operating systems
1276  * allocate bandwidth early, when a configuration is chosen.
1277  *
1278  * This call is synchronous, and may not be used in an interrupt context.
1279  * Also, drivers must not change altsettings while urbs are scheduled for
1280  * endpoints in that interface; all such urbs must first be completed
1281  * (perhaps forced by unlinking).
1282  *
1283  * Return: Zero on success, or else the status code returned by the
1284  * underlying usb_control_msg() call.
1285  */
1286 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1287 {
1288 	struct usb_interface *iface;
1289 	struct usb_host_interface *alt;
1290 	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1291 	int i, ret, manual = 0;
1292 	unsigned int epaddr;
1293 	unsigned int pipe;
1294 
1295 	if (dev->state == USB_STATE_SUSPENDED)
1296 		return -EHOSTUNREACH;
1297 
1298 	iface = usb_ifnum_to_if(dev, interface);
1299 	if (!iface) {
1300 		dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1301 			interface);
1302 		return -EINVAL;
1303 	}
1304 	if (iface->unregistering)
1305 		return -ENODEV;
1306 
1307 	alt = usb_altnum_to_altsetting(iface, alternate);
1308 	if (!alt) {
1309 		dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
1310 			 alternate);
1311 		return -EINVAL;
1312 	}
1313 
1314 	/* Make sure we have enough bandwidth for this alternate interface.
1315 	 * Remove the current alt setting and add the new alt setting.
1316 	 */
1317 	mutex_lock(hcd->bandwidth_mutex);
1318 	/* Disable LPM, and re-enable it once the new alt setting is installed,
1319 	 * so that the xHCI driver can recalculate the U1/U2 timeouts.
1320 	 */
1321 	if (usb_disable_lpm(dev)) {
1322 		dev_err(&iface->dev, "%s Failed to disable LPM\n.", __func__);
1323 		mutex_unlock(hcd->bandwidth_mutex);
1324 		return -ENOMEM;
1325 	}
1326 	/* Changing alt-setting also frees any allocated streams */
1327 	for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
1328 		iface->cur_altsetting->endpoint[i].streams = 0;
1329 
1330 	ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
1331 	if (ret < 0) {
1332 		dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
1333 				alternate);
1334 		usb_enable_lpm(dev);
1335 		mutex_unlock(hcd->bandwidth_mutex);
1336 		return ret;
1337 	}
1338 
1339 	if (dev->quirks & USB_QUIRK_NO_SET_INTF)
1340 		ret = -EPIPE;
1341 	else
1342 		ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1343 				   USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1344 				   alternate, interface, NULL, 0, 5000);
1345 
1346 	/* 9.4.10 says devices don't need this and are free to STALL the
1347 	 * request if the interface only has one alternate setting.
1348 	 */
1349 	if (ret == -EPIPE && iface->num_altsetting == 1) {
1350 		dev_dbg(&dev->dev,
1351 			"manual set_interface for iface %d, alt %d\n",
1352 			interface, alternate);
1353 		manual = 1;
1354 	} else if (ret < 0) {
1355 		/* Re-instate the old alt setting */
1356 		usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
1357 		usb_enable_lpm(dev);
1358 		mutex_unlock(hcd->bandwidth_mutex);
1359 		return ret;
1360 	}
1361 	mutex_unlock(hcd->bandwidth_mutex);
1362 
1363 	/* FIXME drivers shouldn't need to replicate/bugfix the logic here
1364 	 * when they implement async or easily-killable versions of this or
1365 	 * other "should-be-internal" functions (like clear_halt).
1366 	 * should hcd+usbcore postprocess control requests?
1367 	 */
1368 
1369 	/* prevent submissions using previous endpoint settings */
1370 	if (iface->cur_altsetting != alt) {
1371 		remove_intf_ep_devs(iface);
1372 		usb_remove_sysfs_intf_files(iface);
1373 	}
1374 	usb_disable_interface(dev, iface, true);
1375 
1376 	iface->cur_altsetting = alt;
1377 
1378 	/* Now that the interface is installed, re-enable LPM. */
1379 	usb_unlocked_enable_lpm(dev);
1380 
1381 	/* If the interface only has one altsetting and the device didn't
1382 	 * accept the request, we attempt to carry out the equivalent action
1383 	 * by manually clearing the HALT feature for each endpoint in the
1384 	 * new altsetting.
1385 	 */
1386 	if (manual) {
1387 		for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1388 			epaddr = alt->endpoint[i].desc.bEndpointAddress;
1389 			pipe = __create_pipe(dev,
1390 					USB_ENDPOINT_NUMBER_MASK & epaddr) |
1391 					(usb_endpoint_out(epaddr) ?
1392 					USB_DIR_OUT : USB_DIR_IN);
1393 
1394 			usb_clear_halt(dev, pipe);
1395 		}
1396 	}
1397 
1398 	/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1399 	 *
1400 	 * Note:
1401 	 * Despite EP0 is always present in all interfaces/AS, the list of
1402 	 * endpoints from the descriptor does not contain EP0. Due to its
1403 	 * omnipresence one might expect EP0 being considered "affected" by
1404 	 * any SetInterface request and hence assume toggles need to be reset.
1405 	 * However, EP0 toggles are re-synced for every individual transfer
1406 	 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1407 	 * (Likewise, EP0 never "halts" on well designed devices.)
1408 	 */
1409 	usb_enable_interface(dev, iface, true);
1410 	if (device_is_registered(&iface->dev)) {
1411 		usb_create_sysfs_intf_files(iface);
1412 		create_intf_ep_devs(iface);
1413 	}
1414 	return 0;
1415 }
1416 EXPORT_SYMBOL_GPL(usb_set_interface);
1417 
1418 /**
1419  * usb_reset_configuration - lightweight device reset
1420  * @dev: the device whose configuration is being reset
1421  *
1422  * This issues a standard SET_CONFIGURATION request to the device using
1423  * the current configuration.  The effect is to reset most USB-related
1424  * state in the device, including interface altsettings (reset to zero),
1425  * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
1426  * endpoints).  Other usbcore state is unchanged, including bindings of
1427  * usb device drivers to interfaces.
1428  *
1429  * Because this affects multiple interfaces, avoid using this with composite
1430  * (multi-interface) devices.  Instead, the driver for each interface may
1431  * use usb_set_interface() on the interfaces it claims.  Be careful though;
1432  * some devices don't support the SET_INTERFACE request, and others won't
1433  * reset all the interface state (notably endpoint state).  Resetting the whole
1434  * configuration would affect other drivers' interfaces.
1435  *
1436  * The caller must own the device lock.
1437  *
1438  * Return: Zero on success, else a negative error code.
1439  */
1440 int usb_reset_configuration(struct usb_device *dev)
1441 {
1442 	int			i, retval;
1443 	struct usb_host_config	*config;
1444 	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1445 
1446 	if (dev->state == USB_STATE_SUSPENDED)
1447 		return -EHOSTUNREACH;
1448 
1449 	/* caller must have locked the device and must own
1450 	 * the usb bus readlock (so driver bindings are stable);
1451 	 * calls during probe() are fine
1452 	 */
1453 
1454 	for (i = 1; i < 16; ++i) {
1455 		usb_disable_endpoint(dev, i, true);
1456 		usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1457 	}
1458 
1459 	config = dev->actconfig;
1460 	retval = 0;
1461 	mutex_lock(hcd->bandwidth_mutex);
1462 	/* Disable LPM, and re-enable it once the configuration is reset, so
1463 	 * that the xHCI driver can recalculate the U1/U2 timeouts.
1464 	 */
1465 	if (usb_disable_lpm(dev)) {
1466 		dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
1467 		mutex_unlock(hcd->bandwidth_mutex);
1468 		return -ENOMEM;
1469 	}
1470 	/* Make sure we have enough bandwidth for each alternate setting 0 */
1471 	for (i = 0; i < config->desc.bNumInterfaces; i++) {
1472 		struct usb_interface *intf = config->interface[i];
1473 		struct usb_host_interface *alt;
1474 
1475 		alt = usb_altnum_to_altsetting(intf, 0);
1476 		if (!alt)
1477 			alt = &intf->altsetting[0];
1478 		if (alt != intf->cur_altsetting)
1479 			retval = usb_hcd_alloc_bandwidth(dev, NULL,
1480 					intf->cur_altsetting, alt);
1481 		if (retval < 0)
1482 			break;
1483 	}
1484 	/* If not, reinstate the old alternate settings */
1485 	if (retval < 0) {
1486 reset_old_alts:
1487 		for (i--; i >= 0; i--) {
1488 			struct usb_interface *intf = config->interface[i];
1489 			struct usb_host_interface *alt;
1490 
1491 			alt = usb_altnum_to_altsetting(intf, 0);
1492 			if (!alt)
1493 				alt = &intf->altsetting[0];
1494 			if (alt != intf->cur_altsetting)
1495 				usb_hcd_alloc_bandwidth(dev, NULL,
1496 						alt, intf->cur_altsetting);
1497 		}
1498 		usb_enable_lpm(dev);
1499 		mutex_unlock(hcd->bandwidth_mutex);
1500 		return retval;
1501 	}
1502 	retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1503 			USB_REQ_SET_CONFIGURATION, 0,
1504 			config->desc.bConfigurationValue, 0,
1505 			NULL, 0, USB_CTRL_SET_TIMEOUT);
1506 	if (retval < 0)
1507 		goto reset_old_alts;
1508 	mutex_unlock(hcd->bandwidth_mutex);
1509 
1510 	/* re-init hc/hcd interface/endpoint state */
1511 	for (i = 0; i < config->desc.bNumInterfaces; i++) {
1512 		struct usb_interface *intf = config->interface[i];
1513 		struct usb_host_interface *alt;
1514 
1515 		alt = usb_altnum_to_altsetting(intf, 0);
1516 
1517 		/* No altsetting 0?  We'll assume the first altsetting.
1518 		 * We could use a GetInterface call, but if a device is
1519 		 * so non-compliant that it doesn't have altsetting 0
1520 		 * then I wouldn't trust its reply anyway.
1521 		 */
1522 		if (!alt)
1523 			alt = &intf->altsetting[0];
1524 
1525 		if (alt != intf->cur_altsetting) {
1526 			remove_intf_ep_devs(intf);
1527 			usb_remove_sysfs_intf_files(intf);
1528 		}
1529 		intf->cur_altsetting = alt;
1530 		usb_enable_interface(dev, intf, true);
1531 		if (device_is_registered(&intf->dev)) {
1532 			usb_create_sysfs_intf_files(intf);
1533 			create_intf_ep_devs(intf);
1534 		}
1535 	}
1536 	/* Now that the interfaces are installed, re-enable LPM. */
1537 	usb_unlocked_enable_lpm(dev);
1538 	return 0;
1539 }
1540 EXPORT_SYMBOL_GPL(usb_reset_configuration);
1541 
1542 static void usb_release_interface(struct device *dev)
1543 {
1544 	struct usb_interface *intf = to_usb_interface(dev);
1545 	struct usb_interface_cache *intfc =
1546 			altsetting_to_usb_interface_cache(intf->altsetting);
1547 
1548 	kref_put(&intfc->ref, usb_release_interface_cache);
1549 	usb_put_dev(interface_to_usbdev(intf));
1550 	kfree(intf);
1551 }
1552 
1553 /*
1554  * usb_deauthorize_interface - deauthorize an USB interface
1555  *
1556  * @intf: USB interface structure
1557  */
1558 void usb_deauthorize_interface(struct usb_interface *intf)
1559 {
1560 	struct device *dev = &intf->dev;
1561 
1562 	device_lock(dev->parent);
1563 
1564 	if (intf->authorized) {
1565 		device_lock(dev);
1566 		intf->authorized = 0;
1567 		device_unlock(dev);
1568 
1569 		usb_forced_unbind_intf(intf);
1570 	}
1571 
1572 	device_unlock(dev->parent);
1573 }
1574 
1575 /*
1576  * usb_authorize_interface - authorize an USB interface
1577  *
1578  * @intf: USB interface structure
1579  */
1580 void usb_authorize_interface(struct usb_interface *intf)
1581 {
1582 	struct device *dev = &intf->dev;
1583 
1584 	if (!intf->authorized) {
1585 		device_lock(dev);
1586 		intf->authorized = 1; /* authorize interface */
1587 		device_unlock(dev);
1588 	}
1589 }
1590 
1591 static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1592 {
1593 	struct usb_device *usb_dev;
1594 	struct usb_interface *intf;
1595 	struct usb_host_interface *alt;
1596 
1597 	intf = to_usb_interface(dev);
1598 	usb_dev = interface_to_usbdev(intf);
1599 	alt = intf->cur_altsetting;
1600 
1601 	if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
1602 		   alt->desc.bInterfaceClass,
1603 		   alt->desc.bInterfaceSubClass,
1604 		   alt->desc.bInterfaceProtocol))
1605 		return -ENOMEM;
1606 
1607 	if (add_uevent_var(env,
1608 		   "MODALIAS=usb:"
1609 		   "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
1610 		   le16_to_cpu(usb_dev->descriptor.idVendor),
1611 		   le16_to_cpu(usb_dev->descriptor.idProduct),
1612 		   le16_to_cpu(usb_dev->descriptor.bcdDevice),
1613 		   usb_dev->descriptor.bDeviceClass,
1614 		   usb_dev->descriptor.bDeviceSubClass,
1615 		   usb_dev->descriptor.bDeviceProtocol,
1616 		   alt->desc.bInterfaceClass,
1617 		   alt->desc.bInterfaceSubClass,
1618 		   alt->desc.bInterfaceProtocol,
1619 		   alt->desc.bInterfaceNumber))
1620 		return -ENOMEM;
1621 
1622 	return 0;
1623 }
1624 
1625 struct device_type usb_if_device_type = {
1626 	.name =		"usb_interface",
1627 	.release =	usb_release_interface,
1628 	.uevent =	usb_if_uevent,
1629 };
1630 
1631 static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1632 						struct usb_host_config *config,
1633 						u8 inum)
1634 {
1635 	struct usb_interface_assoc_descriptor *retval = NULL;
1636 	struct usb_interface_assoc_descriptor *intf_assoc;
1637 	int first_intf;
1638 	int last_intf;
1639 	int i;
1640 
1641 	for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
1642 		intf_assoc = config->intf_assoc[i];
1643 		if (intf_assoc->bInterfaceCount == 0)
1644 			continue;
1645 
1646 		first_intf = intf_assoc->bFirstInterface;
1647 		last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
1648 		if (inum >= first_intf && inum <= last_intf) {
1649 			if (!retval)
1650 				retval = intf_assoc;
1651 			else
1652 				dev_err(&dev->dev, "Interface #%d referenced"
1653 					" by multiple IADs\n", inum);
1654 		}
1655 	}
1656 
1657 	return retval;
1658 }
1659 
1660 
1661 /*
1662  * Internal function to queue a device reset
1663  * See usb_queue_reset_device() for more details
1664  */
1665 static void __usb_queue_reset_device(struct work_struct *ws)
1666 {
1667 	int rc;
1668 	struct usb_interface *iface =
1669 		container_of(ws, struct usb_interface, reset_ws);
1670 	struct usb_device *udev = interface_to_usbdev(iface);
1671 
1672 	rc = usb_lock_device_for_reset(udev, iface);
1673 	if (rc >= 0) {
1674 		usb_reset_device(udev);
1675 		usb_unlock_device(udev);
1676 	}
1677 	usb_put_intf(iface);	/* Undo _get_ in usb_queue_reset_device() */
1678 }
1679 
1680 
1681 /*
1682  * usb_set_configuration - Makes a particular device setting be current
1683  * @dev: the device whose configuration is being updated
1684  * @configuration: the configuration being chosen.
1685  * Context: !in_interrupt(), caller owns the device lock
1686  *
1687  * This is used to enable non-default device modes.  Not all devices
1688  * use this kind of configurability; many devices only have one
1689  * configuration.
1690  *
1691  * @configuration is the value of the configuration to be installed.
1692  * According to the USB spec (e.g. section 9.1.1.5), configuration values
1693  * must be non-zero; a value of zero indicates that the device in
1694  * unconfigured.  However some devices erroneously use 0 as one of their
1695  * configuration values.  To help manage such devices, this routine will
1696  * accept @configuration = -1 as indicating the device should be put in
1697  * an unconfigured state.
1698  *
1699  * USB device configurations may affect Linux interoperability,
1700  * power consumption and the functionality available.  For example,
1701  * the default configuration is limited to using 100mA of bus power,
1702  * so that when certain device functionality requires more power,
1703  * and the device is bus powered, that functionality should be in some
1704  * non-default device configuration.  Other device modes may also be
1705  * reflected as configuration options, such as whether two ISDN
1706  * channels are available independently; and choosing between open
1707  * standard device protocols (like CDC) or proprietary ones.
1708  *
1709  * Note that a non-authorized device (dev->authorized == 0) will only
1710  * be put in unconfigured mode.
1711  *
1712  * Note that USB has an additional level of device configurability,
1713  * associated with interfaces.  That configurability is accessed using
1714  * usb_set_interface().
1715  *
1716  * This call is synchronous. The calling context must be able to sleep,
1717  * must own the device lock, and must not hold the driver model's USB
1718  * bus mutex; usb interface driver probe() methods cannot use this routine.
1719  *
1720  * Returns zero on success, or else the status code returned by the
1721  * underlying call that failed.  On successful completion, each interface
1722  * in the original device configuration has been destroyed, and each one
1723  * in the new configuration has been probed by all relevant usb device
1724  * drivers currently known to the kernel.
1725  */
1726 int usb_set_configuration(struct usb_device *dev, int configuration)
1727 {
1728 	int i, ret;
1729 	struct usb_host_config *cp = NULL;
1730 	struct usb_interface **new_interfaces = NULL;
1731 	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1732 	int n, nintf;
1733 
1734 	if (dev->authorized == 0 || configuration == -1)
1735 		configuration = 0;
1736 	else {
1737 		for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1738 			if (dev->config[i].desc.bConfigurationValue ==
1739 					configuration) {
1740 				cp = &dev->config[i];
1741 				break;
1742 			}
1743 		}
1744 	}
1745 	if ((!cp && configuration != 0))
1746 		return -EINVAL;
1747 
1748 	/* The USB spec says configuration 0 means unconfigured.
1749 	 * But if a device includes a configuration numbered 0,
1750 	 * we will accept it as a correctly configured state.
1751 	 * Use -1 if you really want to unconfigure the device.
1752 	 */
1753 	if (cp && configuration == 0)
1754 		dev_warn(&dev->dev, "config 0 descriptor??\n");
1755 
1756 	/* Allocate memory for new interfaces before doing anything else,
1757 	 * so that if we run out then nothing will have changed. */
1758 	n = nintf = 0;
1759 	if (cp) {
1760 		nintf = cp->desc.bNumInterfaces;
1761 		new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1762 				GFP_NOIO);
1763 		if (!new_interfaces) {
1764 			dev_err(&dev->dev, "Out of memory\n");
1765 			return -ENOMEM;
1766 		}
1767 
1768 		for (; n < nintf; ++n) {
1769 			new_interfaces[n] = kzalloc(
1770 					sizeof(struct usb_interface),
1771 					GFP_NOIO);
1772 			if (!new_interfaces[n]) {
1773 				dev_err(&dev->dev, "Out of memory\n");
1774 				ret = -ENOMEM;
1775 free_interfaces:
1776 				while (--n >= 0)
1777 					kfree(new_interfaces[n]);
1778 				kfree(new_interfaces);
1779 				return ret;
1780 			}
1781 		}
1782 
1783 		i = dev->bus_mA - usb_get_max_power(dev, cp);
1784 		if (i < 0)
1785 			dev_warn(&dev->dev, "new config #%d exceeds power "
1786 					"limit by %dmA\n",
1787 					configuration, -i);
1788 	}
1789 
1790 	/* Wake up the device so we can send it the Set-Config request */
1791 	ret = usb_autoresume_device(dev);
1792 	if (ret)
1793 		goto free_interfaces;
1794 
1795 	/* if it's already configured, clear out old state first.
1796 	 * getting rid of old interfaces means unbinding their drivers.
1797 	 */
1798 	if (dev->state != USB_STATE_ADDRESS)
1799 		usb_disable_device(dev, 1);	/* Skip ep0 */
1800 
1801 	/* Get rid of pending async Set-Config requests for this device */
1802 	cancel_async_set_config(dev);
1803 
1804 	/* Make sure we have bandwidth (and available HCD resources) for this
1805 	 * configuration.  Remove endpoints from the schedule if we're dropping
1806 	 * this configuration to set configuration 0.  After this point, the
1807 	 * host controller will not allow submissions to dropped endpoints.  If
1808 	 * this call fails, the device state is unchanged.
1809 	 */
1810 	mutex_lock(hcd->bandwidth_mutex);
1811 	/* Disable LPM, and re-enable it once the new configuration is
1812 	 * installed, so that the xHCI driver can recalculate the U1/U2
1813 	 * timeouts.
1814 	 */
1815 	if (dev->actconfig && usb_disable_lpm(dev)) {
1816 		dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
1817 		mutex_unlock(hcd->bandwidth_mutex);
1818 		ret = -ENOMEM;
1819 		goto free_interfaces;
1820 	}
1821 	ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
1822 	if (ret < 0) {
1823 		if (dev->actconfig)
1824 			usb_enable_lpm(dev);
1825 		mutex_unlock(hcd->bandwidth_mutex);
1826 		usb_autosuspend_device(dev);
1827 		goto free_interfaces;
1828 	}
1829 
1830 	/*
1831 	 * Initialize the new interface structures and the
1832 	 * hc/hcd/usbcore interface/endpoint state.
1833 	 */
1834 	for (i = 0; i < nintf; ++i) {
1835 		struct usb_interface_cache *intfc;
1836 		struct usb_interface *intf;
1837 		struct usb_host_interface *alt;
1838 
1839 		cp->interface[i] = intf = new_interfaces[i];
1840 		intfc = cp->intf_cache[i];
1841 		intf->altsetting = intfc->altsetting;
1842 		intf->num_altsetting = intfc->num_altsetting;
1843 		intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
1844 		kref_get(&intfc->ref);
1845 
1846 		alt = usb_altnum_to_altsetting(intf, 0);
1847 
1848 		/* No altsetting 0?  We'll assume the first altsetting.
1849 		 * We could use a GetInterface call, but if a device is
1850 		 * so non-compliant that it doesn't have altsetting 0
1851 		 * then I wouldn't trust its reply anyway.
1852 		 */
1853 		if (!alt)
1854 			alt = &intf->altsetting[0];
1855 
1856 		intf->intf_assoc =
1857 			find_iad(dev, cp, alt->desc.bInterfaceNumber);
1858 		intf->cur_altsetting = alt;
1859 		usb_enable_interface(dev, intf, true);
1860 		intf->dev.parent = &dev->dev;
1861 		intf->dev.driver = NULL;
1862 		intf->dev.bus = &usb_bus_type;
1863 		intf->dev.type = &usb_if_device_type;
1864 		intf->dev.groups = usb_interface_groups;
1865 		intf->dev.dma_mask = dev->dev.dma_mask;
1866 		INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
1867 		intf->minor = -1;
1868 		device_initialize(&intf->dev);
1869 		pm_runtime_no_callbacks(&intf->dev);
1870 		dev_set_name(&intf->dev, "%d-%s:%d.%d",
1871 			dev->bus->busnum, dev->devpath,
1872 			configuration, alt->desc.bInterfaceNumber);
1873 		usb_get_dev(dev);
1874 	}
1875 	kfree(new_interfaces);
1876 
1877 	ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1878 			      USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1879 			      NULL, 0, USB_CTRL_SET_TIMEOUT);
1880 	if (ret < 0 && cp) {
1881 		/*
1882 		 * All the old state is gone, so what else can we do?
1883 		 * The device is probably useless now anyway.
1884 		 */
1885 		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1886 		for (i = 0; i < nintf; ++i) {
1887 			usb_disable_interface(dev, cp->interface[i], true);
1888 			put_device(&cp->interface[i]->dev);
1889 			cp->interface[i] = NULL;
1890 		}
1891 		cp = NULL;
1892 	}
1893 
1894 	dev->actconfig = cp;
1895 	mutex_unlock(hcd->bandwidth_mutex);
1896 
1897 	if (!cp) {
1898 		usb_set_device_state(dev, USB_STATE_ADDRESS);
1899 
1900 		/* Leave LPM disabled while the device is unconfigured. */
1901 		usb_autosuspend_device(dev);
1902 		return ret;
1903 	}
1904 	usb_set_device_state(dev, USB_STATE_CONFIGURED);
1905 
1906 	if (cp->string == NULL &&
1907 			!(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
1908 		cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
1909 
1910 	/* Now that the interfaces are installed, re-enable LPM. */
1911 	usb_unlocked_enable_lpm(dev);
1912 	/* Enable LTM if it was turned off by usb_disable_device. */
1913 	usb_enable_ltm(dev);
1914 
1915 	/* Now that all the interfaces are set up, register them
1916 	 * to trigger binding of drivers to interfaces.  probe()
1917 	 * routines may install different altsettings and may
1918 	 * claim() any interfaces not yet bound.  Many class drivers
1919 	 * need that: CDC, audio, video, etc.
1920 	 */
1921 	for (i = 0; i < nintf; ++i) {
1922 		struct usb_interface *intf = cp->interface[i];
1923 
1924 		dev_dbg(&dev->dev,
1925 			"adding %s (config #%d, interface %d)\n",
1926 			dev_name(&intf->dev), configuration,
1927 			intf->cur_altsetting->desc.bInterfaceNumber);
1928 		device_enable_async_suspend(&intf->dev);
1929 		ret = device_add(&intf->dev);
1930 		if (ret != 0) {
1931 			dev_err(&dev->dev, "device_add(%s) --> %d\n",
1932 				dev_name(&intf->dev), ret);
1933 			continue;
1934 		}
1935 		create_intf_ep_devs(intf);
1936 	}
1937 
1938 	usb_autosuspend_device(dev);
1939 	return 0;
1940 }
1941 EXPORT_SYMBOL_GPL(usb_set_configuration);
1942 
1943 static LIST_HEAD(set_config_list);
1944 static DEFINE_SPINLOCK(set_config_lock);
1945 
1946 struct set_config_request {
1947 	struct usb_device	*udev;
1948 	int			config;
1949 	struct work_struct	work;
1950 	struct list_head	node;
1951 };
1952 
1953 /* Worker routine for usb_driver_set_configuration() */
1954 static void driver_set_config_work(struct work_struct *work)
1955 {
1956 	struct set_config_request *req =
1957 		container_of(work, struct set_config_request, work);
1958 	struct usb_device *udev = req->udev;
1959 
1960 	usb_lock_device(udev);
1961 	spin_lock(&set_config_lock);
1962 	list_del(&req->node);
1963 	spin_unlock(&set_config_lock);
1964 
1965 	if (req->config >= -1)		/* Is req still valid? */
1966 		usb_set_configuration(udev, req->config);
1967 	usb_unlock_device(udev);
1968 	usb_put_dev(udev);
1969 	kfree(req);
1970 }
1971 
1972 /* Cancel pending Set-Config requests for a device whose configuration
1973  * was just changed
1974  */
1975 static void cancel_async_set_config(struct usb_device *udev)
1976 {
1977 	struct set_config_request *req;
1978 
1979 	spin_lock(&set_config_lock);
1980 	list_for_each_entry(req, &set_config_list, node) {
1981 		if (req->udev == udev)
1982 			req->config = -999;	/* Mark as cancelled */
1983 	}
1984 	spin_unlock(&set_config_lock);
1985 }
1986 
1987 /**
1988  * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1989  * @udev: the device whose configuration is being updated
1990  * @config: the configuration being chosen.
1991  * Context: In process context, must be able to sleep
1992  *
1993  * Device interface drivers are not allowed to change device configurations.
1994  * This is because changing configurations will destroy the interface the
1995  * driver is bound to and create new ones; it would be like a floppy-disk
1996  * driver telling the computer to replace the floppy-disk drive with a
1997  * tape drive!
1998  *
1999  * Still, in certain specialized circumstances the need may arise.  This
2000  * routine gets around the normal restrictions by using a work thread to
2001  * submit the change-config request.
2002  *
2003  * Return: 0 if the request was successfully queued, error code otherwise.
2004  * The caller has no way to know whether the queued request will eventually
2005  * succeed.
2006  */
2007 int usb_driver_set_configuration(struct usb_device *udev, int config)
2008 {
2009 	struct set_config_request *req;
2010 
2011 	req = kmalloc(sizeof(*req), GFP_KERNEL);
2012 	if (!req)
2013 		return -ENOMEM;
2014 	req->udev = udev;
2015 	req->config = config;
2016 	INIT_WORK(&req->work, driver_set_config_work);
2017 
2018 	spin_lock(&set_config_lock);
2019 	list_add(&req->node, &set_config_list);
2020 	spin_unlock(&set_config_lock);
2021 
2022 	usb_get_dev(udev);
2023 	schedule_work(&req->work);
2024 	return 0;
2025 }
2026 EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
2027 
2028 /**
2029  * cdc_parse_cdc_header - parse the extra headers present in CDC devices
2030  * @hdr: the place to put the results of the parsing
2031  * @intf: the interface for which parsing is requested
2032  * @buffer: pointer to the extra headers to be parsed
2033  * @buflen: length of the extra headers
2034  *
2035  * This evaluates the extra headers present in CDC devices which
2036  * bind the interfaces for data and control and provide details
2037  * about the capabilities of the device.
2038  *
2039  * Return: number of descriptors parsed or -EINVAL
2040  * if the header is contradictory beyond salvage
2041  */
2042 
2043 int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr,
2044 				struct usb_interface *intf,
2045 				u8 *buffer,
2046 				int buflen)
2047 {
2048 	/* duplicates are ignored */
2049 	struct usb_cdc_union_desc *union_header = NULL;
2050 
2051 	/* duplicates are not tolerated */
2052 	struct usb_cdc_header_desc *header = NULL;
2053 	struct usb_cdc_ether_desc *ether = NULL;
2054 	struct usb_cdc_mdlm_detail_desc *detail = NULL;
2055 	struct usb_cdc_mdlm_desc *desc = NULL;
2056 
2057 	unsigned int elength;
2058 	int cnt = 0;
2059 
2060 	memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header));
2061 	hdr->phonet_magic_present = false;
2062 	while (buflen > 0) {
2063 		elength = buffer[0];
2064 		if (!elength) {
2065 			dev_err(&intf->dev, "skipping garbage byte\n");
2066 			elength = 1;
2067 			goto next_desc;
2068 		}
2069 		if (buffer[1] != USB_DT_CS_INTERFACE) {
2070 			dev_err(&intf->dev, "skipping garbage\n");
2071 			goto next_desc;
2072 		}
2073 
2074 		switch (buffer[2]) {
2075 		case USB_CDC_UNION_TYPE: /* we've found it */
2076 			if (elength < sizeof(struct usb_cdc_union_desc))
2077 				goto next_desc;
2078 			if (union_header) {
2079 				dev_err(&intf->dev, "More than one union descriptor, skipping ...\n");
2080 				goto next_desc;
2081 			}
2082 			union_header = (struct usb_cdc_union_desc *)buffer;
2083 			break;
2084 		case USB_CDC_COUNTRY_TYPE:
2085 			if (elength < sizeof(struct usb_cdc_country_functional_desc))
2086 				goto next_desc;
2087 			hdr->usb_cdc_country_functional_desc =
2088 				(struct usb_cdc_country_functional_desc *)buffer;
2089 			break;
2090 		case USB_CDC_HEADER_TYPE:
2091 			if (elength != sizeof(struct usb_cdc_header_desc))
2092 				goto next_desc;
2093 			if (header)
2094 				return -EINVAL;
2095 			header = (struct usb_cdc_header_desc *)buffer;
2096 			break;
2097 		case USB_CDC_ACM_TYPE:
2098 			if (elength < sizeof(struct usb_cdc_acm_descriptor))
2099 				goto next_desc;
2100 			hdr->usb_cdc_acm_descriptor =
2101 				(struct usb_cdc_acm_descriptor *)buffer;
2102 			break;
2103 		case USB_CDC_ETHERNET_TYPE:
2104 			if (elength != sizeof(struct usb_cdc_ether_desc))
2105 				goto next_desc;
2106 			if (ether)
2107 				return -EINVAL;
2108 			ether = (struct usb_cdc_ether_desc *)buffer;
2109 			break;
2110 		case USB_CDC_CALL_MANAGEMENT_TYPE:
2111 			if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor))
2112 				goto next_desc;
2113 			hdr->usb_cdc_call_mgmt_descriptor =
2114 				(struct usb_cdc_call_mgmt_descriptor *)buffer;
2115 			break;
2116 		case USB_CDC_DMM_TYPE:
2117 			if (elength < sizeof(struct usb_cdc_dmm_desc))
2118 				goto next_desc;
2119 			hdr->usb_cdc_dmm_desc =
2120 				(struct usb_cdc_dmm_desc *)buffer;
2121 			break;
2122 		case USB_CDC_MDLM_TYPE:
2123 			if (elength < sizeof(struct usb_cdc_mdlm_desc *))
2124 				goto next_desc;
2125 			if (desc)
2126 				return -EINVAL;
2127 			desc = (struct usb_cdc_mdlm_desc *)buffer;
2128 			break;
2129 		case USB_CDC_MDLM_DETAIL_TYPE:
2130 			if (elength < sizeof(struct usb_cdc_mdlm_detail_desc *))
2131 				goto next_desc;
2132 			if (detail)
2133 				return -EINVAL;
2134 			detail = (struct usb_cdc_mdlm_detail_desc *)buffer;
2135 			break;
2136 		case USB_CDC_NCM_TYPE:
2137 			if (elength < sizeof(struct usb_cdc_ncm_desc))
2138 				goto next_desc;
2139 			hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer;
2140 			break;
2141 		case USB_CDC_MBIM_TYPE:
2142 			if (elength < sizeof(struct usb_cdc_mbim_desc))
2143 				goto next_desc;
2144 
2145 			hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer;
2146 			break;
2147 		case USB_CDC_MBIM_EXTENDED_TYPE:
2148 			if (elength < sizeof(struct usb_cdc_mbim_extended_desc))
2149 				break;
2150 			hdr->usb_cdc_mbim_extended_desc =
2151 				(struct usb_cdc_mbim_extended_desc *)buffer;
2152 			break;
2153 		case CDC_PHONET_MAGIC_NUMBER:
2154 			hdr->phonet_magic_present = true;
2155 			break;
2156 		default:
2157 			/*
2158 			 * there are LOTS more CDC descriptors that
2159 			 * could legitimately be found here.
2160 			 */
2161 			dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n",
2162 					buffer[2], elength);
2163 			goto next_desc;
2164 		}
2165 		cnt++;
2166 next_desc:
2167 		buflen -= elength;
2168 		buffer += elength;
2169 	}
2170 	hdr->usb_cdc_union_desc = union_header;
2171 	hdr->usb_cdc_header_desc = header;
2172 	hdr->usb_cdc_mdlm_detail_desc = detail;
2173 	hdr->usb_cdc_mdlm_desc = desc;
2174 	hdr->usb_cdc_ether_desc = ether;
2175 	return cnt;
2176 }
2177 
2178 EXPORT_SYMBOL(cdc_parse_cdc_header);
2179