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