File Index
Files and directories
Sign in
FILE

message.c

File preview with syntax highlighting.

linux-6.19.14/drivers/usb/core/message.c C
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * message.c - synchronous message handling
   4 *
   5 * Released under the GPLv2 only.
   6 */
   7
   8#include <linux/acpi.h>
   9#include <linux/pci.h>	/* for scatterlist macros */
  10#include <linux/usb.h>
  11#include <linux/module.h>
  12#include <linux/of.h>
  13#include <linux/slab.h>
  14#include <linux/mm.h>
  15#include <linux/timer.h>
  16#include <linux/ctype.h>
  17#include <linux/nls.h>
  18#include <linux/device.h>
  19#include <linux/scatterlist.h>
  20#include <linux/usb/cdc.h>
  21#include <linux/usb/quirks.h>
  22#include <linux/usb/hcd.h>	/* for usbcore internals */
  23#include <linux/usb/of.h>
  24#include <asm/byteorder.h>
  25
  26#include "usb.h"
  27
  28static void cancel_async_set_config(struct usb_device *udev);
  29
  30struct api_context {
  31	struct completion	done;
  32	int			status;
  33};
  34
  35static void usb_api_blocking_completion(struct urb *urb)
  36{
  37	struct api_context *ctx = urb->context;
  38
  39	ctx->status = urb->status;
  40	complete(&ctx->done);
  41}
  42
  43
  44/*
  45 * Starts urb and waits for completion or timeout.
  46 * Whether or not the wait is killable depends on the flag passed in.
  47 * For example, compare usb_bulk_msg() and usb_bulk_msg_killable().
  48 *
  49 * For non-killable waits, we enforce a maximum limit on the timeout value.
  50 */
  51static int usb_start_wait_urb(struct urb *urb, int timeout, int *actual_length,
  52		bool killable)
  53{
  54	struct api_context ctx;
  55	unsigned long expire;
  56	int retval;
  57	long rc;
  58
  59	init_completion(&ctx.done);
  60	urb->context = &ctx;
  61	urb->actual_length = 0;
  62	retval = usb_submit_urb(urb, GFP_NOIO);
  63	if (unlikely(retval))
  64		goto out;
  65
  66	if (!killable && (timeout <= 0 || timeout > USB_MAX_SYNCHRONOUS_TIMEOUT))
  67		timeout = USB_MAX_SYNCHRONOUS_TIMEOUT;
  68	expire = (timeout > 0) ? msecs_to_jiffies(timeout) : MAX_SCHEDULE_TIMEOUT;
  69	if (killable)
  70		rc = wait_for_completion_killable_timeout(&ctx.done, expire);
  71	else
  72		rc = wait_for_completion_timeout(&ctx.done, expire);
  73	if (rc <= 0) {
  74		usb_kill_urb(urb);
  75		if (ctx.status != -ENOENT)
  76			retval = ctx.status;
  77		else if (rc == 0)
  78			retval = -ETIMEDOUT;
  79		else
  80			retval = rc;
  81
  82		dev_dbg(&urb->dev->dev,
  83			"%s timed out or killed on ep%d%s len=%u/%u\n",
  84			current->comm,
  85			usb_endpoint_num(&urb->ep->desc),
  86			usb_urb_dir_in(urb) ? "in" : "out",
  87			urb->actual_length,
  88			urb->transfer_buffer_length);
  89	} else
  90		retval = ctx.status;
  91out:
  92	if (actual_length)
  93		*actual_length = urb->actual_length;
  94
  95	usb_free_urb(urb);
  96	return retval;
  97}
  98
  99/*-------------------------------------------------------------------*/
 100/* returns status (negative) or length (positive) */
 101static int usb_internal_control_msg(struct usb_device *usb_dev,
 102				    unsigned int pipe,
 103				    struct usb_ctrlrequest *cmd,
 104				    void *data, int len, int timeout)
 105{
 106	struct urb *urb;
 107	int retv;
 108	int length;
 109
 110	urb = usb_alloc_urb(0, GFP_NOIO);
 111	if (!urb)
 112		return -ENOMEM;
 113
 114	usb_fill_control_urb(urb, usb_dev, pipe, (unsigned char *)cmd, data,
 115			     len, usb_api_blocking_completion, NULL);
 116
 117	retv = usb_start_wait_urb(urb, timeout, &length, false);
 118	if (retv < 0)
 119		return retv;
 120	else
 121		return length;
 122}
 123
 124/**
 125 * usb_control_msg - Builds a control urb, sends it off and waits for completion
 126 * @dev: pointer to the usb device to send the message to
 127 * @pipe: endpoint "pipe" to send the message to
 128 * @request: USB message request value
 129 * @requesttype: USB message request type value
 130 * @value: USB message value
 131 * @index: USB message index value
 132 * @data: pointer to the data to send
 133 * @size: length in bytes of the data to send
 134 * @timeout: time in msecs to wait for the message to complete before timing out
 135 *
 136 * Context: task context, might sleep.
 137 *
 138 * This function sends a simple control message to a specified endpoint and
 139 * waits for the message to complete, or timeout.
 140 *
 141 * Don't use this function from within an interrupt context. If you need
 142 * an asynchronous message, or need to send a message from within interrupt
 143 * context, use usb_submit_urb(). If a thread in your driver uses this call,
 144 * make sure your disconnect() method can wait for it to complete. Since you
 145 * don't have a handle on the URB used, you can't cancel the request.
 146 *
 147 * Return: If successful, the number of bytes transferred. Otherwise, a negative
 148 * error number.
 149 */
 150int usb_control_msg(struct usb_device *dev, unsigned int pipe, __u8 request,
 151		    __u8 requesttype, __u16 value, __u16 index, void *data,
 152		    __u16 size, int timeout)
 153{
 154	struct usb_ctrlrequest *dr;
 155	int ret;
 156
 157	dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_NOIO);
 158	if (!dr)
 159		return -ENOMEM;
 160
 161	dr->bRequestType = requesttype;
 162	dr->bRequest = request;
 163	dr->wValue = cpu_to_le16(value);
 164	dr->wIndex = cpu_to_le16(index);
 165	dr->wLength = cpu_to_le16(size);
 166
 167	ret = usb_internal_control_msg(dev, pipe, dr, data, size, timeout);
 168
 169	/* Linger a bit, prior to the next control message. */
 170	if (dev->quirks & USB_QUIRK_DELAY_CTRL_MSG)
 171		msleep(200);
 172
 173	kfree(dr);
 174
 175	return ret;
 176}
 177EXPORT_SYMBOL_GPL(usb_control_msg);
 178
 179/**
 180 * usb_control_msg_send - Builds a control "send" message, sends it off and waits for completion
 181 * @dev: pointer to the usb device to send the message to
 182 * @endpoint: endpoint to send the message to
 183 * @request: USB message request value
 184 * @requesttype: USB message request type value
 185 * @value: USB message value
 186 * @index: USB message index value
 187 * @driver_data: pointer to the data to send
 188 * @size: length in bytes of the data to send
 189 * @timeout: time in msecs to wait for the message to complete before timing out
 190 * @memflags: the flags for memory allocation for buffers
 191 *
 192 * Context: !in_interrupt ()
 193 *
 194 * This function sends a control message to a specified endpoint that is not
 195 * expected to fill in a response (i.e. a "send message") and waits for the
 196 * message to complete, or timeout.
 197 *
 198 * Do not use this function from within an interrupt context. If you need
 199 * an asynchronous message, or need to send a message from within interrupt
 200 * context, use usb_submit_urb(). If a thread in your driver uses this call,
 201 * make sure your disconnect() method can wait for it to complete. Since you
 202 * don't have a handle on the URB used, you can't cancel the request.
 203 *
 204 * The data pointer can be made to a reference on the stack, or anywhere else,
 205 * as it will not be modified at all.  This does not have the restriction that
 206 * usb_control_msg() has where the data pointer must be to dynamically allocated
 207 * memory (i.e. memory that can be successfully DMAed to a device).
 208 *
 209 * Return: If successful, 0 is returned, Otherwise, a negative error number.
 210 */
 211int usb_control_msg_send(struct usb_device *dev, __u8 endpoint, __u8 request,
 212			 __u8 requesttype, __u16 value, __u16 index,
 213			 const void *driver_data, __u16 size, int timeout,
 214			 gfp_t memflags)
 215{
 216	unsigned int pipe = usb_sndctrlpipe(dev, endpoint);
 217	int ret;
 218	u8 *data = NULL;
 219
 220	if (size) {
 221		data = kmemdup(driver_data, size, memflags);
 222		if (!data)
 223			return -ENOMEM;
 224	}
 225
 226	ret = usb_control_msg(dev, pipe, request, requesttype, value, index,
 227			      data, size, timeout);
 228	kfree(data);
 229
 230	if (ret < 0)
 231		return ret;
 232
 233	return 0;
 234}
 235EXPORT_SYMBOL_GPL(usb_control_msg_send);
 236
 237/**
 238 * usb_control_msg_recv - Builds a control "receive" message, sends it off and waits for completion
 239 * @dev: pointer to the usb device to send the message to
 240 * @endpoint: endpoint to send the message to
 241 * @request: USB message request value
 242 * @requesttype: USB message request type value
 243 * @value: USB message value
 244 * @index: USB message index value
 245 * @driver_data: pointer to the data to be filled in by the message
 246 * @size: length in bytes of the data to be received
 247 * @timeout: time in msecs to wait for the message to complete before timing out
 248 * @memflags: the flags for memory allocation for buffers
 249 *
 250 * Context: !in_interrupt ()
 251 *
 252 * This function sends a control message to a specified endpoint that is
 253 * expected to fill in a response (i.e. a "receive message") and waits for the
 254 * message to complete, or timeout.
 255 *
 256 * Do not use this function from within an interrupt context. If you need
 257 * an asynchronous message, or need to send a message from within interrupt
 258 * context, use usb_submit_urb(). If a thread in your driver uses this call,
 259 * make sure your disconnect() method can wait for it to complete. Since you
 260 * don't have a handle on the URB used, you can't cancel the request.
 261 *
 262 * The data pointer can be made to a reference on the stack, or anywhere else
 263 * that can be successfully written to.  This function does not have the
 264 * restriction that usb_control_msg() has where the data pointer must be to
 265 * dynamically allocated memory (i.e. memory that can be successfully DMAed to a
 266 * device).
 267 *
 268 * The "whole" message must be properly received from the device in order for
 269 * this function to be successful.  If a device returns less than the expected
 270 * amount of data, then the function will fail.  Do not use this for messages
 271 * where a variable amount of data might be returned.
 272 *
 273 * Return: If successful, 0 is returned, Otherwise, a negative error number.
 274 */
 275int usb_control_msg_recv(struct usb_device *dev, __u8 endpoint, __u8 request,
 276			 __u8 requesttype, __u16 value, __u16 index,
 277			 void *driver_data, __u16 size, int timeout,
 278			 gfp_t memflags)
 279{
 280	unsigned int pipe = usb_rcvctrlpipe(dev, endpoint);
 281	int ret;
 282	u8 *data;
 283
 284	if (!size || !driver_data)
 285		return -EINVAL;
 286
 287	data = kmalloc(size, memflags);
 288	if (!data)
 289		return -ENOMEM;
 290
 291	ret = usb_control_msg(dev, pipe, request, requesttype, value, index,
 292			      data, size, timeout);
 293
 294	if (ret < 0)
 295		goto exit;
 296
 297	if (ret == size) {
 298		memcpy(driver_data, data, size);
 299		ret = 0;
 300	} else {
 301		ret = -EREMOTEIO;
 302	}
 303
 304exit:
 305	kfree(data);
 306	return ret;
 307}
 308EXPORT_SYMBOL_GPL(usb_control_msg_recv);
 309
 310/**
 311 * usb_interrupt_msg - Builds an interrupt urb, sends it off and waits for completion
 312 * @usb_dev: pointer to the usb device to send the message to
 313 * @pipe: endpoint "pipe" to send the message to
 314 * @data: pointer to the data to send
 315 * @len: length in bytes of the data to send
 316 * @actual_length: pointer to a location to put the actual length transferred
 317 *	in bytes
 318 * @timeout: time in msecs to wait for the message to complete before timing out
 319 *
 320 * Context: task context, might sleep.
 321 *
 322 * This function sends a simple interrupt message to a specified endpoint and
 323 * waits for the message to complete, or timeout.
 324 *
 325 * Don't use this function from within an interrupt context. If you need
 326 * an asynchronous message, or need to send a message from within interrupt
 327 * context, use usb_submit_urb() If a thread in your driver uses this call,
 328 * make sure your disconnect() method can wait for it to complete. Since you
 329 * don't have a handle on the URB used, you can't cancel the request.
 330 *
 331 * Return:
 332 * If successful, 0. Otherwise a negative error number. The number of actual
 333 * bytes transferred will be stored in the @actual_length parameter.
 334 */
 335int usb_interrupt_msg(struct usb_device *usb_dev, unsigned int pipe,
 336		      void *data, int len, int *actual_length, int timeout)
 337{
 338	return usb_bulk_msg(usb_dev, pipe, data, len, actual_length, timeout);
 339}
 340EXPORT_SYMBOL_GPL(usb_interrupt_msg);
 341
 342/**
 343 * usb_bulk_msg - Builds a bulk urb, sends it off and waits for completion
 344 * @usb_dev: pointer to the usb device to send the message to
 345 * @pipe: endpoint "pipe" to send the message to
 346 * @data: pointer to the data to send
 347 * @len: length in bytes of the data to send
 348 * @actual_length: pointer to a location to put the actual length transferred
 349 *	in bytes
 350 * @timeout: time in msecs to wait for the message to complete before timing out
 351 *
 352 * Context: task context, might sleep.
 353 *
 354 * This function sends a simple bulk message to a specified endpoint
 355 * and waits for the message to complete, or timeout.
 356 *
 357 * Don't use this function from within an interrupt context. If you need
 358 * an asynchronous message, or need to send a message from within interrupt
 359 * context, use usb_submit_urb() If a thread in your driver uses this call,
 360 * make sure your disconnect() method can wait for it to complete. Since you
 361 * don't have a handle on the URB used, you can't cancel the request.
 362 *
 363 * Because there is no usb_interrupt_msg() and no USBDEVFS_INTERRUPT ioctl,
 364 * users are forced to abuse this routine by using it to submit URBs for
 365 * interrupt endpoints.  We will take the liberty of creating an interrupt URB
 366 * (with the default interval) if the target is an interrupt endpoint.
 367 *
 368 * Return:
 369 * If successful, 0. Otherwise a negative error number. The number of actual
 370 * bytes transferred will be stored in the @actual_length parameter.
 371 *
 372 */
 373int usb_bulk_msg(struct usb_device *usb_dev, unsigned int pipe,
 374		 void *data, int len, int *actual_length, int timeout)
 375{
 376	struct urb *urb;
 377	struct usb_host_endpoint *ep;
 378
 379	ep = usb_pipe_endpoint(usb_dev, pipe);
 380	if (!ep || len < 0)
 381		return -EINVAL;
 382
 383	urb = usb_alloc_urb(0, GFP_KERNEL);
 384	if (!urb)
 385		return -ENOMEM;
 386
 387	if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
 388			USB_ENDPOINT_XFER_INT) {
 389		pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
 390		usb_fill_int_urb(urb, usb_dev, pipe, data, len,
 391				usb_api_blocking_completion, NULL,
 392				ep->desc.bInterval);
 393	} else
 394		usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
 395				usb_api_blocking_completion, NULL);
 396
 397	return usb_start_wait_urb(urb, timeout, actual_length, false);
 398}
 399EXPORT_SYMBOL_GPL(usb_bulk_msg);
 400
 401/**
 402 * usb_bulk_msg_killable - Builds a bulk urb, sends it off and waits for completion in a killable state
 403 * @usb_dev: pointer to the usb device to send the message to
 404 * @pipe: endpoint "pipe" to send the message to
 405 * @data: pointer to the data to send
 406 * @len: length in bytes of the data to send
 407 * @actual_length: pointer to a location to put the actual length transferred
 408 *	in bytes
 409 * @timeout: time in msecs to wait for the message to complete before
 410 *	timing out (if <= 0, the wait is as long as possible)
 411 *
 412 * Context: task context, might sleep.
 413 *
 414 * This function is just like usb_blk_msg(), except that it waits in a
 415 * killable state and there is no limit on the timeout length.
 416 *
 417 * Return:
 418 * If successful, 0. Otherwise a negative error number. The number of actual
 419 * bytes transferred will be stored in the @actual_length parameter.
 420 *
 421 */
 422int usb_bulk_msg_killable(struct usb_device *usb_dev, unsigned int pipe,
 423		 void *data, int len, int *actual_length, int timeout)
 424{
 425	struct urb *urb;
 426	struct usb_host_endpoint *ep;
 427
 428	ep = usb_pipe_endpoint(usb_dev, pipe);
 429	if (!ep || len < 0)
 430		return -EINVAL;
 431
 432	urb = usb_alloc_urb(0, GFP_KERNEL);
 433	if (!urb)
 434		return -ENOMEM;
 435
 436	if ((ep->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
 437			USB_ENDPOINT_XFER_INT) {
 438		pipe = (pipe & ~(3 << 30)) | (PIPE_INTERRUPT << 30);
 439		usb_fill_int_urb(urb, usb_dev, pipe, data, len,
 440				usb_api_blocking_completion, NULL,
 441				ep->desc.bInterval);
 442	} else
 443		usb_fill_bulk_urb(urb, usb_dev, pipe, data, len,
 444				usb_api_blocking_completion, NULL);
 445
 446	return usb_start_wait_urb(urb, timeout, actual_length, true);
 447}
 448EXPORT_SYMBOL_GPL(usb_bulk_msg_killable);
 449
 450/*-------------------------------------------------------------------*/
 451
 452static void sg_clean(struct usb_sg_request *io)
 453{
 454	if (io->urbs) {
 455		while (io->entries--)
 456			usb_free_urb(io->urbs[io->entries]);
 457		kfree(io->urbs);
 458		io->urbs = NULL;
 459	}
 460	io->dev = NULL;
 461}
 462
 463static void sg_complete(struct urb *urb)
 464{
 465	unsigned long flags;
 466	struct usb_sg_request *io = urb->context;
 467	int status = urb->status;
 468
 469	spin_lock_irqsave(&io->lock, flags);
 470
 471	/* In 2.5 we require hcds' endpoint queues not to progress after fault
 472	 * reports, until the completion callback (this!) returns.  That lets
 473	 * device driver code (like this routine) unlink queued urbs first,
 474	 * if it needs to, since the HC won't work on them at all.  So it's
 475	 * not possible for page N+1 to overwrite page N, and so on.
 476	 *
 477	 * That's only for "hard" faults; "soft" faults (unlinks) sometimes
 478	 * complete before the HCD can get requests away from hardware,
 479	 * though never during cleanup after a hard fault.
 480	 */
 481	if (io->status
 482			&& (io->status != -ECONNRESET
 483				|| status != -ECONNRESET)
 484			&& urb->actual_length) {
 485		dev_err(io->dev->bus->controller,
 486			"dev %s ep%d%s scatterlist error %d/%d\n",
 487			io->dev->devpath,
 488			usb_endpoint_num(&urb->ep->desc),
 489			usb_urb_dir_in(urb) ? "in" : "out",
 490			status, io->status);
 491		/* BUG (); */
 492	}
 493
 494	if (io->status == 0 && status && status != -ECONNRESET) {
 495		int i, found, retval;
 496
 497		io->status = status;
 498
 499		/* the previous urbs, and this one, completed already.
 500		 * unlink pending urbs so they won't rx/tx bad data.
 501		 * careful: unlink can sometimes be synchronous...
 502		 */
 503		spin_unlock_irqrestore(&io->lock, flags);
 504		for (i = 0, found = 0; i < io->entries; i++) {
 505			if (!io->urbs[i])
 506				continue;
 507			if (found) {
 508				usb_block_urb(io->urbs[i]);
 509				retval = usb_unlink_urb(io->urbs[i]);
 510				if (retval != -EINPROGRESS &&
 511				    retval != -ENODEV &&
 512				    retval != -EBUSY &&
 513				    retval != -EIDRM)
 514					dev_err(&io->dev->dev,
 515						"%s, unlink --> %d\n",
 516						__func__, retval);
 517			} else if (urb == io->urbs[i])
 518				found = 1;
 519		}
 520		spin_lock_irqsave(&io->lock, flags);
 521	}
 522
 523	/* on the last completion, signal usb_sg_wait() */
 524	io->bytes += urb->actual_length;
 525	io->count--;
 526	if (!io->count)
 527		complete(&io->complete);
 528
 529	spin_unlock_irqrestore(&io->lock, flags);
 530}
 531
 532
 533/**
 534 * usb_sg_init - initializes scatterlist-based bulk/interrupt I/O request
 535 * @io: request block being initialized.  until usb_sg_wait() returns,
 536 *	treat this as a pointer to an opaque block of memory,
 537 * @dev: the usb device that will send or receive the data
 538 * @pipe: endpoint "pipe" used to transfer the data
 539 * @period: polling rate for interrupt endpoints, in frames or
 540 * 	(for high speed endpoints) microframes; ignored for bulk
 541 * @sg: scatterlist entries
 542 * @nents: how many entries in the scatterlist
 543 * @length: how many bytes to send from the scatterlist, or zero to
 544 * 	send every byte identified in the list.
 545 * @mem_flags: SLAB_* flags affecting memory allocations in this call
 546 *
 547 * This initializes a scatter/gather request, allocating resources such as
 548 * I/O mappings and urb memory (except maybe memory used by USB controller
 549 * drivers).
 550 *
 551 * The request must be issued using usb_sg_wait(), which waits for the I/O to
 552 * complete (or to be canceled) and then cleans up all resources allocated by
 553 * usb_sg_init().
 554 *
 555 * The request may be canceled with usb_sg_cancel(), either before or after
 556 * usb_sg_wait() is called.
 557 *
 558 * Return: Zero for success, else a negative errno value.
 559 */
 560int usb_sg_init(struct usb_sg_request *io, struct usb_device *dev,
 561		unsigned pipe, unsigned	period, struct scatterlist *sg,
 562		int nents, size_t length, gfp_t mem_flags)
 563{
 564	int i;
 565	int urb_flags;
 566	int use_sg;
 567
 568	if (!io || !dev || !sg
 569			|| usb_pipecontrol(pipe)
 570			|| usb_pipeisoc(pipe)
 571			|| nents <= 0)
 572		return -EINVAL;
 573
 574	spin_lock_init(&io->lock);
 575	io->dev = dev;
 576	io->pipe = pipe;
 577
 578	if (dev->bus->sg_tablesize > 0) {
 579		use_sg = true;
 580		io->entries = 1;
 581	} else {
 582		use_sg = false;
 583		io->entries = nents;
 584	}
 585
 586	/* initialize all the urbs we'll use */
 587	io->urbs = kmalloc_array(io->entries, sizeof(*io->urbs), mem_flags);
 588	if (!io->urbs)
 589		goto nomem;
 590
 591	urb_flags = URB_NO_INTERRUPT;
 592	if (usb_pipein(pipe))
 593		urb_flags |= URB_SHORT_NOT_OK;
 594
 595	for_each_sg(sg, sg, io->entries, i) {
 596		struct urb *urb;
 597		unsigned len;
 598
 599		urb = usb_alloc_urb(0, mem_flags);
 600		if (!urb) {
 601			io->entries = i;
 602			goto nomem;
 603		}
 604		io->urbs[i] = urb;
 605
 606		urb->dev = NULL;
 607		urb->pipe = pipe;
 608		urb->interval = period;
 609		urb->transfer_flags = urb_flags;
 610		urb->complete = sg_complete;
 611		urb->context = io;
 612		urb->sg = sg;
 613
 614		if (use_sg) {
 615			/* There is no single transfer buffer */
 616			urb->transfer_buffer = NULL;
 617			urb->num_sgs = nents;
 618
 619			/* A length of zero means transfer the whole sg list */
 620			len = length;
 621			if (len == 0) {
 622				struct scatterlist	*sg2;
 623				int			j;
 624
 625				for_each_sg(sg, sg2, nents, j)
 626					len += sg2->length;
 627			}
 628		} else {
 629			/*
 630			 * Some systems can't use DMA; they use PIO instead.
 631			 * For their sakes, transfer_buffer is set whenever
 632			 * possible.
 633			 */
 634			if (!PageHighMem(sg_page(sg)))
 635				urb->transfer_buffer = sg_virt(sg);
 636			else
 637				urb->transfer_buffer = NULL;
 638
 639			len = sg->length;
 640			if (length) {
 641				len = min_t(size_t, len, length);
 642				length -= len;
 643				if (length == 0)
 644					io->entries = i + 1;
 645			}
 646		}
 647		urb->transfer_buffer_length = len;
 648	}
 649	io->urbs[--i]->transfer_flags &= ~URB_NO_INTERRUPT;
 650
 651	/* transaction state */
 652	io->count = io->entries;
 653	io->status = 0;
 654	io->bytes = 0;
 655	init_completion(&io->complete);
 656	return 0;
 657
 658nomem:
 659	sg_clean(io);
 660	return -ENOMEM;
 661}
 662EXPORT_SYMBOL_GPL(usb_sg_init);
 663
 664/**
 665 * usb_sg_wait - synchronously execute scatter/gather request
 666 * @io: request block handle, as initialized with usb_sg_init().
 667 * 	some fields become accessible when this call returns.
 668 *
 669 * Context: task context, might sleep.
 670 *
 671 * This function blocks until the specified I/O operation completes.  It
 672 * leverages the grouping of the related I/O requests to get good transfer
 673 * rates, by queueing the requests.  At higher speeds, such queuing can
 674 * significantly improve USB throughput.
 675 *
 676 * There are three kinds of completion for this function.
 677 *
 678 * (1) success, where io->status is zero.  The number of io->bytes
 679 *     transferred is as requested.
 680 * (2) error, where io->status is a negative errno value.  The number
 681 *     of io->bytes transferred before the error is usually less
 682 *     than requested, and can be nonzero.
 683 * (3) cancellation, a type of error with status -ECONNRESET that
 684 *     is initiated by usb_sg_cancel().
 685 *
 686 * When this function returns, all memory allocated through usb_sg_init() or
 687 * this call will have been freed.  The request block parameter may still be
 688 * passed to usb_sg_cancel(), or it may be freed.  It could also be
 689 * reinitialized and then reused.
 690 *
 691 * Data Transfer Rates:
 692 *
 693 * Bulk transfers are valid for full or high speed endpoints.
 694 * The best full speed data rate is 19 packets of 64 bytes each
 695 * per frame, or 1216 bytes per millisecond.
 696 * The best high speed data rate is 13 packets of 512 bytes each
 697 * per microframe, or 52 KBytes per millisecond.
 698 *
 699 * The reason to use interrupt transfers through this API would most likely
 700 * be to reserve high speed bandwidth, where up to 24 KBytes per millisecond
 701 * could be transferred.  That capability is less useful for low or full
 702 * speed interrupt endpoints, which allow at most one packet per millisecond,
 703 * of at most 8 or 64 bytes (respectively).
 704 *
 705 * It is not necessary to call this function to reserve bandwidth for devices
 706 * under an xHCI host controller, as the bandwidth is reserved when the
 707 * configuration or interface alt setting is selected.
 708 */
 709void usb_sg_wait(struct usb_sg_request *io)
 710{
 711	int i;
 712	int entries = io->entries;
 713
 714	/* queue the urbs.  */
 715	spin_lock_irq(&io->lock);
 716	i = 0;
 717	while (i < entries && !io->status) {
 718		int retval;
 719
 720		io->urbs[i]->dev = io->dev;
 721		spin_unlock_irq(&io->lock);
 722
 723		retval = usb_submit_urb(io->urbs[i], GFP_NOIO);
 724
 725		switch (retval) {
 726			/* maybe we retrying will recover */
 727		case -ENXIO:	/* hc didn't queue this one */
 728		case -EAGAIN:
 729		case -ENOMEM:
 730			retval = 0;
 731			yield();
 732			break;
 733
 734			/* no error? continue immediately.
 735			 *
 736			 * NOTE: to work better with UHCI (4K I/O buffer may
 737			 * need 3K of TDs) it may be good to limit how many
 738			 * URBs are queued at once; N milliseconds?
 739			 */
 740		case 0:
 741			++i;
 742			cpu_relax();
 743			break;
 744
 745			/* fail any uncompleted urbs */
 746		default:
 747			io->urbs[i]->status = retval;
 748			dev_dbg(&io->dev->dev, "%s, submit --> %d\n",
 749				__func__, retval);
 750			usb_sg_cancel(io);
 751		}
 752		spin_lock_irq(&io->lock);
 753		if (retval && (io->status == 0 || io->status == -ECONNRESET))
 754			io->status = retval;
 755	}
 756	io->count -= entries - i;
 757	if (io->count == 0)
 758		complete(&io->complete);
 759	spin_unlock_irq(&io->lock);
 760
 761	/* OK, yes, this could be packaged as non-blocking.
 762	 * So could the submit loop above ... but it's easier to
 763	 * solve neither problem than to solve both!
 764	 */
 765	wait_for_completion(&io->complete);
 766
 767	sg_clean(io);
 768}
 769EXPORT_SYMBOL_GPL(usb_sg_wait);
 770
 771/**
 772 * usb_sg_cancel - stop scatter/gather i/o issued by usb_sg_wait()
 773 * @io: request block, initialized with usb_sg_init()
 774 *
 775 * This stops a request after it has been started by usb_sg_wait().
 776 * It can also prevents one initialized by usb_sg_init() from starting,
 777 * so that call just frees resources allocated to the request.
 778 */
 779void usb_sg_cancel(struct usb_sg_request *io)
 780{
 781	unsigned long flags;
 782	int i, retval;
 783
 784	spin_lock_irqsave(&io->lock, flags);
 785	if (io->status || io->count == 0) {
 786		spin_unlock_irqrestore(&io->lock, flags);
 787		return;
 788	}
 789	/* shut everything down */
 790	io->status = -ECONNRESET;
 791	io->count++;		/* Keep the request alive until we're done */
 792	spin_unlock_irqrestore(&io->lock, flags);
 793
 794	for (i = io->entries - 1; i >= 0; --i) {
 795		usb_block_urb(io->urbs[i]);
 796
 797		retval = usb_unlink_urb(io->urbs[i]);
 798		if (retval != -EINPROGRESS
 799		    && retval != -ENODEV
 800		    && retval != -EBUSY
 801		    && retval != -EIDRM)
 802			dev_warn(&io->dev->dev, "%s, unlink --> %d\n",
 803				 __func__, retval);
 804	}
 805
 806	spin_lock_irqsave(&io->lock, flags);
 807	io->count--;
 808	if (!io->count)
 809		complete(&io->complete);
 810	spin_unlock_irqrestore(&io->lock, flags);
 811}
 812EXPORT_SYMBOL_GPL(usb_sg_cancel);
 813
 814/*-------------------------------------------------------------------*/
 815
 816/**
 817 * usb_get_descriptor - issues a generic GET_DESCRIPTOR request
 818 * @dev: the device whose descriptor is being retrieved
 819 * @type: the descriptor type (USB_DT_*)
 820 * @index: the number of the descriptor
 821 * @buf: where to put the descriptor
 822 * @size: how big is "buf"?
 823 *
 824 * Context: task context, might sleep.
 825 *
 826 * Gets a USB descriptor.  Convenience functions exist to simplify
 827 * getting some types of descriptors.  Use
 828 * usb_get_string() or usb_string() for USB_DT_STRING.
 829 * Device (USB_DT_DEVICE) and configuration descriptors (USB_DT_CONFIG)
 830 * are part of the device structure.
 831 * In addition to a number of USB-standard descriptors, some
 832 * devices also use class-specific or vendor-specific descriptors.
 833 *
 834 * This call is synchronous, and may not be used in an interrupt context.
 835 *
 836 * Return: The number of bytes received on success, or else the status code
 837 * returned by the underlying usb_control_msg() call.
 838 */
 839int usb_get_descriptor(struct usb_device *dev, unsigned char type,
 840		       unsigned char index, void *buf, int size)
 841{
 842	int i;
 843	int result;
 844
 845	if (size <= 0)		/* No point in asking for no data */
 846		return -EINVAL;
 847
 848	memset(buf, 0, size);	/* Make sure we parse really received data */
 849
 850	for (i = 0; i < 3; ++i) {
 851		/* retry on length 0 or error; some devices are flakey */
 852		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
 853				USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
 854				(type << 8) + index, 0, buf, size,
 855				USB_CTRL_GET_TIMEOUT);
 856		if (result <= 0 && result != -ETIMEDOUT)
 857			continue;
 858		if (result > 1 && ((u8 *)buf)[1] != type) {
 859			result = -ENODATA;
 860			continue;
 861		}
 862		break;
 863	}
 864	return result;
 865}
 866EXPORT_SYMBOL_GPL(usb_get_descriptor);
 867
 868/**
 869 * usb_get_string - gets a string descriptor
 870 * @dev: the device whose string descriptor is being retrieved
 871 * @langid: code for language chosen (from string descriptor zero)
 872 * @index: the number of the descriptor
 873 * @buf: where to put the string
 874 * @size: how big is "buf"?
 875 *
 876 * Context: task context, might sleep.
 877 *
 878 * Retrieves a string, encoded using UTF-16LE (Unicode, 16 bits per character,
 879 * in little-endian byte order).
 880 * The usb_string() function will often be a convenient way to turn
 881 * these strings into kernel-printable form.
 882 *
 883 * Strings may be referenced in device, configuration, interface, or other
 884 * descriptors, and could also be used in vendor-specific ways.
 885 *
 886 * This call is synchronous, and may not be used in an interrupt context.
 887 *
 888 * Return: The number of bytes received on success, or else the status code
 889 * returned by the underlying usb_control_msg() call.
 890 */
 891static int usb_get_string(struct usb_device *dev, unsigned short langid,
 892			  unsigned char index, void *buf, int size)
 893{
 894	int i;
 895	int result;
 896
 897	if (size <= 0)		/* No point in asking for no data */
 898		return -EINVAL;
 899
 900	for (i = 0; i < 3; ++i) {
 901		/* retry on length 0 or stall; some devices are flakey */
 902		result = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
 903			USB_REQ_GET_DESCRIPTOR, USB_DIR_IN,
 904			(USB_DT_STRING << 8) + index, langid, buf, size,
 905			USB_CTRL_GET_TIMEOUT);
 906		if (result == 0 || result == -EPIPE)
 907			continue;
 908		if (result > 1 && ((u8 *) buf)[1] != USB_DT_STRING) {
 909			result = -ENODATA;
 910			continue;
 911		}
 912		break;
 913	}
 914	return result;
 915}
 916
 917static void usb_try_string_workarounds(unsigned char *buf, int *length)
 918{
 919	int newlength, oldlength = *length;
 920
 921	for (newlength = 2; newlength + 1 < oldlength; newlength += 2)
 922		if (!isprint(buf[newlength]) || buf[newlength + 1])
 923			break;
 924
 925	if (newlength > 2) {
 926		buf[0] = newlength;
 927		*length = newlength;
 928	}
 929}
 930
 931static int usb_string_sub(struct usb_device *dev, unsigned int langid,
 932			  unsigned int index, unsigned char *buf)
 933{
 934	int rc;
 935
 936	/* Try to read the string descriptor by asking for the maximum
 937	 * possible number of bytes */
 938	if (dev->quirks & USB_QUIRK_STRING_FETCH_255)
 939		rc = -EIO;
 940	else
 941		rc = usb_get_string(dev, langid, index, buf, 255);
 942
 943	/* If that failed try to read the descriptor length, then
 944	 * ask for just that many bytes */
 945	if (rc < 2) {
 946		rc = usb_get_string(dev, langid, index, buf, 2);
 947		if (rc == 2)
 948			rc = usb_get_string(dev, langid, index, buf, buf[0]);
 949	}
 950
 951	if (rc >= 2) {
 952		if (!buf[0] && !buf[1])
 953			usb_try_string_workarounds(buf, &rc);
 954
 955		/* There might be extra junk at the end of the descriptor */
 956		if (buf[0] < rc)
 957			rc = buf[0];
 958
 959		rc = rc - (rc & 1); /* force a multiple of two */
 960	}
 961
 962	if (rc < 2)
 963		rc = (rc < 0 ? rc : -EINVAL);
 964
 965	return rc;
 966}
 967
 968static int usb_get_langid(struct usb_device *dev, unsigned char *tbuf)
 969{
 970	int err;
 971
 972	if (dev->have_langid)
 973		return 0;
 974
 975	if (dev->string_langid < 0)
 976		return -EPIPE;
 977
 978	err = usb_string_sub(dev, 0, 0, tbuf);
 979
 980	/* If the string was reported but is malformed, default to english
 981	 * (0x0409) */
 982	if (err == -ENODATA || (err > 0 && err < 4)) {
 983		dev->string_langid = 0x0409;
 984		dev->have_langid = 1;
 985		dev_err(&dev->dev,
 986			"language id specifier not provided by device, defaulting to English\n");
 987		return 0;
 988	}
 989
 990	/* In case of all other errors, we assume the device is not able to
 991	 * deal with strings at all. Set string_langid to -1 in order to
 992	 * prevent any string to be retrieved from the device */
 993	if (err < 0) {
 994		dev_info(&dev->dev, "string descriptor 0 read error: %d\n",
 995					err);
 996		dev->string_langid = -1;
 997		return -EPIPE;
 998	}
 999
1000	/* always use the first langid listed */
1001	dev->string_langid = tbuf[2] | (tbuf[3] << 8);
1002	dev->have_langid = 1;
1003	dev_dbg(&dev->dev, "default language 0x%04x\n",
1004				dev->string_langid);
1005	return 0;
1006}
1007
1008/**
1009 * usb_string - returns UTF-8 version of a string descriptor
1010 * @dev: the device whose string descriptor is being retrieved
1011 * @index: the number of the descriptor
1012 * @buf: where to put the string
1013 * @size: how big is "buf"?
1014 *
1015 * Context: task context, might sleep.
1016 *
1017 * This converts the UTF-16LE encoded strings returned by devices, from
1018 * usb_get_string_descriptor(), to null-terminated UTF-8 encoded ones
1019 * that are more usable in most kernel contexts.  Note that this function
1020 * chooses strings in the first language supported by the device.
1021 *
1022 * This call is synchronous, and may not be used in an interrupt context.
1023 *
1024 * Return: length of the string (>= 0) or usb_control_msg status (< 0).
1025 */
1026int usb_string(struct usb_device *dev, int index, char *buf, size_t size)
1027{
1028	unsigned char *tbuf;
1029	int err;
1030
1031	if (dev->state == USB_STATE_SUSPENDED)
1032		return -EHOSTUNREACH;
1033	if (size <= 0 || !buf)
1034		return -EINVAL;
1035	buf[0] = 0;
1036	if (index <= 0 || index >= 256)
1037		return -EINVAL;
1038	tbuf = kmalloc(256, GFP_NOIO);
1039	if (!tbuf)
1040		return -ENOMEM;
1041
1042	err = usb_get_langid(dev, tbuf);
1043	if (err < 0)
1044		goto errout;
1045
1046	err = usb_string_sub(dev, dev->string_langid, index, tbuf);
1047	if (err < 0)
1048		goto errout;
1049
1050	size--;		/* leave room for trailing NULL char in output buffer */
1051	err = utf16s_to_utf8s((wchar_t *) &tbuf[2], (err - 2) / 2,
1052			UTF16_LITTLE_ENDIAN, buf, size);
1053	buf[err] = 0;
1054
1055	if (tbuf[1] != USB_DT_STRING)
1056		dev_dbg(&dev->dev,
1057			"wrong descriptor type %02x for string %d (\"%s\")\n",
1058			tbuf[1], index, buf);
1059
1060 errout:
1061	kfree(tbuf);
1062	return err;
1063}
1064EXPORT_SYMBOL_GPL(usb_string);
1065
1066/* one UTF-8-encoded 16-bit character has at most three bytes */
1067#define MAX_USB_STRING_SIZE (127 * 3 + 1)
1068
1069/**
1070 * usb_cache_string - read a string descriptor and cache it for later use
1071 * @udev: the device whose string descriptor is being read
1072 * @index: the descriptor index
1073 *
1074 * Return: A pointer to a kmalloc'ed buffer containing the descriptor string,
1075 * or %NULL if the index is 0 or the string could not be read.
1076 */
1077char *usb_cache_string(struct usb_device *udev, int index)
1078{
1079	char *buf;
1080	char *smallbuf = NULL;
1081	int len;
1082
1083	if (index <= 0)
1084		return NULL;
1085
1086	buf = kmalloc(MAX_USB_STRING_SIZE, GFP_NOIO);
1087	if (buf) {
1088		len = usb_string(udev, index, buf, MAX_USB_STRING_SIZE);
1089		if (len > 0) {
1090			smallbuf = kmalloc(++len, GFP_NOIO);
1091			if (!smallbuf)
1092				return buf;
1093			memcpy(smallbuf, buf, len);
1094		}
1095		kfree(buf);
1096	}
1097	return smallbuf;
1098}
1099EXPORT_SYMBOL_GPL(usb_cache_string);
1100
1101/*
1102 * usb_get_device_descriptor - read the device descriptor
1103 * @udev: the device whose device descriptor should be read
1104 *
1105 * Context: task context, might sleep.
1106 *
1107 * Not exported, only for use by the core.  If drivers really want to read
1108 * the device descriptor directly, they can call usb_get_descriptor() with
1109 * type = USB_DT_DEVICE and index = 0.
1110 *
1111 * Returns: a pointer to a dynamically allocated usb_device_descriptor
1112 * structure (which the caller must deallocate), or an ERR_PTR value.
1113 */
1114struct usb_device_descriptor *usb_get_device_descriptor(struct usb_device *udev)
1115{
1116	struct usb_device_descriptor *desc;
1117	int ret;
1118
1119	desc = kmalloc(sizeof(*desc), GFP_NOIO);
1120	if (!desc)
1121		return ERR_PTR(-ENOMEM);
1122
1123	ret = usb_get_descriptor(udev, USB_DT_DEVICE, 0, desc, sizeof(*desc));
1124	if (ret == sizeof(*desc))
1125		return desc;
1126
1127	if (ret >= 0)
1128		ret = -EMSGSIZE;
1129	kfree(desc);
1130	return ERR_PTR(ret);
1131}
1132
1133/*
1134 * usb_set_isoch_delay - informs the device of the packet transmit delay
1135 * @dev: the device whose delay is to be informed
1136 * Context: task context, might sleep
1137 *
1138 * Since this is an optional request, we don't bother if it fails.
1139 */
1140int usb_set_isoch_delay(struct usb_device *dev)
1141{
1142	/* skip hub devices */
1143	if (dev->descriptor.bDeviceClass == USB_CLASS_HUB)
1144		return 0;
1145
1146	/* skip non-SS/non-SSP devices */
1147	if (dev->speed < USB_SPEED_SUPER)
1148		return 0;
1149
1150	return usb_control_msg_send(dev, 0,
1151			USB_REQ_SET_ISOCH_DELAY,
1152			USB_DIR_OUT | USB_TYPE_STANDARD | USB_RECIP_DEVICE,
1153			dev->hub_delay, 0, NULL, 0,
1154			USB_CTRL_SET_TIMEOUT,
1155			GFP_NOIO);
1156}
1157
1158/**
1159 * usb_get_status - issues a GET_STATUS call
1160 * @dev: the device whose status is being checked
1161 * @recip: USB_RECIP_*; for device, interface, or endpoint
1162 * @type: USB_STATUS_TYPE_*; for standard or PTM status types
1163 * @target: zero (for device), else interface or endpoint number
1164 * @data: pointer to two bytes of bitmap data
1165 *
1166 * Context: task context, might sleep.
1167 *
1168 * Returns device, interface, or endpoint status.  Normally only of
1169 * interest to see if the device is self powered, or has enabled the
1170 * remote wakeup facility; or whether a bulk or interrupt endpoint
1171 * is halted ("stalled").
1172 *
1173 * Bits in these status bitmaps are set using the SET_FEATURE request,
1174 * and cleared using the CLEAR_FEATURE request.  The usb_clear_halt()
1175 * function should be used to clear halt ("stall") status.
1176 *
1177 * This call is synchronous, and may not be used in an interrupt context.
1178 *
1179 * Returns 0 and the status value in *@data (in host byte order) on success,
1180 * or else the status code from the underlying usb_control_msg() call.
1181 */
1182int usb_get_status(struct usb_device *dev, int recip, int type, int target,
1183		void *data)
1184{
1185	int ret;
1186	void *status;
1187	int length;
1188
1189	switch (type) {
1190	case USB_STATUS_TYPE_STANDARD:
1191		length = 2;
1192		break;
1193	case USB_STATUS_TYPE_PTM:
1194		if (recip != USB_RECIP_DEVICE)
1195			return -EINVAL;
1196
1197		length = 4;
1198		break;
1199	default:
1200		return -EINVAL;
1201	}
1202
1203	status =  kmalloc(length, GFP_KERNEL);
1204	if (!status)
1205		return -ENOMEM;
1206
1207	ret = usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
1208		USB_REQ_GET_STATUS, USB_DIR_IN | recip, USB_STATUS_TYPE_STANDARD,
1209		target, status, length, USB_CTRL_GET_TIMEOUT);
1210
1211	switch (ret) {
1212	case 4:
1213		if (type != USB_STATUS_TYPE_PTM) {
1214			ret = -EIO;
1215			break;
1216		}
1217
1218		*(u32 *) data = le32_to_cpu(*(__le32 *) status);
1219		ret = 0;
1220		break;
1221	case 2:
1222		if (type != USB_STATUS_TYPE_STANDARD) {
1223			ret = -EIO;
1224			break;
1225		}
1226
1227		*(u16 *) data = le16_to_cpu(*(__le16 *) status);
1228		ret = 0;
1229		break;
1230	default:
1231		ret = -EIO;
1232	}
1233
1234	kfree(status);
1235	return ret;
1236}
1237EXPORT_SYMBOL_GPL(usb_get_status);
1238
1239/**
1240 * usb_clear_halt - tells device to clear endpoint halt/stall condition
1241 * @dev: device whose endpoint is halted
1242 * @pipe: endpoint "pipe" being cleared
1243 *
1244 * Context: task context, might sleep.
1245 *
1246 * This is used to clear halt conditions for bulk and interrupt endpoints,
1247 * as reported by URB completion status.  Endpoints that are halted are
1248 * sometimes referred to as being "stalled".  Such endpoints are unable
1249 * to transmit or receive data until the halt status is cleared.  Any URBs
1250 * queued for such an endpoint should normally be unlinked by the driver
1251 * before clearing the halt condition, as described in sections 5.7.5
1252 * and 5.8.5 of the USB 2.0 spec.
1253 *
1254 * Note that control and isochronous endpoints don't halt, although control
1255 * endpoints report "protocol stall" (for unsupported requests) using the
1256 * same status code used to report a true stall.
1257 *
1258 * This call is synchronous, and may not be used in an interrupt context.
1259 * If a thread in your driver uses this call, make sure your disconnect()
1260 * method can wait for it to complete.
1261 *
1262 * Return: Zero on success, or else the status code returned by the
1263 * underlying usb_control_msg() call.
1264 */
1265int usb_clear_halt(struct usb_device *dev, int pipe)
1266{
1267	int result;
1268	int endp = usb_pipeendpoint(pipe);
1269
1270	if (usb_pipein(pipe))
1271		endp |= USB_DIR_IN;
1272
1273	/* we don't care if it wasn't halted first. in fact some devices
1274	 * (like some ibmcam model 1 units) seem to expect hosts to make
1275	 * this request for iso endpoints, which can't halt!
1276	 */
1277	result = usb_control_msg_send(dev, 0,
1278				      USB_REQ_CLEAR_FEATURE, USB_RECIP_ENDPOINT,
1279				      USB_ENDPOINT_HALT, endp, NULL, 0,
1280				      USB_CTRL_SET_TIMEOUT, GFP_NOIO);
1281
1282	/* don't un-halt or force to DATA0 except on success */
1283	if (result)
1284		return result;
1285
1286	/* NOTE:  seems like Microsoft and Apple don't bother verifying
1287	 * the clear "took", so some devices could lock up if you check...
1288	 * such as the Hagiwara FlashGate DUAL.  So we won't bother.
1289	 *
1290	 * NOTE:  make sure the logic here doesn't diverge much from
1291	 * the copy in usb-storage, for as long as we need two copies.
1292	 */
1293
1294	usb_reset_endpoint(dev, endp);
1295
1296	return 0;
1297}
1298EXPORT_SYMBOL_GPL(usb_clear_halt);
1299
1300static int create_intf_ep_devs(struct usb_interface *intf)
1301{
1302	struct usb_device *udev = interface_to_usbdev(intf);
1303	struct usb_host_interface *alt = intf->cur_altsetting;
1304	int i;
1305
1306	if (intf->ep_devs_created || intf->unregistering)
1307		return 0;
1308
1309	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1310		(void) usb_create_ep_devs(&intf->dev, &alt->endpoint[i], udev);
1311	intf->ep_devs_created = 1;
1312	return 0;
1313}
1314
1315static void remove_intf_ep_devs(struct usb_interface *intf)
1316{
1317	struct usb_host_interface *alt = intf->cur_altsetting;
1318	int i;
1319
1320	if (!intf->ep_devs_created)
1321		return;
1322
1323	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1324		usb_remove_ep_devs(&alt->endpoint[i]);
1325	intf->ep_devs_created = 0;
1326}
1327
1328/**
1329 * usb_disable_endpoint -- Disable an endpoint by address
1330 * @dev: the device whose endpoint is being disabled
1331 * @epaddr: the endpoint's address.  Endpoint number for output,
1332 *	endpoint number + USB_DIR_IN for input
1333 * @reset_hardware: flag to erase any endpoint state stored in the
1334 *	controller hardware
1335 *
1336 * Disables the endpoint for URB submission and nukes all pending URBs.
1337 * If @reset_hardware is set then also deallocates hcd/hardware state
1338 * for the endpoint.
1339 */
1340void usb_disable_endpoint(struct usb_device *dev, unsigned int epaddr,
1341		bool reset_hardware)
1342{
1343	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1344	struct usb_host_endpoint *ep;
1345
1346	if (!dev)
1347		return;
1348
1349	if (usb_endpoint_out(epaddr)) {
1350		ep = dev->ep_out[epnum];
1351		if (reset_hardware && epnum != 0)
1352			dev->ep_out[epnum] = NULL;
1353	} else {
1354		ep = dev->ep_in[epnum];
1355		if (reset_hardware && epnum != 0)
1356			dev->ep_in[epnum] = NULL;
1357	}
1358	if (ep) {
1359		ep->enabled = 0;
1360		usb_hcd_flush_endpoint(dev, ep);
1361		if (reset_hardware)
1362			usb_hcd_disable_endpoint(dev, ep);
1363	}
1364}
1365
1366/**
1367 * usb_reset_endpoint - Reset an endpoint's state.
1368 * @dev: the device whose endpoint is to be reset
1369 * @epaddr: the endpoint's address.  Endpoint number for output,
1370 *	endpoint number + USB_DIR_IN for input
1371 *
1372 * Resets any host-side endpoint state such as the toggle bit,
1373 * sequence number or current window.
1374 */
1375void usb_reset_endpoint(struct usb_device *dev, unsigned int epaddr)
1376{
1377	unsigned int epnum = epaddr & USB_ENDPOINT_NUMBER_MASK;
1378	struct usb_host_endpoint *ep;
1379
1380	if (usb_endpoint_out(epaddr))
1381		ep = dev->ep_out[epnum];
1382	else
1383		ep = dev->ep_in[epnum];
1384	if (ep)
1385		usb_hcd_reset_endpoint(dev, ep);
1386}
1387EXPORT_SYMBOL_GPL(usb_reset_endpoint);
1388
1389
1390/**
1391 * usb_disable_interface -- Disable all endpoints for an interface
1392 * @dev: the device whose interface is being disabled
1393 * @intf: pointer to the interface descriptor
1394 * @reset_hardware: flag to erase any endpoint state stored in the
1395 *	controller hardware
1396 *
1397 * Disables all the endpoints for the interface's current altsetting.
1398 */
1399void usb_disable_interface(struct usb_device *dev, struct usb_interface *intf,
1400		bool reset_hardware)
1401{
1402	struct usb_host_interface *alt = intf->cur_altsetting;
1403	int i;
1404
1405	for (i = 0; i < alt->desc.bNumEndpoints; ++i) {
1406		usb_disable_endpoint(dev,
1407				alt->endpoint[i].desc.bEndpointAddress,
1408				reset_hardware);
1409	}
1410}
1411
1412/*
1413 * usb_disable_device_endpoints -- Disable all endpoints for a device
1414 * @dev: the device whose endpoints are being disabled
1415 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1416 */
1417static void usb_disable_device_endpoints(struct usb_device *dev, int skip_ep0)
1418{
1419	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1420	int i;
1421
1422	if (hcd->driver->check_bandwidth) {
1423		/* First pass: Cancel URBs, leave endpoint pointers intact. */
1424		for (i = skip_ep0; i < 16; ++i) {
1425			usb_disable_endpoint(dev, i, false);
1426			usb_disable_endpoint(dev, i + USB_DIR_IN, false);
1427		}
1428		/* Remove endpoints from the host controller internal state */
1429		mutex_lock(hcd->bandwidth_mutex);
1430		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1431		mutex_unlock(hcd->bandwidth_mutex);
1432	}
1433	/* Second pass: remove endpoint pointers */
1434	for (i = skip_ep0; i < 16; ++i) {
1435		usb_disable_endpoint(dev, i, true);
1436		usb_disable_endpoint(dev, i + USB_DIR_IN, true);
1437	}
1438}
1439
1440/**
1441 * usb_disable_device - Disable all the endpoints for a USB device
1442 * @dev: the device whose endpoints are being disabled
1443 * @skip_ep0: 0 to disable endpoint 0, 1 to skip it.
1444 *
1445 * Disables all the device's endpoints, potentially including endpoint 0.
1446 * Deallocates hcd/hardware state for the endpoints (nuking all or most
1447 * pending urbs) and usbcore state for the interfaces, so that usbcore
1448 * must usb_set_configuration() before any interfaces could be used.
1449 */
1450void usb_disable_device(struct usb_device *dev, int skip_ep0)
1451{
1452	int i;
1453
1454	/* getting rid of interfaces will disconnect
1455	 * any drivers bound to them (a key side effect)
1456	 */
1457	if (dev->actconfig) {
1458		/*
1459		 * FIXME: In order to avoid self-deadlock involving the
1460		 * bandwidth_mutex, we have to mark all the interfaces
1461		 * before unregistering any of them.
1462		 */
1463		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++)
1464			dev->actconfig->interface[i]->unregistering = 1;
1465
1466		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1467			struct usb_interface	*interface;
1468
1469			/* remove this interface if it has been registered */
1470			interface = dev->actconfig->interface[i];
1471			if (!device_is_registered(&interface->dev))
1472				continue;
1473			dev_dbg(&dev->dev, "unregistering interface %s\n",
1474				dev_name(&interface->dev));
1475			remove_intf_ep_devs(interface);
1476			device_del(&interface->dev);
1477		}
1478
1479		/* Now that the interfaces are unbound, nobody should
1480		 * try to access them.
1481		 */
1482		for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
1483			put_device(&dev->actconfig->interface[i]->dev);
1484			dev->actconfig->interface[i] = NULL;
1485		}
1486
1487		usb_disable_usb2_hardware_lpm(dev);
1488		usb_unlocked_disable_lpm(dev);
1489		usb_disable_ltm(dev);
1490
1491		dev->actconfig = NULL;
1492		if (dev->state == USB_STATE_CONFIGURED)
1493			usb_set_device_state(dev, USB_STATE_ADDRESS);
1494	}
1495
1496	dev_dbg(&dev->dev, "%s nuking %s URBs\n", __func__,
1497		skip_ep0 ? "non-ep0" : "all");
1498
1499	usb_disable_device_endpoints(dev, skip_ep0);
1500}
1501
1502/**
1503 * usb_enable_endpoint - Enable an endpoint for USB communications
1504 * @dev: the device whose interface is being enabled
1505 * @ep: the endpoint
1506 * @reset_ep: flag to reset the endpoint state
1507 *
1508 * Resets the endpoint state if asked, and sets dev->ep_{in,out} pointers.
1509 * For control endpoints, both the input and output sides are handled.
1510 */
1511void usb_enable_endpoint(struct usb_device *dev, struct usb_host_endpoint *ep,
1512		bool reset_ep)
1513{
1514	int epnum = usb_endpoint_num(&ep->desc);
1515	int is_out = usb_endpoint_dir_out(&ep->desc);
1516	int is_control = usb_endpoint_xfer_control(&ep->desc);
1517
1518	if (reset_ep)
1519		usb_hcd_reset_endpoint(dev, ep);
1520	if (is_out || is_control)
1521		dev->ep_out[epnum] = ep;
1522	if (!is_out || is_control)
1523		dev->ep_in[epnum] = ep;
1524	ep->enabled = 1;
1525}
1526
1527/**
1528 * usb_enable_interface - Enable all the endpoints for an interface
1529 * @dev: the device whose interface is being enabled
1530 * @intf: pointer to the interface descriptor
1531 * @reset_eps: flag to reset the endpoints' state
1532 *
1533 * Enables all the endpoints for the interface's current altsetting.
1534 */
1535void usb_enable_interface(struct usb_device *dev,
1536		struct usb_interface *intf, bool reset_eps)
1537{
1538	struct usb_host_interface *alt = intf->cur_altsetting;
1539	int i;
1540
1541	for (i = 0; i < alt->desc.bNumEndpoints; ++i)
1542		usb_enable_endpoint(dev, &alt->endpoint[i], reset_eps);
1543}
1544
1545/**
1546 * usb_set_interface - Makes a particular alternate setting be current
1547 * @dev: the device whose interface is being updated
1548 * @interface: the interface being updated
1549 * @alternate: the setting being chosen.
1550 *
1551 * Context: task context, might sleep.
1552 *
1553 * This is used to enable data transfers on interfaces that may not
1554 * be enabled by default.  Not all devices support such configurability.
1555 * Only the driver bound to an interface may change its setting.
1556 *
1557 * Within any given configuration, each interface may have several
1558 * alternative settings.  These are often used to control levels of
1559 * bandwidth consumption.  For example, the default setting for a high
1560 * speed interrupt endpoint may not send more than 64 bytes per microframe,
1561 * while interrupt transfers of up to 3KBytes per microframe are legal.
1562 * Also, isochronous endpoints may never be part of an
1563 * interface's default setting.  To access such bandwidth, alternate
1564 * interface settings must be made current.
1565 *
1566 * Note that in the Linux USB subsystem, bandwidth associated with
1567 * an endpoint in a given alternate setting is not reserved until an URB
1568 * is submitted that needs that bandwidth.  Some other operating systems
1569 * allocate bandwidth early, when a configuration is chosen.
1570 *
1571 * xHCI reserves bandwidth and configures the alternate setting in
1572 * usb_hcd_alloc_bandwidth(). If it fails the original interface altsetting
1573 * may be disabled. Drivers cannot rely on any particular alternate
1574 * setting being in effect after a failure.
1575 *
1576 * This call is synchronous, and may not be used in an interrupt context.
1577 * Also, drivers must not change altsettings while urbs are scheduled for
1578 * endpoints in that interface; all such urbs must first be completed
1579 * (perhaps forced by unlinking). If a thread in your driver uses this call,
1580 * make sure your disconnect() method can wait for it to complete.
1581 *
1582 * Return: Zero on success, or else the status code returned by the
1583 * underlying usb_control_msg() call.
1584 */
1585int usb_set_interface(struct usb_device *dev, int interface, int alternate)
1586{
1587	struct usb_interface *iface;
1588	struct usb_host_interface *alt;
1589	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1590	int i, ret, manual = 0;
1591	unsigned int epaddr;
1592	unsigned int pipe;
1593
1594	if (dev->state == USB_STATE_SUSPENDED)
1595		return -EHOSTUNREACH;
1596
1597	iface = usb_ifnum_to_if(dev, interface);
1598	if (!iface) {
1599		dev_dbg(&dev->dev, "selecting invalid interface %d\n",
1600			interface);
1601		return -EINVAL;
1602	}
1603	if (iface->unregistering)
1604		return -ENODEV;
1605
1606	alt = usb_altnum_to_altsetting(iface, alternate);
1607	if (!alt) {
1608		dev_warn(&dev->dev, "selecting invalid altsetting %d\n",
1609			 alternate);
1610		return -EINVAL;
1611	}
1612	/*
1613	 * usb3 hosts configure the interface in usb_hcd_alloc_bandwidth,
1614	 * including freeing dropped endpoint ring buffers.
1615	 * Make sure the interface endpoints are flushed before that
1616	 */
1617	usb_disable_interface(dev, iface, false);
1618
1619	/* Make sure we have enough bandwidth for this alternate interface.
1620	 * Remove the current alt setting and add the new alt setting.
1621	 */
1622	mutex_lock(hcd->bandwidth_mutex);
1623	/* Disable LPM, and re-enable it once the new alt setting is installed,
1624	 * so that the xHCI driver can recalculate the U1/U2 timeouts.
1625	 */
1626	if (usb_disable_lpm(dev)) {
1627		dev_err(&iface->dev, "%s Failed to disable LPM\n", __func__);
1628		mutex_unlock(hcd->bandwidth_mutex);
1629		return -ENOMEM;
1630	}
1631	/* Changing alt-setting also frees any allocated streams */
1632	for (i = 0; i < iface->cur_altsetting->desc.bNumEndpoints; i++)
1633		iface->cur_altsetting->endpoint[i].streams = 0;
1634
1635	ret = usb_hcd_alloc_bandwidth(dev, NULL, iface->cur_altsetting, alt);
1636	if (ret < 0) {
1637		dev_info(&dev->dev, "Not enough bandwidth for altsetting %d\n",
1638				alternate);
1639		usb_enable_lpm(dev);
1640		mutex_unlock(hcd->bandwidth_mutex);
1641		return ret;
1642	}
1643
1644	if (dev->quirks & USB_QUIRK_NO_SET_INTF)
1645		ret = -EPIPE;
1646	else
1647		ret = usb_control_msg_send(dev, 0,
1648					   USB_REQ_SET_INTERFACE,
1649					   USB_RECIP_INTERFACE, alternate,
1650					   interface, NULL, 0, 5000,
1651					   GFP_NOIO);
1652
1653	/* 9.4.10 says devices don't need this and are free to STALL the
1654	 * request if the interface only has one alternate setting.
1655	 */
1656	if (ret == -EPIPE && iface->num_altsetting == 1) {
1657		dev_dbg(&dev->dev,
1658			"manual set_interface for iface %d, alt %d\n",
1659			interface, alternate);
1660		manual = 1;
1661	} else if (ret) {
1662		/* Re-instate the old alt setting */
1663		usb_hcd_alloc_bandwidth(dev, NULL, alt, iface->cur_altsetting);
1664		usb_enable_lpm(dev);
1665		mutex_unlock(hcd->bandwidth_mutex);
1666		return ret;
1667	}
1668	mutex_unlock(hcd->bandwidth_mutex);
1669
1670	/* FIXME drivers shouldn't need to replicate/bugfix the logic here
1671	 * when they implement async or easily-killable versions of this or
1672	 * other "should-be-internal" functions (like clear_halt).
1673	 * should hcd+usbcore postprocess control requests?
1674	 */
1675
1676	/* prevent submissions using previous endpoint settings */
1677	if (iface->cur_altsetting != alt) {
1678		remove_intf_ep_devs(iface);
1679		usb_remove_sysfs_intf_files(iface);
1680	}
1681	usb_disable_interface(dev, iface, true);
1682
1683	iface->cur_altsetting = alt;
1684
1685	/* Now that the interface is installed, re-enable LPM. */
1686	usb_unlocked_enable_lpm(dev);
1687
1688	/* If the interface only has one altsetting and the device didn't
1689	 * accept the request, we attempt to carry out the equivalent action
1690	 * by manually clearing the HALT feature for each endpoint in the
1691	 * new altsetting.
1692	 */
1693	if (manual) {
1694		for (i = 0; i < alt->desc.bNumEndpoints; i++) {
1695			epaddr = alt->endpoint[i].desc.bEndpointAddress;
1696			pipe = __create_pipe(dev,
1697					USB_ENDPOINT_NUMBER_MASK & epaddr) |
1698					(usb_endpoint_out(epaddr) ?
1699					USB_DIR_OUT : USB_DIR_IN);
1700
1701			usb_clear_halt(dev, pipe);
1702		}
1703	}
1704
1705	/* 9.1.1.5: reset toggles for all endpoints in the new altsetting
1706	 *
1707	 * Note:
1708	 * Despite EP0 is always present in all interfaces/AS, the list of
1709	 * endpoints from the descriptor does not contain EP0. Due to its
1710	 * omnipresence one might expect EP0 being considered "affected" by
1711	 * any SetInterface request and hence assume toggles need to be reset.
1712	 * However, EP0 toggles are re-synced for every individual transfer
1713	 * during the SETUP stage - hence EP0 toggles are "don't care" here.
1714	 * (Likewise, EP0 never "halts" on well designed devices.)
1715	 */
1716	usb_enable_interface(dev, iface, true);
1717	if (device_is_registered(&iface->dev)) {
1718		usb_create_sysfs_intf_files(iface);
1719		create_intf_ep_devs(iface);
1720	}
1721	return 0;
1722}
1723EXPORT_SYMBOL_GPL(usb_set_interface);
1724
1725/**
1726 * usb_reset_configuration - lightweight device reset
1727 * @dev: the device whose configuration is being reset
1728 *
1729 * This issues a standard SET_CONFIGURATION request to the device using
1730 * the current configuration.  The effect is to reset most USB-related
1731 * state in the device, including interface altsettings (reset to zero),
1732 * endpoint halts (cleared), and endpoint state (only for bulk and interrupt
1733 * endpoints).  Other usbcore state is unchanged, including bindings of
1734 * usb device drivers to interfaces.
1735 *
1736 * Because this affects multiple interfaces, avoid using this with composite
1737 * (multi-interface) devices.  Instead, the driver for each interface may
1738 * use usb_set_interface() on the interfaces it claims.  Be careful though;
1739 * some devices don't support the SET_INTERFACE request, and others won't
1740 * reset all the interface state (notably endpoint state).  Resetting the whole
1741 * configuration would affect other drivers' interfaces.
1742 *
1743 * The caller must own the device lock.
1744 *
1745 * Return: Zero on success, else a negative error code.
1746 *
1747 * If this routine fails the device will probably be in an unusable state
1748 * with endpoints disabled, and interfaces only partially enabled.
1749 */
1750int usb_reset_configuration(struct usb_device *dev)
1751{
1752	int			i, retval;
1753	struct usb_host_config	*config;
1754	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
1755
1756	if (dev->state == USB_STATE_SUSPENDED)
1757		return -EHOSTUNREACH;
1758
1759	/* caller must have locked the device and must own
1760	 * the usb bus readlock (so driver bindings are stable);
1761	 * calls during probe() are fine
1762	 */
1763
1764	usb_disable_device_endpoints(dev, 1); /* skip ep0*/
1765
1766	config = dev->actconfig;
1767	retval = 0;
1768	mutex_lock(hcd->bandwidth_mutex);
1769	/* Disable LPM, and re-enable it once the configuration is reset, so
1770	 * that the xHCI driver can recalculate the U1/U2 timeouts.
1771	 */
1772	if (usb_disable_lpm(dev)) {
1773		dev_err(&dev->dev, "%s Failed to disable LPM\n", __func__);
1774		mutex_unlock(hcd->bandwidth_mutex);
1775		return -ENOMEM;
1776	}
1777
1778	/* xHCI adds all endpoints in usb_hcd_alloc_bandwidth */
1779	retval = usb_hcd_alloc_bandwidth(dev, config, NULL, NULL);
1780	if (retval < 0) {
1781		usb_enable_lpm(dev);
1782		mutex_unlock(hcd->bandwidth_mutex);
1783		return retval;
1784	}
1785	retval = usb_control_msg_send(dev, 0, USB_REQ_SET_CONFIGURATION, 0,
1786				      config->desc.bConfigurationValue, 0,
1787				      NULL, 0, USB_CTRL_SET_TIMEOUT,
1788				      GFP_NOIO);
1789	if (retval) {
1790		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
1791		usb_enable_lpm(dev);
1792		mutex_unlock(hcd->bandwidth_mutex);
1793		return retval;
1794	}
1795	mutex_unlock(hcd->bandwidth_mutex);
1796
1797	/* re-init hc/hcd interface/endpoint state */
1798	for (i = 0; i < config->desc.bNumInterfaces; i++) {
1799		struct usb_interface *intf = config->interface[i];
1800		struct usb_host_interface *alt;
1801
1802		alt = usb_altnum_to_altsetting(intf, 0);
1803
1804		/* No altsetting 0?  We'll assume the first altsetting.
1805		 * We could use a GetInterface call, but if a device is
1806		 * so non-compliant that it doesn't have altsetting 0
1807		 * then I wouldn't trust its reply anyway.
1808		 */
1809		if (!alt)
1810			alt = &intf->altsetting[0];
1811
1812		if (alt != intf->cur_altsetting) {
1813			remove_intf_ep_devs(intf);
1814			usb_remove_sysfs_intf_files(intf);
1815		}
1816		intf->cur_altsetting = alt;
1817		usb_enable_interface(dev, intf, true);
1818		if (device_is_registered(&intf->dev)) {
1819			usb_create_sysfs_intf_files(intf);
1820			create_intf_ep_devs(intf);
1821		}
1822	}
1823	/* Now that the interfaces are installed, re-enable LPM. */
1824	usb_unlocked_enable_lpm(dev);
1825	return 0;
1826}
1827EXPORT_SYMBOL_GPL(usb_reset_configuration);
1828
1829static void usb_release_interface(struct device *dev)
1830{
1831	struct usb_interface *intf = to_usb_interface(dev);
1832	struct usb_interface_cache *intfc =
1833			altsetting_to_usb_interface_cache(intf->altsetting);
1834
1835	kref_put(&intfc->ref, usb_release_interface_cache);
1836	usb_put_dev(interface_to_usbdev(intf));
1837	of_node_put(dev->of_node);
1838	kfree(intf);
1839}
1840
1841/*
1842 * usb_deauthorize_interface - deauthorize an USB interface
1843 *
1844 * @intf: USB interface structure
1845 */
1846void usb_deauthorize_interface(struct usb_interface *intf)
1847{
1848	struct device *dev = &intf->dev;
1849
1850	device_lock(dev->parent);
1851
1852	if (intf->authorized) {
1853		device_lock(dev);
1854		intf->authorized = 0;
1855		device_unlock(dev);
1856
1857		usb_forced_unbind_intf(intf);
1858	}
1859
1860	device_unlock(dev->parent);
1861}
1862
1863/*
1864 * usb_authorize_interface - authorize an USB interface
1865 *
1866 * @intf: USB interface structure
1867 */
1868void usb_authorize_interface(struct usb_interface *intf)
1869{
1870	struct device *dev = &intf->dev;
1871
1872	if (!intf->authorized) {
1873		device_lock(dev);
1874		intf->authorized = 1; /* authorize interface */
1875		device_unlock(dev);
1876	}
1877}
1878
1879static int usb_if_uevent(const struct device *dev, struct kobj_uevent_env *env)
1880{
1881	const struct usb_device *usb_dev;
1882	const struct usb_interface *intf;
1883	const struct usb_host_interface *alt;
1884
1885	intf = to_usb_interface(dev);
1886	usb_dev = interface_to_usbdev(intf);
1887	alt = intf->cur_altsetting;
1888
1889	if (add_uevent_var(env, "INTERFACE=%d/%d/%d",
1890		   alt->desc.bInterfaceClass,
1891		   alt->desc.bInterfaceSubClass,
1892		   alt->desc.bInterfaceProtocol))
1893		return -ENOMEM;
1894
1895	if (add_uevent_var(env,
1896		   "MODALIAS=usb:"
1897		   "v%04Xp%04Xd%04Xdc%02Xdsc%02Xdp%02Xic%02Xisc%02Xip%02Xin%02X",
1898		   le16_to_cpu(usb_dev->descriptor.idVendor),
1899		   le16_to_cpu(usb_dev->descriptor.idProduct),
1900		   le16_to_cpu(usb_dev->descriptor.bcdDevice),
1901		   usb_dev->descriptor.bDeviceClass,
1902		   usb_dev->descriptor.bDeviceSubClass,
1903		   usb_dev->descriptor.bDeviceProtocol,
1904		   alt->desc.bInterfaceClass,
1905		   alt->desc.bInterfaceSubClass,
1906		   alt->desc.bInterfaceProtocol,
1907		   alt->desc.bInterfaceNumber))
1908		return -ENOMEM;
1909
1910	return 0;
1911}
1912
1913const struct device_type usb_if_device_type = {
1914	.name =		"usb_interface",
1915	.release =	usb_release_interface,
1916	.uevent =	usb_if_uevent,
1917};
1918
1919static struct usb_interface_assoc_descriptor *find_iad(struct usb_device *dev,
1920						struct usb_host_config *config,
1921						u8 inum)
1922{
1923	struct usb_interface_assoc_descriptor *retval = NULL;
1924	struct usb_interface_assoc_descriptor *intf_assoc;
1925	int first_intf;
1926	int last_intf;
1927	int i;
1928
1929	for (i = 0; (i < USB_MAXIADS && config->intf_assoc[i]); i++) {
1930		intf_assoc = config->intf_assoc[i];
1931		if (intf_assoc->bInterfaceCount == 0)
1932			continue;
1933
1934		first_intf = intf_assoc->bFirstInterface;
1935		last_intf = first_intf + (intf_assoc->bInterfaceCount - 1);
1936		if (inum >= first_intf && inum <= last_intf) {
1937			if (!retval)
1938				retval = intf_assoc;
1939			else
1940				dev_err(&dev->dev, "Interface #%d referenced"
1941					" by multiple IADs\n", inum);
1942		}
1943	}
1944
1945	return retval;
1946}
1947
1948
1949/*
1950 * Internal function to queue a device reset
1951 * See usb_queue_reset_device() for more details
1952 */
1953static void __usb_queue_reset_device(struct work_struct *ws)
1954{
1955	int rc;
1956	struct usb_interface *iface =
1957		container_of(ws, struct usb_interface, reset_ws);
1958	struct usb_device *udev = interface_to_usbdev(iface);
1959
1960	rc = usb_lock_device_for_reset(udev, iface);
1961	if (rc >= 0) {
1962		usb_reset_device(udev);
1963		usb_unlock_device(udev);
1964	}
1965	usb_put_intf(iface);	/* Undo _get_ in usb_queue_reset_device() */
1966}
1967
1968/*
1969 * Internal function to set the wireless_status sysfs attribute
1970 * See usb_set_wireless_status() for more details
1971 */
1972static void __usb_wireless_status_intf(struct work_struct *ws)
1973{
1974	struct usb_interface *iface =
1975		container_of(ws, struct usb_interface, wireless_status_work);
1976
1977	device_lock(iface->dev.parent);
1978	if (iface->sysfs_files_created)
1979		usb_update_wireless_status_attr(iface);
1980	device_unlock(iface->dev.parent);
1981	usb_put_intf(iface);	/* Undo _get_ in usb_set_wireless_status() */
1982}
1983
1984/**
1985 * usb_set_wireless_status - sets the wireless_status struct member
1986 * @iface: the interface to modify
1987 * @status: the new wireless status
1988 *
1989 * Set the wireless_status struct member to the new value, and emit
1990 * sysfs changes as necessary.
1991 *
1992 * Returns: 0 on success, -EALREADY if already set.
1993 */
1994int usb_set_wireless_status(struct usb_interface *iface,
1995		enum usb_wireless_status status)
1996{
1997	if (iface->wireless_status == status)
1998		return -EALREADY;
1999
2000	usb_get_intf(iface);
2001	iface->wireless_status = status;
2002	schedule_work(&iface->wireless_status_work);
2003
2004	return 0;
2005}
2006EXPORT_SYMBOL_GPL(usb_set_wireless_status);
2007
2008/*
2009 * usb_set_configuration - Makes a particular device setting be current
2010 * @dev: the device whose configuration is being updated
2011 * @configuration: the configuration being chosen.
2012 *
2013 * Context: task context, might sleep. Caller holds device lock.
2014 *
2015 * This is used to enable non-default device modes.  Not all devices
2016 * use this kind of configurability; many devices only have one
2017 * configuration.
2018 *
2019 * @configuration is the value of the configuration to be installed.
2020 * According to the USB spec (e.g. section 9.1.1.5), configuration values
2021 * must be non-zero; a value of zero indicates that the device in
2022 * unconfigured.  However some devices erroneously use 0 as one of their
2023 * configuration values.  To help manage such devices, this routine will
2024 * accept @configuration = -1 as indicating the device should be put in
2025 * an unconfigured state.
2026 *
2027 * USB device configurations may affect Linux interoperability,
2028 * power consumption and the functionality available.  For example,
2029 * the default configuration is limited to using 100mA of bus power,
2030 * so that when certain device functionality requires more power,
2031 * and the device is bus powered, that functionality should be in some
2032 * non-default device configuration.  Other device modes may also be
2033 * reflected as configuration options, such as whether two ISDN
2034 * channels are available independently; and choosing between open
2035 * standard device protocols (like CDC) or proprietary ones.
2036 *
2037 * Note that a non-authorized device (dev->authorized == 0) will only
2038 * be put in unconfigured mode.
2039 *
2040 * Note that USB has an additional level of device configurability,
2041 * associated with interfaces.  That configurability is accessed using
2042 * usb_set_interface().
2043 *
2044 * This call is synchronous. The calling context must be able to sleep,
2045 * must own the device lock, and must not hold the driver model's USB
2046 * bus mutex; usb interface driver probe() methods cannot use this routine.
2047 *
2048 * Returns zero on success, or else the status code returned by the
2049 * underlying call that failed.  On successful completion, each interface
2050 * in the original device configuration has been destroyed, and each one
2051 * in the new configuration has been probed by all relevant usb device
2052 * drivers currently known to the kernel.
2053 */
2054int usb_set_configuration(struct usb_device *dev, int configuration)
2055{
2056	int i, ret;
2057	struct usb_host_config *cp = NULL;
2058	struct usb_interface **new_interfaces = NULL;
2059	struct usb_hcd *hcd = bus_to_hcd(dev->bus);
2060	int n, nintf;
2061
2062	if (dev->authorized == 0 || configuration == -1)
2063		configuration = 0;
2064	else {
2065		for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
2066			if (dev->config[i].desc.bConfigurationValue ==
2067					configuration) {
2068				cp = &dev->config[i];
2069				break;
2070			}
2071		}
2072	}
2073	if ((!cp && configuration != 0))
2074		return -EINVAL;
2075
2076	/* The USB spec says configuration 0 means unconfigured.
2077	 * But if a device includes a configuration numbered 0,
2078	 * we will accept it as a correctly configured state.
2079	 * Use -1 if you really want to unconfigure the device.
2080	 */
2081	if (cp && configuration == 0)
2082		dev_warn(&dev->dev, "config 0 descriptor??\n");
2083
2084	/* Allocate memory for new interfaces before doing anything else,
2085	 * so that if we run out then nothing will have changed. */
2086	n = nintf = 0;
2087	if (cp) {
2088		nintf = cp->desc.bNumInterfaces;
2089		new_interfaces = kmalloc_array(nintf, sizeof(*new_interfaces),
2090					       GFP_NOIO);
2091		if (!new_interfaces)
2092			return -ENOMEM;
2093
2094		for (; n < nintf; ++n) {
2095			new_interfaces[n] = kzalloc(
2096					sizeof(struct usb_interface),
2097					GFP_NOIO);
2098			if (!new_interfaces[n]) {
2099				ret = -ENOMEM;
2100free_interfaces:
2101				while (--n >= 0)
2102					kfree(new_interfaces[n]);
2103				kfree(new_interfaces);
2104				return ret;
2105			}
2106		}
2107
2108		i = dev->bus_mA - usb_get_max_power(dev, cp);
2109		if (i < 0)
2110			dev_warn(&dev->dev, "new config #%d exceeds power "
2111					"limit by %dmA\n",
2112					configuration, -i);
2113	}
2114
2115	/* Wake up the device so we can send it the Set-Config request */
2116	ret = usb_autoresume_device(dev);
2117	if (ret)
2118		goto free_interfaces;
2119
2120	/* if it's already configured, clear out old state first.
2121	 * getting rid of old interfaces means unbinding their drivers.
2122	 */
2123	if (dev->state != USB_STATE_ADDRESS)
2124		usb_disable_device(dev, 1);	/* Skip ep0 */
2125
2126	/* Get rid of pending async Set-Config requests for this device */
2127	cancel_async_set_config(dev);
2128
2129	/* Make sure we have bandwidth (and available HCD resources) for this
2130	 * configuration.  Remove endpoints from the schedule if we're dropping
2131	 * this configuration to set configuration 0.  After this point, the
2132	 * host controller will not allow submissions to dropped endpoints.  If
2133	 * this call fails, the device state is unchanged.
2134	 */
2135	mutex_lock(hcd->bandwidth_mutex);
2136	/* Disable LPM, and re-enable it once the new configuration is
2137	 * installed, so that the xHCI driver can recalculate the U1/U2
2138	 * timeouts.
2139	 */
2140	if (dev->actconfig && usb_disable_lpm(dev)) {
2141		dev_err(&dev->dev, "%s Failed to disable LPM\n", __func__);
2142		mutex_unlock(hcd->bandwidth_mutex);
2143		ret = -ENOMEM;
2144		goto free_interfaces;
2145	}
2146	ret = usb_hcd_alloc_bandwidth(dev, cp, NULL, NULL);
2147	if (ret < 0) {
2148		if (dev->actconfig)
2149			usb_enable_lpm(dev);
2150		mutex_unlock(hcd->bandwidth_mutex);
2151		usb_autosuspend_device(dev);
2152		goto free_interfaces;
2153	}
2154
2155	/*
2156	 * Initialize the new interface structures and the
2157	 * hc/hcd/usbcore interface/endpoint state.
2158	 */
2159	for (i = 0; i < nintf; ++i) {
2160		struct usb_interface_cache *intfc;
2161		struct usb_interface *intf;
2162		struct usb_host_interface *alt;
2163		u8 ifnum;
2164
2165		cp->interface[i] = intf = new_interfaces[i];
2166		intfc = cp->intf_cache[i];
2167		intf->altsetting = intfc->altsetting;
2168		intf->num_altsetting = intfc->num_altsetting;
2169		intf->authorized = !!HCD_INTF_AUTHORIZED(hcd);
2170		kref_get(&intfc->ref);
2171
2172		alt = usb_altnum_to_altsetting(intf, 0);
2173
2174		/* No altsetting 0?  We'll assume the first altsetting.
2175		 * We could use a GetInterface call, but if a device is
2176		 * so non-compliant that it doesn't have altsetting 0
2177		 * then I wouldn't trust its reply anyway.
2178		 */
2179		if (!alt)
2180			alt = &intf->altsetting[0];
2181
2182		ifnum = alt->desc.bInterfaceNumber;
2183		intf->intf_assoc = find_iad(dev, cp, ifnum);
2184		intf->cur_altsetting = alt;
2185		usb_enable_interface(dev, intf, true);
2186		intf->dev.parent = &dev->dev;
2187		if (usb_of_has_combined_node(dev)) {
2188			device_set_of_node_from_dev(&intf->dev, &dev->dev);
2189		} else {
2190			intf->dev.of_node = usb_of_get_interface_node(dev,
2191					configuration, ifnum);
2192		}
2193		ACPI_COMPANION_SET(&intf->dev, ACPI_COMPANION(&dev->dev));
2194		intf->dev.driver = NULL;
2195		intf->dev.bus = &usb_bus_type;
2196		intf->dev.type = &usb_if_device_type;
2197		intf->dev.groups = usb_interface_groups;
2198		INIT_WORK(&intf->reset_ws, __usb_queue_reset_device);
2199		INIT_WORK(&intf->wireless_status_work, __usb_wireless_status_intf);
2200		intf->minor = -1;
2201		device_initialize(&intf->dev);
2202		pm_runtime_no_callbacks(&intf->dev);
2203		dev_set_name(&intf->dev, "%d-%s:%d.%d", dev->bus->busnum,
2204				dev->devpath, configuration, ifnum);
2205		usb_get_dev(dev);
2206	}
2207	kfree(new_interfaces);
2208
2209	ret = usb_control_msg_send(dev, 0, USB_REQ_SET_CONFIGURATION, 0,
2210				   configuration, 0, NULL, 0,
2211				   USB_CTRL_SET_TIMEOUT, GFP_NOIO);
2212	if (ret && cp) {
2213		/*
2214		 * All the old state is gone, so what else can we do?
2215		 * The device is probably useless now anyway.
2216		 */
2217		usb_hcd_alloc_bandwidth(dev, NULL, NULL, NULL);
2218		for (i = 0; i < nintf; ++i) {
2219			usb_disable_interface(dev, cp->interface[i], true);
2220			put_device(&cp->interface[i]->dev);
2221			cp->interface[i] = NULL;
2222		}
2223		cp = NULL;
2224	}
2225
2226	dev->actconfig = cp;
2227	mutex_unlock(hcd->bandwidth_mutex);
2228
2229	if (!cp) {
2230		usb_set_device_state(dev, USB_STATE_ADDRESS);
2231
2232		/* Leave LPM disabled while the device is unconfigured. */
2233		usb_autosuspend_device(dev);
2234		return ret;
2235	}
2236	usb_set_device_state(dev, USB_STATE_CONFIGURED);
2237
2238	if (cp->string == NULL &&
2239			!(dev->quirks & USB_QUIRK_CONFIG_INTF_STRINGS))
2240		cp->string = usb_cache_string(dev, cp->desc.iConfiguration);
2241
2242	/* Now that the interfaces are installed, re-enable LPM. */
2243	usb_unlocked_enable_lpm(dev);
2244	/* Enable LTM if it was turned off by usb_disable_device. */
2245	usb_enable_ltm(dev);
2246
2247	/* Now that all the interfaces are set up, register them
2248	 * to trigger binding of drivers to interfaces.  probe()
2249	 * routines may install different altsettings and may
2250	 * claim() any interfaces not yet bound.  Many class drivers
2251	 * need that: CDC, audio, video, etc.
2252	 */
2253	for (i = 0; i < nintf; ++i) {
2254		struct usb_interface *intf = cp->interface[i];
2255
2256		if (intf->dev.of_node &&
2257		    !of_device_is_available(intf->dev.of_node)) {
2258			dev_info(&dev->dev, "skipping disabled interface %d\n",
2259				 intf->cur_altsetting->desc.bInterfaceNumber);
2260			continue;
2261		}
2262
2263		dev_dbg(&dev->dev,
2264			"adding %s (config #%d, interface %d)\n",
2265			dev_name(&intf->dev), configuration,
2266			intf->cur_altsetting->desc.bInterfaceNumber);
2267		device_enable_async_suspend(&intf->dev);
2268		ret = device_add(&intf->dev);
2269		if (ret != 0) {
2270			dev_err(&dev->dev, "device_add(%s) --> %d\n",
2271				dev_name(&intf->dev), ret);
2272			continue;
2273		}
2274		create_intf_ep_devs(intf);
2275	}
2276
2277	usb_autosuspend_device(dev);
2278	return 0;
2279}
2280EXPORT_SYMBOL_GPL(usb_set_configuration);
2281
2282static LIST_HEAD(set_config_list);
2283static DEFINE_SPINLOCK(set_config_lock);
2284
2285struct set_config_request {
2286	struct usb_device	*udev;
2287	int			config;
2288	struct work_struct	work;
2289	struct list_head	node;
2290};
2291
2292/* Worker routine for usb_driver_set_configuration() */
2293static void driver_set_config_work(struct work_struct *work)
2294{
2295	struct set_config_request *req =
2296		container_of(work, struct set_config_request, work);
2297	struct usb_device *udev = req->udev;
2298
2299	usb_lock_device(udev);
2300	spin_lock(&set_config_lock);
2301	list_del(&req->node);
2302	spin_unlock(&set_config_lock);
2303
2304	if (req->config >= -1)		/* Is req still valid? */
2305		usb_set_configuration(udev, req->config);
2306	usb_unlock_device(udev);
2307	usb_put_dev(udev);
2308	kfree(req);
2309}
2310
2311/* Cancel pending Set-Config requests for a device whose configuration
2312 * was just changed
2313 */
2314static void cancel_async_set_config(struct usb_device *udev)
2315{
2316	struct set_config_request *req;
2317
2318	spin_lock(&set_config_lock);
2319	list_for_each_entry(req, &set_config_list, node) {
2320		if (req->udev == udev)
2321			req->config = -999;	/* Mark as cancelled */
2322	}
2323	spin_unlock(&set_config_lock);
2324}
2325
2326/**
2327 * usb_driver_set_configuration - Provide a way for drivers to change device configurations
2328 * @udev: the device whose configuration is being updated
2329 * @config: the configuration being chosen.
2330 * Context: In process context, must be able to sleep
2331 *
2332 * Device interface drivers are not allowed to change device configurations.
2333 * This is because changing configurations will destroy the interface the
2334 * driver is bound to and create new ones; it would be like a floppy-disk
2335 * driver telling the computer to replace the floppy-disk drive with a
2336 * tape drive!
2337 *
2338 * Still, in certain specialized circumstances the need may arise.  This
2339 * routine gets around the normal restrictions by using a work thread to
2340 * submit the change-config request.
2341 *
2342 * Return: 0 if the request was successfully queued, error code otherwise.
2343 * The caller has no way to know whether the queued request will eventually
2344 * succeed.
2345 */
2346int usb_driver_set_configuration(struct usb_device *udev, int config)
2347{
2348	struct set_config_request *req;
2349
2350	req = kmalloc(sizeof(*req), GFP_KERNEL);
2351	if (!req)
2352		return -ENOMEM;
2353	req->udev = udev;
2354	req->config = config;
2355	INIT_WORK(&req->work, driver_set_config_work);
2356
2357	spin_lock(&set_config_lock);
2358	list_add(&req->node, &set_config_list);
2359	spin_unlock(&set_config_lock);
2360
2361	usb_get_dev(udev);
2362	schedule_work(&req->work);
2363	return 0;
2364}
2365EXPORT_SYMBOL_GPL(usb_driver_set_configuration);
2366
2367/**
2368 * cdc_parse_cdc_header - parse the extra headers present in CDC devices
2369 * @hdr: the place to put the results of the parsing
2370 * @intf: the interface for which parsing is requested
2371 * @buffer: pointer to the extra headers to be parsed
2372 * @buflen: length of the extra headers
2373 *
2374 * This evaluates the extra headers present in CDC devices which
2375 * bind the interfaces for data and control and provide details
2376 * about the capabilities of the device.
2377 *
2378 * Return: number of descriptors parsed or -EINVAL
2379 * if the header is contradictory beyond salvage
2380 */
2381
2382int cdc_parse_cdc_header(struct usb_cdc_parsed_header *hdr,
2383				struct usb_interface *intf,
2384				u8 *buffer,
2385				int buflen)
2386{
2387	/* duplicates are ignored */
2388	struct usb_cdc_union_desc *union_header = NULL;
2389
2390	/* duplicates are not tolerated */
2391	struct usb_cdc_header_desc *header = NULL;
2392	struct usb_cdc_ether_desc *ether = NULL;
2393	struct usb_cdc_mdlm_detail_desc *detail = NULL;
2394	struct usb_cdc_mdlm_desc *desc = NULL;
2395
2396	unsigned int elength;
2397	int cnt = 0;
2398
2399	memset(hdr, 0x00, sizeof(struct usb_cdc_parsed_header));
2400	hdr->phonet_magic_present = false;
2401	while (buflen > 0) {
2402		elength = buffer[0];
2403		if (!elength) {
2404			dev_err(&intf->dev, "skipping garbage byte\n");
2405			elength = 1;
2406			goto next_desc;
2407		}
2408		if ((buflen < elength) || (elength < 3)) {
2409			dev_err(&intf->dev, "invalid descriptor buffer length\n");
2410			break;
2411		}
2412		if (buffer[1] != USB_DT_CS_INTERFACE) {
2413			dev_err(&intf->dev, "skipping garbage\n");
2414			goto next_desc;
2415		}
2416
2417		switch (buffer[2]) {
2418		case USB_CDC_UNION_TYPE: /* we've found it */
2419			if (elength < sizeof(struct usb_cdc_union_desc))
2420				goto next_desc;
2421			if (union_header) {
2422				dev_err(&intf->dev, "More than one union descriptor, skipping ...\n");
2423				goto next_desc;
2424			}
2425			union_header = (struct usb_cdc_union_desc *)buffer;
2426			break;
2427		case USB_CDC_COUNTRY_TYPE:
2428			if (elength < sizeof(struct usb_cdc_country_functional_desc))
2429				goto next_desc;
2430			hdr->usb_cdc_country_functional_desc =
2431				(struct usb_cdc_country_functional_desc *)buffer;
2432			break;
2433		case USB_CDC_HEADER_TYPE:
2434			if (elength != sizeof(struct usb_cdc_header_desc))
2435				goto next_desc;
2436			if (header)
2437				return -EINVAL;
2438			header = (struct usb_cdc_header_desc *)buffer;
2439			break;
2440		case USB_CDC_ACM_TYPE:
2441			if (elength < sizeof(struct usb_cdc_acm_descriptor))
2442				goto next_desc;
2443			hdr->usb_cdc_acm_descriptor =
2444				(struct usb_cdc_acm_descriptor *)buffer;
2445			break;
2446		case USB_CDC_ETHERNET_TYPE:
2447			if (elength != sizeof(struct usb_cdc_ether_desc))
2448				goto next_desc;
2449			if (ether)
2450				return -EINVAL;
2451			ether = (struct usb_cdc_ether_desc *)buffer;
2452			break;
2453		case USB_CDC_CALL_MANAGEMENT_TYPE:
2454			if (elength < sizeof(struct usb_cdc_call_mgmt_descriptor))
2455				goto next_desc;
2456			hdr->usb_cdc_call_mgmt_descriptor =
2457				(struct usb_cdc_call_mgmt_descriptor *)buffer;
2458			break;
2459		case USB_CDC_DMM_TYPE:
2460			if (elength < sizeof(struct usb_cdc_dmm_desc))
2461				goto next_desc;
2462			hdr->usb_cdc_dmm_desc =
2463				(struct usb_cdc_dmm_desc *)buffer;
2464			break;
2465		case USB_CDC_MDLM_TYPE:
2466			if (elength < sizeof(struct usb_cdc_mdlm_desc))
2467				goto next_desc;
2468			if (desc)
2469				return -EINVAL;
2470			desc = (struct usb_cdc_mdlm_desc *)buffer;
2471			break;
2472		case USB_CDC_MDLM_DETAIL_TYPE:
2473			if (elength < sizeof(struct usb_cdc_mdlm_detail_desc))
2474				goto next_desc;
2475			if (detail)
2476				return -EINVAL;
2477			detail = (struct usb_cdc_mdlm_detail_desc *)buffer;
2478			break;
2479		case USB_CDC_NCM_TYPE:
2480			if (elength < sizeof(struct usb_cdc_ncm_desc))
2481				goto next_desc;
2482			hdr->usb_cdc_ncm_desc = (struct usb_cdc_ncm_desc *)buffer;
2483			break;
2484		case USB_CDC_MBIM_TYPE:
2485			if (elength < sizeof(struct usb_cdc_mbim_desc))
2486				goto next_desc;
2487
2488			hdr->usb_cdc_mbim_desc = (struct usb_cdc_mbim_desc *)buffer;
2489			break;
2490		case USB_CDC_MBIM_EXTENDED_TYPE:
2491			if (elength < sizeof(struct usb_cdc_mbim_extended_desc))
2492				goto next_desc;
2493			hdr->usb_cdc_mbim_extended_desc =
2494				(struct usb_cdc_mbim_extended_desc *)buffer;
2495			break;
2496		case CDC_PHONET_MAGIC_NUMBER:
2497			hdr->phonet_magic_present = true;
2498			break;
2499		default:
2500			/*
2501			 * there are LOTS more CDC descriptors that
2502			 * could legitimately be found here.
2503			 */
2504			dev_dbg(&intf->dev, "Ignoring descriptor: type %02x, length %ud\n",
2505					buffer[2], elength);
2506			goto next_desc;
2507		}
2508		cnt++;
2509next_desc:
2510		buflen -= elength;
2511		buffer += elength;
2512	}
2513	hdr->usb_cdc_union_desc = union_header;
2514	hdr->usb_cdc_header_desc = header;
2515	hdr->usb_cdc_mdlm_detail_desc = detail;
2516	hdr->usb_cdc_mdlm_desc = desc;
2517	hdr->usb_cdc_ether_desc = ether;
2518	return cnt;
2519}
2520
2521EXPORT_SYMBOL(cdc_parse_cdc_header);
~/ Read-only file preview.