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