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