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