Linux Audio

Check our new training course

Loading...
Note: File does not exist in v3.1.
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 * udc.c - Core UDC Framework
   4 *
   5 * Copyright (C) 2010 Texas Instruments
   6 * Author: Felipe Balbi <balbi@ti.com>
   7 */
   8
   9#define pr_fmt(fmt)	"UDC core: " fmt
  10
  11#include <linux/kernel.h>
  12#include <linux/module.h>
  13#include <linux/device.h>
  14#include <linux/list.h>
  15#include <linux/idr.h>
  16#include <linux/err.h>
  17#include <linux/dma-mapping.h>
  18#include <linux/sched/task_stack.h>
  19#include <linux/workqueue.h>
  20
  21#include <linux/usb/ch9.h>
  22#include <linux/usb/gadget.h>
  23#include <linux/usb.h>
  24
  25#include "trace.h"
  26
  27static DEFINE_IDA(gadget_id_numbers);
  28
  29static struct bus_type gadget_bus_type;
  30
  31/**
  32 * struct usb_udc - describes one usb device controller
  33 * @driver: the gadget driver pointer. For use by the class code
  34 * @dev: the child device to the actual controller
  35 * @gadget: the gadget. For use by the class code
  36 * @list: for use by the udc class driver
  37 * @vbus: for udcs who care about vbus status, this value is real vbus status;
  38 * for udcs who do not care about vbus status, this value is always true
  39 * @started: the UDC's started state. True if the UDC had started.
  40 *
  41 * This represents the internal data structure which is used by the UDC-class
  42 * to hold information about udc driver and gadget together.
  43 */
  44struct usb_udc {
  45	struct usb_gadget_driver	*driver;
  46	struct usb_gadget		*gadget;
  47	struct device			dev;
  48	struct list_head		list;
  49	bool				vbus;
  50	bool				started;
  51};
  52
  53static struct class *udc_class;
  54static LIST_HEAD(udc_list);
  55
  56/* Protects udc_list, udc->driver, driver->is_bound, and related calls */
  57static DEFINE_MUTEX(udc_lock);
  58
  59/* ------------------------------------------------------------------------- */
  60
  61/**
  62 * usb_ep_set_maxpacket_limit - set maximum packet size limit for endpoint
  63 * @ep:the endpoint being configured
  64 * @maxpacket_limit:value of maximum packet size limit
  65 *
  66 * This function should be used only in UDC drivers to initialize endpoint
  67 * (usually in probe function).
  68 */
  69void usb_ep_set_maxpacket_limit(struct usb_ep *ep,
  70					      unsigned maxpacket_limit)
  71{
  72	ep->maxpacket_limit = maxpacket_limit;
  73	ep->maxpacket = maxpacket_limit;
  74
  75	trace_usb_ep_set_maxpacket_limit(ep, 0);
  76}
  77EXPORT_SYMBOL_GPL(usb_ep_set_maxpacket_limit);
  78
  79/**
  80 * usb_ep_enable - configure endpoint, making it usable
  81 * @ep:the endpoint being configured.  may not be the endpoint named "ep0".
  82 *	drivers discover endpoints through the ep_list of a usb_gadget.
  83 *
  84 * When configurations are set, or when interface settings change, the driver
  85 * will enable or disable the relevant endpoints.  while it is enabled, an
  86 * endpoint may be used for i/o until the driver receives a disconnect() from
  87 * the host or until the endpoint is disabled.
  88 *
  89 * the ep0 implementation (which calls this routine) must ensure that the
  90 * hardware capabilities of each endpoint match the descriptor provided
  91 * for it.  for example, an endpoint named "ep2in-bulk" would be usable
  92 * for interrupt transfers as well as bulk, but it likely couldn't be used
  93 * for iso transfers or for endpoint 14.  some endpoints are fully
  94 * configurable, with more generic names like "ep-a".  (remember that for
  95 * USB, "in" means "towards the USB host".)
  96 *
  97 * This routine may be called in an atomic (interrupt) context.
  98 *
  99 * returns zero, or a negative error code.
 100 */
 101int usb_ep_enable(struct usb_ep *ep)
 102{
 103	int ret = 0;
 104
 105	if (ep->enabled)
 106		goto out;
 107
 108	/* UDC drivers can't handle endpoints with maxpacket size 0 */
 109	if (usb_endpoint_maxp(ep->desc) == 0) {
 110		/*
 111		 * We should log an error message here, but we can't call
 112		 * dev_err() because there's no way to find the gadget
 113		 * given only ep.
 114		 */
 115		ret = -EINVAL;
 116		goto out;
 117	}
 118
 119	ret = ep->ops->enable(ep, ep->desc);
 120	if (ret)
 121		goto out;
 122
 123	ep->enabled = true;
 124
 125out:
 126	trace_usb_ep_enable(ep, ret);
 127
 128	return ret;
 129}
 130EXPORT_SYMBOL_GPL(usb_ep_enable);
 131
 132/**
 133 * usb_ep_disable - endpoint is no longer usable
 134 * @ep:the endpoint being unconfigured.  may not be the endpoint named "ep0".
 135 *
 136 * no other task may be using this endpoint when this is called.
 137 * any pending and uncompleted requests will complete with status
 138 * indicating disconnect (-ESHUTDOWN) before this call returns.
 139 * gadget drivers must call usb_ep_enable() again before queueing
 140 * requests to the endpoint.
 141 *
 142 * This routine may be called in an atomic (interrupt) context.
 143 *
 144 * returns zero, or a negative error code.
 145 */
 146int usb_ep_disable(struct usb_ep *ep)
 147{
 148	int ret = 0;
 149
 150	if (!ep->enabled)
 151		goto out;
 152
 153	ret = ep->ops->disable(ep);
 154	if (ret)
 155		goto out;
 156
 157	ep->enabled = false;
 158
 159out:
 160	trace_usb_ep_disable(ep, ret);
 161
 162	return ret;
 163}
 164EXPORT_SYMBOL_GPL(usb_ep_disable);
 165
 166/**
 167 * usb_ep_alloc_request - allocate a request object to use with this endpoint
 168 * @ep:the endpoint to be used with with the request
 169 * @gfp_flags:GFP_* flags to use
 170 *
 171 * Request objects must be allocated with this call, since they normally
 172 * need controller-specific setup and may even need endpoint-specific
 173 * resources such as allocation of DMA descriptors.
 174 * Requests may be submitted with usb_ep_queue(), and receive a single
 175 * completion callback.  Free requests with usb_ep_free_request(), when
 176 * they are no longer needed.
 177 *
 178 * Returns the request, or null if one could not be allocated.
 179 */
 180struct usb_request *usb_ep_alloc_request(struct usb_ep *ep,
 181						       gfp_t gfp_flags)
 182{
 183	struct usb_request *req = NULL;
 184
 185	req = ep->ops->alloc_request(ep, gfp_flags);
 186
 187	trace_usb_ep_alloc_request(ep, req, req ? 0 : -ENOMEM);
 188
 189	return req;
 190}
 191EXPORT_SYMBOL_GPL(usb_ep_alloc_request);
 192
 193/**
 194 * usb_ep_free_request - frees a request object
 195 * @ep:the endpoint associated with the request
 196 * @req:the request being freed
 197 *
 198 * Reverses the effect of usb_ep_alloc_request().
 199 * Caller guarantees the request is not queued, and that it will
 200 * no longer be requeued (or otherwise used).
 201 */
 202void usb_ep_free_request(struct usb_ep *ep,
 203				       struct usb_request *req)
 204{
 205	trace_usb_ep_free_request(ep, req, 0);
 206	ep->ops->free_request(ep, req);
 207}
 208EXPORT_SYMBOL_GPL(usb_ep_free_request);
 209
 210/**
 211 * usb_ep_queue - queues (submits) an I/O request to an endpoint.
 212 * @ep:the endpoint associated with the request
 213 * @req:the request being submitted
 214 * @gfp_flags: GFP_* flags to use in case the lower level driver couldn't
 215 *	pre-allocate all necessary memory with the request.
 216 *
 217 * This tells the device controller to perform the specified request through
 218 * that endpoint (reading or writing a buffer).  When the request completes,
 219 * including being canceled by usb_ep_dequeue(), the request's completion
 220 * routine is called to return the request to the driver.  Any endpoint
 221 * (except control endpoints like ep0) may have more than one transfer
 222 * request queued; they complete in FIFO order.  Once a gadget driver
 223 * submits a request, that request may not be examined or modified until it
 224 * is given back to that driver through the completion callback.
 225 *
 226 * Each request is turned into one or more packets.  The controller driver
 227 * never merges adjacent requests into the same packet.  OUT transfers
 228 * will sometimes use data that's already buffered in the hardware.
 229 * Drivers can rely on the fact that the first byte of the request's buffer
 230 * always corresponds to the first byte of some USB packet, for both
 231 * IN and OUT transfers.
 232 *
 233 * Bulk endpoints can queue any amount of data; the transfer is packetized
 234 * automatically.  The last packet will be short if the request doesn't fill it
 235 * out completely.  Zero length packets (ZLPs) should be avoided in portable
 236 * protocols since not all usb hardware can successfully handle zero length
 237 * packets.  (ZLPs may be explicitly written, and may be implicitly written if
 238 * the request 'zero' flag is set.)  Bulk endpoints may also be used
 239 * for interrupt transfers; but the reverse is not true, and some endpoints
 240 * won't support every interrupt transfer.  (Such as 768 byte packets.)
 241 *
 242 * Interrupt-only endpoints are less functional than bulk endpoints, for
 243 * example by not supporting queueing or not handling buffers that are
 244 * larger than the endpoint's maxpacket size.  They may also treat data
 245 * toggle differently.
 246 *
 247 * Control endpoints ... after getting a setup() callback, the driver queues
 248 * one response (even if it would be zero length).  That enables the
 249 * status ack, after transferring data as specified in the response.  Setup
 250 * functions may return negative error codes to generate protocol stalls.
 251 * (Note that some USB device controllers disallow protocol stall responses
 252 * in some cases.)  When control responses are deferred (the response is
 253 * written after the setup callback returns), then usb_ep_set_halt() may be
 254 * used on ep0 to trigger protocol stalls.  Depending on the controller,
 255 * it may not be possible to trigger a status-stage protocol stall when the
 256 * data stage is over, that is, from within the response's completion
 257 * routine.
 258 *
 259 * For periodic endpoints, like interrupt or isochronous ones, the usb host
 260 * arranges to poll once per interval, and the gadget driver usually will
 261 * have queued some data to transfer at that time.
 262 *
 263 * Note that @req's ->complete() callback must never be called from
 264 * within usb_ep_queue() as that can create deadlock situations.
 265 *
 266 * This routine may be called in interrupt context.
 267 *
 268 * Returns zero, or a negative error code.  Endpoints that are not enabled
 269 * report errors; errors will also be
 270 * reported when the usb peripheral is disconnected.
 271 *
 272 * If and only if @req is successfully queued (the return value is zero),
 273 * @req->complete() will be called exactly once, when the Gadget core and
 274 * UDC are finished with the request.  When the completion function is called,
 275 * control of the request is returned to the device driver which submitted it.
 276 * The completion handler may then immediately free or reuse @req.
 277 */
 278int usb_ep_queue(struct usb_ep *ep,
 279			       struct usb_request *req, gfp_t gfp_flags)
 280{
 281	int ret = 0;
 282
 283	if (WARN_ON_ONCE(!ep->enabled && ep->address)) {
 284		ret = -ESHUTDOWN;
 285		goto out;
 286	}
 287
 288	ret = ep->ops->queue(ep, req, gfp_flags);
 289
 290out:
 291	trace_usb_ep_queue(ep, req, ret);
 292
 293	return ret;
 294}
 295EXPORT_SYMBOL_GPL(usb_ep_queue);
 296
 297/**
 298 * usb_ep_dequeue - dequeues (cancels, unlinks) an I/O request from an endpoint
 299 * @ep:the endpoint associated with the request
 300 * @req:the request being canceled
 301 *
 302 * If the request is still active on the endpoint, it is dequeued and
 303 * eventually its completion routine is called (with status -ECONNRESET);
 304 * else a negative error code is returned.  This routine is asynchronous,
 305 * that is, it may return before the completion routine runs.
 306 *
 307 * Note that some hardware can't clear out write fifos (to unlink the request
 308 * at the head of the queue) except as part of disconnecting from usb. Such
 309 * restrictions prevent drivers from supporting configuration changes,
 310 * even to configuration zero (a "chapter 9" requirement).
 311 *
 312 * This routine may be called in interrupt context.
 313 */
 314int usb_ep_dequeue(struct usb_ep *ep, struct usb_request *req)
 315{
 316	int ret;
 317
 318	ret = ep->ops->dequeue(ep, req);
 319	trace_usb_ep_dequeue(ep, req, ret);
 320
 321	return ret;
 322}
 323EXPORT_SYMBOL_GPL(usb_ep_dequeue);
 324
 325/**
 326 * usb_ep_set_halt - sets the endpoint halt feature.
 327 * @ep: the non-isochronous endpoint being stalled
 328 *
 329 * Use this to stall an endpoint, perhaps as an error report.
 330 * Except for control endpoints,
 331 * the endpoint stays halted (will not stream any data) until the host
 332 * clears this feature; drivers may need to empty the endpoint's request
 333 * queue first, to make sure no inappropriate transfers happen.
 334 *
 335 * Note that while an endpoint CLEAR_FEATURE will be invisible to the
 336 * gadget driver, a SET_INTERFACE will not be.  To reset endpoints for the
 337 * current altsetting, see usb_ep_clear_halt().  When switching altsettings,
 338 * it's simplest to use usb_ep_enable() or usb_ep_disable() for the endpoints.
 339 *
 340 * This routine may be called in interrupt context.
 341 *
 342 * Returns zero, or a negative error code.  On success, this call sets
 343 * underlying hardware state that blocks data transfers.
 344 * Attempts to halt IN endpoints will fail (returning -EAGAIN) if any
 345 * transfer requests are still queued, or if the controller hardware
 346 * (usually a FIFO) still holds bytes that the host hasn't collected.
 347 */
 348int usb_ep_set_halt(struct usb_ep *ep)
 349{
 350	int ret;
 351
 352	ret = ep->ops->set_halt(ep, 1);
 353	trace_usb_ep_set_halt(ep, ret);
 354
 355	return ret;
 356}
 357EXPORT_SYMBOL_GPL(usb_ep_set_halt);
 358
 359/**
 360 * usb_ep_clear_halt - clears endpoint halt, and resets toggle
 361 * @ep:the bulk or interrupt endpoint being reset
 362 *
 363 * Use this when responding to the standard usb "set interface" request,
 364 * for endpoints that aren't reconfigured, after clearing any other state
 365 * in the endpoint's i/o queue.
 366 *
 367 * This routine may be called in interrupt context.
 368 *
 369 * Returns zero, or a negative error code.  On success, this call clears
 370 * the underlying hardware state reflecting endpoint halt and data toggle.
 371 * Note that some hardware can't support this request (like pxa2xx_udc),
 372 * and accordingly can't correctly implement interface altsettings.
 373 */
 374int usb_ep_clear_halt(struct usb_ep *ep)
 375{
 376	int ret;
 377
 378	ret = ep->ops->set_halt(ep, 0);
 379	trace_usb_ep_clear_halt(ep, ret);
 380
 381	return ret;
 382}
 383EXPORT_SYMBOL_GPL(usb_ep_clear_halt);
 384
 385/**
 386 * usb_ep_set_wedge - sets the halt feature and ignores clear requests
 387 * @ep: the endpoint being wedged
 388 *
 389 * Use this to stall an endpoint and ignore CLEAR_FEATURE(HALT_ENDPOINT)
 390 * requests. If the gadget driver clears the halt status, it will
 391 * automatically unwedge the endpoint.
 392 *
 393 * This routine may be called in interrupt context.
 394 *
 395 * Returns zero on success, else negative errno.
 396 */
 397int usb_ep_set_wedge(struct usb_ep *ep)
 398{
 399	int ret;
 400
 401	if (ep->ops->set_wedge)
 402		ret = ep->ops->set_wedge(ep);
 403	else
 404		ret = ep->ops->set_halt(ep, 1);
 405
 406	trace_usb_ep_set_wedge(ep, ret);
 407
 408	return ret;
 409}
 410EXPORT_SYMBOL_GPL(usb_ep_set_wedge);
 411
 412/**
 413 * usb_ep_fifo_status - returns number of bytes in fifo, or error
 414 * @ep: the endpoint whose fifo status is being checked.
 415 *
 416 * FIFO endpoints may have "unclaimed data" in them in certain cases,
 417 * such as after aborted transfers.  Hosts may not have collected all
 418 * the IN data written by the gadget driver (and reported by a request
 419 * completion).  The gadget driver may not have collected all the data
 420 * written OUT to it by the host.  Drivers that need precise handling for
 421 * fault reporting or recovery may need to use this call.
 422 *
 423 * This routine may be called in interrupt context.
 424 *
 425 * This returns the number of such bytes in the fifo, or a negative
 426 * errno if the endpoint doesn't use a FIFO or doesn't support such
 427 * precise handling.
 428 */
 429int usb_ep_fifo_status(struct usb_ep *ep)
 430{
 431	int ret;
 432
 433	if (ep->ops->fifo_status)
 434		ret = ep->ops->fifo_status(ep);
 435	else
 436		ret = -EOPNOTSUPP;
 437
 438	trace_usb_ep_fifo_status(ep, ret);
 439
 440	return ret;
 441}
 442EXPORT_SYMBOL_GPL(usb_ep_fifo_status);
 443
 444/**
 445 * usb_ep_fifo_flush - flushes contents of a fifo
 446 * @ep: the endpoint whose fifo is being flushed.
 447 *
 448 * This call may be used to flush the "unclaimed data" that may exist in
 449 * an endpoint fifo after abnormal transaction terminations.  The call
 450 * must never be used except when endpoint is not being used for any
 451 * protocol translation.
 452 *
 453 * This routine may be called in interrupt context.
 454 */
 455void usb_ep_fifo_flush(struct usb_ep *ep)
 456{
 457	if (ep->ops->fifo_flush)
 458		ep->ops->fifo_flush(ep);
 459
 460	trace_usb_ep_fifo_flush(ep, 0);
 461}
 462EXPORT_SYMBOL_GPL(usb_ep_fifo_flush);
 463
 464/* ------------------------------------------------------------------------- */
 465
 466/**
 467 * usb_gadget_frame_number - returns the current frame number
 468 * @gadget: controller that reports the frame number
 469 *
 470 * Returns the usb frame number, normally eleven bits from a SOF packet,
 471 * or negative errno if this device doesn't support this capability.
 472 */
 473int usb_gadget_frame_number(struct usb_gadget *gadget)
 474{
 475	int ret;
 476
 477	ret = gadget->ops->get_frame(gadget);
 478
 479	trace_usb_gadget_frame_number(gadget, ret);
 480
 481	return ret;
 482}
 483EXPORT_SYMBOL_GPL(usb_gadget_frame_number);
 484
 485/**
 486 * usb_gadget_wakeup - tries to wake up the host connected to this gadget
 487 * @gadget: controller used to wake up the host
 488 *
 489 * Returns zero on success, else negative error code if the hardware
 490 * doesn't support such attempts, or its support has not been enabled
 491 * by the usb host.  Drivers must return device descriptors that report
 492 * their ability to support this, or hosts won't enable it.
 493 *
 494 * This may also try to use SRP to wake the host and start enumeration,
 495 * even if OTG isn't otherwise in use.  OTG devices may also start
 496 * remote wakeup even when hosts don't explicitly enable it.
 497 */
 498int usb_gadget_wakeup(struct usb_gadget *gadget)
 499{
 500	int ret = 0;
 501
 502	if (!gadget->ops->wakeup) {
 503		ret = -EOPNOTSUPP;
 504		goto out;
 505	}
 506
 507	ret = gadget->ops->wakeup(gadget);
 508
 509out:
 510	trace_usb_gadget_wakeup(gadget, ret);
 511
 512	return ret;
 513}
 514EXPORT_SYMBOL_GPL(usb_gadget_wakeup);
 515
 516/**
 517 * usb_gadget_set_selfpowered - sets the device selfpowered feature.
 518 * @gadget:the device being declared as self-powered
 519 *
 520 * this affects the device status reported by the hardware driver
 521 * to reflect that it now has a local power supply.
 522 *
 523 * returns zero on success, else negative errno.
 524 */
 525int usb_gadget_set_selfpowered(struct usb_gadget *gadget)
 526{
 527	int ret = 0;
 528
 529	if (!gadget->ops->set_selfpowered) {
 530		ret = -EOPNOTSUPP;
 531		goto out;
 532	}
 533
 534	ret = gadget->ops->set_selfpowered(gadget, 1);
 535
 536out:
 537	trace_usb_gadget_set_selfpowered(gadget, ret);
 538
 539	return ret;
 540}
 541EXPORT_SYMBOL_GPL(usb_gadget_set_selfpowered);
 542
 543/**
 544 * usb_gadget_clear_selfpowered - clear the device selfpowered feature.
 545 * @gadget:the device being declared as bus-powered
 546 *
 547 * this affects the device status reported by the hardware driver.
 548 * some hardware may not support bus-powered operation, in which
 549 * case this feature's value can never change.
 550 *
 551 * returns zero on success, else negative errno.
 552 */
 553int usb_gadget_clear_selfpowered(struct usb_gadget *gadget)
 554{
 555	int ret = 0;
 556
 557	if (!gadget->ops->set_selfpowered) {
 558		ret = -EOPNOTSUPP;
 559		goto out;
 560	}
 561
 562	ret = gadget->ops->set_selfpowered(gadget, 0);
 563
 564out:
 565	trace_usb_gadget_clear_selfpowered(gadget, ret);
 566
 567	return ret;
 568}
 569EXPORT_SYMBOL_GPL(usb_gadget_clear_selfpowered);
 570
 571/**
 572 * usb_gadget_vbus_connect - Notify controller that VBUS is powered
 573 * @gadget:The device which now has VBUS power.
 574 * Context: can sleep
 575 *
 576 * This call is used by a driver for an external transceiver (or GPIO)
 577 * that detects a VBUS power session starting.  Common responses include
 578 * resuming the controller, activating the D+ (or D-) pullup to let the
 579 * host detect that a USB device is attached, and starting to draw power
 580 * (8mA or possibly more, especially after SET_CONFIGURATION).
 581 *
 582 * Returns zero on success, else negative errno.
 583 */
 584int usb_gadget_vbus_connect(struct usb_gadget *gadget)
 585{
 586	int ret = 0;
 587
 588	if (!gadget->ops->vbus_session) {
 589		ret = -EOPNOTSUPP;
 590		goto out;
 591	}
 592
 593	ret = gadget->ops->vbus_session(gadget, 1);
 594
 595out:
 596	trace_usb_gadget_vbus_connect(gadget, ret);
 597
 598	return ret;
 599}
 600EXPORT_SYMBOL_GPL(usb_gadget_vbus_connect);
 601
 602/**
 603 * usb_gadget_vbus_draw - constrain controller's VBUS power usage
 604 * @gadget:The device whose VBUS usage is being described
 605 * @mA:How much current to draw, in milliAmperes.  This should be twice
 606 *	the value listed in the configuration descriptor bMaxPower field.
 607 *
 608 * This call is used by gadget drivers during SET_CONFIGURATION calls,
 609 * reporting how much power the device may consume.  For example, this
 610 * could affect how quickly batteries are recharged.
 611 *
 612 * Returns zero on success, else negative errno.
 613 */
 614int usb_gadget_vbus_draw(struct usb_gadget *gadget, unsigned mA)
 615{
 616	int ret = 0;
 617
 618	if (!gadget->ops->vbus_draw) {
 619		ret = -EOPNOTSUPP;
 620		goto out;
 621	}
 622
 623	ret = gadget->ops->vbus_draw(gadget, mA);
 624	if (!ret)
 625		gadget->mA = mA;
 626
 627out:
 628	trace_usb_gadget_vbus_draw(gadget, ret);
 629
 630	return ret;
 631}
 632EXPORT_SYMBOL_GPL(usb_gadget_vbus_draw);
 633
 634/**
 635 * usb_gadget_vbus_disconnect - notify controller about VBUS session end
 636 * @gadget:the device whose VBUS supply is being described
 637 * Context: can sleep
 638 *
 639 * This call is used by a driver for an external transceiver (or GPIO)
 640 * that detects a VBUS power session ending.  Common responses include
 641 * reversing everything done in usb_gadget_vbus_connect().
 642 *
 643 * Returns zero on success, else negative errno.
 644 */
 645int usb_gadget_vbus_disconnect(struct usb_gadget *gadget)
 646{
 647	int ret = 0;
 648
 649	if (!gadget->ops->vbus_session) {
 650		ret = -EOPNOTSUPP;
 651		goto out;
 652	}
 653
 654	ret = gadget->ops->vbus_session(gadget, 0);
 655
 656out:
 657	trace_usb_gadget_vbus_disconnect(gadget, ret);
 658
 659	return ret;
 660}
 661EXPORT_SYMBOL_GPL(usb_gadget_vbus_disconnect);
 662
 663/**
 664 * usb_gadget_connect - software-controlled connect to USB host
 665 * @gadget:the peripheral being connected
 666 *
 667 * Enables the D+ (or potentially D-) pullup.  The host will start
 668 * enumerating this gadget when the pullup is active and a VBUS session
 669 * is active (the link is powered).
 670 *
 671 * Returns zero on success, else negative errno.
 672 */
 673int usb_gadget_connect(struct usb_gadget *gadget)
 674{
 675	int ret = 0;
 676
 677	if (!gadget->ops->pullup) {
 678		ret = -EOPNOTSUPP;
 679		goto out;
 680	}
 681
 682	if (gadget->deactivated) {
 683		/*
 684		 * If gadget is deactivated we only save new state.
 685		 * Gadget will be connected automatically after activation.
 686		 */
 687		gadget->connected = true;
 688		goto out;
 689	}
 690
 691	ret = gadget->ops->pullup(gadget, 1);
 692	if (!ret)
 693		gadget->connected = 1;
 694
 695out:
 696	trace_usb_gadget_connect(gadget, ret);
 697
 698	return ret;
 699}
 700EXPORT_SYMBOL_GPL(usb_gadget_connect);
 701
 702/**
 703 * usb_gadget_disconnect - software-controlled disconnect from USB host
 704 * @gadget:the peripheral being disconnected
 705 *
 706 * Disables the D+ (or potentially D-) pullup, which the host may see
 707 * as a disconnect (when a VBUS session is active).  Not all systems
 708 * support software pullup controls.
 709 *
 710 * Following a successful disconnect, invoke the ->disconnect() callback
 711 * for the current gadget driver so that UDC drivers don't need to.
 712 *
 713 * Returns zero on success, else negative errno.
 714 */
 715int usb_gadget_disconnect(struct usb_gadget *gadget)
 716{
 717	int ret = 0;
 718
 719	if (!gadget->ops->pullup) {
 720		ret = -EOPNOTSUPP;
 721		goto out;
 722	}
 723
 724	if (!gadget->connected)
 725		goto out;
 726
 727	if (gadget->deactivated) {
 728		/*
 729		 * If gadget is deactivated we only save new state.
 730		 * Gadget will stay disconnected after activation.
 731		 */
 732		gadget->connected = false;
 733		goto out;
 734	}
 735
 736	ret = gadget->ops->pullup(gadget, 0);
 737	if (!ret)
 738		gadget->connected = 0;
 739
 740	mutex_lock(&udc_lock);
 741	if (gadget->udc->driver)
 742		gadget->udc->driver->disconnect(gadget);
 743	mutex_unlock(&udc_lock);
 744
 745out:
 746	trace_usb_gadget_disconnect(gadget, ret);
 747
 748	return ret;
 749}
 750EXPORT_SYMBOL_GPL(usb_gadget_disconnect);
 751
 752/**
 753 * usb_gadget_deactivate - deactivate function which is not ready to work
 754 * @gadget: the peripheral being deactivated
 755 *
 756 * This routine may be used during the gadget driver bind() call to prevent
 757 * the peripheral from ever being visible to the USB host, unless later
 758 * usb_gadget_activate() is called.  For example, user mode components may
 759 * need to be activated before the system can talk to hosts.
 760 *
 761 * Returns zero on success, else negative errno.
 762 */
 763int usb_gadget_deactivate(struct usb_gadget *gadget)
 764{
 765	int ret = 0;
 766
 767	if (gadget->deactivated)
 768		goto out;
 769
 770	if (gadget->connected) {
 771		ret = usb_gadget_disconnect(gadget);
 772		if (ret)
 773			goto out;
 774
 775		/*
 776		 * If gadget was being connected before deactivation, we want
 777		 * to reconnect it in usb_gadget_activate().
 778		 */
 779		gadget->connected = true;
 780	}
 781	gadget->deactivated = true;
 782
 783out:
 784	trace_usb_gadget_deactivate(gadget, ret);
 785
 786	return ret;
 787}
 788EXPORT_SYMBOL_GPL(usb_gadget_deactivate);
 789
 790/**
 791 * usb_gadget_activate - activate function which is not ready to work
 792 * @gadget: the peripheral being activated
 793 *
 794 * This routine activates gadget which was previously deactivated with
 795 * usb_gadget_deactivate() call. It calls usb_gadget_connect() if needed.
 796 *
 797 * Returns zero on success, else negative errno.
 798 */
 799int usb_gadget_activate(struct usb_gadget *gadget)
 800{
 801	int ret = 0;
 802
 803	if (!gadget->deactivated)
 804		goto out;
 805
 806	gadget->deactivated = false;
 807
 808	/*
 809	 * If gadget has been connected before deactivation, or became connected
 810	 * while it was being deactivated, we call usb_gadget_connect().
 811	 */
 812	if (gadget->connected)
 813		ret = usb_gadget_connect(gadget);
 814
 815out:
 816	trace_usb_gadget_activate(gadget, ret);
 817
 818	return ret;
 819}
 820EXPORT_SYMBOL_GPL(usb_gadget_activate);
 821
 822/* ------------------------------------------------------------------------- */
 823
 824#ifdef	CONFIG_HAS_DMA
 825
 826int usb_gadget_map_request_by_dev(struct device *dev,
 827		struct usb_request *req, int is_in)
 828{
 829	if (req->length == 0)
 830		return 0;
 831
 832	if (req->num_sgs) {
 833		int     mapped;
 834
 835		mapped = dma_map_sg(dev, req->sg, req->num_sgs,
 836				is_in ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
 837		if (mapped == 0) {
 838			dev_err(dev, "failed to map SGs\n");
 839			return -EFAULT;
 840		}
 841
 842		req->num_mapped_sgs = mapped;
 843	} else {
 844		if (is_vmalloc_addr(req->buf)) {
 845			dev_err(dev, "buffer is not dma capable\n");
 846			return -EFAULT;
 847		} else if (object_is_on_stack(req->buf)) {
 848			dev_err(dev, "buffer is on stack\n");
 849			return -EFAULT;
 850		}
 851
 852		req->dma = dma_map_single(dev, req->buf, req->length,
 853				is_in ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
 854
 855		if (dma_mapping_error(dev, req->dma)) {
 856			dev_err(dev, "failed to map buffer\n");
 857			return -EFAULT;
 858		}
 859
 860		req->dma_mapped = 1;
 861	}
 862
 863	return 0;
 864}
 865EXPORT_SYMBOL_GPL(usb_gadget_map_request_by_dev);
 866
 867int usb_gadget_map_request(struct usb_gadget *gadget,
 868		struct usb_request *req, int is_in)
 869{
 870	return usb_gadget_map_request_by_dev(gadget->dev.parent, req, is_in);
 871}
 872EXPORT_SYMBOL_GPL(usb_gadget_map_request);
 873
 874void usb_gadget_unmap_request_by_dev(struct device *dev,
 875		struct usb_request *req, int is_in)
 876{
 877	if (req->length == 0)
 878		return;
 879
 880	if (req->num_mapped_sgs) {
 881		dma_unmap_sg(dev, req->sg, req->num_sgs,
 882				is_in ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
 883
 884		req->num_mapped_sgs = 0;
 885	} else if (req->dma_mapped) {
 886		dma_unmap_single(dev, req->dma, req->length,
 887				is_in ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
 888		req->dma_mapped = 0;
 889	}
 890}
 891EXPORT_SYMBOL_GPL(usb_gadget_unmap_request_by_dev);
 892
 893void usb_gadget_unmap_request(struct usb_gadget *gadget,
 894		struct usb_request *req, int is_in)
 895{
 896	usb_gadget_unmap_request_by_dev(gadget->dev.parent, req, is_in);
 897}
 898EXPORT_SYMBOL_GPL(usb_gadget_unmap_request);
 899
 900#endif	/* CONFIG_HAS_DMA */
 901
 902/* ------------------------------------------------------------------------- */
 903
 904/**
 905 * usb_gadget_giveback_request - give the request back to the gadget layer
 906 * @ep: the endpoint to be used with with the request
 907 * @req: the request being given back
 908 *
 909 * This is called by device controller drivers in order to return the
 910 * completed request back to the gadget layer.
 911 */
 912void usb_gadget_giveback_request(struct usb_ep *ep,
 913		struct usb_request *req)
 914{
 915	if (likely(req->status == 0))
 916		usb_led_activity(USB_LED_EVENT_GADGET);
 917
 918	trace_usb_gadget_giveback_request(ep, req, 0);
 919
 920	req->complete(ep, req);
 921}
 922EXPORT_SYMBOL_GPL(usb_gadget_giveback_request);
 923
 924/* ------------------------------------------------------------------------- */
 925
 926/**
 927 * gadget_find_ep_by_name - returns ep whose name is the same as sting passed
 928 *	in second parameter or NULL if searched endpoint not found
 929 * @g: controller to check for quirk
 930 * @name: name of searched endpoint
 931 */
 932struct usb_ep *gadget_find_ep_by_name(struct usb_gadget *g, const char *name)
 933{
 934	struct usb_ep *ep;
 935
 936	gadget_for_each_ep(ep, g) {
 937		if (!strcmp(ep->name, name))
 938			return ep;
 939	}
 940
 941	return NULL;
 942}
 943EXPORT_SYMBOL_GPL(gadget_find_ep_by_name);
 944
 945/* ------------------------------------------------------------------------- */
 946
 947int usb_gadget_ep_match_desc(struct usb_gadget *gadget,
 948		struct usb_ep *ep, struct usb_endpoint_descriptor *desc,
 949		struct usb_ss_ep_comp_descriptor *ep_comp)
 950{
 951	u8		type;
 952	u16		max;
 953	int		num_req_streams = 0;
 954
 955	/* endpoint already claimed? */
 956	if (ep->claimed)
 957		return 0;
 958
 959	type = usb_endpoint_type(desc);
 960	max = usb_endpoint_maxp(desc);
 961
 962	if (usb_endpoint_dir_in(desc) && !ep->caps.dir_in)
 963		return 0;
 964	if (usb_endpoint_dir_out(desc) && !ep->caps.dir_out)
 965		return 0;
 966
 967	if (max > ep->maxpacket_limit)
 968		return 0;
 969
 970	/* "high bandwidth" works only at high speed */
 971	if (!gadget_is_dualspeed(gadget) && usb_endpoint_maxp_mult(desc) > 1)
 972		return 0;
 973
 974	switch (type) {
 975	case USB_ENDPOINT_XFER_CONTROL:
 976		/* only support ep0 for portable CONTROL traffic */
 977		return 0;
 978	case USB_ENDPOINT_XFER_ISOC:
 979		if (!ep->caps.type_iso)
 980			return 0;
 981		/* ISO:  limit 1023 bytes full speed, 1024 high/super speed */
 982		if (!gadget_is_dualspeed(gadget) && max > 1023)
 983			return 0;
 984		break;
 985	case USB_ENDPOINT_XFER_BULK:
 986		if (!ep->caps.type_bulk)
 987			return 0;
 988		if (ep_comp && gadget_is_superspeed(gadget)) {
 989			/* Get the number of required streams from the
 990			 * EP companion descriptor and see if the EP
 991			 * matches it
 992			 */
 993			num_req_streams = ep_comp->bmAttributes & 0x1f;
 994			if (num_req_streams > ep->max_streams)
 995				return 0;
 996		}
 997		break;
 998	case USB_ENDPOINT_XFER_INT:
 999		/* Bulk endpoints handle interrupt transfers,
1000		 * except the toggle-quirky iso-synch kind
1001		 */
1002		if (!ep->caps.type_int && !ep->caps.type_bulk)
1003			return 0;
1004		/* INT:  limit 64 bytes full speed, 1024 high/super speed */
1005		if (!gadget_is_dualspeed(gadget) && max > 64)
1006			return 0;
1007		break;
1008	}
1009
1010	return 1;
1011}
1012EXPORT_SYMBOL_GPL(usb_gadget_ep_match_desc);
1013
1014/**
1015 * usb_gadget_check_config - checks if the UDC can support the binded
1016 *	configuration
1017 * @gadget: controller to check the USB configuration
1018 *
1019 * Ensure that a UDC is able to support the requested resources by a
1020 * configuration, and that there are no resource limitations, such as
1021 * internal memory allocated to all requested endpoints.
1022 *
1023 * Returns zero on success, else a negative errno.
1024 */
1025int usb_gadget_check_config(struct usb_gadget *gadget)
1026{
1027	if (gadget->ops->check_config)
1028		return gadget->ops->check_config(gadget);
1029	return 0;
1030}
1031EXPORT_SYMBOL_GPL(usb_gadget_check_config);
1032
1033/* ------------------------------------------------------------------------- */
1034
1035static void usb_gadget_state_work(struct work_struct *work)
1036{
1037	struct usb_gadget *gadget = work_to_gadget(work);
1038	struct usb_udc *udc = gadget->udc;
1039
1040	if (udc)
1041		sysfs_notify(&udc->dev.kobj, NULL, "state");
1042}
1043
1044void usb_gadget_set_state(struct usb_gadget *gadget,
1045		enum usb_device_state state)
1046{
1047	gadget->state = state;
1048	schedule_work(&gadget->work);
1049}
1050EXPORT_SYMBOL_GPL(usb_gadget_set_state);
1051
1052/* ------------------------------------------------------------------------- */
1053
1054static void usb_udc_connect_control(struct usb_udc *udc)
1055{
1056	if (udc->vbus)
1057		usb_gadget_connect(udc->gadget);
1058	else
1059		usb_gadget_disconnect(udc->gadget);
1060}
1061
1062/**
1063 * usb_udc_vbus_handler - updates the udc core vbus status, and try to
1064 * connect or disconnect gadget
1065 * @gadget: The gadget which vbus change occurs
1066 * @status: The vbus status
1067 *
1068 * The udc driver calls it when it wants to connect or disconnect gadget
1069 * according to vbus status.
1070 */
1071void usb_udc_vbus_handler(struct usb_gadget *gadget, bool status)
1072{
1073	struct usb_udc *udc = gadget->udc;
1074
1075	if (udc) {
1076		udc->vbus = status;
1077		usb_udc_connect_control(udc);
1078	}
1079}
1080EXPORT_SYMBOL_GPL(usb_udc_vbus_handler);
1081
1082/**
1083 * usb_gadget_udc_reset - notifies the udc core that bus reset occurs
1084 * @gadget: The gadget which bus reset occurs
1085 * @driver: The gadget driver we want to notify
1086 *
1087 * If the udc driver has bus reset handler, it needs to call this when the bus
1088 * reset occurs, it notifies the gadget driver that the bus reset occurs as
1089 * well as updates gadget state.
1090 */
1091void usb_gadget_udc_reset(struct usb_gadget *gadget,
1092		struct usb_gadget_driver *driver)
1093{
1094	driver->reset(gadget);
1095	usb_gadget_set_state(gadget, USB_STATE_DEFAULT);
1096}
1097EXPORT_SYMBOL_GPL(usb_gadget_udc_reset);
1098
1099/**
1100 * usb_gadget_udc_start - tells usb device controller to start up
1101 * @udc: The UDC to be started
1102 *
1103 * This call is issued by the UDC Class driver when it's about
1104 * to register a gadget driver to the device controller, before
1105 * calling gadget driver's bind() method.
1106 *
1107 * It allows the controller to be powered off until strictly
1108 * necessary to have it powered on.
1109 *
1110 * Returns zero on success, else negative errno.
1111 */
1112static inline int usb_gadget_udc_start(struct usb_udc *udc)
1113{
1114	int ret;
1115
1116	if (udc->started) {
1117		dev_err(&udc->dev, "UDC had already started\n");
1118		return -EBUSY;
1119	}
1120
1121	ret = udc->gadget->ops->udc_start(udc->gadget, udc->driver);
1122	if (!ret)
1123		udc->started = true;
1124
1125	return ret;
1126}
1127
1128/**
1129 * usb_gadget_udc_stop - tells usb device controller we don't need it anymore
1130 * @udc: The UDC to be stopped
1131 *
1132 * This call is issued by the UDC Class driver after calling
1133 * gadget driver's unbind() method.
1134 *
1135 * The details are implementation specific, but it can go as
1136 * far as powering off UDC completely and disable its data
1137 * line pullups.
1138 */
1139static inline void usb_gadget_udc_stop(struct usb_udc *udc)
1140{
1141	if (!udc->started) {
1142		dev_err(&udc->dev, "UDC had already stopped\n");
1143		return;
1144	}
1145
1146	udc->gadget->ops->udc_stop(udc->gadget);
1147	udc->started = false;
1148}
1149
1150/**
1151 * usb_gadget_udc_set_speed - tells usb device controller speed supported by
1152 *    current driver
1153 * @udc: The device we want to set maximum speed
1154 * @speed: The maximum speed to allowed to run
1155 *
1156 * This call is issued by the UDC Class driver before calling
1157 * usb_gadget_udc_start() in order to make sure that we don't try to
1158 * connect on speeds the gadget driver doesn't support.
1159 */
1160static inline void usb_gadget_udc_set_speed(struct usb_udc *udc,
1161					    enum usb_device_speed speed)
1162{
1163	struct usb_gadget *gadget = udc->gadget;
1164	enum usb_device_speed s;
1165
1166	if (speed == USB_SPEED_UNKNOWN)
1167		s = gadget->max_speed;
1168	else
1169		s = min(speed, gadget->max_speed);
1170
1171	if (s == USB_SPEED_SUPER_PLUS && gadget->ops->udc_set_ssp_rate)
1172		gadget->ops->udc_set_ssp_rate(gadget, gadget->max_ssp_rate);
1173	else if (gadget->ops->udc_set_speed)
1174		gadget->ops->udc_set_speed(gadget, s);
1175}
1176
1177/**
1178 * usb_gadget_enable_async_callbacks - tell usb device controller to enable asynchronous callbacks
1179 * @udc: The UDC which should enable async callbacks
1180 *
1181 * This routine is used when binding gadget drivers.  It undoes the effect
1182 * of usb_gadget_disable_async_callbacks(); the UDC driver should enable IRQs
1183 * (if necessary) and resume issuing callbacks.
1184 *
1185 * This routine will always be called in process context.
1186 */
1187static inline void usb_gadget_enable_async_callbacks(struct usb_udc *udc)
1188{
1189	struct usb_gadget *gadget = udc->gadget;
1190
1191	if (gadget->ops->udc_async_callbacks)
1192		gadget->ops->udc_async_callbacks(gadget, true);
1193}
1194
1195/**
1196 * usb_gadget_disable_async_callbacks - tell usb device controller to disable asynchronous callbacks
1197 * @udc: The UDC which should disable async callbacks
1198 *
1199 * This routine is used when unbinding gadget drivers.  It prevents a race:
1200 * The UDC driver doesn't know when the gadget driver's ->unbind callback
1201 * runs, so unless it is told to disable asynchronous callbacks, it might
1202 * issue a callback (such as ->disconnect) after the unbind has completed.
1203 *
1204 * After this function runs, the UDC driver must suppress all ->suspend,
1205 * ->resume, ->disconnect, ->reset, and ->setup callbacks to the gadget driver
1206 * until async callbacks are again enabled.  A simple-minded but effective
1207 * way to accomplish this is to tell the UDC hardware not to generate any
1208 * more IRQs.
1209 *
1210 * Request completion callbacks must still be issued.  However, it's okay
1211 * to defer them until the request is cancelled, since the pull-up will be
1212 * turned off during the time period when async callbacks are disabled.
1213 *
1214 * This routine will always be called in process context.
1215 */
1216static inline void usb_gadget_disable_async_callbacks(struct usb_udc *udc)
1217{
1218	struct usb_gadget *gadget = udc->gadget;
1219
1220	if (gadget->ops->udc_async_callbacks)
1221		gadget->ops->udc_async_callbacks(gadget, false);
1222}
1223
1224/**
1225 * usb_udc_release - release the usb_udc struct
1226 * @dev: the dev member within usb_udc
1227 *
1228 * This is called by driver's core in order to free memory once the last
1229 * reference is released.
1230 */
1231static void usb_udc_release(struct device *dev)
1232{
1233	struct usb_udc *udc;
1234
1235	udc = container_of(dev, struct usb_udc, dev);
1236	dev_dbg(dev, "releasing '%s'\n", dev_name(dev));
1237	kfree(udc);
1238}
1239
1240static const struct attribute_group *usb_udc_attr_groups[];
1241
1242static void usb_udc_nop_release(struct device *dev)
1243{
1244	dev_vdbg(dev, "%s\n", __func__);
1245}
1246
1247/**
1248 * usb_initialize_gadget - initialize a gadget and its embedded struct device
1249 * @parent: the parent device to this udc. Usually the controller driver's
1250 * device.
1251 * @gadget: the gadget to be initialized.
1252 * @release: a gadget release function.
1253 */
1254void usb_initialize_gadget(struct device *parent, struct usb_gadget *gadget,
1255		void (*release)(struct device *dev))
1256{
1257	INIT_WORK(&gadget->work, usb_gadget_state_work);
1258	gadget->dev.parent = parent;
1259
1260	if (release)
1261		gadget->dev.release = release;
1262	else
1263		gadget->dev.release = usb_udc_nop_release;
1264
1265	device_initialize(&gadget->dev);
1266	gadget->dev.bus = &gadget_bus_type;
1267}
1268EXPORT_SYMBOL_GPL(usb_initialize_gadget);
1269
1270/**
1271 * usb_add_gadget - adds a new gadget to the udc class driver list
1272 * @gadget: the gadget to be added to the list.
1273 *
1274 * Returns zero on success, negative errno otherwise.
1275 * Does not do a final usb_put_gadget() if an error occurs.
1276 */
1277int usb_add_gadget(struct usb_gadget *gadget)
1278{
1279	struct usb_udc		*udc;
1280	int			ret = -ENOMEM;
1281
1282	udc = kzalloc(sizeof(*udc), GFP_KERNEL);
1283	if (!udc)
1284		goto error;
1285
1286	device_initialize(&udc->dev);
1287	udc->dev.release = usb_udc_release;
1288	udc->dev.class = udc_class;
1289	udc->dev.groups = usb_udc_attr_groups;
1290	udc->dev.parent = gadget->dev.parent;
1291	ret = dev_set_name(&udc->dev, "%s",
1292			kobject_name(&gadget->dev.parent->kobj));
1293	if (ret)
1294		goto err_put_udc;
1295
1296	udc->gadget = gadget;
1297	gadget->udc = udc;
1298
1299	udc->started = false;
1300
1301	mutex_lock(&udc_lock);
1302	list_add_tail(&udc->list, &udc_list);
1303	mutex_unlock(&udc_lock);
1304
1305	ret = device_add(&udc->dev);
1306	if (ret)
1307		goto err_unlist_udc;
1308
1309	usb_gadget_set_state(gadget, USB_STATE_NOTATTACHED);
1310	udc->vbus = true;
1311
1312	ret = ida_alloc(&gadget_id_numbers, GFP_KERNEL);
1313	if (ret < 0)
1314		goto err_del_udc;
1315	gadget->id_number = ret;
1316	dev_set_name(&gadget->dev, "gadget.%d", ret);
1317
1318	ret = device_add(&gadget->dev);
1319	if (ret)
1320		goto err_free_id;
1321
1322	return 0;
1323
1324 err_free_id:
1325	ida_free(&gadget_id_numbers, gadget->id_number);
1326
1327 err_del_udc:
1328	flush_work(&gadget->work);
1329	device_del(&udc->dev);
1330
1331 err_unlist_udc:
1332	mutex_lock(&udc_lock);
1333	list_del(&udc->list);
1334	mutex_unlock(&udc_lock);
1335
1336 err_put_udc:
1337	put_device(&udc->dev);
1338
1339 error:
1340	return ret;
1341}
1342EXPORT_SYMBOL_GPL(usb_add_gadget);
1343
1344/**
1345 * usb_add_gadget_udc_release - adds a new gadget to the udc class driver list
1346 * @parent: the parent device to this udc. Usually the controller driver's
1347 * device.
1348 * @gadget: the gadget to be added to the list.
1349 * @release: a gadget release function.
1350 *
1351 * Returns zero on success, negative errno otherwise.
1352 * Calls the gadget release function in the latter case.
1353 */
1354int usb_add_gadget_udc_release(struct device *parent, struct usb_gadget *gadget,
1355		void (*release)(struct device *dev))
1356{
1357	int	ret;
1358
1359	usb_initialize_gadget(parent, gadget, release);
1360	ret = usb_add_gadget(gadget);
1361	if (ret)
1362		usb_put_gadget(gadget);
1363	return ret;
1364}
1365EXPORT_SYMBOL_GPL(usb_add_gadget_udc_release);
1366
1367/**
1368 * usb_get_gadget_udc_name - get the name of the first UDC controller
1369 * This functions returns the name of the first UDC controller in the system.
1370 * Please note that this interface is usefull only for legacy drivers which
1371 * assume that there is only one UDC controller in the system and they need to
1372 * get its name before initialization. There is no guarantee that the UDC
1373 * of the returned name will be still available, when gadget driver registers
1374 * itself.
1375 *
1376 * Returns pointer to string with UDC controller name on success, NULL
1377 * otherwise. Caller should kfree() returned string.
1378 */
1379char *usb_get_gadget_udc_name(void)
1380{
1381	struct usb_udc *udc;
1382	char *name = NULL;
1383
1384	/* For now we take the first available UDC */
1385	mutex_lock(&udc_lock);
1386	list_for_each_entry(udc, &udc_list, list) {
1387		if (!udc->driver) {
1388			name = kstrdup(udc->gadget->name, GFP_KERNEL);
1389			break;
1390		}
1391	}
1392	mutex_unlock(&udc_lock);
1393	return name;
1394}
1395EXPORT_SYMBOL_GPL(usb_get_gadget_udc_name);
1396
1397/**
1398 * usb_add_gadget_udc - adds a new gadget to the udc class driver list
1399 * @parent: the parent device to this udc. Usually the controller
1400 * driver's device.
1401 * @gadget: the gadget to be added to the list
1402 *
1403 * Returns zero on success, negative errno otherwise.
1404 */
1405int usb_add_gadget_udc(struct device *parent, struct usb_gadget *gadget)
1406{
1407	return usb_add_gadget_udc_release(parent, gadget, NULL);
1408}
1409EXPORT_SYMBOL_GPL(usb_add_gadget_udc);
1410
1411/**
1412 * usb_del_gadget - deletes a gadget and unregisters its udc
1413 * @gadget: the gadget to be deleted.
1414 *
1415 * This will unbind @gadget, if it is bound.
1416 * It will not do a final usb_put_gadget().
1417 */
1418void usb_del_gadget(struct usb_gadget *gadget)
1419{
1420	struct usb_udc *udc = gadget->udc;
1421
1422	if (!udc)
1423		return;
1424
1425	dev_vdbg(gadget->dev.parent, "unregistering gadget\n");
1426
1427	mutex_lock(&udc_lock);
1428	list_del(&udc->list);
1429	mutex_unlock(&udc_lock);
1430
1431	kobject_uevent(&udc->dev.kobj, KOBJ_REMOVE);
1432	flush_work(&gadget->work);
1433	device_del(&gadget->dev);
1434	ida_free(&gadget_id_numbers, gadget->id_number);
1435	device_unregister(&udc->dev);
1436}
1437EXPORT_SYMBOL_GPL(usb_del_gadget);
1438
1439/**
1440 * usb_del_gadget_udc - unregisters a gadget
1441 * @gadget: the gadget to be unregistered.
1442 *
1443 * Calls usb_del_gadget() and does a final usb_put_gadget().
1444 */
1445void usb_del_gadget_udc(struct usb_gadget *gadget)
1446{
1447	usb_del_gadget(gadget);
1448	usb_put_gadget(gadget);
1449}
1450EXPORT_SYMBOL_GPL(usb_del_gadget_udc);
1451
1452/* ------------------------------------------------------------------------- */
1453
1454static int gadget_match_driver(struct device *dev, struct device_driver *drv)
1455{
1456	struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1457	struct usb_udc *udc = gadget->udc;
1458	struct usb_gadget_driver *driver = container_of(drv,
1459			struct usb_gadget_driver, driver);
1460
1461	/* If the driver specifies a udc_name, it must match the UDC's name */
1462	if (driver->udc_name &&
1463			strcmp(driver->udc_name, dev_name(&udc->dev)) != 0)
1464		return 0;
1465
1466	/* If the driver is already bound to a gadget, it doesn't match */
1467	if (driver->is_bound)
1468		return 0;
1469
1470	/* Otherwise any gadget driver matches any UDC */
1471	return 1;
1472}
1473
1474static int gadget_bind_driver(struct device *dev)
1475{
1476	struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1477	struct usb_udc *udc = gadget->udc;
1478	struct usb_gadget_driver *driver = container_of(dev->driver,
1479			struct usb_gadget_driver, driver);
1480	int ret = 0;
1481
1482	mutex_lock(&udc_lock);
1483	if (driver->is_bound) {
1484		mutex_unlock(&udc_lock);
1485		return -ENXIO;		/* Driver binds to only one gadget */
1486	}
1487	driver->is_bound = true;
1488	udc->driver = driver;
1489	mutex_unlock(&udc_lock);
1490
1491	dev_dbg(&udc->dev, "binding gadget driver [%s]\n", driver->function);
1492
1493	usb_gadget_udc_set_speed(udc, driver->max_speed);
1494
1495	ret = driver->bind(udc->gadget, driver);
1496	if (ret)
1497		goto err_bind;
1498
1499	ret = usb_gadget_udc_start(udc);
1500	if (ret)
1501		goto err_start;
1502	usb_gadget_enable_async_callbacks(udc);
1503	usb_udc_connect_control(udc);
1504
1505	kobject_uevent(&udc->dev.kobj, KOBJ_CHANGE);
1506	return 0;
1507
1508 err_start:
1509	driver->unbind(udc->gadget);
1510
1511 err_bind:
1512	if (ret != -EISNAM)
1513		dev_err(&udc->dev, "failed to start %s: %d\n",
1514			driver->function, ret);
1515
1516	mutex_lock(&udc_lock);
1517	udc->driver = NULL;
1518	driver->is_bound = false;
1519	mutex_unlock(&udc_lock);
1520
1521	return ret;
1522}
1523
1524static void gadget_unbind_driver(struct device *dev)
1525{
1526	struct usb_gadget *gadget = dev_to_usb_gadget(dev);
1527	struct usb_udc *udc = gadget->udc;
1528	struct usb_gadget_driver *driver = udc->driver;
1529
1530	dev_dbg(&udc->dev, "unbinding gadget driver [%s]\n", driver->function);
1531
1532	kobject_uevent(&udc->dev.kobj, KOBJ_CHANGE);
1533
1534	usb_gadget_disconnect(gadget);
1535	usb_gadget_disable_async_callbacks(udc);
1536	if (gadget->irq)
1537		synchronize_irq(gadget->irq);
1538	udc->driver->unbind(gadget);
1539	usb_gadget_udc_stop(udc);
1540
1541	mutex_lock(&udc_lock);
1542	driver->is_bound = false;
1543	udc->driver = NULL;
1544	mutex_unlock(&udc_lock);
1545}
1546
1547/* ------------------------------------------------------------------------- */
1548
1549int usb_gadget_register_driver_owner(struct usb_gadget_driver *driver,
1550		struct module *owner, const char *mod_name)
1551{
1552	int ret;
1553
1554	if (!driver || !driver->bind || !driver->setup)
1555		return -EINVAL;
1556
1557	driver->driver.bus = &gadget_bus_type;
1558	driver->driver.owner = owner;
1559	driver->driver.mod_name = mod_name;
1560	ret = driver_register(&driver->driver);
1561	if (ret) {
1562		pr_warn("%s: driver registration failed: %d\n",
1563				driver->function, ret);
1564		return ret;
1565	}
1566
1567	mutex_lock(&udc_lock);
1568	if (!driver->is_bound) {
1569		if (driver->match_existing_only) {
1570			pr_warn("%s: couldn't find an available UDC or it's busy\n",
1571					driver->function);
1572			ret = -EBUSY;
1573		} else {
1574			pr_info("%s: couldn't find an available UDC\n",
1575					driver->function);
1576			ret = 0;
1577		}
1578	}
1579	mutex_unlock(&udc_lock);
1580
1581	if (ret)
1582		driver_unregister(&driver->driver);
1583	return ret;
1584}
1585EXPORT_SYMBOL_GPL(usb_gadget_register_driver_owner);
1586
1587int usb_gadget_unregister_driver(struct usb_gadget_driver *driver)
1588{
1589	if (!driver || !driver->unbind)
1590		return -EINVAL;
1591
1592	driver_unregister(&driver->driver);
1593	return 0;
1594}
1595EXPORT_SYMBOL_GPL(usb_gadget_unregister_driver);
1596
1597/* ------------------------------------------------------------------------- */
1598
1599static ssize_t srp_store(struct device *dev,
1600		struct device_attribute *attr, const char *buf, size_t n)
1601{
1602	struct usb_udc		*udc = container_of(dev, struct usb_udc, dev);
1603
1604	if (sysfs_streq(buf, "1"))
1605		usb_gadget_wakeup(udc->gadget);
1606
1607	return n;
1608}
1609static DEVICE_ATTR_WO(srp);
1610
1611static ssize_t soft_connect_store(struct device *dev,
1612		struct device_attribute *attr, const char *buf, size_t n)
1613{
1614	struct usb_udc		*udc = container_of(dev, struct usb_udc, dev);
1615	ssize_t			ret;
1616
1617	device_lock(&udc->gadget->dev);
1618	if (!udc->driver) {
1619		dev_err(dev, "soft-connect without a gadget driver\n");
1620		ret = -EOPNOTSUPP;
1621		goto out;
1622	}
1623
1624	if (sysfs_streq(buf, "connect")) {
1625		usb_gadget_udc_start(udc);
1626		usb_gadget_connect(udc->gadget);
1627	} else if (sysfs_streq(buf, "disconnect")) {
1628		usb_gadget_disconnect(udc->gadget);
1629		usb_gadget_udc_stop(udc);
1630	} else {
1631		dev_err(dev, "unsupported command '%s'\n", buf);
1632		ret = -EINVAL;
1633		goto out;
1634	}
1635
1636	ret = n;
1637out:
1638	device_unlock(&udc->gadget->dev);
1639	return ret;
1640}
1641static DEVICE_ATTR_WO(soft_connect);
1642
1643static ssize_t state_show(struct device *dev, struct device_attribute *attr,
1644			  char *buf)
1645{
1646	struct usb_udc		*udc = container_of(dev, struct usb_udc, dev);
1647	struct usb_gadget	*gadget = udc->gadget;
1648
1649	return sprintf(buf, "%s\n", usb_state_string(gadget->state));
1650}
1651static DEVICE_ATTR_RO(state);
1652
1653static ssize_t function_show(struct device *dev, struct device_attribute *attr,
1654			     char *buf)
1655{
1656	struct usb_udc		*udc = container_of(dev, struct usb_udc, dev);
1657	struct usb_gadget_driver *drv;
1658	int			rc = 0;
1659
1660	mutex_lock(&udc_lock);
1661	drv = udc->driver;
1662	if (drv && drv->function)
1663		rc = scnprintf(buf, PAGE_SIZE, "%s\n", drv->function);
1664	mutex_unlock(&udc_lock);
1665	return rc;
1666}
1667static DEVICE_ATTR_RO(function);
1668
1669#define USB_UDC_SPEED_ATTR(name, param)					\
1670ssize_t name##_show(struct device *dev,					\
1671		struct device_attribute *attr, char *buf)		\
1672{									\
1673	struct usb_udc *udc = container_of(dev, struct usb_udc, dev);	\
1674	return scnprintf(buf, PAGE_SIZE, "%s\n",			\
1675			usb_speed_string(udc->gadget->param));		\
1676}									\
1677static DEVICE_ATTR_RO(name)
1678
1679static USB_UDC_SPEED_ATTR(current_speed, speed);
1680static USB_UDC_SPEED_ATTR(maximum_speed, max_speed);
1681
1682#define USB_UDC_ATTR(name)					\
1683ssize_t name##_show(struct device *dev,				\
1684		struct device_attribute *attr, char *buf)	\
1685{								\
1686	struct usb_udc		*udc = container_of(dev, struct usb_udc, dev); \
1687	struct usb_gadget	*gadget = udc->gadget;		\
1688								\
1689	return scnprintf(buf, PAGE_SIZE, "%d\n", gadget->name);	\
1690}								\
1691static DEVICE_ATTR_RO(name)
1692
1693static USB_UDC_ATTR(is_otg);
1694static USB_UDC_ATTR(is_a_peripheral);
1695static USB_UDC_ATTR(b_hnp_enable);
1696static USB_UDC_ATTR(a_hnp_support);
1697static USB_UDC_ATTR(a_alt_hnp_support);
1698static USB_UDC_ATTR(is_selfpowered);
1699
1700static struct attribute *usb_udc_attrs[] = {
1701	&dev_attr_srp.attr,
1702	&dev_attr_soft_connect.attr,
1703	&dev_attr_state.attr,
1704	&dev_attr_function.attr,
1705	&dev_attr_current_speed.attr,
1706	&dev_attr_maximum_speed.attr,
1707
1708	&dev_attr_is_otg.attr,
1709	&dev_attr_is_a_peripheral.attr,
1710	&dev_attr_b_hnp_enable.attr,
1711	&dev_attr_a_hnp_support.attr,
1712	&dev_attr_a_alt_hnp_support.attr,
1713	&dev_attr_is_selfpowered.attr,
1714	NULL,
1715};
1716
1717static const struct attribute_group usb_udc_attr_group = {
1718	.attrs = usb_udc_attrs,
1719};
1720
1721static const struct attribute_group *usb_udc_attr_groups[] = {
1722	&usb_udc_attr_group,
1723	NULL,
1724};
1725
1726static int usb_udc_uevent(const struct device *dev, struct kobj_uevent_env *env)
1727{
1728	const struct usb_udc	*udc = container_of(dev, struct usb_udc, dev);
1729	int			ret;
1730
1731	ret = add_uevent_var(env, "USB_UDC_NAME=%s", udc->gadget->name);
1732	if (ret) {
1733		dev_err(dev, "failed to add uevent USB_UDC_NAME\n");
1734		return ret;
1735	}
1736
1737	mutex_lock(&udc_lock);
1738	if (udc->driver)
1739		ret = add_uevent_var(env, "USB_UDC_DRIVER=%s",
1740				udc->driver->function);
1741	mutex_unlock(&udc_lock);
1742	if (ret) {
1743		dev_err(dev, "failed to add uevent USB_UDC_DRIVER\n");
1744		return ret;
1745	}
1746
1747	return 0;
1748}
1749
1750static struct bus_type gadget_bus_type = {
1751	.name = "gadget",
1752	.probe = gadget_bind_driver,
1753	.remove = gadget_unbind_driver,
1754	.match = gadget_match_driver,
1755};
1756
1757static int __init usb_udc_init(void)
1758{
1759	int rc;
1760
1761	udc_class = class_create(THIS_MODULE, "udc");
1762	if (IS_ERR(udc_class)) {
1763		pr_err("failed to create udc class --> %ld\n",
1764				PTR_ERR(udc_class));
1765		return PTR_ERR(udc_class);
1766	}
1767
1768	udc_class->dev_uevent = usb_udc_uevent;
1769
1770	rc = bus_register(&gadget_bus_type);
1771	if (rc)
1772		class_destroy(udc_class);
1773	return rc;
1774}
1775subsys_initcall(usb_udc_init);
1776
1777static void __exit usb_udc_exit(void)
1778{
1779	bus_unregister(&gadget_bus_type);
1780	class_destroy(udc_class);
1781}
1782module_exit(usb_udc_exit);
1783
1784MODULE_DESCRIPTION("UDC Framework");
1785MODULE_AUTHOR("Felipe Balbi <balbi@ti.com>");
1786MODULE_LICENSE("GPL v2");