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