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