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