message.c 60.6 KB
Newer Older
L
Linus Torvalds 已提交
1 2 3 4 5 6 7 8 9 10 11
/*
 * message.c - synchronous message handling
 */

#include <linux/pci.h>	/* for scatterlist macros */
#include <linux/usb.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/timer.h>
#include <linux/ctype.h>
12
#include <linux/nls.h>
L
Linus Torvalds 已提交
13
#include <linux/device.h>
14
#include <linux/scatterlist.h>
15
#include <linux/usb/quirks.h>
16
#include <linux/usb/hcd.h>	/* for usbcore internals */
L
Linus Torvalds 已提交
17 18 19 20
#include <asm/byteorder.h>

#include "usb.h"

21 22
static void cancel_async_set_config(struct usb_device *udev);

23 24 25 26 27
struct api_context {
	struct completion	done;
	int			status;
};

28
static void usb_api_blocking_completion(struct urb *urb)
L
Linus Torvalds 已提交
29
{
30 31 32 33
	struct api_context *ctx = urb->context;

	ctx->status = urb->status;
	complete(&ctx->done);
L
Linus Torvalds 已提交
34 35 36
}


37 38 39 40 41 42 43
/*
 * Starts urb and waits for completion or timeout. Note that this call
 * is NOT interruptible. Many device driver i/o requests should be
 * interruptible and therefore these drivers should implement their
 * own interruptible routines.
 */
static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length)
44
{
45
	struct api_context ctx;
46
	unsigned long expire;
47
	int retval;
L
Linus Torvalds 已提交
48

49 50
	init_completion(&ctx.done);
	urb->context = &ctx;
L
Linus Torvalds 已提交
51
	urb->actual_length = 0;
52 53
	retval = usb_submit_urb(urb, GFP_NOIO);
	if (unlikely(retval))
54
		goto out;
L
Linus Torvalds 已提交
55

56
	expire = timeout ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
57 58 59
	if (!wait_for_completion_timeout(&ctx.done, expire)) {
		usb_kill_urb(urb);
		retval = (ctx.status == -ENOENT ? -ETIMEDOUT : ctx.status);
60 61

		dev_dbg(&urb->dev->dev,
62
			"%s timed out on ep%d%s len=%u/%u\n",
63
			current->comm,
A
Alan Stern 已提交
64 65
			usb_endpoint_num(&urb->ep->desc),
			usb_urb_dir_in(urb) ? "in" : "out",
66 67 68
			urb->actual_length,
			urb->transfer_buffer_length);
	} else
69
		retval = ctx.status;
70
out:
L
Linus Torvalds 已提交
71 72
	if (actual_length)
		*actual_length = urb->actual_length;
73

L
Linus Torvalds 已提交
74
	usb_free_urb(urb);
75
	return retval;
L
Linus Torvalds 已提交
76 77 78
}

/*-------------------------------------------------------------------*/
79
/* returns status (negative) or length (positive) */
L
Linus Torvalds 已提交
80
static int usb_internal_control_msg(struct usb_device *usb_dev,
81
				    unsigned int pipe,
L
Linus Torvalds 已提交
82 83 84 85 86 87 88 89 90 91
				    struct usb_ctrlrequest *cmd,
				    void *data, int len, int timeout)
{
	struct urb *urb;
	int retv;
	int length;

	urb = usb_alloc_urb(0, GFP_NOIO);
	if (!urb)
		return -ENOMEM;
92

L
Linus Torvalds 已提交
93 94 95 96 97 98 99 100 101 102 103
	usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
			     len, usb_api_blocking_completion, NULL);

	retv = usb_start_wait_urb(urb, timeout, &length);
	if (retv < 0)
		return retv;
	else
		return length;
}

/**
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
 * usb_control_msg - Builds a control urb, sends it off and waits for completion
 * @dev: pointer to the usb device to send the message to
 * @pipe: endpoint "pipe" to send the message to
 * @request: USB message request value
 * @requesttype: USB message request type value
 * @value: USB message value
 * @index: USB message index value
 * @data: pointer to the data to send
 * @size: length in bytes of the data to send
 * @timeout: time in msecs to wait for the message to complete before timing
 *	out (if 0 the wait is forever)
 *
 * Context: !in_interrupt ()
 *
 * This function sends a simple control message to a specified endpoint and
 * waits for the message to complete, or timeout.
 *
 * Don't use this function from within an interrupt context, like a bottom half
 * handler.  If you need an asynchronous message, or need to send a message
 * from within interrupt context, use usb_submit_urb().
 * If a thread in your driver uses this call, make sure your disconnect()
 * method can wait for it to complete.  Since you don't have a handle on the
 * URB used, you can't cancel the request.
127 128 129
 *
 * Return: If successful, the number of bytes transferred. Otherwise, a negative
 * error number.
L
Linus Torvalds 已提交
130
 */
131 132 133
int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
		    __u8 requesttype, __u16 value, __u16 index, void *data,
		    __u16 size, int timeout)
L
Linus Torvalds 已提交
134
{
135
	struct usb_ctrlrequest *dr;
L
Linus Torvalds 已提交
136
	int ret;
137 138

	dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
L
Linus Torvalds 已提交
139 140 141
	if (!dr)
		return -ENOMEM;

142
	dr->bRequestType = requesttype;
L
Linus Torvalds 已提交
143
	dr->bRequest = request;
144 145 146
	dr->wValue = cpu_to_le16(value);
	dr->wIndex = cpu_to_le16(index);
	dr->wLength = cpu_to_le16(size);
L
Linus Torvalds 已提交
147 148 149 150 151 152 153

	ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);

	kfree(dr);

	return ret;
}
154
EXPORT_SYMBOL_GPL(usb_control_msg);
L
Linus Torvalds 已提交
155

156 157 158 159 160 161
/**
 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
 * @usb_dev: pointer to the usb device to send the message to
 * @pipe: endpoint "pipe" to send the message to
 * @data: pointer to the data to send
 * @len: length in bytes of the data to send
162 163
 * @actual_length: pointer to a location to put the actual length transferred
 *	in bytes
164 165
 * @timeout: time in msecs to wait for the message to complete before
 *	timing out (if 0 the wait is forever)
166
 *
167 168 169 170 171 172 173 174 175 176 177
 * Context: !in_interrupt ()
 *
 * This function sends a simple interrupt message to a specified endpoint and
 * waits for the message to complete, or timeout.
 *
 * Don't use this function from within an interrupt context, like a bottom half
 * handler.  If you need an asynchronous message, or need to send a message
 * from within interrupt context, use usb_submit_urb() If a thread in your
 * driver uses this call, make sure your disconnect() method can wait for it to
 * complete.  Since you don't have a handle on the URB used, you can't cancel
 * the request.
178 179 180
 *
 * Return:
 * If successful, 0. Otherwise a negative error number. The number of actual
181
 * bytes transferred will be stored in the @actual_length parameter.
182 183 184 185 186 187 188 189
 */
int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
		      void *data, int len, int *actual_length, int timeout)
{
	return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
}
EXPORT_SYMBOL_GPL(usb_interrupt_msg);

L
Linus Torvalds 已提交
190
/**
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
 * @usb_dev: pointer to the usb device to send the message to
 * @pipe: endpoint "pipe" to send the message to
 * @data: pointer to the data to send
 * @len: length in bytes of the data to send
 * @actual_length: pointer to a location to put the actual length transferred
 *	in bytes
 * @timeout: time in msecs to wait for the message to complete before
 *	timing out (if 0 the wait is forever)
 *
 * Context: !in_interrupt ()
 *
 * This function sends a simple bulk message to a specified endpoint
 * and waits for the message to complete, or timeout.
 *
 * Don't use this function from within an interrupt context, like a bottom half
 * handler.  If you need an asynchronous message, or need to send a message
 * from within interrupt context, use usb_submit_urb() If a thread in your
 * driver uses this call, make sure your disconnect() method can wait for it to
 * complete.  Since you don't have a handle on the URB used, you can't cancel
 * the request.
 *
 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
 * users are forced to abuse this routine by using it to submit URBs for
 * interrupt endpoints.  We will take the liberty of creating an interrupt URB
 * (with the default interval) if the target is an interrupt endpoint.
217 218 219
 *
 * Return:
 * If successful, 0. Otherwise a negative error number. The number of actual
220
 * bytes transferred will be stored in the @actual_length parameter.
221
 *
L
Linus Torvalds 已提交
222
 */
223 224
int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
		 void *data, int len, int *actual_length, int timeout)
L
Linus Torvalds 已提交
225 226
{
	struct urb *urb;
227
	struct usb_host_endpoint *ep;
L
Linus Torvalds 已提交
228

229
	ep = usb_pipe_endpoint(usb_dev, pipe);
230
	if (!ep || len < 0)
L
Linus Torvalds 已提交
231 232
		return -EINVAL;

233
	urb = usb_alloc_urb(0, GFP_KERNEL);
L
Linus Torvalds 已提交
234 235 236
	if (!urb)
		return -ENOMEM;

237 238 239 240
	if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
			USB_ENDPOINT_XFER_INT) {
		pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
		usb_fill_int_urb(urb, usb_dev, pipe, data, len,
241 242
				usb_api_blocking_completion, NULL,
				ep->desc.bInterval);
243 244 245
	} else
		usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
				usb_api_blocking_completion, NULL);
L
Linus Torvalds 已提交
246 247 248

	return usb_start_wait_urb(urb, timeout, actual_length);
}
249
EXPORT_SYMBOL_GPL(usb_bulk_msg);
L
Linus Torvalds 已提交
250 251 252

/*-------------------------------------------------------------------*/

253
static void sg_clean(struct usb_sg_request *io)
L
Linus Torvalds 已提交
254 255 256
{
	if (io->urbs) {
		while (io->entries--)
257
			usb_free_urb(io->urbs[io->entries]);
258
		kfree(io->urbs);
L
Linus Torvalds 已提交
259 260 261 262 263
		io->urbs = NULL;
	}
	io->dev = NULL;
}

264
static void sg_complete(struct urb *urb)
L
Linus Torvalds 已提交
265
{
266
	struct usb_sg_request *io = urb->context;
267
	int status = urb->status;
L
Linus Torvalds 已提交
268

269
	spin_lock(&io->lock);
L
Linus Torvalds 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282

	/* In 2.5 we require hcds' endpoint queues not to progress after fault
	 * reports, until the completion callback (this!) returns.  That lets
	 * device driver code (like this routine) unlink queued urbs first,
	 * if it needs to, since the HC won't work on them at all.  So it's
	 * not possible for page N+1 to overwrite page N, and so on.
	 *
	 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
	 * complete before the HCD can get requests away from hardware,
	 * though never during cleanup after a hard fault.
	 */
	if (io->status
			&& (io->status != -ECONNRESET
283
				|| status != -ECONNRESET)
L
Linus Torvalds 已提交
284
			&& urb->actual_length) {
285
		dev_err(io->dev->bus->controller,
L
Linus Torvalds 已提交
286 287
			"dev %s ep%d%s scatterlist error %d/%d\n",
			io->dev->devpath,
A
Alan Stern 已提交
288 289
			usb_endpoint_num(&urb->ep->desc),
			usb_urb_dir_in(urb) ? "in" : "out",
290
			status, io->status);
291
		/* BUG (); */
L
Linus Torvalds 已提交
292 293
	}

294 295
	if (io->status == 0 && status && status != -ECONNRESET) {
		int i, found, retval;
L
Linus Torvalds 已提交
296

297
		io->status = status;
L
Linus Torvalds 已提交
298 299 300 301 302

		/* the previous urbs, and this one, completed already.
		 * unlink pending urbs so they won't rx/tx bad data.
		 * careful: unlink can sometimes be synchronous...
		 */
303
		spin_unlock(&io->lock);
L
Linus Torvalds 已提交
304
		for (i = 0, found = 0; i < io->entries; i++) {
305
			if (!io->urbs[i] || !io->urbs[i]->dev)
L
Linus Torvalds 已提交
306 307
				continue;
			if (found) {
308
				retval = usb_unlink_urb(io->urbs[i]);
309 310
				if (retval != -EINPROGRESS &&
				    retval != -ENODEV &&
311 312
				    retval != -EBUSY &&
				    retval != -EIDRM)
313
					dev_err(&io->dev->dev,
L
Linus Torvalds 已提交
314
						"%s, unlink --> %d\n",
315
						__func__, retval);
316
			} else if (urb == io->urbs[i])
L
Linus Torvalds 已提交
317 318
				found = 1;
		}
319
		spin_lock(&io->lock);
L
Linus Torvalds 已提交
320 321 322 323 324 325
	}

	/* on the last completion, signal usb_sg_wait() */
	io->bytes += urb->actual_length;
	io->count--;
	if (!io->count)
326
		complete(&io->complete);
L
Linus Torvalds 已提交
327

328
	spin_unlock(&io->lock);
L
Linus Torvalds 已提交
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
}


/**
 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
 * @io: request block being initialized.  until usb_sg_wait() returns,
 *	treat this as a pointer to an opaque block of memory,
 * @dev: the usb device that will send or receive the data
 * @pipe: endpoint "pipe" used to transfer the data
 * @period: polling rate for interrupt endpoints, in frames or
 * 	(for high speed endpoints) microframes; ignored for bulk
 * @sg: scatterlist entries
 * @nents: how many entries in the scatterlist
 * @length: how many bytes to send from the scatterlist, or zero to
 * 	send every byte identified in the list.
 * @mem_flags: SLAB_* flags affecting memory allocations in this call
 *
346 347 348
 * This initializes a scatter/gather request, allocating resources such as
 * I/O mappings and urb memory (except maybe memory used by USB controller
 * drivers).
L
Linus Torvalds 已提交
349 350 351 352 353 354 355
 *
 * The request must be issued using usb_sg_wait(), which waits for the I/O to
 * complete (or to be canceled) and then cleans up all resources allocated by
 * usb_sg_init().
 *
 * The request may be canceled with usb_sg_cancel(), either before or after
 * usb_sg_wait() is called.
356 357
 *
 * Return: Zero for success, else a negative errno value.
L
Linus Torvalds 已提交
358
 */
359 360 361
int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
		unsigned pipe, unsigned	period, struct scatterlist *sg,
		int nents, size_t length, gfp_t mem_flags)
L
Linus Torvalds 已提交
362
{
363 364
	int i;
	int urb_flags;
365
	int use_sg;
L
Linus Torvalds 已提交
366 367

	if (!io || !dev || !sg
368 369
			|| usb_pipecontrol(pipe)
			|| usb_pipeisoc(pipe)
L
Linus Torvalds 已提交
370 371 372
			|| nents <= 0)
		return -EINVAL;

373
	spin_lock_init(&io->lock);
L
Linus Torvalds 已提交
374 375 376
	io->dev = dev;
	io->pipe = pipe;

377
	if (dev->bus->sg_tablesize > 0) {
378
		use_sg = true;
A
Alan Stern 已提交
379
		io->entries = 1;
380 381
	} else {
		use_sg = false;
A
Alan Stern 已提交
382
		io->entries = nents;
383
	}
A
Alan Stern 已提交
384 385

	/* initialize all the urbs we'll use */
386
	io->urbs = kmalloc(io->entries * sizeof(*io->urbs), mem_flags);
L
Linus Torvalds 已提交
387 388 389
	if (!io->urbs)
		goto nomem;

A
Alan Stern 已提交
390
	urb_flags = URB_NO_INTERRUPT;
391
	if (usb_pipein(pipe))
L
Linus Torvalds 已提交
392 393
		urb_flags |= URB_SHORT_NOT_OK;

A
Alan Stern 已提交
394 395 396
	for_each_sg(sg, sg, io->entries, i) {
		struct urb *urb;
		unsigned len;
397

A
Alan Stern 已提交
398 399 400 401
		urb = usb_alloc_urb(0, mem_flags);
		if (!urb) {
			io->entries = i;
			goto nomem;
402
		}
A
Alan Stern 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
		io->urbs[i] = urb;

		urb->dev = NULL;
		urb->pipe = pipe;
		urb->interval = period;
		urb->transfer_flags = urb_flags;
		urb->complete = sg_complete;
		urb->context = io;
		urb->sg = sg;

		if (use_sg) {
			/* There is no single transfer buffer */
			urb->transfer_buffer = NULL;
			urb->num_sgs = nents;

			/* A length of zero means transfer the whole sg list */
			len = length;
			if (len == 0) {
A
Alan Stern 已提交
421 422 423 424 425
				struct scatterlist	*sg2;
				int			j;

				for_each_sg(sg, sg2, nents, j)
					len += sg2->length;
426
			}
A
Alan Stern 已提交
427
		} else {
428
			/*
429 430 431
			 * Some systems can't use DMA; they use PIO instead.
			 * For their sakes, transfer_buffer is set whenever
			 * possible.
432
			 */
433
			if (!PageHighMem(sg_page(sg)))
A
Alan Stern 已提交
434
				urb->transfer_buffer = sg_virt(sg);
435
			else
A
Alan Stern 已提交
436
				urb->transfer_buffer = NULL;
437

438
			len = sg->length;
439
			if (length) {
440
				len = min_t(size_t, len, length);
441 442 443 444
				length -= len;
				if (length == 0)
					io->entries = i + 1;
			}
L
Linus Torvalds 已提交
445
		}
A
Alan Stern 已提交
446
		urb->transfer_buffer_length = len;
L
Linus Torvalds 已提交
447
	}
A
Alan Stern 已提交
448
	io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
L
Linus Torvalds 已提交
449 450

	/* transaction state */
451
	io->count = io->entries;
L
Linus Torvalds 已提交
452 453
	io->status = 0;
	io->bytes = 0;
454
	init_completion(&io->complete);
L
Linus Torvalds 已提交
455 456 457
	return 0;

nomem:
458
	sg_clean(io);
L
Linus Torvalds 已提交
459 460
	return -ENOMEM;
}
461
EXPORT_SYMBOL_GPL(usb_sg_init);
L
Linus Torvalds 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

/**
 * usb_sg_wait - synchronously execute scatter/gather request
 * @io: request block handle, as initialized with usb_sg_init().
 * 	some fields become accessible when this call returns.
 * Context: !in_interrupt ()
 *
 * This function blocks until the specified I/O operation completes.  It
 * leverages the grouping of the related I/O requests to get good transfer
 * rates, by queueing the requests.  At higher speeds, such queuing can
 * significantly improve USB throughput.
 *
 * There are three kinds of completion for this function.
 * (1) success, where io->status is zero.  The number of io->bytes
 *     transferred is as requested.
 * (2) error, where io->status is a negative errno value.  The number
 *     of io->bytes transferred before the error is usually less
 *     than requested, and can be nonzero.
480
 * (3) cancellation, a type of error with status -ECONNRESET that
L
Linus Torvalds 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
 *     is initiated by usb_sg_cancel().
 *
 * When this function returns, all memory allocated through usb_sg_init() or
 * this call will have been freed.  The request block parameter may still be
 * passed to usb_sg_cancel(), or it may be freed.  It could also be
 * reinitialized and then reused.
 *
 * Data Transfer Rates:
 *
 * Bulk transfers are valid for full or high speed endpoints.
 * The best full speed data rate is 19 packets of 64 bytes each
 * per frame, or 1216 bytes per millisecond.
 * The best high speed data rate is 13 packets of 512 bytes each
 * per microframe, or 52 KBytes per millisecond.
 *
 * The reason to use interrupt transfers through this API would most likely
 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
 * could be transferred.  That capability is less useful for low or full
 * speed interrupt endpoints, which allow at most one packet per millisecond,
 * of at most 8 or 64 bytes (respectively).
501 502 503 504
 *
 * It is not necessary to call this function to reserve bandwidth for devices
 * under an xHCI host controller, as the bandwidth is reserved when the
 * configuration or interface alt setting is selected.
L
Linus Torvalds 已提交
505
 */
506
void usb_sg_wait(struct usb_sg_request *io)
L
Linus Torvalds 已提交
507
{
508 509
	int i;
	int entries = io->entries;
L
Linus Torvalds 已提交
510 511

	/* queue the urbs.  */
512
	spin_lock_irq(&io->lock);
513 514
	i = 0;
	while (i < entries && !io->status) {
515
		int retval;
L
Linus Torvalds 已提交
516

517
		io->urbs[i]->dev = io->dev;
518
		retval = usb_submit_urb(io->urbs[i], GFP_ATOMIC);
L
Linus Torvalds 已提交
519

520
		/* after we submit, let completions or cancellations fire;
L
Linus Torvalds 已提交
521 522
		 * we handshake using io->status.
		 */
523
		spin_unlock_irq(&io->lock);
L
Linus Torvalds 已提交
524 525
		switch (retval) {
			/* maybe we retrying will recover */
526
		case -ENXIO:	/* hc didn't queue this one */
L
Linus Torvalds 已提交
527 528 529
		case -EAGAIN:
		case -ENOMEM:
			retval = 0;
530
			yield();
L
Linus Torvalds 已提交
531 532 533 534 535 536 537 538 539
			break;

			/* no error? continue immediately.
			 *
			 * NOTE: to work better with UHCI (4K I/O buffer may
			 * need 3K of TDs) it may be good to limit how many
			 * URBs are queued at once; N milliseconds?
			 */
		case 0:
540
			++i;
541
			cpu_relax();
L
Linus Torvalds 已提交
542 543 544 545
			break;

			/* fail any uncompleted urbs */
		default:
546 547
			io->urbs[i]->status = retval;
			dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
548
				__func__, retval);
549
			usb_sg_cancel(io);
L
Linus Torvalds 已提交
550
		}
551
		spin_lock_irq(&io->lock);
L
Linus Torvalds 已提交
552 553 554 555 556
		if (retval && (io->status == 0 || io->status == -ECONNRESET))
			io->status = retval;
	}
	io->count -= entries - i;
	if (io->count == 0)
557 558
		complete(&io->complete);
	spin_unlock_irq(&io->lock);
L
Linus Torvalds 已提交
559 560 561 562 563

	/* OK, yes, this could be packaged as non-blocking.
	 * So could the submit loop above ... but it's easier to
	 * solve neither problem than to solve both!
	 */
564
	wait_for_completion(&io->complete);
L
Linus Torvalds 已提交
565

566
	sg_clean(io);
L
Linus Torvalds 已提交
567
}
568
EXPORT_SYMBOL_GPL(usb_sg_wait);
L
Linus Torvalds 已提交
569 570 571 572 573 574 575 576 577

/**
 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
 * @io: request block, initialized with usb_sg_init()
 *
 * This stops a request after it has been started by usb_sg_wait().
 * It can also prevents one initialized by usb_sg_init() from starting,
 * so that call just frees resources allocated to the request.
 */
578
void usb_sg_cancel(struct usb_sg_request *io)
L
Linus Torvalds 已提交
579
{
580
	unsigned long flags;
L
Linus Torvalds 已提交
581

582
	spin_lock_irqsave(&io->lock, flags);
L
Linus Torvalds 已提交
583 584 585

	/* shut everything down, if it didn't already */
	if (!io->status) {
586
		int i;
L
Linus Torvalds 已提交
587 588

		io->status = -ECONNRESET;
589
		spin_unlock(&io->lock);
L
Linus Torvalds 已提交
590
		for (i = 0; i < io->entries; i++) {
591
			int retval;
L
Linus Torvalds 已提交
592

593
			if (!io->urbs[i]->dev)
L
Linus Torvalds 已提交
594
				continue;
595
			retval = usb_unlink_urb(io->urbs[i]);
596 597 598 599
			if (retval != -EINPROGRESS
					&& retval != -ENODEV
					&& retval != -EBUSY
					&& retval != -EIDRM)
600
				dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
601
					__func__, retval);
L
Linus Torvalds 已提交
602
		}
603
		spin_lock(&io->lock);
L
Linus Torvalds 已提交
604
	}
605
	spin_unlock_irqrestore(&io->lock, flags);
L
Linus Torvalds 已提交
606
}
607
EXPORT_SYMBOL_GPL(usb_sg_cancel);
L
Linus Torvalds 已提交
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629

/*-------------------------------------------------------------------*/

/**
 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
 * @dev: the device whose descriptor is being retrieved
 * @type: the descriptor type (USB_DT_*)
 * @index: the number of the descriptor
 * @buf: where to put the descriptor
 * @size: how big is "buf"?
 * Context: !in_interrupt ()
 *
 * Gets a USB descriptor.  Convenience functions exist to simplify
 * getting some types of descriptors.  Use
 * usb_get_string() or usb_string() for USB_DT_STRING.
 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
 * are part of the device structure.
 * In addition to a number of USB-standard descriptors, some
 * devices also use class-specific or vendor-specific descriptors.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
630
 * Return: The number of bytes received on success, or else the status code
L
Linus Torvalds 已提交
631 632
 * returned by the underlying usb_control_msg() call.
 */
633 634
int usb_get_descriptor(struct usb_device *dev, unsigned char type,
		       unsigned char index, void *buf, int size)
L
Linus Torvalds 已提交
635 636 637
{
	int i;
	int result;
638 639

	memset(buf, 0, size);	/* Make sure we parse really received data */
L
Linus Torvalds 已提交
640 641

	for (i = 0; i < 3; ++i) {
642
		/* retry on length 0 or error; some devices are flakey */
L
Linus Torvalds 已提交
643 644 645 646
		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
				USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
				(type << 8) + index, 0, buf, size,
				USB_CTRL_GET_TIMEOUT);
647
		if (result <= 0 && result != -ETIMEDOUT)
L
Linus Torvalds 已提交
648 649
			continue;
		if (result > 1 && ((u8 *)buf)[1] != type) {
650
			result = -ENODATA;
L
Linus Torvalds 已提交
651 652 653 654 655 656
			continue;
		}
		break;
	}
	return result;
}
657
EXPORT_SYMBOL_GPL(usb_get_descriptor);
L
Linus Torvalds 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677

/**
 * usb_get_string - gets a string descriptor
 * @dev: the device whose string descriptor is being retrieved
 * @langid: code for language chosen (from string descriptor zero)
 * @index: the number of the descriptor
 * @buf: where to put the string
 * @size: how big is "buf"?
 * Context: !in_interrupt ()
 *
 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
 * in little-endian byte order).
 * The usb_string() function will often be a convenient way to turn
 * these strings into kernel-printable form.
 *
 * Strings may be referenced in device, configuration, interface, or other
 * descriptors, and could also be used in vendor-specific ways.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
678
 * Return: The number of bytes received on success, or else the status code
L
Linus Torvalds 已提交
679 680
 * returned by the underlying usb_control_msg() call.
 */
681 682
static int usb_get_string(struct usb_device *dev, unsigned short langid,
			  unsigned char index, void *buf, int size)
L
Linus Torvalds 已提交
683 684 685 686 687 688 689 690 691 692
{
	int i;
	int result;

	for (i = 0; i < 3; ++i) {
		/* retry on length 0 or stall; some devices are flakey */
		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
			(USB_DT_STRING << 8) + index, langid, buf, size,
			USB_CTRL_GET_TIMEOUT);
693 694 695 696 697 698 699
		if (result == 0 || result == -EPIPE)
			continue;
		if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
			result = -ENODATA;
			continue;
		}
		break;
L
Linus Torvalds 已提交
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
	}
	return result;
}

static void usb_try_string_workarounds(unsigned char *buf, int *length)
{
	int newlength, oldlength = *length;

	for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
		if (!isprint(buf[newlength]) || buf[newlength + 1])
			break;

	if (newlength > 2) {
		buf[0] = newlength;
		*length = newlength;
	}
}

static int usb_string_sub(struct usb_device *dev, unsigned int langid,
719
			  unsigned int index, unsigned char *buf)
L
Linus Torvalds 已提交
720 721 722 723 724
{
	int rc;

	/* Try to read the string descriptor by asking for the maximum
	 * possible number of bytes */
725 726 727 728
	if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
		rc = -EIO;
	else
		rc = usb_get_string(dev, langid, index, buf, 255);
L
Linus Torvalds 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754

	/* If that failed try to read the descriptor length, then
	 * ask for just that many bytes */
	if (rc < 2) {
		rc = usb_get_string(dev, langid, index, buf, 2);
		if (rc == 2)
			rc = usb_get_string(dev, langid, index, buf, buf[0]);
	}

	if (rc >= 2) {
		if (!buf[0] && !buf[1])
			usb_try_string_workarounds(buf, &rc);

		/* There might be extra junk at the end of the descriptor */
		if (buf[0] < rc)
			rc = buf[0];

		rc = rc - (rc & 1); /* force a multiple of two */
	}

	if (rc < 2)
		rc = (rc < 0 ? rc : -EINVAL);

	return rc;
}

D
Daniel Mack 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
{
	int err;

	if (dev->have_langid)
		return 0;

	if (dev->string_langid < 0)
		return -EPIPE;

	err = usb_string_sub(dev, 0, 0, tbuf);

	/* If the string was reported but is malformed, default to english
	 * (0x0409) */
	if (err == -ENODATA || (err > 0 && err < 4)) {
		dev->string_langid = 0x0409;
		dev->have_langid = 1;
		dev_err(&dev->dev,
773
			"language id specifier not provided by device, defaulting to English\n");
D
Daniel Mack 已提交
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
		return 0;
	}

	/* In case of all other errors, we assume the device is not able to
	 * deal with strings at all. Set string_langid to -1 in order to
	 * prevent any string to be retrieved from the device */
	if (err < 0) {
		dev_err(&dev->dev, "string descriptor 0 read error: %d\n",
					err);
		dev->string_langid = -1;
		return -EPIPE;
	}

	/* always use the first langid listed */
	dev->string_langid = tbuf[2] | (tbuf[3] << 8);
	dev->have_langid = 1;
	dev_dbg(&dev->dev, "default language 0x%04x\n",
				dev->string_langid);
	return 0;
}

L
Linus Torvalds 已提交
795
/**
796
 * usb_string - returns UTF-8 version of a string descriptor
L
Linus Torvalds 已提交
797 798 799 800 801
 * @dev: the device whose string descriptor is being retrieved
 * @index: the number of the descriptor
 * @buf: where to put the string
 * @size: how big is "buf"?
 * Context: !in_interrupt ()
802
 *
L
Linus Torvalds 已提交
803
 * This converts the UTF-16LE encoded strings returned by devices, from
804 805
 * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
 * that are more usable in most kernel contexts.  Note that this function
L
Linus Torvalds 已提交
806 807 808 809
 * chooses strings in the first language supported by the device.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
810
 * Return: length of the string (>= 0) or usb_control_msg status (< 0).
L
Linus Torvalds 已提交
811 812 813 814 815 816 817 818 819 820 821
 */
int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
{
	unsigned char *tbuf;
	int err;

	if (dev->state == USB_STATE_SUSPENDED)
		return -EHOSTUNREACH;
	if (size <= 0 || !buf || !index)
		return -EINVAL;
	buf[0] = 0;
A
Alan Stern 已提交
822
	tbuf = kmalloc(256, GFP_NOIO);
L
Linus Torvalds 已提交
823 824 825
	if (!tbuf)
		return -ENOMEM;

D
Daniel Mack 已提交
826 827 828
	err = usb_get_langid(dev, tbuf);
	if (err < 0)
		goto errout;
829

L
Linus Torvalds 已提交
830 831 832 833 834
	err = usb_string_sub(dev, dev->string_langid, index, tbuf);
	if (err < 0)
		goto errout;

	size--;		/* leave room for trailing NULL char in output buffer */
A
Alan Stern 已提交
835 836
	err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
			UTF16_LITTLE_ENDIAN, buf, size);
837
	buf[err] = 0;
L
Linus Torvalds 已提交
838 839

	if (tbuf[1] != USB_DT_STRING)
840 841 842
		dev_dbg(&dev->dev,
			"wrong descriptor type %02x for string %d (\"%s\")\n",
			tbuf[1], index, buf);
L
Linus Torvalds 已提交
843 844 845 846 847

 errout:
	kfree(tbuf);
	return err;
}
848
EXPORT_SYMBOL_GPL(usb_string);
L
Linus Torvalds 已提交
849

850 851 852
/* one UTF-8-encoded 16-bit character has at most three bytes */
#define MAX_USB_STRING_SIZE (127 * 3 + 1)

853 854 855 856 857
/**
 * usb_cache_string - read a string descriptor and cache it for later use
 * @udev: the device whose string descriptor is being read
 * @index: the descriptor index
 *
858 859
 * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
 * or %NULL if the index is 0 or the string could not be read.
860 861 862 863 864 865 866
 */
char *usb_cache_string(struct usb_device *udev, int index)
{
	char *buf;
	char *smallbuf = NULL;
	int len;

867 868 869
	if (index <= 0)
		return NULL;

870
	buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
871
	if (buf) {
872
		len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
873
		if (len > 0) {
874
			smallbuf = kmalloc(++len, GFP_NOIO);
875
			if (!smallbuf)
876 877 878 879 880 881 882 883
				return buf;
			memcpy(smallbuf, buf, len);
		}
		kfree(buf);
	}
	return smallbuf;
}

L
Linus Torvalds 已提交
884 885 886 887 888 889 890
/*
 * usb_get_device_descriptor - (re)reads the device descriptor (usbcore)
 * @dev: the device whose device descriptor is being updated
 * @size: how much of the descriptor to read
 * Context: !in_interrupt ()
 *
 * Updates the copy of the device descriptor stored in the device structure,
891
 * which dedicates space for this purpose.
L
Linus Torvalds 已提交
892 893 894 895 896 897 898
 *
 * Not exported, only for use by the core.  If drivers really want to read
 * the device descriptor directly, they can call usb_get_descriptor() with
 * type = USB_DT_DEVICE and index = 0.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
899
 * Return: The number of bytes received on success, or else the status code
L
Linus Torvalds 已提交
900 901 902 903 904 905 906 907 908 909 910 911 912 913
 * returned by the underlying usb_control_msg() call.
 */
int usb_get_device_descriptor(struct usb_device *dev, unsigned int size)
{
	struct usb_device_descriptor *desc;
	int ret;

	if (size > sizeof(*desc))
		return -EINVAL;
	desc = kmalloc(sizeof(*desc), GFP_NOIO);
	if (!desc)
		return -ENOMEM;

	ret = usb_get_descriptor(dev, USB_DT_DEVICE, 0, desc, size);
914
	if (ret >= 0)
L
Linus Torvalds 已提交
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
		memcpy(&dev->descriptor, desc, size);
	kfree(desc);
	return ret;
}

/**
 * usb_get_status - issues a GET_STATUS call
 * @dev: the device whose status is being checked
 * @type: USB_RECIP_*; for device, interface, or endpoint
 * @target: zero (for device), else interface or endpoint number
 * @data: pointer to two bytes of bitmap data
 * Context: !in_interrupt ()
 *
 * Returns device, interface, or endpoint status.  Normally only of
 * interest to see if the device is self powered, or has enabled the
 * remote wakeup facility; or whether a bulk or interrupt endpoint
 * is halted ("stalled").
 *
 * Bits in these status bitmaps are set using the SET_FEATURE request,
 * and cleared using the CLEAR_FEATURE request.  The usb_clear_halt()
 * function should be used to clear halt ("stall") status.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
939 940
 * Returns 0 and the status value in *@data (in host byte order) on success,
 * or else the status code from the underlying usb_control_msg() call.
L
Linus Torvalds 已提交
941 942 943 944
 */
int usb_get_status(struct usb_device *dev, int type, int target, void *data)
{
	int ret;
945
	__le16 *status = kmalloc(sizeof(*status), GFP_KERNEL);
L
Linus Torvalds 已提交
946 947 948 949 950 951 952 953

	if (!status)
		return -ENOMEM;

	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
		USB_REQ_GET_STATUS, USB_DIR_IN | type, 0, target, status,
		sizeof(*status), USB_CTRL_GET_TIMEOUT);

954 955 956 957 958 959
	if (ret == 2) {
		*(u16 *) data = le16_to_cpu(*status);
		ret = 0;
	} else if (ret >= 0) {
		ret = -EIO;
	}
L
Linus Torvalds 已提交
960 961 962
	kfree(status);
	return ret;
}
963
EXPORT_SYMBOL_GPL(usb_get_status);
L
Linus Torvalds 已提交
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984

/**
 * usb_clear_halt - tells device to clear endpoint halt/stall condition
 * @dev: device whose endpoint is halted
 * @pipe: endpoint "pipe" being cleared
 * Context: !in_interrupt ()
 *
 * This is used to clear halt conditions for bulk and interrupt endpoints,
 * as reported by URB completion status.  Endpoints that are halted are
 * sometimes referred to as being "stalled".  Such endpoints are unable
 * to transmit or receive data until the halt status is cleared.  Any URBs
 * queued for such an endpoint should normally be unlinked by the driver
 * before clearing the halt condition, as described in sections 5.7.5
 * and 5.8.5 of the USB 2.0 spec.
 *
 * Note that control and isochronous endpoints don't halt, although control
 * endpoints report "protocol stall" (for unsupported requests) using the
 * same status code used to report a true stall.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 *
985
 * Return: Zero on success, or else the status code returned by the
L
Linus Torvalds 已提交
986 987 988 989 990 991
 * underlying usb_control_msg() call.
 */
int usb_clear_halt(struct usb_device *dev, int pipe)
{
	int result;
	int endp = usb_pipeendpoint(pipe);
992 993

	if (usb_pipein(pipe))
L
Linus Torvalds 已提交
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
		endp |= USB_DIR_IN;

	/* we don't care if it wasn't halted first. in fact some devices
	 * (like some ibmcam model 1 units) seem to expect hosts to make
	 * this request for iso endpoints, which can't halt!
	 */
	result = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
		USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
		USB_ENDPOINT_HALT, endp, NULL, 0,
		USB_CTRL_SET_TIMEOUT);

	/* don't un-halt or force to DATA0 except on success */
	if (result < 0)
		return result;

	/* NOTE:  seems like Microsoft and Apple don't bother verifying
	 * the clear "took", so some devices could lock up if you check...
	 * such as the Hagiwara FlashGate DUAL.  So we won't bother.
	 *
	 * NOTE:  make sure the logic here doesn't diverge much from
	 * the copy in usb-storage, for as long as we need two copies.
	 */

1017
	usb_reset_endpoint(dev, endp);
L
Linus Torvalds 已提交
1018 1019 1020

	return 0;
}
1021
EXPORT_SYMBOL_GPL(usb_clear_halt);
L
Linus Torvalds 已提交
1022

A
Alan Stern 已提交
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
static int create_intf_ep_devs(struct usb_interface *intf)
{
	struct usb_device *udev = interface_to_usbdev(intf);
	struct usb_host_interface *alt = intf->cur_altsetting;
	int i;

	if (intf->ep_devs_created || intf->unregistering)
		return 0;

	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
		(void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
	intf->ep_devs_created = 1;
	return 0;
}

static void remove_intf_ep_devs(struct usb_interface *intf)
{
	struct usb_host_interface *alt = intf->cur_altsetting;
	int i;

	if (!intf->ep_devs_created)
		return;

	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
		usb_remove_ep_devs(&alt->endpoint[i]);
	intf->ep_devs_created = 0;
}

L
Linus Torvalds 已提交
1051 1052 1053 1054 1055
/**
 * usb_disable_endpoint -- Disable an endpoint by address
 * @dev: the device whose endpoint is being disabled
 * @epaddr: the endpoint's address.  Endpoint number for output,
 *	endpoint number + USB_DIR_IN for input
1056 1057
 * @reset_hardware: flag to erase any endpoint state stored in the
 *	controller hardware
L
Linus Torvalds 已提交
1058
 *
1059 1060 1061
 * Disables the endpoint for URB submission and nukes all pending URBs.
 * If @reset_hardware is set then also deallocates hcd/hardware state
 * for the endpoint.
L
Linus Torvalds 已提交
1062
 */
1063 1064
void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
		bool reset_hardware)
L
Linus Torvalds 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073
{
	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
	struct usb_host_endpoint *ep;

	if (!dev)
		return;

	if (usb_endpoint_out(epaddr)) {
		ep = dev->ep_out[epnum];
1074 1075
		if (reset_hardware)
			dev->ep_out[epnum] = NULL;
L
Linus Torvalds 已提交
1076 1077
	} else {
		ep = dev->ep_in[epnum];
1078 1079
		if (reset_hardware)
			dev->ep_in[epnum] = NULL;
L
Linus Torvalds 已提交
1080
	}
A
Alan Stern 已提交
1081 1082
	if (ep) {
		ep->enabled = 0;
1083
		usb_hcd_flush_endpoint(dev, ep);
1084 1085
		if (reset_hardware)
			usb_hcd_disable_endpoint(dev, ep);
A
Alan Stern 已提交
1086
	}
L
Linus Torvalds 已提交
1087 1088
}

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
/**
 * usb_reset_endpoint - Reset an endpoint's state.
 * @dev: the device whose endpoint is to be reset
 * @epaddr: the endpoint's address.  Endpoint number for output,
 *	endpoint number + USB_DIR_IN for input
 *
 * Resets any host-side endpoint state such as the toggle bit,
 * sequence number or current window.
 */
void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
{
	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
	struct usb_host_endpoint *ep;

	if (usb_endpoint_out(epaddr))
		ep = dev->ep_out[epnum];
	else
		ep = dev->ep_in[epnum];
	if (ep)
		usb_hcd_reset_endpoint(dev, ep);
}
EXPORT_SYMBOL_GPL(usb_reset_endpoint);


L
Linus Torvalds 已提交
1113 1114 1115 1116
/**
 * usb_disable_interface -- Disable all endpoints for an interface
 * @dev: the device whose interface is being disabled
 * @intf: pointer to the interface descriptor
1117 1118
 * @reset_hardware: flag to erase any endpoint state stored in the
 *	controller hardware
L
Linus Torvalds 已提交
1119 1120 1121
 *
 * Disables all the endpoints for the interface's current altsetting.
 */
1122 1123
void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
		bool reset_hardware)
L
Linus Torvalds 已提交
1124 1125 1126 1127 1128 1129
{
	struct usb_host_interface *alt = intf->cur_altsetting;
	int i;

	for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
		usb_disable_endpoint(dev,
1130 1131
				alt->endpoint[i].desc.bEndpointAddress,
				reset_hardware);
L
Linus Torvalds 已提交
1132 1133 1134
	}
}

1135
/**
L
Linus Torvalds 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
 * usb_disable_device - Disable all the endpoints for a USB device
 * @dev: the device whose endpoints are being disabled
 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
 *
 * Disables all the device's endpoints, potentially including endpoint 0.
 * Deallocates hcd/hardware state for the endpoints (nuking all or most
 * pending urbs) and usbcore state for the interfaces, so that usbcore
 * must usb_set_configuration() before any interfaces could be used.
 */
void usb_disable_device(struct usb_device *dev, int skip_ep0)
{
	int i;
1148
	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
L
Linus Torvalds 已提交
1149 1150 1151 1152 1153

	/* getting rid of interfaces will disconnect
	 * any drivers bound to them (a key side effect)
	 */
	if (dev->actconfig) {
1154 1155 1156 1157 1158 1159 1160 1161
		/*
		 * FIXME: In order to avoid self-deadlock involving the
		 * bandwidth_mutex, we have to mark all the interfaces
		 * before unregistering any of them.
		 */
		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
			dev->actconfig->interface[i]->unregistering = 1;

L
Linus Torvalds 已提交
1162 1163 1164
		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
			struct usb_interface	*interface;

1165
			/* remove this interface if it has been registered */
L
Linus Torvalds 已提交
1166
			interface = dev->actconfig->interface[i];
1167
			if (!device_is_registered(&interface->dev))
1168
				continue;
1169
			dev_dbg(&dev->dev, "unregistering interface %s\n",
1170
				dev_name(&interface->dev));
A
Alan Stern 已提交
1171
			remove_intf_ep_devs(interface);
1172
			device_del(&interface->dev);
L
Linus Torvalds 已提交
1173 1174 1175 1176 1177 1178
		}

		/* Now that the interfaces are unbound, nobody should
		 * try to access them.
		 */
		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1179
			put_device(&dev->actconfig->interface[i]->dev);
L
Linus Torvalds 已提交
1180 1181
			dev->actconfig->interface[i] = NULL;
		}
1182 1183 1184

		if (dev->usb2_hw_lpm_enabled == 1)
			usb_set_usb2_hardware_lpm(dev, 0);
1185
		usb_unlocked_disable_lpm(dev);
1186
		usb_disable_ltm(dev);
1187

L
Linus Torvalds 已提交
1188 1189 1190 1191
		dev->actconfig = NULL;
		if (dev->state == USB_STATE_CONFIGURED)
			usb_set_device_state(dev, USB_STATE_ADDRESS);
	}
1192 1193 1194

	dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
		skip_ep0 ? "non-ep0" : "all");
1195 1196 1197 1198 1199 1200 1201
	if (hcd->driver->check_bandwidth) {
		/* First pass: Cancel URBs, leave endpoint pointers intact. */
		for (i = skip_ep0; i < 16; ++i) {
			usb_disable_endpoint(dev, i, false);
			usb_disable_endpoint(dev, i + USB_DIR_IN, false);
		}
		/* Remove endpoints from the host controller internal state */
1202
		mutex_lock(hcd->bandwidth_mutex);
1203
		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1204
		mutex_unlock(hcd->bandwidth_mutex);
1205 1206
		/* Second pass: remove endpoint pointers */
	}
1207 1208 1209 1210
	for (i = skip_ep0; i < 16; ++i) {
		usb_disable_endpoint(dev, i, true);
		usb_disable_endpoint(dev, i + USB_DIR_IN, true);
	}
L
Linus Torvalds 已提交
1211 1212
}

1213
/**
L
Linus Torvalds 已提交
1214 1215 1216
 * usb_enable_endpoint - Enable an endpoint for USB communications
 * @dev: the device whose interface is being enabled
 * @ep: the endpoint
1217
 * @reset_ep: flag to reset the endpoint state
L
Linus Torvalds 已提交
1218
 *
1219
 * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
L
Linus Torvalds 已提交
1220 1221
 * For control endpoints, both the input and output sides are handled.
 */
1222
void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
1223
		bool reset_ep)
L
Linus Torvalds 已提交
1224
{
A
Alan Stern 已提交
1225 1226 1227
	int epnum = usb_endpoint_num(&ep->desc);
	int is_out = usb_endpoint_dir_out(&ep->desc);
	int is_control = usb_endpoint_xfer_control(&ep->desc);
L
Linus Torvalds 已提交
1228

1229 1230 1231
	if (reset_ep)
		usb_hcd_reset_endpoint(dev, ep);
	if (is_out || is_control)
L
Linus Torvalds 已提交
1232
		dev->ep_out[epnum] = ep;
1233
	if (!is_out || is_control)
L
Linus Torvalds 已提交
1234
		dev->ep_in[epnum] = ep;
A
Alan Stern 已提交
1235
	ep->enabled = 1;
L
Linus Torvalds 已提交
1236 1237
}

1238
/**
L
Linus Torvalds 已提交
1239 1240 1241
 * usb_enable_interface - Enable all the endpoints for an interface
 * @dev: the device whose interface is being enabled
 * @intf: pointer to the interface descriptor
1242
 * @reset_eps: flag to reset the endpoints' state
L
Linus Torvalds 已提交
1243 1244 1245
 *
 * Enables all the endpoints for the interface's current altsetting.
 */
1246
void usb_enable_interface(struct usb_device *dev,
1247
		struct usb_interface *intf, bool reset_eps)
L
Linus Torvalds 已提交
1248 1249 1250 1251 1252
{
	struct usb_host_interface *alt = intf->cur_altsetting;
	int i;

	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1253
		usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
L
Linus Torvalds 已提交
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
}

/**
 * usb_set_interface - Makes a particular alternate setting be current
 * @dev: the device whose interface is being updated
 * @interface: the interface being updated
 * @alternate: the setting being chosen.
 * Context: !in_interrupt ()
 *
 * This is used to enable data transfers on interfaces that may not
 * be enabled by default.  Not all devices support such configurability.
 * Only the driver bound to an interface may change its setting.
 *
 * Within any given configuration, each interface may have several
 * alternative settings.  These are often used to control levels of
 * bandwidth consumption.  For example, the default setting for a high
 * speed interrupt endpoint may not send more than 64 bytes per microframe,
 * while interrupt transfers of up to 3KBytes per microframe are legal.
 * Also, isochronous endpoints may never be part of an
 * interface's default setting.  To access such bandwidth, alternate
 * interface settings must be made current.
 *
 * Note that in the Linux USB subsystem, bandwidth associated with
 * an endpoint in a given alternate setting is not reserved until an URB
 * is submitted that needs that bandwidth.  Some other operating systems
 * allocate bandwidth early, when a configuration is chosen.
 *
 * This call is synchronous, and may not be used in an interrupt context.
 * Also, drivers must not change altsettings while urbs are scheduled for
 * endpoints in that interface; all such urbs must first be completed
 * (perhaps forced by unlinking).
 *
1286
 * Return: Zero on success, or else the status code returned by the
L
Linus Torvalds 已提交
1287 1288 1289 1290 1291 1292
 * underlying usb_control_msg() call.
 */
int usb_set_interface(struct usb_device *dev, int interface, int alternate)
{
	struct usb_interface *iface;
	struct usb_host_interface *alt;
1293
	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1294
	int i, ret, manual = 0;
1295 1296
	unsigned int epaddr;
	unsigned int pipe;
L
Linus Torvalds 已提交
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306

	if (dev->state == USB_STATE_SUSPENDED)
		return -EHOSTUNREACH;

	iface = usb_ifnum_to_if(dev, interface);
	if (!iface) {
		dev_dbg(&dev->dev, "selecting invalid interface %d\n",
			interface);
		return -EINVAL;
	}
1307 1308
	if (iface->unregistering)
		return -ENODEV;
L
Linus Torvalds 已提交
1309 1310 1311

	alt = usb_altnum_to_altsetting(iface, alternate);
	if (!alt) {
1312
		dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
1313
			 alternate);
L
Linus Torvalds 已提交
1314 1315 1316
		return -EINVAL;
	}

1317 1318 1319
	/* Make sure we have enough bandwidth for this alternate interface.
	 * Remove the current alt setting and add the new alt setting.
	 */
1320
	mutex_lock(hcd->bandwidth_mutex);
1321 1322 1323 1324 1325 1326 1327 1328
	/* Disable LPM, and re-enable it once the new alt setting is installed,
	 * so that the xHCI driver can recalculate the U1/U2 timeouts.
	 */
	if (usb_disable_lpm(dev)) {
		dev_err(&iface->dev, "%s Failed to disable LPM\n.", __func__);
		mutex_unlock(hcd->bandwidth_mutex);
		return -ENOMEM;
	}
1329 1330 1331 1332
	/* Changing alt-setting also frees any allocated streams */
	for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
		iface->cur_altsetting->endpoint[i].streams = 0;

1333 1334 1335 1336
	ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
	if (ret < 0) {
		dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
				alternate);
1337
		usb_enable_lpm(dev);
1338
		mutex_unlock(hcd->bandwidth_mutex);
1339 1340 1341
		return ret;
	}

1342 1343 1344 1345
	if (dev->quirks & USB_QUIRK_NO_SET_INTF)
		ret = -EPIPE;
	else
		ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
L
Linus Torvalds 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
				   USB_REQ_SET_INTERFACE, USB_RECIP_INTERFACE,
				   alternate, interface, NULL, 0, 5000);

	/* 9.4.10 says devices don't need this and are free to STALL the
	 * request if the interface only has one alternate setting.
	 */
	if (ret == -EPIPE && iface->num_altsetting == 1) {
		dev_dbg(&dev->dev,
			"manual set_interface for iface %d, alt %d\n",
			interface, alternate);
		manual = 1;
1357 1358 1359
	} else if (ret < 0) {
		/* Re-instate the old alt setting */
		usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
1360
		usb_enable_lpm(dev);
1361
		mutex_unlock(hcd->bandwidth_mutex);
L
Linus Torvalds 已提交
1362
		return ret;
1363
	}
1364
	mutex_unlock(hcd->bandwidth_mutex);
L
Linus Torvalds 已提交
1365 1366 1367 1368 1369 1370 1371 1372

	/* FIXME drivers shouldn't need to replicate/bugfix the logic here
	 * when they implement async or easily-killable versions of this or
	 * other "should-be-internal" functions (like clear_halt).
	 * should hcd+usbcore postprocess control requests?
	 */

	/* prevent submissions using previous endpoint settings */
A
Alan Stern 已提交
1373 1374
	if (iface->cur_altsetting != alt) {
		remove_intf_ep_devs(iface);
1375
		usb_remove_sysfs_intf_files(iface);
A
Alan Stern 已提交
1376
	}
1377
	usb_disable_interface(dev, iface, true);
L
Linus Torvalds 已提交
1378 1379 1380

	iface->cur_altsetting = alt;

1381 1382 1383
	/* Now that the interface is installed, re-enable LPM. */
	usb_unlocked_enable_lpm(dev);

L
Linus Torvalds 已提交
1384
	/* If the interface only has one altsetting and the device didn't
1385
	 * accept the request, we attempt to carry out the equivalent action
L
Linus Torvalds 已提交
1386 1387 1388 1389 1390 1391 1392
	 * by manually clearing the HALT feature for each endpoint in the
	 * new altsetting.
	 */
	if (manual) {
		int i;

		for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1393 1394 1395 1396 1397
			epaddr = alt->endpoint[i].desc.bEndpointAddress;
			pipe = __create_pipe(dev,
					USB_ENDPOINT_NUMBER_MASK & epaddr) |
					(usb_endpoint_out(epaddr) ?
					USB_DIR_OUT : USB_DIR_IN);
L
Linus Torvalds 已提交
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413

			usb_clear_halt(dev, pipe);
		}
	}

	/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
	 *
	 * Note:
	 * Despite EP0 is always present in all interfaces/AS, the list of
	 * endpoints from the descriptor does not contain EP0. Due to its
	 * omnipresence one might expect EP0 being considered "affected" by
	 * any SetInterface request and hence assume toggles need to be reset.
	 * However, EP0 toggles are re-synced for every individual transfer
	 * during the SETUP stage - hence EP0 toggles are "don't care" here.
	 * (Likewise, EP0 never "halts" on well designed devices.)
	 */
1414
	usb_enable_interface(dev, iface, true);
A
Alan Stern 已提交
1415
	if (device_is_registered(&iface->dev)) {
1416
		usb_create_sysfs_intf_files(iface);
A
Alan Stern 已提交
1417 1418
		create_intf_ep_devs(iface);
	}
L
Linus Torvalds 已提交
1419 1420
	return 0;
}
1421
EXPORT_SYMBOL_GPL(usb_set_interface);
L
Linus Torvalds 已提交
1422 1423 1424 1425 1426 1427 1428 1429

/**
 * usb_reset_configuration - lightweight device reset
 * @dev: the device whose configuration is being reset
 *
 * This issues a standard SET_CONFIGURATION request to the device using
 * the current configuration.  The effect is to reset most USB-related
 * state in the device, including interface altsettings (reset to zero),
1430
 * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
L
Linus Torvalds 已提交
1431 1432 1433 1434 1435
 * endpoints).  Other usbcore state is unchanged, including bindings of
 * usb device drivers to interfaces.
 *
 * Because this affects multiple interfaces, avoid using this with composite
 * (multi-interface) devices.  Instead, the driver for each interface may
1436 1437
 * use usb_set_interface() on the interfaces it claims.  Be careful though;
 * some devices don't support the SET_INTERFACE request, and others won't
1438
 * reset all the interface state (notably endpoint state).  Resetting the whole
L
Linus Torvalds 已提交
1439 1440 1441 1442
 * configuration would affect other drivers' interfaces.
 *
 * The caller must own the device lock.
 *
1443
 * Return: Zero on success, else a negative error code.
L
Linus Torvalds 已提交
1444 1445 1446 1447 1448
 */
int usb_reset_configuration(struct usb_device *dev)
{
	int			i, retval;
	struct usb_host_config	*config;
1449
	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
L
Linus Torvalds 已提交
1450 1451 1452 1453 1454 1455 1456 1457 1458 1459

	if (dev->state == USB_STATE_SUSPENDED)
		return -EHOSTUNREACH;

	/* caller must have locked the device and must own
	 * the usb bus readlock (so driver bindings are stable);
	 * calls during probe() are fine
	 */

	for (i = 1; i < 16; ++i) {
1460 1461
		usb_disable_endpoint(dev, i, true);
		usb_disable_endpoint(dev, i + USB_DIR_IN, true);
L
Linus Torvalds 已提交
1462 1463 1464
	}

	config = dev->actconfig;
1465
	retval = 0;
1466
	mutex_lock(hcd->bandwidth_mutex);
1467 1468 1469 1470 1471 1472 1473 1474
	/* Disable LPM, and re-enable it once the configuration is reset, so
	 * that the xHCI driver can recalculate the U1/U2 timeouts.
	 */
	if (usb_disable_lpm(dev)) {
		dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
		mutex_unlock(hcd->bandwidth_mutex);
		return -ENOMEM;
	}
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
	/* Make sure we have enough bandwidth for each alternate setting 0 */
	for (i = 0; i < config->desc.bNumInterfaces; i++) {
		struct usb_interface *intf = config->interface[i];
		struct usb_host_interface *alt;

		alt = usb_altnum_to_altsetting(intf, 0);
		if (!alt)
			alt = &intf->altsetting[0];
		if (alt != intf->cur_altsetting)
			retval = usb_hcd_alloc_bandwidth(dev, NULL,
					intf->cur_altsetting, alt);
		if (retval < 0)
			break;
	}
	/* If not, reinstate the old alternate settings */
	if (retval < 0) {
reset_old_alts:
1492
		for (i--; i >= 0; i--) {
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
			struct usb_interface *intf = config->interface[i];
			struct usb_host_interface *alt;

			alt = usb_altnum_to_altsetting(intf, 0);
			if (!alt)
				alt = &intf->altsetting[0];
			if (alt != intf->cur_altsetting)
				usb_hcd_alloc_bandwidth(dev, NULL,
						alt, intf->cur_altsetting);
		}
1503
		usb_enable_lpm(dev);
1504
		mutex_unlock(hcd->bandwidth_mutex);
1505 1506
		return retval;
	}
L
Linus Torvalds 已提交
1507 1508 1509 1510
	retval = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
			USB_REQ_SET_CONFIGURATION, 0,
			config->desc.bConfigurationValue, 0,
			NULL, 0, USB_CTRL_SET_TIMEOUT);
1511
	if (retval < 0)
1512
		goto reset_old_alts;
1513
	mutex_unlock(hcd->bandwidth_mutex);
L
Linus Torvalds 已提交
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529

	/* re-init hc/hcd interface/endpoint state */
	for (i = 0; i < config->desc.bNumInterfaces; i++) {
		struct usb_interface *intf = config->interface[i];
		struct usb_host_interface *alt;

		alt = usb_altnum_to_altsetting(intf, 0);

		/* No altsetting 0?  We'll assume the first altsetting.
		 * We could use a GetInterface call, but if a device is
		 * so non-compliant that it doesn't have altsetting 0
		 * then I wouldn't trust its reply anyway.
		 */
		if (!alt)
			alt = &intf->altsetting[0];

A
Alan Stern 已提交
1530 1531 1532 1533
		if (alt != intf->cur_altsetting) {
			remove_intf_ep_devs(intf);
			usb_remove_sysfs_intf_files(intf);
		}
L
Linus Torvalds 已提交
1534
		intf->cur_altsetting = alt;
1535
		usb_enable_interface(dev, intf, true);
A
Alan Stern 已提交
1536
		if (device_is_registered(&intf->dev)) {
1537
			usb_create_sysfs_intf_files(intf);
A
Alan Stern 已提交
1538 1539
			create_intf_ep_devs(intf);
		}
L
Linus Torvalds 已提交
1540
	}
1541 1542
	/* Now that the interfaces are installed, re-enable LPM. */
	usb_unlocked_enable_lpm(dev);
L
Linus Torvalds 已提交
1543 1544
	return 0;
}
1545
EXPORT_SYMBOL_GPL(usb_reset_configuration);
L
Linus Torvalds 已提交
1546

1547
static void usb_release_interface(struct device *dev)
L
Linus Torvalds 已提交
1548 1549 1550 1551 1552 1553 1554 1555 1556
{
	struct usb_interface *intf = to_usb_interface(dev);
	struct usb_interface_cache *intfc =
			altsetting_to_usb_interface_cache(intf->altsetting);

	kref_put(&intfc->ref, usb_release_interface_cache);
	kfree(intf);
}

1557
static int usb_if_uevent(struct device *dev, struct kobj_uevent_env *env)
1558 1559 1560 1561 1562 1563 1564 1565 1566
{
	struct usb_device *usb_dev;
	struct usb_interface *intf;
	struct usb_host_interface *alt;

	intf = to_usb_interface(dev);
	usb_dev = interface_to_usbdev(intf);
	alt = intf->cur_altsetting;

1567
	if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
1568 1569 1570 1571 1572
		   alt->desc.bInterfaceClass,
		   alt->desc.bInterfaceSubClass,
		   alt->desc.bInterfaceProtocol))
		return -ENOMEM;

1573
	if (add_uevent_var(env,
1574
		   "MODALIAS=usb:"
1575
		   "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
1576 1577 1578 1579 1580 1581 1582 1583
		   le16_to_cpu(usb_dev->descriptor.idVendor),
		   le16_to_cpu(usb_dev->descriptor.idProduct),
		   le16_to_cpu(usb_dev->descriptor.bcdDevice),
		   usb_dev->descriptor.bDeviceClass,
		   usb_dev->descriptor.bDeviceSubClass,
		   usb_dev->descriptor.bDeviceProtocol,
		   alt->desc.bInterfaceClass,
		   alt->desc.bInterfaceSubClass,
1584 1585
		   alt->desc.bInterfaceProtocol,
		   alt->desc.bInterfaceNumber))
1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
		return -ENOMEM;

	return 0;
}

struct device_type usb_if_device_type = {
	.name =		"usb_interface",
	.release =	usb_release_interface,
	.uevent =	usb_if_uevent,
};

1597
static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1598 1599
						struct usb_host_config *config,
						u8 inum)
1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
{
	struct usb_interface_assoc_descriptor *retval = NULL;
	struct usb_interface_assoc_descriptor *intf_assoc;
	int first_intf;
	int last_intf;
	int i;

	for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
		intf_assoc = config->intf_assoc[i];
		if (intf_assoc->bInterfaceCount == 0)
			continue;

		first_intf = intf_assoc->bFirstInterface;
		last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
		if (inum >= first_intf && inum <= last_intf) {
			if (!retval)
				retval = intf_assoc;
			else
				dev_err(&dev->dev, "Interface #%d referenced"
					" by multiple IADs\n", inum);
		}
	}

	return retval;
}

1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648

/*
 * Internal function to queue a device reset
 *
 * This is initialized into the workstruct in 'struct
 * usb_device->reset_ws' that is launched by
 * message.c:usb_set_configuration() when initializing each 'struct
 * usb_interface'.
 *
 * It is safe to get the USB device without reference counts because
 * the life cycle of @iface is bound to the life cycle of @udev. Then,
 * this function will be ran only if @iface is alive (and before
 * freeing it any scheduled instances of it will have been cancelled).
 *
 * We need to set a flag (usb_dev->reset_running) because when we call
 * the reset, the interfaces might be unbound. The current interface
 * cannot try to remove the queued work as it would cause a deadlock
 * (you cannot remove your work from within your executing
 * workqueue). This flag lets it know, so that
 * usb_cancel_queued_reset() doesn't try to do it.
 *
 * See usb_queue_reset_device() for more details
 */
1649
static void __usb_queue_reset_device(struct work_struct *ws)
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665
{
	int rc;
	struct usb_interface *iface =
		container_of(ws, struct usb_interface, reset_ws);
	struct usb_device *udev = interface_to_usbdev(iface);

	rc = usb_lock_device_for_reset(udev, iface);
	if (rc >= 0) {
		iface->reset_running = 1;
		usb_reset_device(udev);
		iface->reset_running = 0;
		usb_unlock_device(udev);
	}
}


L
Linus Torvalds 已提交
1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
/*
 * usb_set_configuration - Makes a particular device setting be current
 * @dev: the device whose configuration is being updated
 * @configuration: the configuration being chosen.
 * Context: !in_interrupt(), caller owns the device lock
 *
 * This is used to enable non-default device modes.  Not all devices
 * use this kind of configurability; many devices only have one
 * configuration.
 *
1676 1677 1678 1679 1680 1681 1682 1683
 * @configuration is the value of the configuration to be installed.
 * According to the USB spec (e.g. section 9.1.1.5), configuration values
 * must be non-zero; a value of zero indicates that the device in
 * unconfigured.  However some devices erroneously use 0 as one of their
 * configuration values.  To help manage such devices, this routine will
 * accept @configuration = -1 as indicating the device should be put in
 * an unconfigured state.
 *
L
Linus Torvalds 已提交
1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
 * USB device configurations may affect Linux interoperability,
 * power consumption and the functionality available.  For example,
 * the default configuration is limited to using 100mA of bus power,
 * so that when certain device functionality requires more power,
 * and the device is bus powered, that functionality should be in some
 * non-default device configuration.  Other device modes may also be
 * reflected as configuration options, such as whether two ISDN
 * channels are available independently; and choosing between open
 * standard device protocols (like CDC) or proprietary ones.
 *
1694 1695 1696
 * Note that a non-authorized device (dev->authorized == 0) will only
 * be put in unconfigured mode.
 *
L
Linus Torvalds 已提交
1697 1698 1699 1700 1701 1702
 * Note that USB has an additional level of device configurability,
 * associated with interfaces.  That configurability is accessed using
 * usb_set_interface().
 *
 * This call is synchronous. The calling context must be able to sleep,
 * must own the device lock, and must not hold the driver model's USB
1703
 * bus mutex; usb interface driver probe() methods cannot use this routine.
L
Linus Torvalds 已提交
1704 1705
 *
 * Returns zero on success, or else the status code returned by the
1706
 * underlying call that failed.  On successful completion, each interface
L
Linus Torvalds 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715
 * in the original device configuration has been destroyed, and each one
 * in the new configuration has been probed by all relevant usb device
 * drivers currently known to the kernel.
 */
int usb_set_configuration(struct usb_device *dev, int configuration)
{
	int i, ret;
	struct usb_host_config *cp = NULL;
	struct usb_interface **new_interfaces = NULL;
1716
	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
L
Linus Torvalds 已提交
1717 1718
	int n, nintf;

1719
	if (dev->authorized == 0 || configuration == -1)
1720 1721 1722 1723 1724 1725 1726 1727
		configuration = 0;
	else {
		for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
			if (dev->config[i].desc.bConfigurationValue ==
					configuration) {
				cp = &dev->config[i];
				break;
			}
L
Linus Torvalds 已提交
1728 1729 1730 1731 1732 1733 1734 1735
		}
	}
	if ((!cp && configuration != 0))
		return -EINVAL;

	/* The USB spec says configuration 0 means unconfigured.
	 * But if a device includes a configuration numbered 0,
	 * we will accept it as a correctly configured state.
1736
	 * Use -1 if you really want to unconfigure the device.
L
Linus Torvalds 已提交
1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
	 */
	if (cp && configuration == 0)
		dev_warn(&dev->dev, "config 0 descriptor??\n");

	/* Allocate memory for new interfaces before doing anything else,
	 * so that if we run out then nothing will have changed. */
	n = nintf = 0;
	if (cp) {
		nintf = cp->desc.bNumInterfaces;
		new_interfaces = kmalloc(nintf * sizeof(*new_interfaces),
1747
				GFP_NOIO);
L
Linus Torvalds 已提交
1748
		if (!new_interfaces) {
1749
			dev_err(&dev->dev, "Out of memory\n");
L
Linus Torvalds 已提交
1750 1751 1752 1753
			return -ENOMEM;
		}

		for (; n < nintf; ++n) {
1754
			new_interfaces[n] = kzalloc(
L
Linus Torvalds 已提交
1755
					sizeof(struct usb_interface),
1756
					GFP_NOIO);
L
Linus Torvalds 已提交
1757
			if (!new_interfaces[n]) {
1758
				dev_err(&dev->dev, "Out of memory\n");
L
Linus Torvalds 已提交
1759 1760 1761 1762 1763 1764 1765 1766 1767
				ret = -ENOMEM;
free_interfaces:
				while (--n >= 0)
					kfree(new_interfaces[n]);
				kfree(new_interfaces);
				return ret;
			}
		}

1768
		i = dev->bus_mA - usb_get_max_power(dev, cp);
1769 1770 1771 1772 1773
		if (i < 0)
			dev_warn(&dev->dev, "new config #%d exceeds power "
					"limit by %dmA\n",
					configuration, -i);
	}
1774

1775
	/* Wake up the device so we can send it the Set-Config request */
1776
	ret = usb_autoresume_device(dev);
1777 1778 1779
	if (ret)
		goto free_interfaces;

1780 1781 1782 1783 1784 1785 1786 1787 1788
	/* if it's already configured, clear out old state first.
	 * getting rid of old interfaces means unbinding their drivers.
	 */
	if (dev->state != USB_STATE_ADDRESS)
		usb_disable_device(dev, 1);	/* Skip ep0 */

	/* Get rid of pending async Set-Config requests for this device */
	cancel_async_set_config(dev);

1789 1790 1791 1792 1793 1794
	/* Make sure we have bandwidth (and available HCD resources) for this
	 * configuration.  Remove endpoints from the schedule if we're dropping
	 * this configuration to set configuration 0.  After this point, the
	 * host controller will not allow submissions to dropped endpoints.  If
	 * this call fails, the device state is unchanged.
	 */
1795
	mutex_lock(hcd->bandwidth_mutex);
1796 1797 1798 1799
	/* Disable LPM, and re-enable it once the new configuration is
	 * installed, so that the xHCI driver can recalculate the U1/U2
	 * timeouts.
	 */
1800
	if (dev->actconfig && usb_disable_lpm(dev)) {
1801 1802
		dev_err(&dev->dev, "%s Failed to disable LPM\n.", __func__);
		mutex_unlock(hcd->bandwidth_mutex);
1803 1804
		ret = -ENOMEM;
		goto free_interfaces;
1805
	}
1806
	ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
1807
	if (ret < 0) {
1808 1809
		if (dev->actconfig)
			usb_enable_lpm(dev);
1810
		mutex_unlock(hcd->bandwidth_mutex);
1811
		usb_autosuspend_device(dev);
1812 1813 1814
		goto free_interfaces;
	}

1815 1816
	/*
	 * Initialize the new interface structures and the
1817 1818 1819 1820 1821 1822
	 * hc/hcd/usbcore interface/endpoint state.
	 */
	for (i = 0; i < nintf; ++i) {
		struct usb_interface_cache *intfc;
		struct usb_interface *intf;
		struct usb_host_interface *alt;
L
Linus Torvalds 已提交
1823

1824 1825 1826 1827 1828
		cp->interface[i] = intf = new_interfaces[i];
		intfc = cp->intf_cache[i];
		intf->altsetting = intfc->altsetting;
		intf->num_altsetting = intfc->num_altsetting;
		kref_get(&intfc->ref);
L
Linus Torvalds 已提交
1829

1830 1831 1832 1833 1834 1835
		alt = usb_altnum_to_altsetting(intf, 0);

		/* No altsetting 0?  We'll assume the first altsetting.
		 * We could use a GetInterface call, but if a device is
		 * so non-compliant that it doesn't have altsetting 0
		 * then I wouldn't trust its reply anyway.
L
Linus Torvalds 已提交
1836
		 */
1837 1838 1839
		if (!alt)
			alt = &intf->altsetting[0];

1840 1841
		intf->intf_assoc =
			find_iad(dev, cp, alt->desc.bInterfaceNumber);
1842
		intf->cur_altsetting = alt;
1843
		usb_enable_interface(dev, intf, true);
1844 1845 1846
		intf->dev.parent = &dev->dev;
		intf->dev.driver = NULL;
		intf->dev.bus = &usb_bus_type;
1847
		intf->dev.type = &usb_if_device_type;
1848
		intf->dev.groups = usb_interface_groups;
1849
		intf->dev.dma_mask = dev->dev.dma_mask;
1850
		INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
1851
		intf->minor = -1;
1852
		device_initialize(&intf->dev);
1853
		pm_runtime_no_callbacks(&intf->dev);
1854
		dev_set_name(&intf->dev, "%d-%s:%d.%d",
1855 1856
			dev->bus->busnum, dev->devpath,
			configuration, alt->desc.bInterfaceNumber);
1857 1858 1859
	}
	kfree(new_interfaces);

1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
	ret = usb_control_msg(dev, usb_sndctrlpipe(dev, 0),
			      USB_REQ_SET_CONFIGURATION, 0, configuration, 0,
			      NULL, 0, USB_CTRL_SET_TIMEOUT);
	if (ret < 0 && cp) {
		/*
		 * All the old state is gone, so what else can we do?
		 * The device is probably useless now anyway.
		 */
		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
		for (i = 0; i < nintf; ++i) {
			usb_disable_interface(dev, cp->interface[i], true);
			put_device(&cp->interface[i]->dev);
			cp->interface[i] = NULL;
		}
		cp = NULL;
	}

	dev->actconfig = cp;
	mutex_unlock(hcd->bandwidth_mutex);

	if (!cp) {
		usb_set_device_state(dev, USB_STATE_ADDRESS);

		/* Leave LPM disabled while the device is unconfigured. */
		usb_autosuspend_device(dev);
		return ret;
	}
	usb_set_device_state(dev, USB_STATE_CONFIGURED);

1889 1890
	if (cp->string == NULL &&
			!(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
1891 1892
		cp->string = usb_cache_string(dev, cp->desc.iConfiguration);

1893 1894
	/* Now that the interfaces are installed, re-enable LPM. */
	usb_unlocked_enable_lpm(dev);
1895 1896
	/* Enable LTM if it was turned off by usb_disable_device. */
	usb_enable_ltm(dev);
1897

1898 1899 1900 1901 1902 1903 1904 1905 1906
	/* Now that all the interfaces are set up, register them
	 * to trigger binding of drivers to interfaces.  probe()
	 * routines may install different altsettings and may
	 * claim() any interfaces not yet bound.  Many class drivers
	 * need that: CDC, audio, video, etc.
	 */
	for (i = 0; i < nintf; ++i) {
		struct usb_interface *intf = cp->interface[i];

1907
		dev_dbg(&dev->dev,
1908
			"adding %s (config #%d, interface %d)\n",
1909
			dev_name(&intf->dev), configuration,
1910
			intf->cur_altsetting->desc.bInterfaceNumber);
1911
		device_enable_async_suspend(&intf->dev);
1912
		ret = device_add(&intf->dev);
1913 1914
		if (ret != 0) {
			dev_err(&dev->dev, "device_add(%s) --> %d\n",
1915
				dev_name(&intf->dev), ret);
1916
			continue;
L
Linus Torvalds 已提交
1917
		}
A
Alan Stern 已提交
1918
		create_intf_ep_devs(intf);
L
Linus Torvalds 已提交
1919 1920
	}

1921
	usb_autosuspend_device(dev);
1922
	return 0;
L
Linus Torvalds 已提交
1923
}
1924
EXPORT_SYMBOL_GPL(usb_set_configuration);
L
Linus Torvalds 已提交
1925

1926 1927 1928
static LIST_HEAD(set_config_list);
static DEFINE_SPINLOCK(set_config_lock);

1929 1930 1931 1932
struct set_config_request {
	struct usb_device	*udev;
	int			config;
	struct work_struct	work;
1933
	struct list_head	node;
1934 1935 1936
};

/* Worker routine for usb_driver_set_configuration() */
D
David Howells 已提交
1937
static void driver_set_config_work(struct work_struct *work)
1938
{
D
David Howells 已提交
1939 1940
	struct set_config_request *req =
		container_of(work, struct set_config_request, work);
1941
	struct usb_device *udev = req->udev;
1942

1943 1944 1945 1946 1947 1948 1949 1950 1951
	usb_lock_device(udev);
	spin_lock(&set_config_lock);
	list_del(&req->node);
	spin_unlock(&set_config_lock);

	if (req->config >= -1)		/* Is req still valid? */
		usb_set_configuration(udev, req->config);
	usb_unlock_device(udev);
	usb_put_dev(udev);
1952 1953 1954
	kfree(req);
}

1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
/* Cancel pending Set-Config requests for a device whose configuration
 * was just changed
 */
static void cancel_async_set_config(struct usb_device *udev)
{
	struct set_config_request *req;

	spin_lock(&set_config_lock);
	list_for_each_entry(req, &set_config_list, node) {
		if (req->udev == udev)
			req->config = -999;	/* Mark as cancelled */
	}
	spin_unlock(&set_config_lock);
}

1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
/**
 * usb_driver_set_configuration - Provide a way for drivers to change device configurations
 * @udev: the device whose configuration is being updated
 * @config: the configuration being chosen.
 * Context: In process context, must be able to sleep
 *
 * Device interface drivers are not allowed to change device configurations.
 * This is because changing configurations will destroy the interface the
 * driver is bound to and create new ones; it would be like a floppy-disk
 * driver telling the computer to replace the floppy-disk drive with a
 * tape drive!
 *
 * Still, in certain specialized circumstances the need may arise.  This
 * routine gets around the normal restrictions by using a work thread to
 * submit the change-config request.
 *
1986
 * Return: 0 if the request was successfully queued, error code otherwise.
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
 * The caller has no way to know whether the queued request will eventually
 * succeed.
 */
int usb_driver_set_configuration(struct usb_device *udev, int config)
{
	struct set_config_request *req;

	req = kmalloc(sizeof(*req), GFP_KERNEL);
	if (!req)
		return -ENOMEM;
	req->udev = udev;
	req->config = config;
D
David Howells 已提交
1999
	INIT_WORK(&req->work, driver_set_config_work);
2000

2001 2002 2003 2004
	spin_lock(&set_config_lock);
	list_add(&req->node, &set_config_list);
	spin_unlock(&set_config_lock);

2005
	usb_get_dev(udev);
2006
	schedule_work(&req->work);
2007 2008 2009
	return 0;
}
EXPORT_SYMBOL_GPL(usb_driver_set_configuration);