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