2 * inode.c -- user mode filesystem api for usb gadget controllers
4 * Copyright (C) 2003 David Brownell
5 * Copyright (C) 2003 Agilent Technologies
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #define DEBUG 1 /* data to help fault diagnosis */
24 // #define VERBOSE /* extra debug messages (success too) */
26 #include <linux/init.h>
27 #include <linux/module.h>
29 #include <linux/pagemap.h>
30 #include <linux/uts.h>
31 #include <linux/wait.h>
32 #include <linux/compiler.h>
33 #include <asm/uaccess.h>
34 #include <linux/slab.h>
36 #include <linux/device.h>
37 #include <linux/moduleparam.h>
39 #include <linux/usb_gadgetfs.h>
40 #include <linux/usb_gadget.h>
44 * The gadgetfs API maps each endpoint to a file descriptor so that you
45 * can use standard synchronous read/write calls for I/O. There's some
46 * O_NONBLOCK and O_ASYNC/FASYNC style i/o support. Example usermode
47 * drivers show how this works in practice.
49 * Key parts that must be USB-specific are protocols defining how the
50 * read/write operations relate to the hardware state machines. There
51 * are two types of files. One type is for the device, implementing ep0.
52 * The other type is for each IN or OUT endpoint. In both cases, the
53 * user mode driver must configure the hardware before using it.
55 * - First, dev_config() is called when /dev/gadget/$CHIP is configured
56 * (by writing configuration and device descriptors). Afterwards it
57 * may serve as a source of device events, used to handle all control
58 * requests other than basic enumeration.
60 * - Then either immediately, or after a SET_CONFIGURATION control request,
61 * ep_config() is called when each /dev/gadget/ep* file is configured
62 * (by writing endpoint descriptors). Afterwards these files are used
63 * to write() IN data or to read() OUT data. To halt the endpoint, a
64 * "wrong direction" request is issued (like reading an IN endpoint).
66 * Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe
67 * not possible on all hardware. For example, precise fault handling with
68 * respect to data left in endpoint fifos after aborted operations; or
69 * selective clearing of endpoint halts, to implement SET_INTERFACE.
72 #define DRIVER_DESC "USB Gadget filesystem"
73 #define DRIVER_VERSION "20 Aug 2003"
75 static const char driver_desc [] = DRIVER_DESC;
76 static const char shortname [] = "gadgetfs";
78 MODULE_DESCRIPTION (DRIVER_DESC);
79 MODULE_AUTHOR ("David Brownell");
80 MODULE_LICENSE ("GPL");
83 /*----------------------------------------------------------------------*/
85 #define GADGETFS_MAGIC 0xaee71ee7
86 #define DMA_ADDR_INVALID (~(dma_addr_t)0)
88 /* /dev/gadget/$CHIP represents ep0 and the whole device */
90 /* DISBLED is the initial state.
92 STATE_DEV_DISABLED = 0,
94 /* Only one open() of /dev/gadget/$CHIP; only one file tracks
95 * ep0/device i/o modes and binding to the controller. Driver
96 * must always write descriptors to initialize the device, then
97 * the device becomes UNCONNECTED until enumeration.
101 /* From then on, ep0 fd is in either of two basic modes:
102 * - (UN)CONNECTED: read usb_gadgetfs_event(s) from it
103 * - SETUP: read/write will transfer control data and succeed;
104 * or if "wrong direction", performs protocol stall
110 /* UNBOUND means the driver closed ep0, so the device won't be
111 * accessible again (DEV_DISABLED) until all fds are closed.
116 /* enough for the whole queue: most events invalidate others */
122 enum ep0_state state;
123 struct usb_gadgetfs_event event [N_EVENT];
125 struct fasync_struct *fasync;
128 /* drivers reading ep0 MUST handle control requests (SETUP)
129 * reported that way; else the host will time out.
131 unsigned usermode_setup : 1,
138 /* the rest is basically write-once */
139 struct usb_config_descriptor *config, *hs_config;
140 struct usb_device_descriptor *dev;
141 struct usb_request *req;
142 struct usb_gadget *gadget;
143 struct list_head epfiles;
145 wait_queue_head_t wait;
146 struct super_block *sb;
147 struct dentry *dentry;
149 /* except this scratch i/o buffer for ep0 */
153 static inline void get_dev (struct dev_data *data)
155 atomic_inc (&data->count);
158 static void put_dev (struct dev_data *data)
160 if (likely (!atomic_dec_and_test (&data->count)))
162 /* needs no more cleanup */
163 BUG_ON (waitqueue_active (&data->wait));
167 static struct dev_data *dev_new (void)
169 struct dev_data *dev;
171 dev = kmalloc (sizeof *dev, GFP_KERNEL);
174 memset (dev, 0, sizeof *dev);
175 dev->state = STATE_DEV_DISABLED;
176 atomic_set (&dev->count, 1);
177 spin_lock_init (&dev->lock);
178 INIT_LIST_HEAD (&dev->epfiles);
179 init_waitqueue_head (&dev->wait);
183 /*----------------------------------------------------------------------*/
185 /* other /dev/gadget/$ENDPOINT files represent endpoints */
187 STATE_EP_DISABLED = 0,
189 STATE_EP_DEFER_ENABLE,
195 struct semaphore lock;
198 struct dev_data *dev;
199 /* must hold dev->lock before accessing ep or req */
201 struct usb_request *req;
204 struct usb_endpoint_descriptor desc, hs_desc;
205 struct list_head epfiles;
206 wait_queue_head_t wait;
207 struct dentry *dentry;
211 static inline void get_ep (struct ep_data *data)
213 atomic_inc (&data->count);
216 static void put_ep (struct ep_data *data)
218 if (likely (!atomic_dec_and_test (&data->count)))
221 /* needs no more cleanup */
222 BUG_ON (!list_empty (&data->epfiles));
223 BUG_ON (waitqueue_active (&data->wait));
224 BUG_ON (down_trylock (&data->lock) != 0);
228 /*----------------------------------------------------------------------*/
230 /* most "how to use the hardware" policy choices are in userspace:
231 * mapping endpoint roles the driver needs to the capabilities that
232 * the usb controller exposes.
235 #ifdef CONFIG_USB_GADGET_DUMMY_HCD
236 /* act (mostly) like a net2280 */
237 #define CONFIG_USB_GADGET_NET2280
240 #ifdef CONFIG_USB_GADGET_NET2280
241 #define CHIP "net2280"
245 #ifdef CONFIG_USB_GADGET_PXA2XX
246 #define CHIP "pxa2xx_udc"
247 /* earlier hardware doesn't have UDCCFR, races set_{config,interface} */
248 #warning works best with pxa255 or newer
251 #ifdef CONFIG_USB_GADGET_GOKU
252 #define CHIP "goku_udc"
255 #ifdef CONFIG_USB_GADGET_SA1100
256 #define CHIP "sa1100"
259 /*----------------------------------------------------------------------*/
261 /* NOTE: don't use dev_printk calls before binding to the gadget
262 * at the end of ep0 configuration, or after unbind.
265 /* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */
266 #define xprintk(d,level,fmt,args...) \
267 printk(level "%s: " fmt , shortname , ## args)
270 #define DBG(dev,fmt,args...) \
271 xprintk(dev , KERN_DEBUG , fmt , ## args)
273 #define DBG(dev,fmt,args...) \
280 #define VDEBUG(dev,fmt,args...) \
284 #define ERROR(dev,fmt,args...) \
285 xprintk(dev , KERN_ERR , fmt , ## args)
286 #define WARN(dev,fmt,args...) \
287 xprintk(dev , KERN_WARNING , fmt , ## args)
288 #define INFO(dev,fmt,args...) \
289 xprintk(dev , KERN_INFO , fmt , ## args)
292 /*----------------------------------------------------------------------*/
294 /* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
296 * After opening, configure non-control endpoints. Then use normal
297 * stream read() and write() requests; and maybe ioctl() to get more
298 * precise FIFO status when recovering from cancelation.
301 static void epio_complete (struct usb_ep *ep, struct usb_request *req)
303 struct ep_data *epdata = ep->driver_data;
308 epdata->status = req->status;
310 epdata->status = req->actual;
311 complete ((struct completion *)req->context);
314 /* tasklock endpoint, returning when it's connected.
315 * still need dev->lock to use epdata->ep.
318 get_ready_ep (unsigned f_flags, struct ep_data *epdata)
322 if (f_flags & O_NONBLOCK) {
323 if (down_trylock (&epdata->lock) != 0)
325 if (epdata->state != STATE_EP_ENABLED) {
334 if ((val = down_interruptible (&epdata->lock)) < 0)
337 switch (epdata->state) {
338 case STATE_EP_ENABLED:
340 case STATE_EP_DEFER_ENABLE:
341 DBG (epdata->dev, "%s wait for host\n", epdata->name);
342 if ((val = wait_event_interruptible (epdata->wait,
343 epdata->state != STATE_EP_DEFER_ENABLE
344 || epdata->dev->state == STATE_DEV_UNBOUND
348 // case STATE_EP_DISABLED: /* "can't happen" */
349 // case STATE_EP_READY: /* "can't happen" */
350 default: /* error! */
351 pr_debug ("%s: ep %p not available, state %d\n",
352 shortname, epdata, epdata->state);
354 case STATE_EP_UNBOUND: /* clean disconnect */
363 ep_io (struct ep_data *epdata, void *buf, unsigned len)
365 DECLARE_COMPLETION (done);
368 spin_lock_irq (&epdata->dev->lock);
369 if (likely (epdata->ep != NULL)) {
370 struct usb_request *req = epdata->req;
372 req->context = &done;
373 req->complete = epio_complete;
376 value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
379 spin_unlock_irq (&epdata->dev->lock);
381 if (likely (value == 0)) {
382 value = wait_event_interruptible (done.wait, done.done);
384 spin_lock_irq (&epdata->dev->lock);
385 if (likely (epdata->ep != NULL)) {
386 DBG (epdata->dev, "%s i/o interrupted\n",
388 usb_ep_dequeue (epdata->ep, epdata->req);
389 spin_unlock_irq (&epdata->dev->lock);
391 wait_event (done.wait, done.done);
392 if (epdata->status == -ECONNRESET)
393 epdata->status = -EINTR;
395 spin_unlock_irq (&epdata->dev->lock);
397 DBG (epdata->dev, "endpoint gone\n");
398 epdata->status = -ENODEV;
401 return epdata->status;
407 /* handle a synchronous OUT bulk/intr/iso transfer */
409 ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
411 struct ep_data *data = fd->private_data;
415 if ((value = get_ready_ep (fd->f_flags, data)) < 0)
418 /* halt any endpoint by doing a "wrong direction" i/o call */
419 if (data->desc.bEndpointAddress & USB_DIR_IN) {
420 if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
421 == USB_ENDPOINT_XFER_ISOC)
423 DBG (data->dev, "%s halt\n", data->name);
424 spin_lock_irq (&data->dev->lock);
425 if (likely (data->ep != NULL))
426 usb_ep_set_halt (data->ep);
427 spin_unlock_irq (&data->dev->lock);
432 /* FIXME readahead for O_NONBLOCK and poll(); careful with ZLPs */
435 kbuf = kmalloc (len, SLAB_KERNEL);
436 if (unlikely (!kbuf))
439 value = ep_io (data, kbuf, len);
440 VDEBUG (data->dev, "%s read %d OUT, status %d\n",
441 data->name, len, value);
442 if (value >= 0 && copy_to_user (buf, kbuf, value))
451 /* handle a synchronous IN bulk/intr/iso transfer */
453 ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
455 struct ep_data *data = fd->private_data;
459 if ((value = get_ready_ep (fd->f_flags, data)) < 0)
462 /* halt any endpoint by doing a "wrong direction" i/o call */
463 if (!(data->desc.bEndpointAddress & USB_DIR_IN)) {
464 if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
465 == USB_ENDPOINT_XFER_ISOC)
467 DBG (data->dev, "%s halt\n", data->name);
468 spin_lock_irq (&data->dev->lock);
469 if (likely (data->ep != NULL))
470 usb_ep_set_halt (data->ep);
471 spin_unlock_irq (&data->dev->lock);
476 /* FIXME writebehind for O_NONBLOCK and poll(), qlen = 1 */
479 kbuf = kmalloc (len, SLAB_KERNEL);
482 if (copy_from_user (kbuf, buf, len)) {
487 value = ep_io (data, kbuf, len);
488 VDEBUG (data->dev, "%s write %d IN, status %d\n",
489 data->name, len, value);
497 ep_release (struct inode *inode, struct file *fd)
499 struct ep_data *data = fd->private_data;
501 /* clean up if this can be reopened */
502 if (data->state != STATE_EP_UNBOUND) {
503 data->state = STATE_EP_DISABLED;
504 data->desc.bDescriptorType = 0;
505 data->hs_desc.bDescriptorType = 0;
511 static int ep_ioctl (struct inode *inode, struct file *fd,
512 unsigned code, unsigned long value)
514 struct ep_data *data = fd->private_data;
517 if ((status = get_ready_ep (fd->f_flags, data)) < 0)
520 spin_lock_irq (&data->dev->lock);
521 if (likely (data->ep != NULL)) {
523 case GADGETFS_FIFO_STATUS:
524 status = usb_ep_fifo_status (data->ep);
526 case GADGETFS_FIFO_FLUSH:
527 usb_ep_fifo_flush (data->ep);
529 case GADGETFS_CLEAR_HALT:
530 status = usb_ep_clear_halt (data->ep);
537 spin_unlock_irq (&data->dev->lock);
542 /* used after endpoint configuration */
543 static struct file_operations ep_io_operations = {
544 .owner = THIS_MODULE,
548 .release = ep_release,
550 // .aio_read = ep_aio_read,
551 // .aio_write = ep_aio_write,
554 /* ENDPOINT INITIALIZATION
556 * fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
557 * status = write (fd, descriptors, sizeof descriptors)
559 * That write establishes the endpoint configuration, configuring
560 * the controller to process bulk, interrupt, or isochronous transfers
561 * at the right maxpacket size, and so on.
563 * The descriptors are message type 1, identified by a host order u32
564 * at the beginning of what's written. Descriptor order is: full/low
565 * speed descriptor, then optional high speed descriptor.
568 ep_config (struct file *fd, const char *buf, size_t len, loff_t *ptr)
570 struct ep_data *data = fd->private_data;
575 if ((value = down_interruptible (&data->lock)) < 0)
578 if (data->state != STATE_EP_READY) {
584 if (len < USB_DT_ENDPOINT_SIZE + 4)
587 /* we might need to change message format someday */
588 if (copy_from_user (&tag, buf, 4)) {
592 DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
598 /* NOTE: audio endpoint extensions not accepted here;
599 * just don't include the extra bytes.
602 /* full/low speed descriptor, then high speed */
603 if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
606 if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
607 || data->desc.bDescriptorType != USB_DT_ENDPOINT)
609 if (len != USB_DT_ENDPOINT_SIZE) {
610 if (len != 2 * USB_DT_ENDPOINT_SIZE)
612 if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
613 USB_DT_ENDPOINT_SIZE)) {
616 if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
617 || data->hs_desc.bDescriptorType
618 != USB_DT_ENDPOINT) {
619 DBG(data->dev, "config %s, bad hs length or type\n",
626 spin_lock_irq (&data->dev->lock);
627 if (data->dev->state == STATE_DEV_UNBOUND) {
630 } else if ((ep = data->ep) == NULL) {
634 switch (data->dev->gadget->speed) {
637 value = usb_ep_enable (ep, &data->desc);
639 data->state = STATE_EP_ENABLED;
643 /* fails if caller didn't provide that descriptor... */
644 value = usb_ep_enable (ep, &data->hs_desc);
646 data->state = STATE_EP_ENABLED;
650 DBG (data->dev, "unconnected, %s init deferred\n",
652 data->state = STATE_EP_DEFER_ENABLE;
655 fd->f_op = &ep_io_operations;
657 spin_unlock_irq (&data->dev->lock);
660 data->desc.bDescriptorType = 0;
661 data->hs_desc.bDescriptorType = 0;
674 ep_open (struct inode *inode, struct file *fd)
676 struct ep_data *data = inode->u.generic_ip;
679 if (down_interruptible (&data->lock) != 0)
681 spin_lock_irq (&data->dev->lock);
682 if (data->dev->state == STATE_DEV_UNBOUND)
684 else if (data->state == STATE_EP_DISABLED) {
686 data->state = STATE_EP_READY;
688 fd->private_data = data;
689 VDEBUG (data->dev, "%s ready\n", data->name);
691 DBG (data->dev, "%s state %d\n",
692 data->name, data->state);
693 spin_unlock_irq (&data->dev->lock);
698 /* used before endpoint configuration */
699 static struct file_operations ep_config_operations = {
700 .owner = THIS_MODULE,
703 .release = ep_release,
706 /*----------------------------------------------------------------------*/
708 /* EP0 IMPLEMENTATION can be partly in userspace.
710 * Drivers that use this facility receive various events, including
711 * control requests the kernel doesn't handle. Drivers that don't
712 * use this facility may be too simple-minded for real applications.
715 static inline void ep0_readable (struct dev_data *dev)
717 wake_up (&dev->wait);
718 kill_fasync (&dev->fasync, SIGIO, POLL_IN);
721 static void clean_req (struct usb_ep *ep, struct usb_request *req)
723 struct dev_data *dev = ep->driver_data;
725 if (req->buf != dev->rbuf) {
726 usb_ep_free_buffer (ep, req->buf, req->dma, req->length);
727 req->buf = dev->rbuf;
728 req->dma = DMA_ADDR_INVALID;
730 req->complete = epio_complete;
731 dev->setup_out_ready = 0;
734 static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
736 struct dev_data *dev = ep->driver_data;
739 /* for control OUT, data must still get to userspace */
740 if (!dev->setup_in) {
741 dev->setup_out_error = (req->status != 0);
742 if (!dev->setup_out_error)
744 dev->setup_out_ready = 1;
746 } else if (dev->state == STATE_SETUP)
747 dev->state = STATE_CONNECTED;
749 /* clean up as appropriate */
750 if (free && req->buf != &dev->rbuf)
752 req->complete = epio_complete;
755 static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
757 struct dev_data *dev = ep->driver_data;
759 if (dev->setup_out_ready) {
760 DBG (dev, "ep0 request busy!\n");
763 if (len > sizeof (dev->rbuf))
764 req->buf = usb_ep_alloc_buffer (ep, len, &req->dma, GFP_ATOMIC);
766 req->buf = dev->rbuf;
769 req->complete = ep0_complete;
775 ep0_read (struct file *fd, char *buf, size_t len, loff_t *ptr)
777 struct dev_data *dev = fd->private_data;
779 enum ep0_state state;
781 spin_lock_irq (&dev->lock);
783 /* report fd mode change before acting on it */
784 if (dev->setup_abort) {
785 dev->setup_abort = 0;
790 /* control DATA stage */
791 if ((state = dev->state) == STATE_SETUP) {
793 if (dev->setup_in) { /* stall IN */
794 VDEBUG(dev, "ep0in stall\n");
795 (void) usb_ep_set_halt (dev->gadget->ep0);
797 dev->state = STATE_CONNECTED;
799 } else if (len == 0) { /* ack SET_CONFIGURATION etc */
800 struct usb_ep *ep = dev->gadget->ep0;
801 struct usb_request *req = dev->req;
803 if ((retval = setup_req (ep, req, 0)) == 0)
804 retval = usb_ep_queue (ep, req, GFP_ATOMIC);
805 dev->state = STATE_CONNECTED;
807 } else { /* collect OUT data */
808 if ((fd->f_flags & O_NONBLOCK) != 0
809 && !dev->setup_out_ready) {
813 spin_unlock_irq (&dev->lock);
814 retval = wait_event_interruptible (dev->wait,
815 dev->setup_out_ready != 0);
817 /* FIXME state could change from under us */
818 spin_lock_irq (&dev->lock);
821 if (dev->setup_out_error)
824 len = min (len, (size_t)dev->req->actual);
825 // FIXME don't call this with the spinlock held ...
826 if (copy_to_user (buf, &dev->req->buf, len))
828 clean_req (dev->gadget->ep0, dev->req);
829 /* NOTE userspace can't yet choose to stall */
835 /* else normal: return event data */
836 if (len < sizeof dev->event [0]) {
840 len -= len % sizeof (struct usb_gadgetfs_event);
841 dev->usermode_setup = 1;
844 /* return queued events right away */
845 if (dev->ev_next != 0) {
847 int tmp = dev->ev_next;
849 len = min (len, tmp * sizeof (struct usb_gadgetfs_event));
850 n = len / sizeof (struct usb_gadgetfs_event);
852 /* ep0 can't deliver events when STATE_SETUP */
853 for (i = 0; i < n; i++) {
854 if (dev->event [i].type == GADGETFS_SETUP) {
856 len *= sizeof (struct usb_gadgetfs_event);
861 spin_unlock_irq (&dev->lock);
862 if (copy_to_user (buf, &dev->event, len))
867 len /= sizeof (struct usb_gadgetfs_event);
869 /* NOTE this doesn't guard against broken drivers;
870 * concurrent ep0 readers may lose events.
872 spin_lock_irq (&dev->lock);
874 if (dev->ev_next != 0)
875 memmove (&dev->event, &dev->event [len],
876 sizeof (struct usb_gadgetfs_event)
879 dev->state = STATE_SETUP;
880 spin_unlock_irq (&dev->lock);
884 if (fd->f_flags & O_NONBLOCK) {
891 DBG (dev, "fail %s, state %d\n", __FUNCTION__, state);
894 case STATE_UNCONNECTED:
895 case STATE_CONNECTED:
896 spin_unlock_irq (&dev->lock);
897 DBG (dev, "%s wait\n", __FUNCTION__);
899 /* wait for events */
900 retval = wait_event_interruptible (dev->wait,
904 spin_lock_irq (&dev->lock);
909 spin_unlock_irq (&dev->lock);
913 static struct usb_gadgetfs_event *
914 next_event (struct dev_data *dev, enum usb_gadgetfs_event_type type)
916 struct usb_gadgetfs_event *event;
920 /* these events purge the queue */
921 case GADGETFS_DISCONNECT:
922 if (dev->state == STATE_SETUP)
923 dev->setup_abort = 1;
925 case GADGETFS_CONNECT:
928 case GADGETFS_SETUP: /* previous request timed out */
929 case GADGETFS_SUSPEND: /* same effect */
930 /* these events can't be repeated */
931 for (i = 0; i != dev->ev_next; i++) {
932 if (dev->event [i].type != type)
934 DBG (dev, "discard old event %d\n", type);
936 if (i == dev->ev_next)
938 /* indices start at zero, for simplicity */
939 memmove (&dev->event [i], &dev->event [i + 1],
940 sizeof (struct usb_gadgetfs_event)
941 * (dev->ev_next - i));
947 event = &dev->event [dev->ev_next++];
948 BUG_ON (dev->ev_next > N_EVENT);
949 VDEBUG (dev, "ev %d, next %d\n", type, dev->ev_next);
950 memset (event, 0, sizeof *event);
956 ep0_write (struct file *fd, const char *buf, size_t len, loff_t *ptr)
958 struct dev_data *dev = fd->private_data;
959 ssize_t retval = -ESRCH;
961 spin_lock_irq (&dev->lock);
963 /* report fd mode change before acting on it */
964 if (dev->setup_abort) {
965 dev->setup_abort = 0;
968 /* data and/or status stage for control request */
969 } else if (dev->state == STATE_SETUP) {
971 /* IN DATA+STATUS caller makes len <= wLength */
973 retval = setup_req (dev->gadget->ep0, dev->req, len);
975 spin_unlock_irq (&dev->lock);
976 if (copy_from_user (dev->req->buf, buf, len))
979 retval = usb_ep_queue (
980 dev->gadget->ep0, dev->req,
983 spin_lock_irq (&dev->lock);
984 clean_req (dev->gadget->ep0, dev->req);
985 spin_unlock_irq (&dev->lock);
992 /* can stall some OUT transfers */
993 } else if (dev->setup_can_stall) {
994 VDEBUG(dev, "ep0out stall\n");
995 (void) usb_ep_set_halt (dev->gadget->ep0);
997 dev->state = STATE_CONNECTED;
999 DBG(dev, "bogus ep0out stall!\n");
1002 DBG (dev, "fail %s, state %d\n", __FUNCTION__, dev->state);
1004 spin_unlock_irq (&dev->lock);
1009 ep0_fasync (int f, struct file *fd, int on)
1011 struct dev_data *dev = fd->private_data;
1012 // caller must F_SETOWN before signal delivery happens
1013 VDEBUG (dev, "%s %s\n", __FUNCTION__, on ? "on" : "off");
1014 return fasync_helper (f, fd, on, &dev->fasync);
1017 static struct usb_gadget_driver gadgetfs_driver;
1020 dev_release (struct inode *inode, struct file *fd)
1022 struct dev_data *dev = fd->private_data;
1024 /* closing ep0 === shutdown all */
1026 usb_gadget_unregister_driver (&gadgetfs_driver);
1028 /* at this point "good" hardware has disconnected the
1029 * device from USB; the host won't see it any more.
1030 * alternatively, all host requests will time out.
1033 fasync_helper (-1, fd, 0, &dev->fasync);
1038 /* other endpoints were all decoupled from this device */
1039 dev->state = STATE_DEV_DISABLED;
1043 static int dev_ioctl (struct inode *inode, struct file *fd,
1044 unsigned code, unsigned long value)
1046 struct dev_data *dev = fd->private_data;
1047 struct usb_gadget *gadget = dev->gadget;
1049 if (gadget->ops->ioctl)
1050 return gadget->ops->ioctl (gadget, code, value);
1054 /* used after device configuration */
1055 static struct file_operations ep0_io_operations = {
1056 .owner = THIS_MODULE,
1059 .fasync = ep0_fasync,
1060 // .poll = ep0_poll,
1062 .release = dev_release,
1065 /*----------------------------------------------------------------------*/
1067 /* The in-kernel gadget driver handles most ep0 issues, in particular
1068 * enumerating the single configuration (as provided from user space).
1070 * Unrecognized ep0 requests may be handled in user space.
1074 static void make_qualifier (struct dev_data *dev)
1076 struct usb_qualifier_descriptor qual;
1077 struct usb_device_descriptor *desc;
1079 qual.bLength = sizeof qual;
1080 qual.bDescriptorType = USB_DT_DEVICE_QUALIFIER;
1081 qual.bcdUSB = __constant_cpu_to_le16 (0x0200);
1084 qual.bDeviceClass = desc->bDeviceClass;
1085 qual.bDeviceSubClass = desc->bDeviceSubClass;
1086 qual.bDeviceProtocol = desc->bDeviceProtocol;
1088 /* assumes ep0 uses the same value for both speeds ... */
1089 qual.bMaxPacketSize0 = desc->bMaxPacketSize0;
1091 qual.bNumConfigurations = 1;
1094 memcpy (dev->rbuf, &qual, sizeof qual);
1099 config_buf (struct dev_data *dev, u8 type, unsigned index)
1106 /* only one configuration */
1111 hs = (dev->gadget->speed == USB_SPEED_HIGH);
1112 if (type == USB_DT_OTHER_SPEED_CONFIG)
1115 dev->req->buf = dev->hs_config;
1116 len = le16_to_cpup (&dev->hs_config->wTotalLength);
1120 dev->req->buf = dev->config;
1121 len = le16_to_cpup (&dev->config->wTotalLength);
1123 ((u8 *)dev->req->buf) [1] = type;
1128 gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1130 struct dev_data *dev = get_gadget_data (gadget);
1131 struct usb_request *req = dev->req;
1132 int value = -EOPNOTSUPP;
1133 struct usb_gadgetfs_event *event;
1135 spin_lock (&dev->lock);
1136 dev->setup_abort = 0;
1137 if (dev->state == STATE_UNCONNECTED) {
1139 struct ep_data *data;
1141 dev->state = STATE_CONNECTED;
1142 dev->dev->bMaxPacketSize0 = gadget->ep0->maxpacket;
1145 if (gadget->speed == USB_SPEED_HIGH && dev->hs_config == 0) {
1146 ERROR (dev, "no high speed config??\n");
1149 #endif /* HIGHSPEED */
1151 INFO (dev, "connected\n");
1152 event = next_event (dev, GADGETFS_CONNECT);
1153 event->u.speed = gadget->speed;
1156 list_for_each_entry (ep, &gadget->ep_list, ep_list) {
1157 data = ep->driver_data;
1158 /* ... down_trylock (&data->lock) ... */
1159 if (data->state != STATE_EP_DEFER_ENABLE)
1162 if (gadget->speed == USB_SPEED_HIGH)
1163 value = usb_ep_enable (ep, &data->hs_desc);
1165 #endif /* HIGHSPEED */
1166 value = usb_ep_enable (ep, &data->desc);
1168 ERROR (dev, "deferred %s enable --> %d\n",
1172 data->state = STATE_EP_ENABLED;
1173 wake_up (&data->wait);
1174 DBG (dev, "woke up %s waiters\n", data->name);
1177 /* host may have given up waiting for response. we can miss control
1178 * requests handled lower down (device/endpoint status and features);
1179 * then ep0_{read,write} will report the wrong status. controller
1180 * driver will have aborted pending i/o.
1182 } else if (dev->state == STATE_SETUP)
1183 dev->setup_abort = 1;
1185 req->buf = dev->rbuf;
1186 req->dma = DMA_ADDR_INVALID;
1188 value = -EOPNOTSUPP;
1189 switch (ctrl->bRequest) {
1191 case USB_REQ_GET_DESCRIPTOR:
1192 if (ctrl->bRequestType != USB_DIR_IN)
1194 switch (ctrl->wValue >> 8) {
1197 value = min (ctrl->wLength, (u16) sizeof *dev->dev);
1198 req->buf = dev->dev;
1201 case USB_DT_DEVICE_QUALIFIER:
1202 if (!dev->hs_config)
1204 value = min (ctrl->wLength, (u16)
1205 sizeof (struct usb_qualifier_descriptor));
1206 make_qualifier (dev);
1208 case USB_DT_OTHER_SPEED_CONFIG:
1212 value = config_buf (dev,
1214 ctrl->wValue & 0xff);
1216 value = min (ctrl->wLength, (u16) value);
1221 default: // all others are errors
1226 /* currently one config, two speeds */
1227 case USB_REQ_SET_CONFIGURATION:
1228 if (ctrl->bRequestType != 0)
1230 if (0 == (u8) ctrl->wValue) {
1232 dev->current_config = 0;
1233 // user mode expected to disable endpoints
1237 if (gadget->speed == USB_SPEED_HIGH)
1238 config = dev->hs_config->bConfigurationValue;
1241 config = dev->config->bConfigurationValue;
1243 if (config == (u8) ctrl->wValue) {
1245 dev->current_config = config;
1249 /* report SET_CONFIGURATION like any other control request,
1250 * except that usermode may not stall this. the next
1251 * request mustn't be allowed start until this finishes:
1252 * endpoints and threads set up, etc.
1254 * NOTE: older PXA hardware (before PXA 255: without UDCCFR)
1255 * has bad/racey automagic that prevents synchronizing here.
1256 * even kernel mode drivers often miss them.
1259 INFO (dev, "configuration #%d\n", dev->current_config);
1260 if (dev->usermode_setup) {
1261 dev->setup_can_stall = 0;
1267 #ifndef CONFIG_USB_GADGETFS_PXA2XX
1268 /* PXA automagically handles this request too */
1269 case USB_REQ_GET_CONFIGURATION:
1270 if (ctrl->bRequestType != 0x80)
1272 *(u8 *)req->buf = dev->current_config;
1273 value = min (ctrl->wLength, (u16) 1);
1279 VDEBUG (dev, "%s req%02x.%02x v%04x i%04x l%d\n",
1280 dev->usermode_setup ? "delegate" : "fail",
1281 ctrl->bRequestType, ctrl->bRequest,
1282 ctrl->wValue, ctrl->wIndex, ctrl->wLength);
1284 /* if there's an ep0 reader, don't stall */
1285 if (dev->usermode_setup) {
1286 dev->setup_can_stall = 1;
1288 dev->setup_in = (ctrl->bRequestType & USB_DIR_IN)
1290 dev->setup_out_ready = 0;
1291 dev->setup_out_error = 0;
1294 /* read DATA stage for OUT right away */
1295 if (unlikely (!dev->setup_in && ctrl->wLength)) {
1296 value = setup_req (gadget->ep0, dev->req,
1300 value = usb_ep_queue (gadget->ep0, dev->req,
1303 clean_req (gadget->ep0, dev->req);
1307 /* we can't currently stall these */
1308 dev->setup_can_stall = 0;
1311 /* state changes when reader collects event */
1312 event = next_event (dev, GADGETFS_SETUP);
1313 event->u.setup = *ctrl;
1315 spin_unlock (&dev->lock);
1320 /* proceed with data transfer and status phases? */
1321 if (value >= 0 && dev->state != STATE_SETUP) {
1322 req->length = value;
1323 value = usb_ep_queue (gadget->ep0, req, GFP_ATOMIC);
1325 DBG (dev, "ep_queue --> %d\n", value);
1330 /* device stalls when value < 0 */
1331 spin_unlock (&dev->lock);
1335 static void destroy_ep_files (struct dev_data *dev)
1337 struct list_head *entry, *tmp;
1339 DBG (dev, "%s %d\n", __FUNCTION__, dev->state);
1341 /* dev->state must prevent interference */
1343 spin_lock_irq (&dev->lock);
1344 list_for_each_safe (entry, tmp, &dev->epfiles) {
1346 struct inode *parent;
1347 struct dentry *dentry;
1349 /* break link to FS */
1350 ep = list_entry (entry, struct ep_data, epfiles);
1351 list_del_init (&ep->epfiles);
1352 dentry = ep->dentry;
1354 parent = dentry->d_parent->d_inode;
1356 /* break link to controller */
1357 if (ep->state == STATE_EP_ENABLED)
1358 (void) usb_ep_disable (ep->ep);
1359 ep->state = STATE_EP_UNBOUND;
1360 usb_ep_free_request (ep->ep, ep->req);
1362 wake_up (&ep->wait);
1365 spin_unlock_irq (&dev->lock);
1367 /* break link to dcache */
1368 down (&parent->i_sem);
1371 up (&parent->i_sem);
1373 /* fds may still be open */
1376 spin_unlock_irq (&dev->lock);
1380 static struct inode *
1381 gadgetfs_create_file (struct super_block *sb, char const *name,
1382 void *data, struct file_operations *fops,
1383 struct dentry **dentry_p);
1385 static int activate_ep_files (struct dev_data *dev)
1389 gadget_for_each_ep (ep, dev->gadget) {
1390 struct ep_data *data;
1392 data = kmalloc (sizeof *data, GFP_KERNEL);
1395 memset (data, 0, sizeof data);
1396 data->state = STATE_EP_DISABLED;
1397 init_MUTEX (&data->lock);
1398 init_waitqueue_head (&data->wait);
1400 strncpy (data->name, ep->name, sizeof (data->name) - 1);
1401 atomic_set (&data->count, 1);
1406 ep->driver_data = data;
1408 data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1412 data->inode = gadgetfs_create_file (dev->sb, data->name,
1413 data, &ep_config_operations,
1419 list_add_tail (&data->epfiles, &dev->epfiles);
1424 DBG (dev, "%s enomem\n", __FUNCTION__);
1425 destroy_ep_files (dev);
1430 gadgetfs_unbind (struct usb_gadget *gadget)
1432 struct dev_data *dev = get_gadget_data (gadget);
1434 DBG (dev, "%s\n", __FUNCTION__);
1436 spin_lock_irq (&dev->lock);
1437 dev->state = STATE_DEV_UNBOUND;
1438 spin_unlock_irq (&dev->lock);
1440 destroy_ep_files (dev);
1441 gadget->ep0->driver_data = 0;
1442 set_gadget_data (gadget, 0);
1444 /* we've already been disconnected ... no i/o is active */
1446 usb_ep_free_request (gadget->ep0, dev->req);
1447 DBG (dev, "%s done\n", __FUNCTION__);
1451 static struct dev_data *the_device;
1454 gadgetfs_bind (struct usb_gadget *gadget)
1456 struct dev_data *dev = the_device;
1460 if (0 != strcmp (CHIP, gadget->name)) {
1461 printk (KERN_ERR "%s expected " CHIP " controller not %s\n",
1462 shortname, gadget->name);
1466 set_gadget_data (gadget, dev);
1467 dev->gadget = gadget;
1468 gadget->ep0->driver_data = dev;
1469 dev->dev->bMaxPacketSize0 = gadget->ep0->maxpacket;
1471 /* preallocate control response and buffer */
1472 dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1475 dev->req->context = 0;
1476 dev->req->complete = epio_complete;
1478 if (activate_ep_files (dev) < 0)
1481 INFO (dev, "bound to %s driver\n", gadget->name);
1482 dev->state = STATE_UNCONNECTED;
1487 gadgetfs_unbind (gadget);
1492 gadgetfs_disconnect (struct usb_gadget *gadget)
1494 struct dev_data *dev = get_gadget_data (gadget);
1496 if (dev->state == STATE_UNCONNECTED) {
1497 DBG (dev, "already unconnected\n");
1500 dev->state = STATE_UNCONNECTED;
1502 INFO (dev, "disconnected\n");
1503 spin_lock (&dev->lock);
1504 next_event (dev, GADGETFS_DISCONNECT);
1506 spin_unlock (&dev->lock);
1510 gadgetfs_suspend (struct usb_gadget *gadget)
1512 struct dev_data *dev = get_gadget_data (gadget);
1514 INFO (dev, "suspended from state %d\n", dev->state);
1515 spin_lock (&dev->lock);
1516 switch (dev->state) {
1517 case STATE_SETUP: // VERY odd... host died??
1518 case STATE_CONNECTED:
1519 case STATE_UNCONNECTED:
1520 next_event (dev, GADGETFS_SUSPEND);
1526 spin_unlock (&dev->lock);
1529 static struct usb_gadget_driver gadgetfs_driver = {
1531 .speed = USB_SPEED_HIGH,
1533 .speed = USB_SPEED_FULL,
1535 .function = (char *) driver_desc,
1536 .bind = gadgetfs_bind,
1537 .unbind = gadgetfs_unbind,
1538 .setup = gadgetfs_setup,
1539 .disconnect = gadgetfs_disconnect,
1540 .suspend = gadgetfs_suspend,
1543 .name = (char *) shortname,
1550 /*----------------------------------------------------------------------*/
1552 /* DEVICE INITIALIZATION
1554 * fd = open ("/dev/gadget/$CHIP", O_RDWR)
1555 * status = write (fd, descriptors, sizeof descriptors)
1557 * That write establishes the device configuration, so the kernel can
1558 * bind to the controller ... guaranteeing it can handle enumeration
1559 * at all necessary speeds. Descriptor order is:
1561 * . message tag (u32, host order) ... for now, must be zero; it
1562 * would change to support features like multi-config devices
1563 * . full/low speed config ... all wTotalLength bytes (with interface,
1564 * class, altsetting, endpoint, and other descriptors)
1565 * . high speed config ... all descriptors, for high speed operation;
1566 * this one's optional except for high-speed hardware
1567 * . device descriptor
1569 * Endpoints are not yet enabled. Drivers may want to immediately
1570 * initialize them, using the /dev/gadget/ep* files that are available
1571 * as soon as the kernel sees the configuration, or they can wait
1572 * until device configuration and interface altsetting changes create
1573 * the need to configure (or unconfigure) them.
1575 * After initialization, the device stays active for as long as that
1576 * $CHIP file is open. Events may then be read from that descriptor,
1577 * such configuration notifications. More complex drivers will handle
1578 * some control requests in user space.
1581 static int is_valid_config (struct usb_config_descriptor *config)
1583 return config->bDescriptorType == USB_DT_CONFIG
1584 && config->bLength == USB_DT_CONFIG_SIZE
1585 && config->bConfigurationValue != 0
1586 && (config->bmAttributes & USB_CONFIG_ATT_ONE) != 0
1587 && (config->bmAttributes & USB_CONFIG_ATT_WAKEUP) == 0;
1588 /* FIXME check lengths: walk to end */
1592 dev_config (struct file *fd, const char *buf, size_t len, loff_t *ptr)
1594 struct dev_data *dev = fd->private_data;
1595 ssize_t value = len, length = len;
1600 if (dev->state != STATE_OPENED)
1603 if (len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4))
1606 /* we might need to change message format someday */
1607 if (copy_from_user (&tag, buf, 4))
1614 kbuf = kmalloc (length, SLAB_KERNEL);
1617 if (copy_from_user (kbuf, buf, length)) {
1622 spin_lock_irq (&dev->lock);
1628 /* full or low speed config */
1629 dev->config = (void *) kbuf;
1630 total = le16_to_cpup (&dev->config->wTotalLength);
1631 if (!is_valid_config (dev->config) || total >= length)
1636 /* optional high speed config */
1637 if (kbuf [1] == USB_DT_CONFIG) {
1638 dev->hs_config = (void *) kbuf;
1639 total = le16_to_cpup (&dev->hs_config->wTotalLength);
1640 if (!is_valid_config (dev->hs_config) || total >= length)
1646 /* could support multiple configs, using another encoding! */
1648 /* device descriptor (tweaked for paranoia) */
1649 if (length != USB_DT_DEVICE_SIZE)
1651 dev->dev = (void *)kbuf;
1652 if (dev->dev->bLength != USB_DT_DEVICE_SIZE
1653 || dev->dev->bDescriptorType != USB_DT_DEVICE
1654 || dev->dev->bNumConfigurations != 1)
1656 dev->dev->bNumConfigurations = 1;
1657 dev->dev->bcdUSB = __constant_cpu_to_le16 (0x0200);
1659 /* triggers gadgetfs_bind(); then we can enumerate. */
1660 spin_unlock_irq (&dev->lock);
1661 value = usb_gadget_register_driver (&gadgetfs_driver);
1666 /* at this point "good" hardware has for the first time
1667 * let the USB the host see us. alternatively, if users
1668 * unplug/replug that will clear all the error state.
1670 * note: everything running before here was guaranteed
1671 * to choke driver model style diagnostics. from here
1672 * on, they can work ... except in cleanup paths that
1673 * kick in after the ep0 descriptor is closed.
1675 fd->f_op = &ep0_io_operations;
1681 spin_unlock_irq (&dev->lock);
1682 pr_debug ("%s: %s fail %Zd, %p\n", shortname, __FUNCTION__, value, dev);
1689 dev_open (struct inode *inode, struct file *fd)
1691 struct dev_data *dev = inode->u.generic_ip;
1694 if (dev->state == STATE_DEV_DISABLED) {
1696 dev->state = STATE_OPENED;
1697 fd->private_data = dev;
1704 static struct file_operations dev_init_operations = {
1705 .owner = THIS_MODULE,
1707 .write = dev_config,
1708 .fasync = ep0_fasync,
1710 .release = dev_release,
1713 /*----------------------------------------------------------------------*/
1715 /* FILESYSTEM AND SUPERBLOCK OPERATIONS
1717 * Mounting the filesystem creates a controller file, used first for
1718 * device configuration then later for event monitoring.
1722 /* FIXME PAM etc could set this security policy without mount options
1723 * if epfiles inherited ownership and permissons from ep0 ...
1726 static unsigned default_uid;
1727 static unsigned default_gid;
1728 static unsigned default_perm = S_IRUSR | S_IWUSR;
1730 module_param (default_uid, uint, 0644);
1731 module_param (default_gid, uint, 0644);
1732 module_param (default_perm, uint, 0644);
1735 static struct inode *
1736 gadgetfs_make_inode (struct super_block *sb,
1737 void *data, struct file_operations *fops,
1740 struct inode *inode = new_inode (sb);
1743 inode->i_mode = mode;
1744 inode->i_uid = default_uid;
1745 inode->i_gid = default_gid;
1746 inode->i_blksize = PAGE_CACHE_SIZE;
1747 inode->i_blocks = 0;
1748 inode->i_atime = inode->i_mtime = inode->i_ctime
1750 inode->u.generic_ip = data;
1751 inode->i_fop = fops;
1756 /* creates in fs root directory, so non-renamable and non-linkable.
1757 * so inode and dentry are paired, until device reconfig.
1759 static struct inode *
1760 gadgetfs_create_file (struct super_block *sb, char const *name,
1761 void *data, struct file_operations *fops,
1762 struct dentry **dentry_p)
1764 struct dentry *dentry;
1765 struct inode *inode;
1769 qname.len = strlen (name);
1770 qname.hash = full_name_hash (qname.name, qname.len);
1771 dentry = d_alloc (sb->s_root, &qname);
1775 inode = gadgetfs_make_inode (sb, data, fops,
1776 S_IFREG | (default_perm & S_IRWXUGO));
1781 d_add (dentry, inode);
1786 static struct super_operations gadget_fs_operations = {
1787 .statfs = simple_statfs,
1788 .drop_inode = generic_delete_inode,
1792 gadgetfs_fill_super (struct super_block *sb, void *opts, int silent)
1794 struct inode *inode;
1796 struct dev_data *dev;
1802 sb->s_blocksize = PAGE_CACHE_SIZE;
1803 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1804 sb->s_magic = GADGETFS_MAGIC;
1805 sb->s_op = &gadget_fs_operations;
1808 inode = gadgetfs_make_inode (sb,
1809 0, &simple_dir_operations,
1810 S_IFDIR | S_IRUGO | S_IXUGO);
1813 inode->i_op = &simple_dir_inode_operations;
1814 if (!(d = d_alloc_root (inode))) {
1820 /* the ep0 file is named after the controller we expect;
1821 * user mode code can use it for sanity checks, like we do.
1828 if (!(inode = gadgetfs_create_file (sb, CHIP,
1829 dev, &dev_init_operations,
1835 /* other endpoint files are available after hardware setup,
1836 * from binding to a controller.
1842 /* "mount -t gadgetfs path /dev/gadget" ends up here */
1843 static struct super_block *
1844 gadgetfs_get_sb (struct file_system_type *t, int flags,
1845 const char *path, void *opts)
1847 return get_sb_single (t, flags, opts, gadgetfs_fill_super);
1851 gadgetfs_kill_sb (struct super_block *sb)
1853 kill_litter_super (sb);
1855 put_dev (the_device);
1860 /*----------------------------------------------------------------------*/
1862 static struct file_system_type gadgetfs_type = {
1863 .owner = THIS_MODULE,
1865 .get_sb = gadgetfs_get_sb,
1866 .kill_sb = gadgetfs_kill_sb,
1869 /*----------------------------------------------------------------------*/
1871 static int __init init (void)
1875 status = register_filesystem (&gadgetfs_type);
1877 pr_info ("%s: %s, version " DRIVER_VERSION "\n",
1878 shortname, driver_desc);
1883 static void __exit cleanup (void)
1885 pr_debug ("unregister %s\n", shortname);
1886 unregister_filesystem (&gadgetfs_type);
1888 module_exit (cleanup);