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