xref: /openbmc/linux/drivers/usb/core/message.c (revision c21b37f6)
1 /*
2  * message.c - synchronous message handling
3  */
4 
5 #include <linux/pci.h>	/* for scatterlist macros */
6 #include <linux/usb.h>
7 #include <linux/module.h>
8 #include <linux/slab.h>
9 #include <linux/init.h>
10 #include <linux/mm.h>
11 #include <linux/timer.h>
12 #include <linux/ctype.h>
13 #include <linux/device.h>
14 #include <linux/usb/quirks.h>
15 #include <asm/byteorder.h>
16 #include <asm/scatterlist.h>
17 
18 #include "hcd.h"	/* for usbcore internals */
19 #include "usb.h"
20 
21 struct api_context {
22 	struct completion	done;
23 	int			status;
24 };
25 
26 static void usb_api_blocking_completion(struct urb *urb)
27 {
28 	struct api_context *ctx = urb->context;
29 
30 	ctx->status = urb->status;
31 	complete(&ctx->done);
32 }
33 
34 
35 /*
36  * Starts urb and waits for completion or timeout. Note that this call
37  * is NOT interruptible. Many device driver i/o requests should be
38  * interruptible and therefore these drivers should implement their
39  * own interruptible routines.
40  */
41 static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
42 {
43 	struct api_context ctx;
44 	unsigned long expire;
45 	int retval;
46 
47 	init_completion(&ctx.done);
48 	urb->context = &ctx;
49 	urb->actual_length = 0;
50 	retval = usb_submit_urb(urb, GFP_NOIO);
51 	if (unlikely(retval))
52 		goto out;
53 
54 	expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
55 	if (!wait_for_completion_timeout(&ctx.done, expire)) {
56 		usb_kill_urb(urb);
57 		retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
58 
59 		dev_dbg(&urb->dev->dev,
60 			"%s timed out on ep%d%s len=%d/%d\n",
61 			current->comm,
62 			usb_pipeendpoint(urb->pipe),
63 			usb_pipein(urb->pipe) ? "in" : "out",
64 			urb->actual_length,
65 			urb->transfer_buffer_length);
66 	} else
67 		retval = ctx.status;
68 out:
69 	if (actual_length)
70 		*actual_length = urb->actual_length;
71 
72 	usb_free_urb(urb);
73 	return retval;
74 }
75 
76 /*-------------------------------------------------------------------*/
77 // returns status (negative) or length (positive)
78 static int usb_internal_control_msg(struct usb_device *usb_dev,
79 				    unsigned int pipe,
80 				    struct usb_ctrlrequest *cmd,
81 				    void *data, int len, int timeout)
82 {
83 	struct urb *urb;
84 	int retv;
85 	int length;
86 
87 	urb = usb_alloc_urb(0, GFP_NOIO);
88 	if (!urb)
89 		return -ENOMEM;
90 
91 	usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
92 			     len, usb_api_blocking_completion, NULL);
93 
94 	retv = usb_start_wait_urb(urb, timeout, &length);
95 	if (retv < 0)
96 		return retv;
97 	else
98 		return length;
99 }
100 
101 /**
102  *	usb_control_msg - Builds a control urb, sends it off and waits for completion
103  *	@dev: pointer to the usb device to send the message to
104  *	@pipe: endpoint "pipe" to send the message to
105  *	@request: USB message request value
106  *	@requesttype: USB message request type value
107  *	@value: USB message value
108  *	@index: USB message index value
109  *	@data: pointer to the data to send
110  *	@size: length in bytes of the data to send
111  *	@timeout: time in msecs to wait for the message to complete before
112  *		timing out (if 0 the wait is forever)
113  *	Context: !in_interrupt ()
114  *
115  *	This function sends a simple control message to a specified endpoint
116  *	and waits for the message to complete, or timeout.
117  *
118  *	If successful, it returns the number of bytes transferred, otherwise a negative error number.
119  *
120  *	Don't use this function from within an interrupt context, like a
121  *	bottom half handler.  If you need an asynchronous message, or need to send
122  *	a message from within interrupt context, use usb_submit_urb()
123  *      If a thread in your driver uses this call, make sure your disconnect()
124  *      method can wait for it to complete.  Since you don't have a handle on
125  *      the URB used, you can't cancel the request.
126  */
127 int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request, __u8 requesttype,
128 			 __u16 value, __u16 index, void *data, __u16 size, int timeout)
129 {
130 	struct usb_ctrlrequest *dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
131 	int ret;
132 
133 	if (!dr)
134 		return -ENOMEM;
135 
136 	dr->bRequestType= requesttype;
137 	dr->bRequest = request;
138 	dr->wValue = cpu_to_le16p(&value);
139 	dr->wIndex = cpu_to_le16p(&index);
140 	dr->wLength = cpu_to_le16p(&size);
141 
142 	//dbg("usb_control_msg");
143 
144 	ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
145 
146 	kfree(dr);
147 
148 	return ret;
149 }
150 
151 
152 /**
153  * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
154  * @usb_dev: pointer to the usb device to send the message to
155  * @pipe: endpoint "pipe" to send the message to
156  * @data: pointer to the data to send
157  * @len: length in bytes of the data to send
158  * @actual_length: pointer to a location to put the actual length transferred in bytes
159  * @timeout: time in msecs to wait for the message to complete before
160  *	timing out (if 0 the wait is forever)
161  * Context: !in_interrupt ()
162  *
163  * This function sends a simple interrupt message to a specified endpoint and
164  * waits for the message to complete, or timeout.
165  *
166  * If successful, it returns 0, otherwise a negative error number.  The number
167  * of actual bytes transferred will be stored in the actual_length paramater.
168  *
169  * Don't use this function from within an interrupt context, like a bottom half
170  * handler.  If you need an asynchronous message, or need to send a message
171  * from within interrupt context, use usb_submit_urb() If a thread in your
172  * driver uses this call, make sure your disconnect() method can wait for it to
173  * complete.  Since you don't have a handle on the URB used, you can't cancel
174  * the request.
175  */
176 int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
177 		      void *data, int len, int *actual_length, int timeout)
178 {
179 	return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
180 }
181 EXPORT_SYMBOL_GPL(usb_interrupt_msg);
182 
183 /**
184  *	usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
185  *	@usb_dev: pointer to the usb device to send the message to
186  *	@pipe: endpoint "pipe" to send the message to
187  *	@data: pointer to the data to send
188  *	@len: length in bytes of the data to send
189  *	@actual_length: pointer to a location to put the actual length transferred in bytes
190  *	@timeout: time in msecs to wait for the message to complete before
191  *		timing out (if 0 the wait is forever)
192  *	Context: !in_interrupt ()
193  *
194  *	This function sends a simple bulk message to a specified endpoint
195  *	and waits for the message to complete, or timeout.
196  *
197  *	If successful, it returns 0, otherwise a negative error number.
198  *	The number of actual bytes transferred will be stored in the
199  *	actual_length paramater.
200  *
201  *	Don't use this function from within an interrupt context, like a
202  *	bottom half handler.  If you need an asynchronous message, or need to
203  *	send a message from within interrupt context, use usb_submit_urb()
204  *      If a thread in your driver uses this call, make sure your disconnect()
205  *      method can wait for it to complete.  Since you don't have a handle on
206  *      the URB used, you can't cancel the request.
207  *
208  *	Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT
209  *	ioctl, users are forced to abuse this routine by using it to submit
210  *	URBs for interrupt endpoints.  We will take the liberty of creating
211  *	an interrupt URB (with the default interval) if the target is an
212  *	interrupt endpoint.
213  */
214 int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
215 			void *data, int len, int *actual_length, int timeout)
216 {
217 	struct urb *urb;
218 	struct usb_host_endpoint *ep;
219 
220 	ep = (usb_pipein(pipe) ? usb_dev->ep_in : usb_dev->ep_out)
221 			[usb_pipeendpoint(pipe)];
222 	if (!ep || len < 0)
223 		return -EINVAL;
224 
225 	urb = usb_alloc_urb(0, GFP_KERNEL);
226 	if (!urb)
227 		return -ENOMEM;
228 
229 	if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
230 			USB_ENDPOINT_XFER_INT) {
231 		pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
232 		usb_fill_int_urb(urb, usb_dev, pipe, data, len,
233 				usb_api_blocking_completion, NULL,
234 				ep->desc.bInterval);
235 	} else
236 		usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
237 				usb_api_blocking_completion, NULL);
238 
239 	return usb_start_wait_urb(urb, timeout, actual_length);
240 }
241 
242 /*-------------------------------------------------------------------*/
243 
244 static void sg_clean (struct usb_sg_request *io)
245 {
246 	if (io->urbs) {
247 		while (io->entries--)
248 			usb_free_urb (io->urbs [io->entries]);
249 		kfree (io->urbs);
250 		io->urbs = NULL;
251 	}
252 	if (io->dev->dev.dma_mask != NULL)
253 		usb_buffer_unmap_sg (io->dev, io->pipe, io->sg, io->nents);
254 	io->dev = NULL;
255 }
256 
257 static void sg_complete (struct urb *urb)
258 {
259 	struct usb_sg_request	*io = urb->context;
260 	int status = urb->status;
261 
262 	spin_lock (&io->lock);
263 
264 	/* In 2.5 we require hcds' endpoint queues not to progress after fault
265 	 * reports, until the completion callback (this!) returns.  That lets
266 	 * device driver code (like this routine) unlink queued urbs first,
267 	 * if it needs to, since the HC won't work on them at all.  So it's
268 	 * not possible for page N+1 to overwrite page N, and so on.
269 	 *
270 	 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
271 	 * complete before the HCD can get requests away from hardware,
272 	 * though never during cleanup after a hard fault.
273 	 */
274 	if (io->status
275 			&& (io->status != -ECONNRESET
276 				|| status != -ECONNRESET)
277 			&& urb->actual_length) {
278 		dev_err (io->dev->bus->controller,
279 			"dev %s ep%d%s scatterlist error %d/%d\n",
280 			io->dev->devpath,
281 			usb_pipeendpoint (urb->pipe),
282 			usb_pipein (urb->pipe) ? "in" : "out",
283 			status, io->status);
284 		// BUG ();
285 	}
286 
287 	if (io->status == 0 && status && status != -ECONNRESET) {
288 		int i, found, retval;
289 
290 		io->status = status;
291 
292 		/* the previous urbs, and this one, completed already.
293 		 * unlink pending urbs so they won't rx/tx bad data.
294 		 * careful: unlink can sometimes be synchronous...
295 		 */
296 		spin_unlock (&io->lock);
297 		for (i = 0, found = 0; i < io->entries; i++) {
298 			if (!io->urbs [i] || !io->urbs [i]->dev)
299 				continue;
300 			if (found) {
301 				retval = usb_unlink_urb (io->urbs [i]);
302 				if (retval != -EINPROGRESS &&
303 				    retval != -ENODEV &&
304 				    retval != -EBUSY)
305 					dev_err (&io->dev->dev,
306 						"%s, unlink --> %d\n",
307 						__FUNCTION__, retval);
308 			} else if (urb == io->urbs [i])
309 				found = 1;
310 		}
311 		spin_lock (&io->lock);
312 	}
313 	urb->dev = NULL;
314 
315 	/* on the last completion, signal usb_sg_wait() */
316 	io->bytes += urb->actual_length;
317 	io->count--;
318 	if (!io->count)
319 		complete (&io->complete);
320 
321 	spin_unlock (&io->lock);
322 }
323 
324 
325 /**
326  * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
327  * @io: request block being initialized.  until usb_sg_wait() returns,
328  *	treat this as a pointer to an opaque block of memory,
329  * @dev: the usb device that will send or receive the data
330  * @pipe: endpoint "pipe" used to transfer the data
331  * @period: polling rate for interrupt endpoints, in frames or
332  * 	(for high speed endpoints) microframes; ignored for bulk
333  * @sg: scatterlist entries
334  * @nents: how many entries in the scatterlist
335  * @length: how many bytes to send from the scatterlist, or zero to
336  * 	send every byte identified in the list.
337  * @mem_flags: SLAB_* flags affecting memory allocations in this call
338  *
339  * Returns zero for success, else a negative errno value.  This initializes a
340  * scatter/gather request, allocating resources such as I/O mappings and urb
341  * memory (except maybe memory used by USB controller drivers).
342  *
343  * The request must be issued using usb_sg_wait(), which waits for the I/O to
344  * complete (or to be canceled) and then cleans up all resources allocated by
345  * usb_sg_init().
346  *
347  * The request may be canceled with usb_sg_cancel(), either before or after
348  * usb_sg_wait() is called.
349  */
350 int usb_sg_init (
351 	struct usb_sg_request	*io,
352 	struct usb_device	*dev,
353 	unsigned		pipe,
354 	unsigned		period,
355 	struct scatterlist	*sg,
356 	int			nents,
357 	size_t			length,
358 	gfp_t			mem_flags
359 )
360 {
361 	int			i;
362 	int			urb_flags;
363 	int			dma;
364 
365 	if (!io || !dev || !sg
366 			|| usb_pipecontrol (pipe)
367 			|| usb_pipeisoc (pipe)
368 			|| nents <= 0)
369 		return -EINVAL;
370 
371 	spin_lock_init (&io->lock);
372 	io->dev = dev;
373 	io->pipe = pipe;
374 	io->sg = sg;
375 	io->nents = nents;
376 
377 	/* not all host controllers use DMA (like the mainstream pci ones);
378 	 * they can use PIO (sl811) or be software over another transport.
379 	 */
380 	dma = (dev->dev.dma_mask != NULL);
381 	if (dma)
382 		io->entries = usb_buffer_map_sg (dev, pipe, sg, nents);
383 	else
384 		io->entries = nents;
385 
386 	/* initialize all the urbs we'll use */
387 	if (io->entries <= 0)
388 		return io->entries;
389 
390 	io->count = io->entries;
391 	io->urbs = kmalloc (io->entries * sizeof *io->urbs, mem_flags);
392 	if (!io->urbs)
393 		goto nomem;
394 
395 	urb_flags = URB_NO_TRANSFER_DMA_MAP | URB_NO_INTERRUPT;
396 	if (usb_pipein (pipe))
397 		urb_flags |= URB_SHORT_NOT_OK;
398 
399 	for (i = 0; i < io->entries; i++) {
400 		unsigned		len;
401 
402 		io->urbs [i] = usb_alloc_urb (0, mem_flags);
403 		if (!io->urbs [i]) {
404 			io->entries = i;
405 			goto nomem;
406 		}
407 
408 		io->urbs [i]->dev = NULL;
409 		io->urbs [i]->pipe = pipe;
410 		io->urbs [i]->interval = period;
411 		io->urbs [i]->transfer_flags = urb_flags;
412 
413 		io->urbs [i]->complete = sg_complete;
414 		io->urbs [i]->context = io;
415 
416 		/*
417 		 * Some systems need to revert to PIO when DMA is temporarily
418 		 * unavailable.  For their sakes, both transfer_buffer and
419 		 * transfer_dma are set when possible.  However this can only
420 		 * work on systems without:
421 		 *
422 		 *  - HIGHMEM, since DMA buffers located in high memory are
423 		 *    not directly addressable by the CPU for PIO;
424 		 *
425 		 *  - IOMMU, since dma_map_sg() is allowed to use an IOMMU to
426 		 *    make virtually discontiguous buffers be "dma-contiguous"
427 		 *    so that PIO and DMA need diferent numbers of URBs.
428 		 *
429 		 * So when HIGHMEM or IOMMU are in use, transfer_buffer is NULL
430 		 * to prevent stale pointers and to help spot bugs.
431 		 */
432 		if (dma) {
433 			io->urbs [i]->transfer_dma = sg_dma_address (sg + i);
434 			len = sg_dma_len (sg + i);
435 #if defined(CONFIG_HIGHMEM) || defined(CONFIG_IOMMU)
436 			io->urbs[i]->transfer_buffer = NULL;
437 #else
438 			io->urbs[i]->transfer_buffer =
439 				page_address(sg[i].page) + sg[i].offset;
440 #endif
441 		} else {
442 			/* hc may use _only_ transfer_buffer */
443 			io->urbs [i]->transfer_buffer =
444 				page_address (sg [i].page) + sg [i].offset;
445 			len = sg [i].length;
446 		}
447 
448 		if (length) {
449 			len = min_t (unsigned, len, length);
450 			length -= len;
451 			if (length == 0)
452 				io->entries = i + 1;
453 		}
454 		io->urbs [i]->transfer_buffer_length = len;
455 	}
456 	io->urbs [--i]->transfer_flags &= ~URB_NO_INTERRUPT;
457 
458 	/* transaction state */
459 	io->status = 0;
460 	io->bytes = 0;
461 	init_completion (&io->complete);
462 	return 0;
463 
464 nomem:
465 	sg_clean (io);
466 	return -ENOMEM;
467 }
468 
469 
470 /**
471  * usb_sg_wait - synchronously execute scatter/gather request
472  * @io: request block handle, as initialized with usb_sg_init().
473  * 	some fields become accessible when this call returns.
474  * Context: !in_interrupt ()
475  *
476  * This function blocks until the specified I/O operation completes.  It
477  * leverages the grouping of the related I/O requests to get good transfer
478  * rates, by queueing the requests.  At higher speeds, such queuing can
479  * significantly improve USB throughput.
480  *
481  * There are three kinds of completion for this function.
482  * (1) success, where io->status is zero.  The number of io->bytes
483  *     transferred is as requested.
484  * (2) error, where io->status is a negative errno value.  The number
485  *     of io->bytes transferred before the error is usually less
486  *     than requested, and can be nonzero.
487  * (3) cancellation, a type of error with status -ECONNRESET that
488  *     is initiated by usb_sg_cancel().
489  *
490  * When this function returns, all memory allocated through usb_sg_init() or
491  * this call will have been freed.  The request block parameter may still be
492  * passed to usb_sg_cancel(), or it may be freed.  It could also be
493  * reinitialized and then reused.
494  *
495  * Data Transfer Rates:
496  *
497  * Bulk transfers are valid for full or high speed endpoints.
498  * The best full speed data rate is 19 packets of 64 bytes each
499  * per frame, or 1216 bytes per millisecond.
500  * The best high speed data rate is 13 packets of 512 bytes each
501  * per microframe, or 52 KBytes per millisecond.
502  *
503  * The reason to use interrupt transfers through this API would most likely
504  * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
505  * could be transferred.  That capability is less useful for low or full
506  * speed interrupt endpoints, which allow at most one packet per millisecond,
507  * of at most 8 or 64 bytes (respectively).
508  */
509 void usb_sg_wait (struct usb_sg_request *io)
510 {
511 	int		i, entries = io->entries;
512 
513 	/* queue the urbs.  */
514 	spin_lock_irq (&io->lock);
515 	i = 0;
516 	while (i < entries && !io->status) {
517 		int	retval;
518 
519 		io->urbs [i]->dev = io->dev;
520 		retval = usb_submit_urb (io->urbs [i], GFP_ATOMIC);
521 
522 		/* after we submit, let completions or cancelations fire;
523 		 * we handshake using io->status.
524 		 */
525 		spin_unlock_irq (&io->lock);
526 		switch (retval) {
527 			/* maybe we retrying will recover */
528 		case -ENXIO:	// hc didn't queue this one
529 		case -EAGAIN:
530 		case -ENOMEM:
531 			io->urbs[i]->dev = NULL;
532 			retval = 0;
533 			yield ();
534 			break;
535 
536 			/* no error? continue immediately.
537 			 *
538 			 * NOTE: to work better with UHCI (4K I/O buffer may
539 			 * need 3K of TDs) it may be good to limit how many
540 			 * URBs are queued at once; N milliseconds?
541 			 */
542 		case 0:
543 			++i;
544 			cpu_relax ();
545 			break;
546 
547 			/* fail any uncompleted urbs */
548 		default:
549 			io->urbs [i]->dev = NULL;
550 			io->urbs [i]->status = retval;
551 			dev_dbg (&io->dev->dev, "%s, submit --> %d\n",
552 				__FUNCTION__, retval);
553 			usb_sg_cancel (io);
554 		}
555 		spin_lock_irq (&io->lock);
556 		if (retval && (io->status == 0 || io->status == -ECONNRESET))
557 			io->status = retval;
558 	}
559 	io->count -= entries - i;
560 	if (io->count == 0)
561 		complete (&io->complete);
562 	spin_unlock_irq (&io->lock);
563 
564 	/* OK, yes, this could be packaged as non-blocking.
565 	 * So could the submit loop above ... but it's easier to
566 	 * solve neither problem than to solve both!
567 	 */
568 	wait_for_completion (&io->complete);
569 
570 	sg_clean (io);
571 }
572 
573 /**
574  * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
575  * @io: request block, initialized with usb_sg_init()
576  *
577  * This stops a request after it has been started by usb_sg_wait().
578  * It can also prevents one initialized by usb_sg_init() from starting,
579  * so that call just frees resources allocated to the request.
580  */
581 void usb_sg_cancel (struct usb_sg_request *io)
582 {
583 	unsigned long	flags;
584 
585 	spin_lock_irqsave (&io->lock, flags);
586 
587 	/* shut everything down, if it didn't already */
588 	if (!io->status) {
589 		int	i;
590 
591 		io->status = -ECONNRESET;
592 		spin_unlock (&io->lock);
593 		for (i = 0; i < io->entries; i++) {
594 			int	retval;
595 
596 			if (!io->urbs [i]->dev)
597 				continue;
598 			retval = usb_unlink_urb (io->urbs [i]);
599 			if (retval != -EINPROGRESS && retval != -EBUSY)
600 				dev_warn (&io->dev->dev, "%s, unlink --> %d\n",
601 					__FUNCTION__, retval);
602 		}
603 		spin_lock (&io->lock);
604 	}
605 	spin_unlock_irqrestore (&io->lock, flags);
606 }
607 
608 /*-------------------------------------------------------------------*/
609 
610 /**
611  * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
612  * @dev: the device whose descriptor is being retrieved
613  * @type: the descriptor type (USB_DT_*)
614  * @index: the number of the descriptor
615  * @buf: where to put the descriptor
616  * @size: how big is "buf"?
617  * Context: !in_interrupt ()
618  *
619  * Gets a USB descriptor.  Convenience functions exist to simplify
620  * getting some types of descriptors.  Use
621  * usb_get_string() or usb_string() for USB_DT_STRING.
622  * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
623  * are part of the device structure.
624  * In addition to a number of USB-standard descriptors, some
625  * devices also use class-specific or vendor-specific descriptors.
626  *
627  * This call is synchronous, and may not be used in an interrupt context.
628  *
629  * Returns the number of bytes received on success, or else the status code
630  * returned by the underlying usb_control_msg() call.
631  */
632 int usb_get_descriptor(struct usb_device *dev, unsigned char type, unsigned char index, void *buf, int size)
633 {
634 	int i;
635 	int result;
636 
637 	memset(buf,0,size);	// Make sure we parse really received data
638 
639 	for (i = 0; i < 3; ++i) {
640 		/* retry on length 0 or stall; some devices are flakey */
641 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
642 				USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
643 				(type << 8) + index, 0, buf, size,
644 				USB_CTRL_GET_TIMEOUT);
645 		if (result == 0 || result == -EPIPE)
646 			continue;
647 		if (result > 1 && ((u8 *)buf)[1] != type) {
648 			result = -EPROTO;
649 			continue;
650 		}
651 		break;
652 	}
653 	return result;
654 }
655 
656 /**
657  * usb_get_string - gets a string descriptor
658  * @dev: the device whose string descriptor is being retrieved
659  * @langid: code for language chosen (from string descriptor zero)
660  * @index: the number of the descriptor
661  * @buf: where to put the string
662  * @size: how big is "buf"?
663  * Context: !in_interrupt ()
664  *
665  * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
666  * in little-endian byte order).
667  * The usb_string() function will often be a convenient way to turn
668  * these strings into kernel-printable form.
669  *
670  * Strings may be referenced in device, configuration, interface, or other
671  * descriptors, and could also be used in vendor-specific ways.
672  *
673  * This call is synchronous, and may not be used in an interrupt context.
674  *
675  * Returns the number of bytes received on success, or else the status code
676  * returned by the underlying usb_control_msg() call.
677  */
678 static int usb_get_string(struct usb_device *dev, unsigned short langid,
679 			  unsigned char index, void *buf, int size)
680 {
681 	int i;
682 	int result;
683 
684 	for (i = 0; i < 3; ++i) {
685 		/* retry on length 0 or stall; some devices are flakey */
686 		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
687 			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
688 			(USB_DT_STRING << 8) + index, langid, buf, size,
689 			USB_CTRL_GET_TIMEOUT);
690 		if (!(result == 0 || result == -EPIPE))
691 			break;
692 	}
693 	return result;
694 }
695 
696 static void usb_try_string_workarounds(unsigned char *buf, int *length)
697 {
698 	int newlength, oldlength = *length;
699 
700 	for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
701 		if (!isprint(buf[newlength]) || buf[newlength + 1])
702 			break;
703 
704 	if (newlength > 2) {
705 		buf[0] = newlength;
706 		*length = newlength;
707 	}
708 }
709 
710 static int usb_string_sub(struct usb_device *dev, unsigned int langid,
711 		unsigned int index, unsigned char *buf)
712 {
713 	int rc;
714 
715 	/* Try to read the string descriptor by asking for the maximum
716 	 * possible number of bytes */
717 	if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
718 		rc = -EIO;
719 	else
720 		rc = usb_get_string(dev, langid, index, buf, 255);
721 
722 	/* If that failed try to read the descriptor length, then
723 	 * ask for just that many bytes */
724 	if (rc < 2) {
725 		rc = usb_get_string(dev, langid, index, buf, 2);
726 		if (rc == 2)
727 			rc = usb_get_string(dev, langid, index, buf, buf[0]);
728 	}
729 
730 	if (rc >= 2) {
731 		if (!buf[0] && !buf[1])
732 			usb_try_string_workarounds(buf, &rc);
733 
734 		/* There might be extra junk at the end of the descriptor */
735 		if (buf[0] < rc)
736 			rc = buf[0];
737 
738 		rc = rc - (rc & 1); /* force a multiple of two */
739 	}
740 
741 	if (rc < 2)
742 		rc = (rc < 0 ? rc : -EINVAL);
743 
744 	return rc;
745 }
746 
747 /**
748  * usb_string - returns ISO 8859-1 version of a string descriptor
749  * @dev: the device whose string descriptor is being retrieved
750  * @index: the number of the descriptor
751  * @buf: where to put the string
752  * @size: how big is "buf"?
753  * Context: !in_interrupt ()
754  *
755  * This converts the UTF-16LE encoded strings returned by devices, from
756  * usb_get_string_descriptor(), to null-terminated ISO-8859-1 encoded ones
757  * that are more usable in most kernel contexts.  Note that all characters
758  * in the chosen descriptor that can't be encoded using ISO-8859-1
759  * are converted to the question mark ("?") character, and this function
760  * chooses strings in the first language supported by the device.
761  *
762  * The ASCII (or, redundantly, "US-ASCII") character set is the seven-bit
763  * subset of ISO 8859-1. ISO-8859-1 is the eight-bit subset of Unicode,
764  * and is appropriate for use many uses of English and several other
765  * Western European languages.  (But it doesn't include the "Euro" symbol.)
766  *
767  * This call is synchronous, and may not be used in an interrupt context.
768  *
769  * Returns length of the string (>= 0) or usb_control_msg status (< 0).
770  */
771 int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
772 {
773 	unsigned char *tbuf;
774 	int err;
775 	unsigned int u, idx;
776 
777 	if (dev->state == USB_STATE_SUSPENDED)
778 		return -EHOSTUNREACH;
779 	if (size <= 0 || !buf || !index)
780 		return -EINVAL;
781 	buf[0] = 0;
782 	tbuf = kmalloc(256, GFP_KERNEL);
783 	if (!tbuf)
784 		return -ENOMEM;
785 
786 	/* get langid for strings if it's not yet known */
787 	if (!dev->have_langid) {
788 		err = usb_string_sub(dev, 0, 0, tbuf);
789 		if (err < 0) {
790 			dev_err (&dev->dev,
791 				"string descriptor 0 read error: %d\n",
792 				err);
793 			goto errout;
794 		} else if (err < 4) {
795 			dev_err (&dev->dev, "string descriptor 0 too short\n");
796 			err = -EINVAL;
797 			goto errout;
798 		} else {
799 			dev->have_langid = 1;
800 			dev->string_langid = tbuf[2] | (tbuf[3]<< 8);
801 				/* always use the first langid listed */
802 			dev_dbg (&dev->dev, "default language 0x%04x\n",
803 				dev->string_langid);
804 		}
805 	}
806 
807 	err = usb_string_sub(dev, dev->string_langid, index, tbuf);
808 	if (err < 0)
809 		goto errout;
810 
811 	size--;		/* leave room for trailing NULL char in output buffer */
812 	for (idx = 0, u = 2; u < err; u += 2) {
813 		if (idx >= size)
814 			break;
815 		if (tbuf[u+1])			/* high byte */
816 			buf[idx++] = '?';  /* non ISO-8859-1 character */
817 		else
818 			buf[idx++] = tbuf[u];
819 	}
820 	buf[idx] = 0;
821 	err = idx;
822 
823 	if (tbuf[1] != USB_DT_STRING)
824 		dev_dbg(&dev->dev, "wrong descriptor type %02x for string %d (\"%s\")\n", tbuf[1], index, buf);
825 
826  errout:
827 	kfree(tbuf);
828 	return err;
829 }
830 
831 /**
832  * usb_cache_string - read a string descriptor and cache it for later use
833  * @udev: the device whose string descriptor is being read
834  * @index: the descriptor index
835  *
836  * Returns a pointer to a kmalloc'ed buffer containing the descriptor string,
837  * or NULL if the index is 0 or the string could not be read.
838  */
839 char *usb_cache_string(struct usb_device *udev, int index)
840 {
841 	char *buf;
842 	char *smallbuf = NULL;
843 	int len;
844 
845 	if (index > 0 && (buf = kmalloc(256, GFP_KERNEL)) != NULL) {
846 		if ((len = usb_string(udev, index, buf, 256)) > 0) {
847 			if ((smallbuf = kmalloc(++len, GFP_KERNEL)) == NULL)
848 				return buf;
849 			memcpy(smallbuf, buf, len);
850 		}
851 		kfree(buf);
852 	}
853 	return smallbuf;
854 }
855 
856 /*
857  * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
858  * @dev: the device whose device descriptor is being updated
859  * @size: how much of the descriptor to read
860  * Context: !in_interrupt ()
861  *
862  * Updates the copy of the device descriptor stored in the device structure,
863  * which dedicates space for this purpose.
864  *
865  * Not exported, only for use by the core.  If drivers really want to read
866  * the device descriptor directly, they can call usb_get_descriptor() with
867  * type = USB_DT_DEVICE and index = 0.
868  *
869  * This call is synchronous, and may not be used in an interrupt context.
870  *
871  * Returns the number of bytes received on success, or else the status code
872  * returned by the underlying usb_control_msg() call.
873  */
874 int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
875 {
876 	struct usb_device_descriptor *desc;
877 	int ret;
878 
879 	if (size > sizeof(*desc))
880 		return -EINVAL;
881 	desc = kmalloc(sizeof(*desc), GFP_NOIO);
882 	if (!desc)
883 		return -ENOMEM;
884 
885 	ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
886 	if (ret >= 0)
887 		memcpy(&dev->descriptor, desc, size);
888 	kfree(desc);
889 	return ret;
890 }
891 
892 /**
893  * usb_get_status - issues a GET_STATUS call
894  * @dev: the device whose status is being checked
895  * @type: USB_RECIP_*; for device, interface, or endpoint
896  * @target: zero (for device), else interface or endpoint number
897  * @data: pointer to two bytes of bitmap data
898  * Context: !in_interrupt ()
899  *
900  * Returns device, interface, or endpoint status.  Normally only of
901  * interest to see if the device is self powered, or has enabled the
902  * remote wakeup facility; or whether a bulk or interrupt endpoint
903  * is halted ("stalled").
904  *
905  * Bits in these status bitmaps are set using the SET_FEATURE request,
906  * and cleared using the CLEAR_FEATURE request.  The usb_clear_halt()
907  * function should be used to clear halt ("stall") status.
908  *
909  * This call is synchronous, and may not be used in an interrupt context.
910  *
911  * Returns the number of bytes received on success, or else the status code
912  * returned by the underlying usb_control_msg() call.
913  */
914 int usb_get_status(struct usb_device *dev, int type, int target, void *data)
915 {
916 	int ret;
917 	u16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
918 
919 	if (!status)
920 		return -ENOMEM;
921 
922 	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
923 		USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
924 		sizeof(*status), USB_CTRL_GET_TIMEOUT);
925 
926 	*(u16 *)data = *status;
927 	kfree(status);
928 	return ret;
929 }
930 
931 /**
932  * usb_clear_halt - tells device to clear endpoint halt/stall condition
933  * @dev: device whose endpoint is halted
934  * @pipe: endpoint "pipe" being cleared
935  * Context: !in_interrupt ()
936  *
937  * This is used to clear halt conditions for bulk and interrupt endpoints,
938  * as reported by URB completion status.  Endpoints that are halted are
939  * sometimes referred to as being "stalled".  Such endpoints are unable
940  * to transmit or receive data until the halt status is cleared.  Any URBs
941  * queued for such an endpoint should normally be unlinked by the driver
942  * before clearing the halt condition, as described in sections 5.7.5
943  * and 5.8.5 of the USB 2.0 spec.
944  *
945  * Note that control and isochronous endpoints don't halt, although control
946  * endpoints report "protocol stall" (for unsupported requests) using the
947  * same status code used to report a true stall.
948  *
949  * This call is synchronous, and may not be used in an interrupt context.
950  *
951  * Returns zero on success, or else the status code returned by the
952  * underlying usb_control_msg() call.
953  */
954 int usb_clear_halt(struct usb_device *dev, int pipe)
955 {
956 	int result;
957 	int endp = usb_pipeendpoint(pipe);
958 
959 	if (usb_pipein (pipe))
960 		endp |= USB_DIR_IN;
961 
962 	/* we don't care if it wasn't halted first. in fact some devices
963 	 * (like some ibmcam model 1 units) seem to expect hosts to make
964 	 * this request for iso endpoints, which can't halt!
965 	 */
966 	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
967 		USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
968 		USB_ENDPOINT_HALT, endp, NULL, 0,
969 		USB_CTRL_SET_TIMEOUT);
970 
971 	/* don't un-halt or force to DATA0 except on success */
972 	if (result < 0)
973 		return result;
974 
975 	/* NOTE:  seems like Microsoft and Apple don't bother verifying
976 	 * the clear "took", so some devices could lock up if you check...
977 	 * such as the Hagiwara FlashGate DUAL.  So we won't bother.
978 	 *
979 	 * NOTE:  make sure the logic here doesn't diverge much from
980 	 * the copy in usb-storage, for as long as we need two copies.
981 	 */
982 
983 	/* toggle was reset by the clear */
984 	usb_settoggle(dev, usb_pipeendpoint(pipe), usb_pipeout(pipe), 0);
985 
986 	return 0;
987 }
988 
989 /**
990  * usb_disable_endpoint -- Disable an endpoint by address
991  * @dev: the device whose endpoint is being disabled
992  * @epaddr: the endpoint's address.  Endpoint number for output,
993  *	endpoint number + USB_DIR_IN for input
994  *
995  * Deallocates hcd/hardware state for this endpoint ... and nukes all
996  * pending urbs.
997  *
998  * If the HCD hasn't registered a disable() function, this sets the
999  * endpoint's maxpacket size to 0 to prevent further submissions.
1000  */
1001 void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr)
1002 {
1003 	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1004 	struct usb_host_endpoint *ep;
1005 
1006 	if (!dev)
1007 		return;
1008 
1009 	if (usb_endpoint_out(epaddr)) {
1010 		ep = dev->ep_out[epnum];
1011 		dev->ep_out[epnum] = NULL;
1012 	} else {
1013 		ep = dev->ep_in[epnum];
1014 		dev->ep_in[epnum] = NULL;
1015 	}
1016 	if (ep && dev->bus)
1017 		usb_hcd_endpoint_disable(dev, ep);
1018 }
1019 
1020 /**
1021  * usb_disable_interface -- Disable all endpoints for an interface
1022  * @dev: the device whose interface is being disabled
1023  * @intf: pointer to the interface descriptor
1024  *
1025  * Disables all the endpoints for the interface's current altsetting.
1026  */
1027 void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf)
1028 {
1029 	struct usb_host_interface *alt = intf->cur_altsetting;
1030 	int i;
1031 
1032 	for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1033 		usb_disable_endpoint(dev,
1034 				alt->endpoint[i].desc.bEndpointAddress);
1035 	}
1036 }
1037 
1038 /*
1039  * usb_disable_device - Disable all the endpoints for a USB device
1040  * @dev: the device whose endpoints are being disabled
1041  * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1042  *
1043  * Disables all the device's endpoints, potentially including endpoint 0.
1044  * Deallocates hcd/hardware state for the endpoints (nuking all or most
1045  * pending urbs) and usbcore state for the interfaces, so that usbcore
1046  * must usb_set_configuration() before any interfaces could be used.
1047  */
1048 void usb_disable_device(struct usb_device *dev, int skip_ep0)
1049 {
1050 	int i;
1051 
1052 	dev_dbg(&dev->dev, "%s nuking %s URBs\n", __FUNCTION__,
1053 			skip_ep0 ? "non-ep0" : "all");
1054 	for (i = skip_ep0; i < 16; ++i) {
1055 		usb_disable_endpoint(dev, i);
1056 		usb_disable_endpoint(dev, i + USB_DIR_IN);
1057 	}
1058 	dev->toggle[0] = dev->toggle[1] = 0;
1059 
1060 	/* getting rid of interfaces will disconnect
1061 	 * any drivers bound to them (a key side effect)
1062 	 */
1063 	if (dev->actconfig) {
1064 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1065 			struct usb_interface	*interface;
1066 
1067 			/* remove this interface if it has been registered */
1068 			interface = dev->actconfig->interface[i];
1069 			if (!device_is_registered(&interface->dev))
1070 				continue;
1071 			dev_dbg (&dev->dev, "unregistering interface %s\n",
1072 				interface->dev.bus_id);
1073 			usb_remove_sysfs_intf_files(interface);
1074 			device_del (&interface->dev);
1075 		}
1076 
1077 		/* Now that the interfaces are unbound, nobody should
1078 		 * try to access them.
1079 		 */
1080 		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1081 			put_device (&dev->actconfig->interface[i]->dev);
1082 			dev->actconfig->interface[i] = NULL;
1083 		}
1084 		dev->actconfig = NULL;
1085 		if (dev->state == USB_STATE_CONFIGURED)
1086 			usb_set_device_state(dev, USB_STATE_ADDRESS);
1087 	}
1088 }
1089 
1090 
1091 /*
1092  * usb_enable_endpoint - Enable an endpoint for USB communications
1093  * @dev: the device whose interface is being enabled
1094  * @ep: the endpoint
1095  *
1096  * Resets the endpoint toggle, and sets dev->ep_{in,out} pointers.
1097  * For control endpoints, both the input and output sides are handled.
1098  */
1099 static void
1100 usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep)
1101 {
1102 	unsigned int epaddr = ep->desc.bEndpointAddress;
1103 	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1104 	int is_control;
1105 
1106 	is_control = ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1107 			== USB_ENDPOINT_XFER_CONTROL);
1108 	if (usb_endpoint_out(epaddr) || is_control) {
1109 		usb_settoggle(dev, epnum, 1, 0);
1110 		dev->ep_out[epnum] = ep;
1111 	}
1112 	if (!usb_endpoint_out(epaddr) || is_control) {
1113 		usb_settoggle(dev, epnum, 0, 0);
1114 		dev->ep_in[epnum] = ep;
1115 	}
1116 }
1117 
1118 /*
1119  * usb_enable_interface - Enable all the endpoints for an interface
1120  * @dev: the device whose interface is being enabled
1121  * @intf: pointer to the interface descriptor
1122  *
1123  * Enables all the endpoints for the interface's current altsetting.
1124  */
1125 static void usb_enable_interface(struct usb_device *dev,
1126 				 struct usb_interface *intf)
1127 {
1128 	struct usb_host_interface *alt = intf->cur_altsetting;
1129 	int i;
1130 
1131 	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1132 		usb_enable_endpoint(dev, &alt->endpoint[i]);
1133 }
1134 
1135 /**
1136  * usb_set_interface - Makes a particular alternate setting be current
1137  * @dev: the device whose interface is being updated
1138  * @interface: the interface being updated
1139  * @alternate: the setting being chosen.
1140  * Context: !in_interrupt ()
1141  *
1142  * This is used to enable data transfers on interfaces that may not
1143  * be enabled by default.  Not all devices support such configurability.
1144  * Only the driver bound to an interface may change its setting.
1145  *
1146  * Within any given configuration, each interface may have several
1147  * alternative settings.  These are often used to control levels of
1148  * bandwidth consumption.  For example, the default setting for a high
1149  * speed interrupt endpoint may not send more than 64 bytes per microframe,
1150  * while interrupt transfers of up to 3KBytes per microframe are legal.
1151  * Also, isochronous endpoints may never be part of an
1152  * interface's default setting.  To access such bandwidth, alternate
1153  * interface settings must be made current.
1154  *
1155  * Note that in the Linux USB subsystem, bandwidth associated with
1156  * an endpoint in a given alternate setting is not reserved until an URB
1157  * is submitted that needs that bandwidth.  Some other operating systems
1158  * allocate bandwidth early, when a configuration is chosen.
1159  *
1160  * This call is synchronous, and may not be used in an interrupt context.
1161  * Also, drivers must not change altsettings while urbs are scheduled for
1162  * endpoints in that interface; all such urbs must first be completed
1163  * (perhaps forced by unlinking).
1164  *
1165  * Returns zero on success, or else the status code returned by the
1166  * underlying usb_control_msg() call.
1167  */
1168 int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1169 {
1170 	struct usb_interface *iface;
1171 	struct usb_host_interface *alt;
1172 	int ret;
1173 	int manual = 0;
1174 
1175 	if (dev->state == USB_STATE_SUSPENDED)
1176 		return -EHOSTUNREACH;
1177 
1178 	iface = usb_ifnum_to_if(dev, interface);
1179 	if (!iface) {
1180 		dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1181 			interface);
1182 		return -EINVAL;
1183 	}
1184 
1185 	alt = usb_altnum_to_altsetting(iface, alternate);
1186 	if (!alt) {
1187 		warn("selecting invalid altsetting %d", alternate);
1188 		return -EINVAL;
1189 	}
1190 
1191 	ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1192 				   USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
1193 				   alternate, interface, NULL, 0, 5000);
1194 
1195 	/* 9.4.10 says devices don't need this and are free to STALL the
1196 	 * request if the interface only has one alternate setting.
1197 	 */
1198 	if (ret == -EPIPE && iface->num_altsetting == 1) {
1199 		dev_dbg(&dev->dev,
1200 			"manual set_interface for iface %d, alt %d\n",
1201 			interface, alternate);
1202 		manual = 1;
1203 	} else if (ret < 0)
1204 		return ret;
1205 
1206 	/* FIXME drivers shouldn't need to replicate/bugfix the logic here
1207 	 * when they implement async or easily-killable versions of this or
1208 	 * other "should-be-internal" functions (like clear_halt).
1209 	 * should hcd+usbcore postprocess control requests?
1210 	 */
1211 
1212 	/* prevent submissions using previous endpoint settings */
1213 	if (device_is_registered(&iface->dev))
1214 		usb_remove_sysfs_intf_files(iface);
1215 	usb_disable_interface(dev, iface);
1216 
1217 	iface->cur_altsetting = alt;
1218 
1219 	/* If the interface only has one altsetting and the device didn't
1220 	 * accept the request, we attempt to carry out the equivalent action
1221 	 * by manually clearing the HALT feature for each endpoint in the
1222 	 * new altsetting.
1223 	 */
1224 	if (manual) {
1225 		int i;
1226 
1227 		for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1228 			unsigned int epaddr =
1229 				alt->endpoint[i].desc.bEndpointAddress;
1230 			unsigned int pipe =
1231 	__create_pipe(dev, USB_ENDPOINT_NUMBER_MASK & epaddr)
1232 	| (usb_endpoint_out(epaddr) ? USB_DIR_OUT : USB_DIR_IN);
1233 
1234 			usb_clear_halt(dev, pipe);
1235 		}
1236 	}
1237 
1238 	/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1239 	 *
1240 	 * Note:
1241 	 * Despite EP0 is always present in all interfaces/AS, the list of
1242 	 * endpoints from the descriptor does not contain EP0. Due to its
1243 	 * omnipresence one might expect EP0 being considered "affected" by
1244 	 * any SetInterface request and hence assume toggles need to be reset.
1245 	 * However, EP0 toggles are re-synced for every individual transfer
1246 	 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1247 	 * (Likewise, EP0 never "halts" on well designed devices.)
1248 	 */
1249 	usb_enable_interface(dev, iface);
1250 	if (device_is_registered(&iface->dev))
1251 		usb_create_sysfs_intf_files(iface);
1252 
1253 	return 0;
1254 }
1255 
1256 /**
1257  * usb_reset_configuration - lightweight device reset
1258  * @dev: the device whose configuration is being reset
1259  *
1260  * This issues a standard SET_CONFIGURATION request to the device using
1261  * the current configuration.  The effect is to reset most USB-related
1262  * state in the device, including interface altsettings (reset to zero),
1263  * endpoint halts (cleared), and data toggle (only for bulk and interrupt
1264  * endpoints).  Other usbcore state is unchanged, including bindings of
1265  * usb device drivers to interfaces.
1266  *
1267  * Because this affects multiple interfaces, avoid using this with composite
1268  * (multi-interface) devices.  Instead, the driver for each interface may
1269  * use usb_set_interface() on the interfaces it claims.  Be careful though;
1270  * some devices don't support the SET_INTERFACE request, and others won't
1271  * reset all the interface state (notably data toggles).  Resetting the whole
1272  * configuration would affect other drivers' interfaces.
1273  *
1274  * The caller must own the device lock.
1275  *
1276  * Returns zero on success, else a negative error code.
1277  */
1278 int usb_reset_configuration(struct usb_device *dev)
1279 {
1280 	int			i, retval;
1281 	struct usb_host_config	*config;
1282 
1283 	if (dev->state == USB_STATE_SUSPENDED)
1284 		return -EHOSTUNREACH;
1285 
1286 	/* caller must have locked the device and must own
1287 	 * the usb bus readlock (so driver bindings are stable);
1288 	 * calls during probe() are fine
1289 	 */
1290 
1291 	for (i = 1; i < 16; ++i) {
1292 		usb_disable_endpoint(dev, i);
1293 		usb_disable_endpoint(dev, i + USB_DIR_IN);
1294 	}
1295 
1296 	config = dev->actconfig;
1297 	retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1298 			USB_REQ_SET_CONFIGURATION, 0,
1299 			config->desc.bConfigurationValue, 0,
1300 			NULL, 0, USB_CTRL_SET_TIMEOUT);
1301 	if (retval < 0)
1302 		return retval;
1303 
1304 	dev->toggle[0] = dev->toggle[1] = 0;
1305 
1306 	/* re-init hc/hcd interface/endpoint state */
1307 	for (i = 0; i < config->desc.bNumInterfaces; i++) {
1308 		struct usb_interface *intf = config->interface[i];
1309 		struct usb_host_interface *alt;
1310 
1311 		if (device_is_registered(&intf->dev))
1312 			usb_remove_sysfs_intf_files(intf);
1313 		alt = usb_altnum_to_altsetting(intf, 0);
1314 
1315 		/* No altsetting 0?  We'll assume the first altsetting.
1316 		 * We could use a GetInterface call, but if a device is
1317 		 * so non-compliant that it doesn't have altsetting 0
1318 		 * then I wouldn't trust its reply anyway.
1319 		 */
1320 		if (!alt)
1321 			alt = &intf->altsetting[0];
1322 
1323 		intf->cur_altsetting = alt;
1324 		usb_enable_interface(dev, intf);
1325 		if (device_is_registered(&intf->dev))
1326 			usb_create_sysfs_intf_files(intf);
1327 	}
1328 	return 0;
1329 }
1330 
1331 void usb_release_interface(struct device *dev)
1332 {
1333 	struct usb_interface *intf = to_usb_interface(dev);
1334 	struct usb_interface_cache *intfc =
1335 			altsetting_to_usb_interface_cache(intf->altsetting);
1336 
1337 	kref_put(&intfc->ref, usb_release_interface_cache);
1338 	kfree(intf);
1339 }
1340 
1341 #ifdef	CONFIG_HOTPLUG
1342 static int usb_if_uevent(struct device *dev, char **envp, int num_envp,
1343 		 char *buffer, int buffer_size)
1344 {
1345 	struct usb_device *usb_dev;
1346 	struct usb_interface *intf;
1347 	struct usb_host_interface *alt;
1348 	int i = 0;
1349 	int length = 0;
1350 
1351 	if (!dev)
1352 		return -ENODEV;
1353 
1354 	/* driver is often null here; dev_dbg() would oops */
1355 	pr_debug ("usb %s: uevent\n", dev->bus_id);
1356 
1357 	intf = to_usb_interface(dev);
1358 	usb_dev = interface_to_usbdev(intf);
1359 	alt = intf->cur_altsetting;
1360 
1361 	if (add_uevent_var(envp, num_envp, &i,
1362 		   buffer, buffer_size, &length,
1363 		   "INTERFACE=%d/%d/%d",
1364 		   alt->desc.bInterfaceClass,
1365 		   alt->desc.bInterfaceSubClass,
1366 		   alt->desc.bInterfaceProtocol))
1367 		return -ENOMEM;
1368 
1369 	if (add_uevent_var(envp, num_envp, &i,
1370 		   buffer, buffer_size, &length,
1371 		   "MODALIAS=usb:v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02X",
1372 		   le16_to_cpu(usb_dev->descriptor.idVendor),
1373 		   le16_to_cpu(usb_dev->descriptor.idProduct),
1374 		   le16_to_cpu(usb_dev->descriptor.bcdDevice),
1375 		   usb_dev->descriptor.bDeviceClass,
1376 		   usb_dev->descriptor.bDeviceSubClass,
1377 		   usb_dev->descriptor.bDeviceProtocol,
1378 		   alt->desc.bInterfaceClass,
1379 		   alt->desc.bInterfaceSubClass,
1380 		   alt->desc.bInterfaceProtocol))
1381 		return -ENOMEM;
1382 
1383 	envp[i] = NULL;
1384 	return 0;
1385 }
1386 
1387 #else
1388 
1389 static int usb_if_uevent(struct device *dev, char **envp,
1390 			 int num_envp, char *buffer, int buffer_size)
1391 {
1392 	return -ENODEV;
1393 }
1394 #endif	/* CONFIG_HOTPLUG */
1395 
1396 struct device_type usb_if_device_type = {
1397 	.name =		"usb_interface",
1398 	.release =	usb_release_interface,
1399 	.uevent =	usb_if_uevent,
1400 };
1401 
1402 static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1403 						       struct usb_host_config *config,
1404 						       u8 inum)
1405 {
1406 	struct usb_interface_assoc_descriptor *retval = NULL;
1407 	struct usb_interface_assoc_descriptor *intf_assoc;
1408 	int first_intf;
1409 	int last_intf;
1410 	int i;
1411 
1412 	for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
1413 		intf_assoc = config->intf_assoc[i];
1414 		if (intf_assoc->bInterfaceCount == 0)
1415 			continue;
1416 
1417 		first_intf = intf_assoc->bFirstInterface;
1418 		last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
1419 		if (inum >= first_intf && inum <= last_intf) {
1420 			if (!retval)
1421 				retval = intf_assoc;
1422 			else
1423 				dev_err(&dev->dev, "Interface #%d referenced"
1424 					" by multiple IADs\n", inum);
1425 		}
1426 	}
1427 
1428 	return retval;
1429 }
1430 
1431 
1432 /*
1433  * usb_set_configuration - Makes a particular device setting be current
1434  * @dev: the device whose configuration is being updated
1435  * @configuration: the configuration being chosen.
1436  * Context: !in_interrupt(), caller owns the device lock
1437  *
1438  * This is used to enable non-default device modes.  Not all devices
1439  * use this kind of configurability; many devices only have one
1440  * configuration.
1441  *
1442  * @configuration is the value of the configuration to be installed.
1443  * According to the USB spec (e.g. section 9.1.1.5), configuration values
1444  * must be non-zero; a value of zero indicates that the device in
1445  * unconfigured.  However some devices erroneously use 0 as one of their
1446  * configuration values.  To help manage such devices, this routine will
1447  * accept @configuration = -1 as indicating the device should be put in
1448  * an unconfigured state.
1449  *
1450  * USB device configurations may affect Linux interoperability,
1451  * power consumption and the functionality available.  For example,
1452  * the default configuration is limited to using 100mA of bus power,
1453  * so that when certain device functionality requires more power,
1454  * and the device is bus powered, that functionality should be in some
1455  * non-default device configuration.  Other device modes may also be
1456  * reflected as configuration options, such as whether two ISDN
1457  * channels are available independently; and choosing between open
1458  * standard device protocols (like CDC) or proprietary ones.
1459  *
1460  * Note that USB has an additional level of device configurability,
1461  * associated with interfaces.  That configurability is accessed using
1462  * usb_set_interface().
1463  *
1464  * This call is synchronous. The calling context must be able to sleep,
1465  * must own the device lock, and must not hold the driver model's USB
1466  * bus mutex; usb device driver probe() methods cannot use this routine.
1467  *
1468  * Returns zero on success, or else the status code returned by the
1469  * underlying call that failed.  On successful completion, each interface
1470  * in the original device configuration has been destroyed, and each one
1471  * in the new configuration has been probed by all relevant usb device
1472  * drivers currently known to the kernel.
1473  */
1474 int usb_set_configuration(struct usb_device *dev, int configuration)
1475 {
1476 	int i, ret;
1477 	struct usb_host_config *cp = NULL;
1478 	struct usb_interface **new_interfaces = NULL;
1479 	int n, nintf;
1480 
1481 	if (configuration == -1)
1482 		configuration = 0;
1483 	else {
1484 		for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
1485 			if (dev->config[i].desc.bConfigurationValue ==
1486 					configuration) {
1487 				cp = &dev->config[i];
1488 				break;
1489 			}
1490 		}
1491 	}
1492 	if ((!cp && configuration != 0))
1493 		return -EINVAL;
1494 
1495 	/* The USB spec says configuration 0 means unconfigured.
1496 	 * But if a device includes a configuration numbered 0,
1497 	 * we will accept it as a correctly configured state.
1498 	 * Use -1 if you really want to unconfigure the device.
1499 	 */
1500 	if (cp && configuration == 0)
1501 		dev_warn(&dev->dev, "config 0 descriptor??\n");
1502 
1503 	/* Allocate memory for new interfaces before doing anything else,
1504 	 * so that if we run out then nothing will have changed. */
1505 	n = nintf = 0;
1506 	if (cp) {
1507 		nintf = cp->desc.bNumInterfaces;
1508 		new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1509 				GFP_KERNEL);
1510 		if (!new_interfaces) {
1511 			dev_err(&dev->dev, "Out of memory");
1512 			return -ENOMEM;
1513 		}
1514 
1515 		for (; n < nintf; ++n) {
1516 			new_interfaces[n] = kzalloc(
1517 					sizeof(struct usb_interface),
1518 					GFP_KERNEL);
1519 			if (!new_interfaces[n]) {
1520 				dev_err(&dev->dev, "Out of memory");
1521 				ret = -ENOMEM;
1522 free_interfaces:
1523 				while (--n >= 0)
1524 					kfree(new_interfaces[n]);
1525 				kfree(new_interfaces);
1526 				return ret;
1527 			}
1528 		}
1529 
1530 		i = dev->bus_mA - cp->desc.bMaxPower * 2;
1531 		if (i < 0)
1532 			dev_warn(&dev->dev, "new config #%d exceeds power "
1533 					"limit by %dmA\n",
1534 					configuration, -i);
1535 	}
1536 
1537 	/* Wake up the device so we can send it the Set-Config request */
1538 	ret = usb_autoresume_device(dev);
1539 	if (ret)
1540 		goto free_interfaces;
1541 
1542 	/* if it's already configured, clear out old state first.
1543 	 * getting rid of old interfaces means unbinding their drivers.
1544 	 */
1545 	if (dev->state != USB_STATE_ADDRESS)
1546 		usb_disable_device (dev, 1);	// Skip ep0
1547 
1548 	if ((ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
1549 			USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
1550 			NULL, 0, USB_CTRL_SET_TIMEOUT)) < 0) {
1551 
1552 		/* All the old state is gone, so what else can we do?
1553 		 * The device is probably useless now anyway.
1554 		 */
1555 		cp = NULL;
1556 	}
1557 
1558 	dev->actconfig = cp;
1559 	if (!cp) {
1560 		usb_set_device_state(dev, USB_STATE_ADDRESS);
1561 		usb_autosuspend_device(dev);
1562 		goto free_interfaces;
1563 	}
1564 	usb_set_device_state(dev, USB_STATE_CONFIGURED);
1565 
1566 	/* Initialize the new interface structures and the
1567 	 * hc/hcd/usbcore interface/endpoint state.
1568 	 */
1569 	for (i = 0; i < nintf; ++i) {
1570 		struct usb_interface_cache *intfc;
1571 		struct usb_interface *intf;
1572 		struct usb_host_interface *alt;
1573 
1574 		cp->interface[i] = intf = new_interfaces[i];
1575 		intfc = cp->intf_cache[i];
1576 		intf->altsetting = intfc->altsetting;
1577 		intf->num_altsetting = intfc->num_altsetting;
1578 		intf->intf_assoc = find_iad(dev, cp, i);
1579 		kref_get(&intfc->ref);
1580 
1581 		alt = usb_altnum_to_altsetting(intf, 0);
1582 
1583 		/* No altsetting 0?  We'll assume the first altsetting.
1584 		 * We could use a GetInterface call, but if a device is
1585 		 * so non-compliant that it doesn't have altsetting 0
1586 		 * then I wouldn't trust its reply anyway.
1587 		 */
1588 		if (!alt)
1589 			alt = &intf->altsetting[0];
1590 
1591 		intf->cur_altsetting = alt;
1592 		usb_enable_interface(dev, intf);
1593 		intf->dev.parent = &dev->dev;
1594 		intf->dev.driver = NULL;
1595 		intf->dev.bus = &usb_bus_type;
1596 		intf->dev.type = &usb_if_device_type;
1597 		intf->dev.dma_mask = dev->dev.dma_mask;
1598 		device_initialize (&intf->dev);
1599 		mark_quiesced(intf);
1600 		sprintf (&intf->dev.bus_id[0], "%d-%s:%d.%d",
1601 			 dev->bus->busnum, dev->devpath,
1602 			 configuration, alt->desc.bInterfaceNumber);
1603 	}
1604 	kfree(new_interfaces);
1605 
1606 	if (cp->string == NULL)
1607 		cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
1608 
1609 	/* Now that all the interfaces are set up, register them
1610 	 * to trigger binding of drivers to interfaces.  probe()
1611 	 * routines may install different altsettings and may
1612 	 * claim() any interfaces not yet bound.  Many class drivers
1613 	 * need that: CDC, audio, video, etc.
1614 	 */
1615 	for (i = 0; i < nintf; ++i) {
1616 		struct usb_interface *intf = cp->interface[i];
1617 
1618 		dev_dbg (&dev->dev,
1619 			"adding %s (config #%d, interface %d)\n",
1620 			intf->dev.bus_id, configuration,
1621 			intf->cur_altsetting->desc.bInterfaceNumber);
1622 		ret = device_add (&intf->dev);
1623 		if (ret != 0) {
1624 			dev_err(&dev->dev, "device_add(%s) --> %d\n",
1625 				intf->dev.bus_id, ret);
1626 			continue;
1627 		}
1628 		usb_create_sysfs_intf_files (intf);
1629 	}
1630 
1631 	usb_autosuspend_device(dev);
1632 	return 0;
1633 }
1634 
1635 struct set_config_request {
1636 	struct usb_device	*udev;
1637 	int			config;
1638 	struct work_struct	work;
1639 };
1640 
1641 /* Worker routine for usb_driver_set_configuration() */
1642 static void driver_set_config_work(struct work_struct *work)
1643 {
1644 	struct set_config_request *req =
1645 		container_of(work, struct set_config_request, work);
1646 
1647 	usb_lock_device(req->udev);
1648 	usb_set_configuration(req->udev, req->config);
1649 	usb_unlock_device(req->udev);
1650 	usb_put_dev(req->udev);
1651 	kfree(req);
1652 }
1653 
1654 /**
1655  * usb_driver_set_configuration - Provide a way for drivers to change device configurations
1656  * @udev: the device whose configuration is being updated
1657  * @config: the configuration being chosen.
1658  * Context: In process context, must be able to sleep
1659  *
1660  * Device interface drivers are not allowed to change device configurations.
1661  * This is because changing configurations will destroy the interface the
1662  * driver is bound to and create new ones; it would be like a floppy-disk
1663  * driver telling the computer to replace the floppy-disk drive with a
1664  * tape drive!
1665  *
1666  * Still, in certain specialized circumstances the need may arise.  This
1667  * routine gets around the normal restrictions by using a work thread to
1668  * submit the change-config request.
1669  *
1670  * Returns 0 if the request was succesfully queued, error code otherwise.
1671  * The caller has no way to know whether the queued request will eventually
1672  * succeed.
1673  */
1674 int usb_driver_set_configuration(struct usb_device *udev, int config)
1675 {
1676 	struct set_config_request *req;
1677 
1678 	req = kmalloc(sizeof(*req), GFP_KERNEL);
1679 	if (!req)
1680 		return -ENOMEM;
1681 	req->udev = udev;
1682 	req->config = config;
1683 	INIT_WORK(&req->work, driver_set_config_work);
1684 
1685 	usb_get_dev(udev);
1686 	schedule_work(&req->work);
1687 	return 0;
1688 }
1689 EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
1690 
1691 // synchronous request completion model
1692 EXPORT_SYMBOL(usb_control_msg);
1693 EXPORT_SYMBOL(usb_bulk_msg);
1694 
1695 EXPORT_SYMBOL(usb_sg_init);
1696 EXPORT_SYMBOL(usb_sg_cancel);
1697 EXPORT_SYMBOL(usb_sg_wait);
1698 
1699 // synchronous control message convenience routines
1700 EXPORT_SYMBOL(usb_get_descriptor);
1701 EXPORT_SYMBOL(usb_get_status);
1702 EXPORT_SYMBOL(usb_string);
1703 
1704 // synchronous calls that also maintain usbcore state
1705 EXPORT_SYMBOL(usb_clear_halt);
1706 EXPORT_SYMBOL(usb_reset_configuration);
1707 EXPORT_SYMBOL(usb_set_interface);
1708 
1709