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