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