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