• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 	if (size <= 0)		/* No point in asking for no data */
789 		return -EINVAL;
790 
791 	memset(buf, 0, size);	/* Make sure we parse really received data */
792 
793 	for (i = 0; i < 3; ++i) {
794 		/* retry on length 0 or error; some devices are flakey */
795 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
796 				USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
797 				(type << 8) + index, 0, buf, size,
798 				USB_CTRL_GET_TIMEOUT);
799 		if (result <= 0 && result != -ETIMEDOUT)
800 			continue;
801 		if (result > 1 && ((u8 *)buf)[1] != type) {
802 			result = -ENODATA;
803 			continue;
804 		}
805 		break;
806 	}
807 	return result;
808 }
809 EXPORT_SYMBOL_GPL(usb_get_descriptor);
810 
811 /**
812  * usb_get_string - gets a string descriptor
813  * @dev: the device whose string descriptor is being retrieved
814  * @langid: code for language chosen (from string descriptor zero)
815  * @index: the number of the descriptor
816  * @buf: where to put the string
817  * @size: how big is "buf"?
818  * Context: !in_interrupt ()
819  *
820  * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
821  * in little-endian byte order).
822  * The usb_string() function will often be a convenient way to turn
823  * these strings into kernel-printable form.
824  *
825  * Strings may be referenced in device, configuration, interface, or other
826  * descriptors, and could also be used in vendor-specific ways.
827  *
828  * This call is synchronous, and may not be used in an interrupt context.
829  *
830  * Return: The number of bytes received on success, or else the status code
831  * returned by the underlying usb_control_msg() call.
832  */
usb_get_string(struct usb_device * dev,unsigned short langid,unsigned char index,void * buf,int size)833 static int usb_get_string(struct usb_device *dev, unsigned short langid,
834 			  unsigned char index, void *buf, int size)
835 {
836 	int i;
837 	int result;
838 
839 	if (size <= 0)		/* No point in asking for no data */
840 		return -EINVAL;
841 
842 	for (i = 0; i < 3; ++i) {
843 		/* retry on length 0 or stall; some devices are flakey */
844 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
845 			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
846 			(USB_DT_STRING << 8) + index, langid, buf, size,
847 			USB_CTRL_GET_TIMEOUT);
848 		if (result == 0 || result == -EPIPE)
849 			continue;
850 		if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
851 			result = -ENODATA;
852 			continue;
853 		}
854 		break;
855 	}
856 	return result;
857 }
858 
usb_try_string_workarounds(unsigned char * buf,int * length)859 static void usb_try_string_workarounds(unsigned char *buf, int *length)
860 {
861 	int newlength, oldlength = *length;
862 
863 	for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
864 		if (!isprint(buf[newlength]) || buf[newlength + 1])
865 			break;
866 
867 	if (newlength > 2) {
868 		buf[0] = newlength;
869 		*length = newlength;
870 	}
871 }
872 
usb_string_sub(struct usb_device * dev,unsigned int langid,unsigned int index,unsigned char * buf)873 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
874 			  unsigned int index, unsigned char *buf)
875 {
876 	int rc;
877 
878 	/* Try to read the string descriptor by asking for the maximum
879 	 * possible number of bytes */
880 	if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
881 		rc = -EIO;
882 	else
883 		rc = usb_get_string(dev, langid, index, buf, 255);
884 
885 	/* If that failed try to read the descriptor length, then
886 	 * ask for just that many bytes */
887 	if (rc < 2) {
888 		rc = usb_get_string(dev, langid, index, buf, 2);
889 		if (rc == 2)
890 			rc = usb_get_string(dev, langid, index, buf, buf[0]);
891 	}
892 
893 	if (rc >= 2) {
894 		if (!buf[0] && !buf[1])
895 			usb_try_string_workarounds(buf, &rc);
896 
897 		/* There might be extra junk at the end of the descriptor */
898 		if (buf[0] < rc)
899 			rc = buf[0];
900 
901 		rc = rc - (rc & 1); /* force a multiple of two */
902 	}
903 
904 	if (rc < 2)
905 		rc = (rc < 0 ? rc : -EINVAL);
906 
907 	return rc;
908 }
909 
usb_get_langid(struct usb_device * dev,unsigned char * tbuf)910 static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
911 {
912 	int err;
913 
914 	if (dev->have_langid)
915 		return 0;
916 
917 	if (dev->string_langid < 0)
918 		return -EPIPE;
919 
920 	err = usb_string_sub(dev, 0, 0, tbuf);
921 
922 	/* If the string was reported but is malformed, default to english
923 	 * (0x0409) */
924 	if (err == -ENODATA || (err > 0 && err < 4)) {
925 		dev->string_langid = 0x0409;
926 		dev->have_langid = 1;
927 		dev_err(&dev->dev,
928 			"language id specifier not provided by device, defaulting to English\n");
929 		return 0;
930 	}
931 
932 	/* In case of all other errors, we assume the device is not able to
933 	 * deal with strings at all. Set string_langid to -1 in order to
934 	 * prevent any string to be retrieved from the device */
935 	if (err < 0) {
936 		dev_info(&dev->dev, "string descriptor 0 read error: %d\n",
937 					err);
938 		dev->string_langid = -1;
939 		return -EPIPE;
940 	}
941 
942 	/* always use the first langid listed */
943 	dev->string_langid = tbuf[2] | (tbuf[3] << 8);
944 	dev->have_langid = 1;
945 	dev_dbg(&dev->dev, "default language 0x%04x\n",
946 				dev->string_langid);
947 	return 0;
948 }
949 
950 /**
951  * usb_string - returns UTF-8 version of a string descriptor
952  * @dev: the device whose string descriptor is being retrieved
953  * @index: the number of the descriptor
954  * @buf: where to put the string
955  * @size: how big is "buf"?
956  * Context: !in_interrupt ()
957  *
958  * This converts the UTF-16LE encoded strings returned by devices, from
959  * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
960  * that are more usable in most kernel contexts.  Note that this function
961  * chooses strings in the first language supported by the device.
962  *
963  * This call is synchronous, and may not be used in an interrupt context.
964  *
965  * Return: length of the string (>= 0) or usb_control_msg status (< 0).
966  */
usb_string(struct usb_device * dev,int index,char * buf,size_t size)967 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
968 {
969 	unsigned char *tbuf;
970 	int err;
971 
972 	if (dev->state == USB_STATE_SUSPENDED)
973 		return -EHOSTUNREACH;
974 	if (size <= 0 || !buf)
975 		return -EINVAL;
976 	buf[0] = 0;
977 	if (index <= 0 || index >= 256)
978 		return -EINVAL;
979 	tbuf = kmalloc(256, GFP_NOIO);
980 	if (!tbuf)
981 		return -ENOMEM;
982 
983 	err = usb_get_langid(dev, tbuf);
984 	if (err < 0)
985 		goto errout;
986 
987 	err = usb_string_sub(dev, dev->string_langid, index, tbuf);
988 	if (err < 0)
989 		goto errout;
990 
991 	size--;		/* leave room for trailing NULL char in output buffer */
992 	err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
993 			UTF16_LITTLE_ENDIAN, buf, size);
994 	buf[err] = 0;
995 
996 	if (tbuf[1] != USB_DT_STRING)
997 		dev_dbg(&dev->dev,
998 			"wrong descriptor type %02x for string %d (\"%s\")\n",
999 			tbuf[1], index, buf);
1000 
1001  errout:
1002 	kfree(tbuf);
1003 	return err;
1004 }
1005 EXPORT_SYMBOL_GPL(usb_string);
1006 
1007 /* one UTF-8-encoded 16-bit character has at most three bytes */
1008 #define MAX_USB_STRING_SIZE (127 * 3 + 1)
1009 
1010 /**
1011  * usb_cache_string - read a string descriptor and cache it for later use
1012  * @udev: the device whose string descriptor is being read
1013  * @index: the descriptor index
1014  *
1015  * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
1016  * or %NULL if the index is 0 or the string could not be read.
1017  */
usb_cache_string(struct usb_device * udev,int index)1018 char *usb_cache_string(struct usb_device *udev, int index)
1019 {
1020 	char *buf;
1021 	char *smallbuf = NULL;
1022 	int len;
1023 
1024 	if (index <= 0)
1025 		return NULL;
1026 
1027 	buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
1028 	if (buf) {
1029 		len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
1030 		if (len > 0) {
1031 			smallbuf = kmalloc(++len, GFP_NOIO);
1032 			if (!smallbuf)
1033 				return buf;
1034 			memcpy(smallbuf, buf, len);
1035 		}
1036 		kfree(buf);
1037 	}
1038 	return smallbuf;
1039 }
1040 
1041 /*
1042  * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
1043  * @dev: the device whose device descriptor is being updated
1044  * @size: how much of the descriptor to read
1045  * Context: !in_interrupt ()
1046  *
1047  * Updates the copy of the device descriptor stored in the device structure,
1048  * which dedicates space for this purpose.
1049  *
1050  * Not exported, only for use by the core.  If drivers really want to read
1051  * the device descriptor directly, they can call usb_get_descriptor() with
1052  * type = USB_DT_DEVICE and index = 0.
1053  *
1054  * This call is synchronous, and may not be used in an interrupt context.
1055  *
1056  * Return: The number of bytes received on success, or else the status code
1057  * returned by the underlying usb_control_msg() call.
1058  */
usb_get_device_descriptor(struct usb_device * dev,unsigned int size)1059 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
1060 {
1061 	struct usb_device_descriptor *desc;
1062 	int ret;
1063 
1064 	if (size > sizeof(*desc))
1065 		return -EINVAL;
1066 	desc = kmalloc(sizeof(*desc), GFP_NOIO);
1067 	if (!desc)
1068 		return -ENOMEM;
1069 
1070 	ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
1071 	if (ret >= 0)
1072 		memcpy(&dev->descriptor, desc, size);
1073 	kfree(desc);
1074 	return ret;
1075 }
1076 
1077 /*
1078  * usb_set_isoch_delay - informs the device of the packet transmit delay
1079  * @dev: the device whose delay is to be informed
1080  * Context: !in_interrupt()
1081  *
1082  * Since this is an optional request, we don't bother if it fails.
1083  */
usb_set_isoch_delay(struct usb_device * dev)1084 int usb_set_isoch_delay(struct usb_device *dev)
1085 {
1086 	/* skip hub devices */
1087 	if (dev->descriptor.bDeviceClass == USB_CLASS_HUB)
1088 		return 0;
1089 
1090 	/* skip non-SS/non-SSP devices */
1091 	if (dev->speed < USB_SPEED_SUPER)
1092 		return 0;
1093 
1094 	return usb_control_msg_send(dev, 0,
1095 			USB_REQ_SET_ISOCH_DELAY,
1096 			USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
1097 			dev->hub_delay, 0, NULL, 0,
1098 			USB_CTRL_SET_TIMEOUT,
1099 			GFP_NOIO);
1100 }
1101 
1102 /**
1103  * usb_get_status - issues a GET_STATUS call
1104  * @dev: the device whose status is being checked
1105  * @recip: USB_RECIP_*; for device, interface, or endpoint
1106  * @type: USB_STATUS_TYPE_*; for standard or PTM status types
1107  * @target: zero (for device), else interface or endpoint number
1108  * @data: pointer to two bytes of bitmap data
1109  * Context: !in_interrupt ()
1110  *
1111  * Returns device, interface, or endpoint status.  Normally only of
1112  * interest to see if the device is self powered, or has enabled the
1113  * remote wakeup facility; or whether a bulk or interrupt endpoint
1114  * is halted ("stalled").
1115  *
1116  * Bits in these status bitmaps are set using the SET_FEATURE request,
1117  * and cleared using the CLEAR_FEATURE request.  The usb_clear_halt()
1118  * function should be used to clear halt ("stall") status.
1119  *
1120  * This call is synchronous, and may not be used in an interrupt context.
1121  *
1122  * Returns 0 and the status value in *@data (in host byte order) on success,
1123  * or else the status code from the underlying usb_control_msg() call.
1124  */
usb_get_status(struct usb_device * dev,int recip,int type,int target,void * data)1125 int usb_get_status(struct usb_device *dev, int recip, int type, int target,
1126 		void *data)
1127 {
1128 	int ret;
1129 	void *status;
1130 	int length;
1131 
1132 	switch (type) {
1133 	case USB_STATUS_TYPE_STANDARD:
1134 		length = 2;
1135 		break;
1136 	case USB_STATUS_TYPE_PTM:
1137 		if (recip != USB_RECIP_DEVICE)
1138 			return -EINVAL;
1139 
1140 		length = 4;
1141 		break;
1142 	default:
1143 		return -EINVAL;
1144 	}
1145 
1146 	status =  kmalloc(length, GFP_KERNEL);
1147 	if (!status)
1148 		return -ENOMEM;
1149 
1150 	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1151 		USB_REQ_GET_STATUS, USB_DIR_IN | recip, USB_STATUS_TYPE_STANDARD,
1152 		target, status, length, USB_CTRL_GET_TIMEOUT);
1153 
1154 	switch (ret) {
1155 	case 4:
1156 		if (type != USB_STATUS_TYPE_PTM) {
1157 			ret = -EIO;
1158 			break;
1159 		}
1160 
1161 		*(u32 *) data = le32_to_cpu(*(__le32 *) status);
1162 		ret = 0;
1163 		break;
1164 	case 2:
1165 		if (type != USB_STATUS_TYPE_STANDARD) {
1166 			ret = -EIO;
1167 			break;
1168 		}
1169 
1170 		*(u16 *) data = le16_to_cpu(*(__le16 *) status);
1171 		ret = 0;
1172 		break;
1173 	default:
1174 		ret = -EIO;
1175 	}
1176 
1177 	kfree(status);
1178 	return ret;
1179 }
1180 EXPORT_SYMBOL_GPL(usb_get_status);
1181 
1182 /**
1183  * usb_clear_halt - tells device to clear endpoint halt/stall condition
1184  * @dev: device whose endpoint is halted
1185  * @pipe: endpoint "pipe" being cleared
1186  * Context: !in_interrupt ()
1187  *
1188  * This is used to clear halt conditions for bulk and interrupt endpoints,
1189  * as reported by URB completion status.  Endpoints that are halted are
1190  * sometimes referred to as being "stalled".  Such endpoints are unable
1191  * to transmit or receive data until the halt status is cleared.  Any URBs
1192  * queued for such an endpoint should normally be unlinked by the driver
1193  * before clearing the halt condition, as described in sections 5.7.5
1194  * and 5.8.5 of the USB 2.0 spec.
1195  *
1196  * Note that control and isochronous endpoints don't halt, although control
1197  * endpoints report "protocol stall" (for unsupported requests) using the
1198  * same status code used to report a true stall.
1199  *
1200  * This call is synchronous, and may not be used in an interrupt context.
1201  *
1202  * Return: Zero on success, or else the status code returned by the
1203  * underlying usb_control_msg() call.
1204  */
usb_clear_halt(struct usb_device * dev,int pipe)1205 int usb_clear_halt(struct usb_device *dev, int pipe)
1206 {
1207 	int result;
1208 	int endp = usb_pipeendpoint(pipe);
1209 
1210 	if (usb_pipein(pipe))
1211 		endp |= USB_DIR_IN;
1212 
1213 	/* we don't care if it wasn't halted first. in fact some devices
1214 	 * (like some ibmcam model 1 units) seem to expect hosts to make
1215 	 * this request for iso endpoints, which can't halt!
1216 	 */
1217 	result = usb_control_msg_send(dev, 0,
1218 				      USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
1219 				      USB_ENDPOINT_HALT, endp, NULL, 0,
1220 				      USB_CTRL_SET_TIMEOUT, GFP_NOIO);
1221 
1222 	/* don't un-halt or force to DATA0 except on success */
1223 	if (result)
1224 		return result;
1225 
1226 	/* NOTE:  seems like Microsoft and Apple don't bother verifying
1227 	 * the clear "took", so some devices could lock up if you check...
1228 	 * such as the Hagiwara FlashGate DUAL.  So we won't bother.
1229 	 *
1230 	 * NOTE:  make sure the logic here doesn't diverge much from
1231 	 * the copy in usb-storage, for as long as we need two copies.
1232 	 */
1233 
1234 	usb_reset_endpoint(dev, endp);
1235 
1236 	return 0;
1237 }
1238 EXPORT_SYMBOL_GPL(usb_clear_halt);
1239 
create_intf_ep_devs(struct usb_interface * intf)1240 static int create_intf_ep_devs(struct usb_interface *intf)
1241 {
1242 	struct usb_device *udev = interface_to_usbdev(intf);
1243 	struct usb_host_interface *alt = intf->cur_altsetting;
1244 	int i;
1245 
1246 	if (intf->ep_devs_created || intf->unregistering)
1247 		return 0;
1248 
1249 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1250 		(void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
1251 	intf->ep_devs_created = 1;
1252 	return 0;
1253 }
1254 
remove_intf_ep_devs(struct usb_interface * intf)1255 static void remove_intf_ep_devs(struct usb_interface *intf)
1256 {
1257 	struct usb_host_interface *alt = intf->cur_altsetting;
1258 	int i;
1259 
1260 	if (!intf->ep_devs_created)
1261 		return;
1262 
1263 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1264 		usb_remove_ep_devs(&alt->endpoint[i]);
1265 	intf->ep_devs_created = 0;
1266 }
1267 
1268 /**
1269  * usb_disable_endpoint -- Disable an endpoint by address
1270  * @dev: the device whose endpoint is being disabled
1271  * @epaddr: the endpoint's address.  Endpoint number for output,
1272  *	endpoint number + USB_DIR_IN for input
1273  * @reset_hardware: flag to erase any endpoint state stored in the
1274  *	controller hardware
1275  *
1276  * Disables the endpoint for URB submission and nukes all pending URBs.
1277  * If @reset_hardware is set then also deallocates hcd/hardware state
1278  * for the endpoint.
1279  */
usb_disable_endpoint(struct usb_device * dev,unsigned int epaddr,bool reset_hardware)1280 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
1281 		bool reset_hardware)
1282 {
1283 	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1284 	struct usb_host_endpoint *ep;
1285 
1286 	if (!dev)
1287 		return;
1288 
1289 	if (usb_endpoint_out(epaddr)) {
1290 		ep = dev->ep_out[epnum];
1291 		if (reset_hardware && epnum != 0)
1292 			dev->ep_out[epnum] = NULL;
1293 	} else {
1294 		ep = dev->ep_in[epnum];
1295 		if (reset_hardware && epnum != 0)
1296 			dev->ep_in[epnum] = NULL;
1297 	}
1298 	if (ep) {
1299 		ep->enabled = 0;
1300 		usb_hcd_flush_endpoint(dev, ep);
1301 		if (reset_hardware)
1302 			usb_hcd_disable_endpoint(dev, ep);
1303 	}
1304 }
1305 
1306 /**
1307  * usb_reset_endpoint - Reset an endpoint's state.
1308  * @dev: the device whose endpoint is to be reset
1309  * @epaddr: the endpoint's address.  Endpoint number for output,
1310  *	endpoint number + USB_DIR_IN for input
1311  *
1312  * Resets any host-side endpoint state such as the toggle bit,
1313  * sequence number or current window.
1314  */
usb_reset_endpoint(struct usb_device * dev,unsigned int epaddr)1315 void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
1316 {
1317 	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1318 	struct usb_host_endpoint *ep;
1319 
1320 	if (usb_endpoint_out(epaddr))
1321 		ep = dev->ep_out[epnum];
1322 	else
1323 		ep = dev->ep_in[epnum];
1324 	if (ep)
1325 		usb_hcd_reset_endpoint(dev, ep);
1326 }
1327 EXPORT_SYMBOL_GPL(usb_reset_endpoint);
1328 
1329 
1330 /**
1331  * usb_disable_interface -- Disable all endpoints for an interface
1332  * @dev: the device whose interface is being disabled
1333  * @intf: pointer to the interface descriptor
1334  * @reset_hardware: flag to erase any endpoint state stored in the
1335  *	controller hardware
1336  *
1337  * Disables all the endpoints for the interface's current altsetting.
1338  */
usb_disable_interface(struct usb_device * dev,struct usb_interface * intf,bool reset_hardware)1339 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
1340 		bool reset_hardware)
1341 {
1342 	struct usb_host_interface *alt = intf->cur_altsetting;
1343 	int i;
1344 
1345 	for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1346 		usb_disable_endpoint(dev,
1347 				alt->endpoint[i].desc.bEndpointAddress,
1348 				reset_hardware);
1349 	}
1350 }
1351 
1352 /*
1353  * usb_disable_device_endpoints -- Disable all endpoints for a device
1354  * @dev: the device whose endpoints are being disabled
1355  * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1356  */
usb_disable_device_endpoints(struct usb_device * dev,int skip_ep0)1357 static void usb_disable_device_endpoints(struct usb_device *dev, int skip_ep0)
1358 {
1359 	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1360 	int i;
1361 
1362 	if (hcd->driver->check_bandwidth) {
1363 		/* First pass: Cancel URBs, leave endpoint pointers intact. */
1364 		for (i = skip_ep0; i < 16; ++i) {
1365 			usb_disable_endpoint(dev, i, false);
1366 			usb_disable_endpoint(dev, i + USB_DIR_IN, false);
1367 		}
1368 		/* Remove endpoints from the host controller internal state */
1369 		mutex_lock(hcd->bandwidth_mutex);
1370 		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1371 		mutex_unlock(hcd->bandwidth_mutex);
1372 	}
1373 	/* Second pass: remove endpoint pointers */
1374 	for (i = skip_ep0; i < 16; ++i) {
1375 		usb_disable_endpoint(dev, i, true);
1376 		usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1377 	}
1378 }
1379 
1380 /**
1381  * usb_disable_device - Disable all the endpoints for a USB device
1382  * @dev: the device whose endpoints are being disabled
1383  * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1384  *
1385  * Disables all the device's endpoints, potentially including endpoint 0.
1386  * Deallocates hcd/hardware state for the endpoints (nuking all or most
1387  * pending urbs) and usbcore state for the interfaces, so that usbcore
1388  * must usb_set_configuration() before any interfaces could be used.
1389  */
usb_disable_device(struct usb_device * dev,int skip_ep0)1390 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1391 {
1392 	int i;
1393 
1394 	/* getting rid of interfaces will disconnect
1395 	 * any drivers bound to them (a key side effect)
1396 	 */
1397 	if (dev->actconfig) {
1398 		/*
1399 		 * FIXME: In order to avoid self-deadlock involving the
1400 		 * bandwidth_mutex, we have to mark all the interfaces
1401 		 * before unregistering any of them.
1402 		 */
1403 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
1404 			dev->actconfig->interface[i]->unregistering = 1;
1405 
1406 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1407 			struct usb_interface	*interface;
1408 
1409 			/* remove this interface if it has been registered */
1410 			interface = dev->actconfig->interface[i];
1411 			if (!device_is_registered(&interface->dev))
1412 				continue;
1413 			dev_dbg(&dev->dev, "unregistering interface %s\n",
1414 				dev_name(&interface->dev));
1415 			remove_intf_ep_devs(interface);
1416 			device_del(&interface->dev);
1417 		}
1418 
1419 		/* Now that the interfaces are unbound, nobody should
1420 		 * try to access them.
1421 		 */
1422 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1423 			put_device(&dev->actconfig->interface[i]->dev);
1424 			dev->actconfig->interface[i] = NULL;
1425 		}
1426 
1427 		usb_disable_usb2_hardware_lpm(dev);
1428 		usb_unlocked_disable_lpm(dev);
1429 		usb_disable_ltm(dev);
1430 
1431 		dev->actconfig = NULL;
1432 		if (dev->state == USB_STATE_CONFIGURED)
1433 			usb_set_device_state(dev, USB_STATE_ADDRESS);
1434 	}
1435 
1436 	dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
1437 		skip_ep0 ? "non-ep0" : "all");
1438 
1439 	usb_disable_device_endpoints(dev, skip_ep0);
1440 }
1441 
1442 /**
1443  * usb_enable_endpoint - Enable an endpoint for USB communications
1444  * @dev: the device whose interface is being enabled
1445  * @ep: the endpoint
1446  * @reset_ep: flag to reset the endpoint state
1447  *
1448  * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
1449  * For control endpoints, both the input and output sides are handled.
1450  */
usb_enable_endpoint(struct usb_device * dev,struct usb_host_endpoint * ep,bool reset_ep)1451 void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
1452 		bool reset_ep)
1453 {
1454 	int epnum = usb_endpoint_num(&ep->desc);
1455 	int is_out = usb_endpoint_dir_out(&ep->desc);
1456 	int is_control = usb_endpoint_xfer_control(&ep->desc);
1457 
1458 	if (reset_ep)
1459 		usb_hcd_reset_endpoint(dev, ep);
1460 	if (is_out || is_control)
1461 		dev->ep_out[epnum] = ep;
1462 	if (!is_out || is_control)
1463 		dev->ep_in[epnum] = ep;
1464 	ep->enabled = 1;
1465 }
1466 
1467 /**
1468  * usb_enable_interface - Enable all the endpoints for an interface
1469  * @dev: the device whose interface is being enabled
1470  * @intf: pointer to the interface descriptor
1471  * @reset_eps: flag to reset the endpoints' state
1472  *
1473  * Enables all the endpoints for the interface's current altsetting.
1474  */
usb_enable_interface(struct usb_device * dev,struct usb_interface * intf,bool reset_eps)1475 void usb_enable_interface(struct usb_device *dev,
1476 		struct usb_interface *intf, bool reset_eps)
1477 {
1478 	struct usb_host_interface *alt = intf->cur_altsetting;
1479 	int i;
1480 
1481 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1482 		usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
1483 }
1484 
1485 /**
1486  * usb_set_interface - Makes a particular alternate setting be current
1487  * @dev: the device whose interface is being updated
1488  * @interface: the interface being updated
1489  * @alternate: the setting being chosen.
1490  * Context: !in_interrupt ()
1491  *
1492  * This is used to enable data transfers on interfaces that may not
1493  * be enabled by default.  Not all devices support such configurability.
1494  * Only the driver bound to an interface may change its setting.
1495  *
1496  * Within any given configuration, each interface may have several
1497  * alternative settings.  These are often used to control levels of
1498  * bandwidth consumption.  For example, the default setting for a high
1499  * speed interrupt endpoint may not send more than 64 bytes per microframe,
1500  * while interrupt transfers of up to 3KBytes per microframe are legal.
1501  * Also, isochronous endpoints may never be part of an
1502  * interface's default setting.  To access such bandwidth, alternate
1503  * interface settings must be made current.
1504  *
1505  * Note that in the Linux USB subsystem, bandwidth associated with
1506  * an endpoint in a given alternate setting is not reserved until an URB
1507  * is submitted that needs that bandwidth.  Some other operating systems
1508  * allocate bandwidth early, when a configuration is chosen.
1509  *
1510  * xHCI reserves bandwidth and configures the alternate setting in
1511  * usb_hcd_alloc_bandwidth(). If it fails the original interface altsetting
1512  * may be disabled. Drivers cannot rely on any particular alternate
1513  * setting being in effect after a failure.
1514  *
1515  * This call is synchronous, and may not be used in an interrupt context.
1516  * Also, drivers must not change altsettings while urbs are scheduled for
1517  * endpoints in that interface; all such urbs must first be completed
1518  * (perhaps forced by unlinking).
1519  *
1520  * Return: Zero on success, or else the status code returned by the
1521  * underlying usb_control_msg() call.
1522  */
usb_set_interface(struct usb_device * dev,int interface,int alternate)1523 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1524 {
1525 	struct usb_interface *iface;
1526 	struct usb_host_interface *alt;
1527 	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1528 	int i, ret, manual = 0;
1529 	unsigned int epaddr;
1530 	unsigned int pipe;
1531 
1532 	if (dev->state == USB_STATE_SUSPENDED)
1533 		return -EHOSTUNREACH;
1534 
1535 	iface = usb_ifnum_to_if(dev, interface);
1536 	if (!iface) {
1537 		dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1538 			interface);
1539 		return -EINVAL;
1540 	}
1541 	if (iface->unregistering)
1542 		return -ENODEV;
1543 
1544 	alt = usb_altnum_to_altsetting(iface, alternate);
1545 	if (!alt) {
1546 		dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
1547 			 alternate);
1548 		return -EINVAL;
1549 	}
1550 	/*
1551 	 * usb3 hosts configure the interface in usb_hcd_alloc_bandwidth,
1552 	 * including freeing dropped endpoint ring buffers.
1553 	 * Make sure the interface endpoints are flushed before that
1554 	 */
1555 	usb_disable_interface(dev, iface, false);
1556 
1557 	/* Make sure we have enough bandwidth for this alternate interface.
1558 	 * Remove the current alt setting and add the new alt setting.
1559 	 */
1560 	mutex_lock(hcd->bandwidth_mutex);
1561 	/* Disable LPM, and re-enable it once the new alt setting is installed,
1562 	 * so that the xHCI driver can recalculate the U1/U2 timeouts.
1563 	 */
1564 	if (usb_disable_lpm(dev)) {
1565 		dev_err(&iface->dev, "%s Failed to disable LPM\n", __func__);
1566 		mutex_unlock(hcd->bandwidth_mutex);
1567 		return -ENOMEM;
1568 	}
1569 	/* Changing alt-setting also frees any allocated streams */
1570 	for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
1571 		iface->cur_altsetting->endpoint[i].streams = 0;
1572 
1573 	ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
1574 	if (ret < 0) {
1575 		dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
1576 				alternate);
1577 		usb_enable_lpm(dev);
1578 		mutex_unlock(hcd->bandwidth_mutex);
1579 		return ret;
1580 	}
1581 
1582 	if (dev->quirks & USB_QUIRK_NO_SET_INTF)
1583 		ret = -EPIPE;
1584 	else
1585 		ret = usb_control_msg_send(dev, 0,
1586 					   USB_REQ_SET_INTERFACE,
1587 					   USB_RECIP_INTERFACE, alternate,
1588 					   interface, NULL, 0, 5000,
1589 					   GFP_NOIO);
1590 
1591 	/* 9.4.10 says devices don't need this and are free to STALL the
1592 	 * request if the interface only has one alternate setting.
1593 	 */
1594 	if (ret == -EPIPE && iface->num_altsetting == 1) {
1595 		dev_dbg(&dev->dev,
1596 			"manual set_interface for iface %d, alt %d\n",
1597 			interface, alternate);
1598 		manual = 1;
1599 	} else if (ret) {
1600 		/* Re-instate the old alt setting */
1601 		usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
1602 		usb_enable_lpm(dev);
1603 		mutex_unlock(hcd->bandwidth_mutex);
1604 		return ret;
1605 	}
1606 	mutex_unlock(hcd->bandwidth_mutex);
1607 
1608 	/* FIXME drivers shouldn't need to replicate/bugfix the logic here
1609 	 * when they implement async or easily-killable versions of this or
1610 	 * other "should-be-internal" functions (like clear_halt).
1611 	 * should hcd+usbcore postprocess control requests?
1612 	 */
1613 
1614 	/* prevent submissions using previous endpoint settings */
1615 	if (iface->cur_altsetting != alt) {
1616 		remove_intf_ep_devs(iface);
1617 		usb_remove_sysfs_intf_files(iface);
1618 	}
1619 	usb_disable_interface(dev, iface, true);
1620 
1621 	iface->cur_altsetting = alt;
1622 
1623 	/* Now that the interface is installed, re-enable LPM. */
1624 	usb_unlocked_enable_lpm(dev);
1625 
1626 	/* If the interface only has one altsetting and the device didn't
1627 	 * accept the request, we attempt to carry out the equivalent action
1628 	 * by manually clearing the HALT feature for each endpoint in the
1629 	 * new altsetting.
1630 	 */
1631 	if (manual) {
1632 		for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1633 			epaddr = alt->endpoint[i].desc.bEndpointAddress;
1634 			pipe = __create_pipe(dev,
1635 					USB_ENDPOINT_NUMBER_MASK & epaddr) |
1636 					(usb_endpoint_out(epaddr) ?
1637 					USB_DIR_OUT : USB_DIR_IN);
1638 
1639 			usb_clear_halt(dev, pipe);
1640 		}
1641 	}
1642 
1643 	/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1644 	 *
1645 	 * Note:
1646 	 * Despite EP0 is always present in all interfaces/AS, the list of
1647 	 * endpoints from the descriptor does not contain EP0. Due to its
1648 	 * omnipresence one might expect EP0 being considered "affected" by
1649 	 * any SetInterface request and hence assume toggles need to be reset.
1650 	 * However, EP0 toggles are re-synced for every individual transfer
1651 	 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1652 	 * (Likewise, EP0 never "halts" on well designed devices.)
1653 	 */
1654 	usb_enable_interface(dev, iface, true);
1655 	if (device_is_registered(&iface->dev)) {
1656 		usb_create_sysfs_intf_files(iface);
1657 		create_intf_ep_devs(iface);
1658 	}
1659 	return 0;
1660 }
1661 EXPORT_SYMBOL_GPL(usb_set_interface);
1662 
1663 /**
1664  * usb_reset_configuration - lightweight device reset
1665  * @dev: the device whose configuration is being reset
1666  *
1667  * This issues a standard SET_CONFIGURATION request to the device using
1668  * the current configuration.  The effect is to reset most USB-related
1669  * state in the device, including interface altsettings (reset to zero),
1670  * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
1671  * endpoints).  Other usbcore state is unchanged, including bindings of
1672  * usb device drivers to interfaces.
1673  *
1674  * Because this affects multiple interfaces, avoid using this with composite
1675  * (multi-interface) devices.  Instead, the driver for each interface may
1676  * use usb_set_interface() on the interfaces it claims.  Be careful though;
1677  * some devices don't support the SET_INTERFACE request, and others won't
1678  * reset all the interface state (notably endpoint state).  Resetting the whole
1679  * configuration would affect other drivers' interfaces.
1680  *
1681  * The caller must own the device lock.
1682  *
1683  * Return: Zero on success, else a negative error code.
1684  *
1685  * If this routine fails the device will probably be in an unusable state
1686  * with endpoints disabled, and interfaces only partially enabled.
1687  */
usb_reset_configuration(struct usb_device * dev)1688 int usb_reset_configuration(struct usb_device *dev)
1689 {
1690 	int			i, retval;
1691 	struct usb_host_config	*config;
1692 	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1693 
1694 	if (dev->state == USB_STATE_SUSPENDED)
1695 		return -EHOSTUNREACH;
1696 
1697 	/* caller must have locked the device and must own
1698 	 * the usb bus readlock (so driver bindings are stable);
1699 	 * calls during probe() are fine
1700 	 */
1701 
1702 	usb_disable_device_endpoints(dev, 1); /* skip ep0*/
1703 
1704 	config = dev->actconfig;
1705 	retval = 0;
1706 	mutex_lock(hcd->bandwidth_mutex);
1707 	/* Disable LPM, and re-enable it once the configuration is reset, so
1708 	 * that the xHCI driver can recalculate the U1/U2 timeouts.
1709 	 */
1710 	if (usb_disable_lpm(dev)) {
1711 		dev_err(&dev->dev, "%s Failed to disable LPM\n", __func__);
1712 		mutex_unlock(hcd->bandwidth_mutex);
1713 		return -ENOMEM;
1714 	}
1715 
1716 	/* xHCI adds all endpoints in usb_hcd_alloc_bandwidth */
1717 	retval = usb_hcd_alloc_bandwidth(dev, config, NULL, NULL);
1718 	if (retval < 0) {
1719 		usb_enable_lpm(dev);
1720 		mutex_unlock(hcd->bandwidth_mutex);
1721 		return retval;
1722 	}
1723 	retval = usb_control_msg_send(dev, 0, USB_REQ_SET_CONFIGURATION, 0,
1724 				      config->desc.bConfigurationValue, 0,
1725 				      NULL, 0, USB_CTRL_SET_TIMEOUT,
1726 				      GFP_NOIO);
1727 	if (retval) {
1728 		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1729 		usb_enable_lpm(dev);
1730 		mutex_unlock(hcd->bandwidth_mutex);
1731 		return retval;
1732 	}
1733 	mutex_unlock(hcd->bandwidth_mutex);
1734 
1735 	/* re-init hc/hcd interface/endpoint state */
1736 	for (i = 0; i < config->desc.bNumInterfaces; i++) {
1737 		struct usb_interface *intf = config->interface[i];
1738 		struct usb_host_interface *alt;
1739 
1740 		alt = usb_altnum_to_altsetting(intf, 0);
1741 
1742 		/* No altsetting 0?  We'll assume the first altsetting.
1743 		 * We could use a GetInterface call, but if a device is
1744 		 * so non-compliant that it doesn't have altsetting 0
1745 		 * then I wouldn't trust its reply anyway.
1746 		 */
1747 		if (!alt)
1748 			alt = &intf->altsetting[0];
1749 
1750 		if (alt != intf->cur_altsetting) {
1751 			remove_intf_ep_devs(intf);
1752 			usb_remove_sysfs_intf_files(intf);
1753 		}
1754 		intf->cur_altsetting = alt;
1755 		usb_enable_interface(dev, intf, true);
1756 		if (device_is_registered(&intf->dev)) {
1757 			usb_create_sysfs_intf_files(intf);
1758 			create_intf_ep_devs(intf);
1759 		}
1760 	}
1761 	/* Now that the interfaces are installed, re-enable LPM. */
1762 	usb_unlocked_enable_lpm(dev);
1763 	return 0;
1764 }
1765 EXPORT_SYMBOL_GPL(usb_reset_configuration);
1766 
usb_release_interface(struct device * dev)1767 static void usb_release_interface(struct device *dev)
1768 {
1769 	struct usb_interface *intf = to_usb_interface(dev);
1770 	struct usb_interface_cache *intfc =
1771 			altsetting_to_usb_interface_cache(intf->altsetting);
1772 
1773 	kref_put(&intfc->ref, usb_release_interface_cache);
1774 	usb_put_dev(interface_to_usbdev(intf));
1775 	of_node_put(dev->of_node);
1776 	kfree(intf);
1777 }
1778 
1779 /*
1780  * usb_deauthorize_interface - deauthorize an USB interface
1781  *
1782  * @intf: USB interface structure
1783  */
usb_deauthorize_interface(struct usb_interface * intf)1784 void usb_deauthorize_interface(struct usb_interface *intf)
1785 {
1786 	struct device *dev = &intf->dev;
1787 
1788 	device_lock(dev->parent);
1789 
1790 	if (intf->authorized) {
1791 		device_lock(dev);
1792 		intf->authorized = 0;
1793 		device_unlock(dev);
1794 
1795 		usb_forced_unbind_intf(intf);
1796 	}
1797 
1798 	device_unlock(dev->parent);
1799 }
1800 
1801 /*
1802  * usb_authorize_interface - authorize an USB interface
1803  *
1804  * @intf: USB interface structure
1805  */
usb_authorize_interface(struct usb_interface * intf)1806 void usb_authorize_interface(struct usb_interface *intf)
1807 {
1808 	struct device *dev = &intf->dev;
1809 
1810 	if (!intf->authorized) {
1811 		device_lock(dev);
1812 		intf->authorized = 1; /* authorize interface */
1813 		device_unlock(dev);
1814 	}
1815 }
1816 
usb_if_uevent(struct device * dev,struct kobj_uevent_env * env)1817 static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1818 {
1819 	struct usb_device *usb_dev;
1820 	struct usb_interface *intf;
1821 	struct usb_host_interface *alt;
1822 
1823 	intf = to_usb_interface(dev);
1824 	usb_dev = interface_to_usbdev(intf);
1825 	alt = intf->cur_altsetting;
1826 
1827 	if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
1828 		   alt->desc.bInterfaceClass,
1829 		   alt->desc.bInterfaceSubClass,
1830 		   alt->desc.bInterfaceProtocol))
1831 		return -ENOMEM;
1832 
1833 	if (add_uevent_var(env,
1834 		   "MODALIAS=usb:"
1835 		   "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
1836 		   le16_to_cpu(usb_dev->descriptor.idVendor),
1837 		   le16_to_cpu(usb_dev->descriptor.idProduct),
1838 		   le16_to_cpu(usb_dev->descriptor.bcdDevice),
1839 		   usb_dev->descriptor.bDeviceClass,
1840 		   usb_dev->descriptor.bDeviceSubClass,
1841 		   usb_dev->descriptor.bDeviceProtocol,
1842 		   alt->desc.bInterfaceClass,
1843 		   alt->desc.bInterfaceSubClass,
1844 		   alt->desc.bInterfaceProtocol,
1845 		   alt->desc.bInterfaceNumber))
1846 		return -ENOMEM;
1847 
1848 	return 0;
1849 }
1850 
1851 struct device_type usb_if_device_type = {
1852 	.name =		"usb_interface",
1853 	.release =	usb_release_interface,
1854 	.uevent =	usb_if_uevent,
1855 };
1856 
find_iad(struct usb_device * dev,struct usb_host_config * config,u8 inum)1857 static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1858 						struct usb_host_config *config,
1859 						u8 inum)
1860 {
1861 	struct usb_interface_assoc_descriptor *retval = NULL;
1862 	struct usb_interface_assoc_descriptor *intf_assoc;
1863 	int first_intf;
1864 	int last_intf;
1865 	int i;
1866 
1867 	for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
1868 		intf_assoc = config->intf_assoc[i];
1869 		if (intf_assoc->bInterfaceCount == 0)
1870 			continue;
1871 
1872 		first_intf = intf_assoc->bFirstInterface;
1873 		last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
1874 		if (inum >= first_intf && inum <= last_intf) {
1875 			if (!retval)
1876 				retval = intf_assoc;
1877 			else
1878 				dev_err(&dev->dev, "Interface #%d referenced"
1879 					" by multiple IADs\n", inum);
1880 		}
1881 	}
1882 
1883 	return retval;
1884 }
1885 
1886 
1887 /*
1888  * Internal function to queue a device reset
1889  * See usb_queue_reset_device() for more details
1890  */
__usb_queue_reset_device(struct work_struct * ws)1891 static void __usb_queue_reset_device(struct work_struct *ws)
1892 {
1893 	int rc;
1894 	struct usb_interface *iface =
1895 		container_of(ws, struct usb_interface, reset_ws);
1896 	struct usb_device *udev = interface_to_usbdev(iface);
1897 
1898 	rc = usb_lock_device_for_reset(udev, iface);
1899 	if (rc >= 0) {
1900 		usb_reset_device(udev);
1901 		usb_unlock_device(udev);
1902 	}
1903 	usb_put_intf(iface);	/* Undo _get_ in usb_queue_reset_device() */
1904 }
1905 
1906 
1907 /*
1908  * usb_set_configuration - Makes a particular device setting be current
1909  * @dev: the device whose configuration is being updated
1910  * @configuration: the configuration being chosen.
1911  * Context: !in_interrupt(), caller owns the device lock
1912  *
1913  * This is used to enable non-default device modes.  Not all devices
1914  * use this kind of configurability; many devices only have one
1915  * configuration.
1916  *
1917  * @configuration is the value of the configuration to be installed.
1918  * According to the USB spec (e.g. section 9.1.1.5), configuration values
1919  * must be non-zero; a value of zero indicates that the device in
1920  * unconfigured.  However some devices erroneously use 0 as one of their
1921  * configuration values.  To help manage such devices, this routine will
1922  * accept @configuration = -1 as indicating the device should be put in
1923  * an unconfigured state.
1924  *
1925  * USB device configurations may affect Linux interoperability,
1926  * power consumption and the functionality available.  For example,
1927  * the default configuration is limited to using 100mA of bus power,
1928  * so that when certain device functionality requires more power,
1929  * and the device is bus powered, that functionality should be in some
1930  * non-default device configuration.  Other device modes may also be
1931  * reflected as configuration options, such as whether two ISDN
1932  * channels are available independently; and choosing between open
1933  * standard device protocols (like CDC) or proprietary ones.
1934  *
1935  * Note that a non-authorized device (dev->authorized == 0) will only
1936  * be put in unconfigured mode.
1937  *
1938  * Note that USB has an additional level of device configurability,
1939  * associated with interfaces.  That configurability is accessed using
1940  * usb_set_interface().
1941  *
1942  * This call is synchronous. The calling context must be able to sleep,
1943  * must own the device lock, and must not hold the driver model's USB
1944  * bus mutex; usb interface driver probe() methods cannot use this routine.
1945  *
1946  * Returns zero on success, or else the status code returned by the
1947  * underlying call that failed.  On successful completion, each interface
1948  * in the original device configuration has been destroyed, and each one
1949  * in the new configuration has been probed by all relevant usb device
1950  * drivers currently known to the kernel.
1951  */
usb_set_configuration(struct usb_device * dev,int configuration)1952 int usb_set_configuration(struct usb_device *dev, int configuration)
1953 {
1954 	int i, ret;
1955 	struct usb_host_config *cp = NULL;
1956 	struct usb_interface **new_interfaces = NULL;
1957 	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1958 	int n, nintf;
1959 
1960 	if (dev->authorized == 0 || configuration == -1)
1961 		configuration = 0;
1962 	else {
1963 		for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1964 			if (dev->config[i].desc.bConfigurationValue ==
1965 					configuration) {
1966 				cp = &dev->config[i];
1967 				break;
1968 			}
1969 		}
1970 	}
1971 	if ((!cp && configuration != 0))
1972 		return -EINVAL;
1973 
1974 	/* The USB spec says configuration 0 means unconfigured.
1975 	 * But if a device includes a configuration numbered 0,
1976 	 * we will accept it as a correctly configured state.
1977 	 * Use -1 if you really want to unconfigure the device.
1978 	 */
1979 	if (cp && configuration == 0)
1980 		dev_warn(&dev->dev, "config 0 descriptor??\n");
1981 
1982 	/* Allocate memory for new interfaces before doing anything else,
1983 	 * so that if we run out then nothing will have changed. */
1984 	n = nintf = 0;
1985 	if (cp) {
1986 		nintf = cp->desc.bNumInterfaces;
1987 		new_interfaces = kmalloc_array(nintf, sizeof(*new_interfaces),
1988 					       GFP_NOIO);
1989 		if (!new_interfaces)
1990 			return -ENOMEM;
1991 
1992 		for (; n < nintf; ++n) {
1993 			new_interfaces[n] = kzalloc(
1994 					sizeof(struct usb_interface),
1995 					GFP_NOIO);
1996 			if (!new_interfaces[n]) {
1997 				ret = -ENOMEM;
1998 free_interfaces:
1999 				while (--n >= 0)
2000 					kfree(new_interfaces[n]);
2001 				kfree(new_interfaces);
2002 				return ret;
2003 			}
2004 		}
2005 
2006 		i = dev->bus_mA - usb_get_max_power(dev, cp);
2007 		if (i < 0)
2008 			dev_warn(&dev->dev, "new config #%d exceeds power "
2009 					"limit by %dmA\n",
2010 					configuration, -i);
2011 	}
2012 
2013 	/* Wake up the device so we can send it the Set-Config request */
2014 	ret = usb_autoresume_device(dev);
2015 	if (ret)
2016 		goto free_interfaces;
2017 
2018 	/* if it's already configured, clear out old state first.
2019 	 * getting rid of old interfaces means unbinding their drivers.
2020 	 */
2021 	if (dev->state != USB_STATE_ADDRESS)
2022 		usb_disable_device(dev, 1);	/* Skip ep0 */
2023 
2024 	/* Get rid of pending async Set-Config requests for this device */
2025 	cancel_async_set_config(dev);
2026 
2027 	/* Make sure we have bandwidth (and available HCD resources) for this
2028 	 * configuration.  Remove endpoints from the schedule if we're dropping
2029 	 * this configuration to set configuration 0.  After this point, the
2030 	 * host controller will not allow submissions to dropped endpoints.  If
2031 	 * this call fails, the device state is unchanged.
2032 	 */
2033 	mutex_lock(hcd->bandwidth_mutex);
2034 	/* Disable LPM, and re-enable it once the new configuration is
2035 	 * installed, so that the xHCI driver can recalculate the U1/U2
2036 	 * timeouts.
2037 	 */
2038 	if (dev->actconfig && usb_disable_lpm(dev)) {
2039 		dev_err(&dev->dev, "%s Failed to disable LPM\n", __func__);
2040 		mutex_unlock(hcd->bandwidth_mutex);
2041 		ret = -ENOMEM;
2042 		goto free_interfaces;
2043 	}
2044 	ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
2045 	if (ret < 0) {
2046 		if (dev->actconfig)
2047 			usb_enable_lpm(dev);
2048 		mutex_unlock(hcd->bandwidth_mutex);
2049 		usb_autosuspend_device(dev);
2050 		goto free_interfaces;
2051 	}
2052 
2053 	/*
2054 	 * Initialize the new interface structures and the
2055 	 * hc/hcd/usbcore interface/endpoint state.
2056 	 */
2057 	for (i = 0; i < nintf; ++i) {
2058 		struct usb_interface_cache *intfc;
2059 		struct usb_interface *intf;
2060 		struct usb_host_interface *alt;
2061 		u8 ifnum;
2062 
2063 		cp->interface[i] = intf = new_interfaces[i];
2064 		intfc = cp->intf_cache[i];
2065 		intf->altsetting = intfc->altsetting;
2066 		intf->num_altsetting = intfc->num_altsetting;
2067 		intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
2068 		kref_get(&intfc->ref);
2069 
2070 		alt = usb_altnum_to_altsetting(intf, 0);
2071 
2072 		/* No altsetting 0?  We'll assume the first altsetting.
2073 		 * We could use a GetInterface call, but if a device is
2074 		 * so non-compliant that it doesn't have altsetting 0
2075 		 * then I wouldn't trust its reply anyway.
2076 		 */
2077 		if (!alt)
2078 			alt = &intf->altsetting[0];
2079 
2080 		ifnum = alt->desc.bInterfaceNumber;
2081 		intf->intf_assoc = find_iad(dev, cp, ifnum);
2082 		intf->cur_altsetting = alt;
2083 		usb_enable_interface(dev, intf, true);
2084 		intf->dev.parent = &dev->dev;
2085 		if (usb_of_has_combined_node(dev)) {
2086 			device_set_of_node_from_dev(&intf->dev, &dev->dev);
2087 		} else {
2088 			intf->dev.of_node = usb_of_get_interface_node(dev,
2089 					configuration, ifnum);
2090 		}
2091 		ACPI_COMPANION_SET(&intf->dev, ACPI_COMPANION(&dev->dev));
2092 		intf->dev.driver = NULL;
2093 		intf->dev.bus = &usb_bus_type;
2094 		intf->dev.type = &usb_if_device_type;
2095 		intf->dev.groups = usb_interface_groups;
2096 		INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
2097 		intf->minor = -1;
2098 		device_initialize(&intf->dev);
2099 		pm_runtime_no_callbacks(&intf->dev);
2100 		dev_set_name(&intf->dev, "%d-%s:%d.%d", dev->bus->busnum,
2101 				dev->devpath, configuration, ifnum);
2102 		usb_get_dev(dev);
2103 	}
2104 	kfree(new_interfaces);
2105 
2106 	ret = usb_control_msg_send(dev, 0, USB_REQ_SET_CONFIGURATION, 0,
2107 				   configuration, 0, NULL, 0,
2108 				   USB_CTRL_SET_TIMEOUT, GFP_NOIO);
2109 	if (ret && cp) {
2110 		/*
2111 		 * All the old state is gone, so what else can we do?
2112 		 * The device is probably useless now anyway.
2113 		 */
2114 		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
2115 		for (i = 0; i < nintf; ++i) {
2116 			usb_disable_interface(dev, cp->interface[i], true);
2117 			put_device(&cp->interface[i]->dev);
2118 			cp->interface[i] = NULL;
2119 		}
2120 		cp = NULL;
2121 	}
2122 
2123 	dev->actconfig = cp;
2124 	mutex_unlock(hcd->bandwidth_mutex);
2125 
2126 	if (!cp) {
2127 		usb_set_device_state(dev, USB_STATE_ADDRESS);
2128 
2129 		/* Leave LPM disabled while the device is unconfigured. */
2130 		usb_autosuspend_device(dev);
2131 		return ret;
2132 	}
2133 	usb_set_device_state(dev, USB_STATE_CONFIGURED);
2134 
2135 	if (cp->string == NULL &&
2136 			!(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
2137 		cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
2138 
2139 	/* Now that the interfaces are installed, re-enable LPM. */
2140 	usb_unlocked_enable_lpm(dev);
2141 	/* Enable LTM if it was turned off by usb_disable_device. */
2142 	usb_enable_ltm(dev);
2143 
2144 	/* Now that all the interfaces are set up, register them
2145 	 * to trigger binding of drivers to interfaces.  probe()
2146 	 * routines may install different altsettings and may
2147 	 * claim() any interfaces not yet bound.  Many class drivers
2148 	 * need that: CDC, audio, video, etc.
2149 	 */
2150 	for (i = 0; i < nintf; ++i) {
2151 		struct usb_interface *intf = cp->interface[i];
2152 
2153 		if (intf->dev.of_node &&
2154 		    !of_device_is_available(intf->dev.of_node)) {
2155 			dev_info(&dev->dev, "skipping disabled interface %d\n",
2156 				 intf->cur_altsetting->desc.bInterfaceNumber);
2157 			continue;
2158 		}
2159 
2160 		dev_dbg(&dev->dev,
2161 			"adding %s (config #%d, interface %d)\n",
2162 			dev_name(&intf->dev), configuration,
2163 			intf->cur_altsetting->desc.bInterfaceNumber);
2164 		device_enable_async_suspend(&intf->dev);
2165 		ret = device_add(&intf->dev);
2166 		if (ret != 0) {
2167 			dev_err(&dev->dev, "device_add(%s) --> %d\n",
2168 				dev_name(&intf->dev), ret);
2169 			continue;
2170 		}
2171 		create_intf_ep_devs(intf);
2172 	}
2173 
2174 	usb_autosuspend_device(dev);
2175 	return 0;
2176 }
2177 EXPORT_SYMBOL_GPL(usb_set_configuration);
2178 
2179 static LIST_HEAD(set_config_list);
2180 static DEFINE_SPINLOCK(set_config_lock);
2181 
2182 struct set_config_request {
2183 	struct usb_device	*udev;
2184 	int			config;
2185 	struct work_struct	work;
2186 	struct list_head	node;
2187 };
2188 
2189 /* Worker routine for usb_driver_set_configuration() */
driver_set_config_work(struct work_struct * work)2190 static void driver_set_config_work(struct work_struct *work)
2191 {
2192 	struct set_config_request *req =
2193 		container_of(work, struct set_config_request, work);
2194 	struct usb_device *udev = req->udev;
2195 
2196 	usb_lock_device(udev);
2197 	spin_lock(&set_config_lock);
2198 	list_del(&req->node);
2199 	spin_unlock(&set_config_lock);
2200 
2201 	if (req->config >= -1)		/* Is req still valid? */
2202 		usb_set_configuration(udev, req->config);
2203 	usb_unlock_device(udev);
2204 	usb_put_dev(udev);
2205 	kfree(req);
2206 }
2207 
2208 /* Cancel pending Set-Config requests for a device whose configuration
2209  * was just changed
2210  */
cancel_async_set_config(struct usb_device * udev)2211 static void cancel_async_set_config(struct usb_device *udev)
2212 {
2213 	struct set_config_request *req;
2214 
2215 	spin_lock(&set_config_lock);
2216 	list_for_each_entry(req, &set_config_list, node) {
2217 		if (req->udev == udev)
2218 			req->config = -999;	/* Mark as cancelled */
2219 	}
2220 	spin_unlock(&set_config_lock);
2221 }
2222 
2223 /**
2224  * usb_driver_set_configuration - Provide a way for drivers to change device configurations
2225  * @udev: the device whose configuration is being updated
2226  * @config: the configuration being chosen.
2227  * Context: In process context, must be able to sleep
2228  *
2229  * Device interface drivers are not allowed to change device configurations.
2230  * This is because changing configurations will destroy the interface the
2231  * driver is bound to and create new ones; it would be like a floppy-disk
2232  * driver telling the computer to replace the floppy-disk drive with a
2233  * tape drive!
2234  *
2235  * Still, in certain specialized circumstances the need may arise.  This
2236  * routine gets around the normal restrictions by using a work thread to
2237  * submit the change-config request.
2238  *
2239  * Return: 0 if the request was successfully queued, error code otherwise.
2240  * The caller has no way to know whether the queued request will eventually
2241  * succeed.
2242  */
usb_driver_set_configuration(struct usb_device * udev,int config)2243 int usb_driver_set_configuration(struct usb_device *udev, int config)
2244 {
2245 	struct set_config_request *req;
2246 
2247 	req = kmalloc(sizeof(*req), GFP_KERNEL);
2248 	if (!req)
2249 		return -ENOMEM;
2250 	req->udev = udev;
2251 	req->config = config;
2252 	INIT_WORK(&req->work, driver_set_config_work);
2253 
2254 	spin_lock(&set_config_lock);
2255 	list_add(&req->node, &set_config_list);
2256 	spin_unlock(&set_config_lock);
2257 
2258 	usb_get_dev(udev);
2259 	schedule_work(&req->work);
2260 	return 0;
2261 }
2262 EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
2263 
2264 /**
2265  * cdc_parse_cdc_header - parse the extra headers present in CDC devices
2266  * @hdr: the place to put the results of the parsing
2267  * @intf: the interface for which parsing is requested
2268  * @buffer: pointer to the extra headers to be parsed
2269  * @buflen: length of the extra headers
2270  *
2271  * This evaluates the extra headers present in CDC devices which
2272  * bind the interfaces for data and control and provide details
2273  * about the capabilities of the device.
2274  *
2275  * Return: number of descriptors parsed or -EINVAL
2276  * if the header is contradictory beyond salvage
2277  */
2278 
cdc_parse_cdc_header(struct usb_cdc_parsed_header * hdr,struct usb_interface * intf,u8 * buffer,int buflen)2279 int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr,
2280 				struct usb_interface *intf,
2281 				u8 *buffer,
2282 				int buflen)
2283 {
2284 	/* duplicates are ignored */
2285 	struct usb_cdc_union_desc *union_header = NULL;
2286 
2287 	/* duplicates are not tolerated */
2288 	struct usb_cdc_header_desc *header = NULL;
2289 	struct usb_cdc_ether_desc *ether = NULL;
2290 	struct usb_cdc_mdlm_detail_desc *detail = NULL;
2291 	struct usb_cdc_mdlm_desc *desc = NULL;
2292 
2293 	unsigned int elength;
2294 	int cnt = 0;
2295 
2296 	memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header));
2297 	hdr->phonet_magic_present = false;
2298 	while (buflen > 0) {
2299 		elength = buffer[0];
2300 		if (!elength) {
2301 			dev_err(&intf->dev, "skipping garbage byte\n");
2302 			elength = 1;
2303 			goto next_desc;
2304 		}
2305 		if ((buflen < elength) || (elength < 3)) {
2306 			dev_err(&intf->dev, "invalid descriptor buffer length\n");
2307 			break;
2308 		}
2309 		if (buffer[1] != USB_DT_CS_INTERFACE) {
2310 			dev_err(&intf->dev, "skipping garbage\n");
2311 			goto next_desc;
2312 		}
2313 
2314 		switch (buffer[2]) {
2315 		case USB_CDC_UNION_TYPE: /* we've found it */
2316 			if (elength < sizeof(struct usb_cdc_union_desc))
2317 				goto next_desc;
2318 			if (union_header) {
2319 				dev_err(&intf->dev, "More than one union descriptor, skipping ...\n");
2320 				goto next_desc;
2321 			}
2322 			union_header = (struct usb_cdc_union_desc *)buffer;
2323 			break;
2324 		case USB_CDC_COUNTRY_TYPE:
2325 			if (elength < sizeof(struct usb_cdc_country_functional_desc))
2326 				goto next_desc;
2327 			hdr->usb_cdc_country_functional_desc =
2328 				(struct usb_cdc_country_functional_desc *)buffer;
2329 			break;
2330 		case USB_CDC_HEADER_TYPE:
2331 			if (elength != sizeof(struct usb_cdc_header_desc))
2332 				goto next_desc;
2333 			if (header)
2334 				return -EINVAL;
2335 			header = (struct usb_cdc_header_desc *)buffer;
2336 			break;
2337 		case USB_CDC_ACM_TYPE:
2338 			if (elength < sizeof(struct usb_cdc_acm_descriptor))
2339 				goto next_desc;
2340 			hdr->usb_cdc_acm_descriptor =
2341 				(struct usb_cdc_acm_descriptor *)buffer;
2342 			break;
2343 		case USB_CDC_ETHERNET_TYPE:
2344 			if (elength != sizeof(struct usb_cdc_ether_desc))
2345 				goto next_desc;
2346 			if (ether)
2347 				return -EINVAL;
2348 			ether = (struct usb_cdc_ether_desc *)buffer;
2349 			break;
2350 		case USB_CDC_CALL_MANAGEMENT_TYPE:
2351 			if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor))
2352 				goto next_desc;
2353 			hdr->usb_cdc_call_mgmt_descriptor =
2354 				(struct usb_cdc_call_mgmt_descriptor *)buffer;
2355 			break;
2356 		case USB_CDC_DMM_TYPE:
2357 			if (elength < sizeof(struct usb_cdc_dmm_desc))
2358 				goto next_desc;
2359 			hdr->usb_cdc_dmm_desc =
2360 				(struct usb_cdc_dmm_desc *)buffer;
2361 			break;
2362 		case USB_CDC_MDLM_TYPE:
2363 			if (elength < sizeof(struct usb_cdc_mdlm_desc))
2364 				goto next_desc;
2365 			if (desc)
2366 				return -EINVAL;
2367 			desc = (struct usb_cdc_mdlm_desc *)buffer;
2368 			break;
2369 		case USB_CDC_MDLM_DETAIL_TYPE:
2370 			if (elength < sizeof(struct usb_cdc_mdlm_detail_desc))
2371 				goto next_desc;
2372 			if (detail)
2373 				return -EINVAL;
2374 			detail = (struct usb_cdc_mdlm_detail_desc *)buffer;
2375 			break;
2376 		case USB_CDC_NCM_TYPE:
2377 			if (elength < sizeof(struct usb_cdc_ncm_desc))
2378 				goto next_desc;
2379 			hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer;
2380 			break;
2381 		case USB_CDC_MBIM_TYPE:
2382 			if (elength < sizeof(struct usb_cdc_mbim_desc))
2383 				goto next_desc;
2384 
2385 			hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer;
2386 			break;
2387 		case USB_CDC_MBIM_EXTENDED_TYPE:
2388 			if (elength < sizeof(struct usb_cdc_mbim_extended_desc))
2389 				break;
2390 			hdr->usb_cdc_mbim_extended_desc =
2391 				(struct usb_cdc_mbim_extended_desc *)buffer;
2392 			break;
2393 		case CDC_PHONET_MAGIC_NUMBER:
2394 			hdr->phonet_magic_present = true;
2395 			break;
2396 		default:
2397 			/*
2398 			 * there are LOTS more CDC descriptors that
2399 			 * could legitimately be found here.
2400 			 */
2401 			dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n",
2402 					buffer[2], elength);
2403 			goto next_desc;
2404 		}
2405 		cnt++;
2406 next_desc:
2407 		buflen -= elength;
2408 		buffer += elength;
2409 	}
2410 	hdr->usb_cdc_union_desc = union_header;
2411 	hdr->usb_cdc_header_desc = header;
2412 	hdr->usb_cdc_mdlm_detail_desc = detail;
2413 	hdr->usb_cdc_mdlm_desc = desc;
2414 	hdr->usb_cdc_ether_desc = ether;
2415 	return cnt;
2416 }
2417 
2418 EXPORT_SYMBOL(cdc_parse_cdc_header);
2419