ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / usb / gadget / inode.c
1 /*
2  * inode.c -- user mode filesystem api for usb gadget controllers
3  *
4  * Copyright (C) 2003 David Brownell
5  * Copyright (C) 2003 Agilent Technologies
6  *
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.
11  *
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.
16  *
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
20  */
21
22
23 #define DEBUG 1                 /* data to help fault diagnosis */
24 // #define      VERBOSE         /* extra debug messages (success too) */
25
26 #include <linux/init.h>
27 #include <linux/module.h>
28 #include <linux/fs.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>
35
36 #include <linux/device.h>
37 #include <linux/moduleparam.h>
38
39 #include <linux/usb_gadgetfs.h>
40 #include <linux/usb_gadget.h>
41
42
43 /*
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.
48  *
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.
54  *
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.
59  *
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).
65  *
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.
70  */
71
72 #define DRIVER_DESC     "USB Gadget filesystem"
73 #define DRIVER_VERSION  "20 Aug 2003"
74
75 static const char driver_desc [] = DRIVER_DESC;
76 static const char shortname [] = "gadgetfs";
77
78 MODULE_DESCRIPTION (DRIVER_DESC);
79 MODULE_AUTHOR ("David Brownell");
80 MODULE_LICENSE ("GPL");
81
82
83 /*----------------------------------------------------------------------*/
84
85 #define GADGETFS_MAGIC          0xaee71ee7
86 #define DMA_ADDR_INVALID        (~(dma_addr_t)0)
87
88 /* /dev/gadget/$CHIP represents ep0 and the whole device */
89 enum ep0_state {
90         /* DISBLED is the initial state.
91          */
92         STATE_DEV_DISABLED = 0,
93
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.
98          */
99         STATE_OPENED,
100
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
105          */
106         STATE_UNCONNECTED,
107         STATE_CONNECTED,
108         STATE_SETUP,
109
110         /* UNBOUND means the driver closed ep0, so the device won't be
111          * accessible again (DEV_DISABLED) until all fds are closed.
112          */
113         STATE_DEV_UNBOUND,
114 };
115
116 /* enough for the whole queue: most events invalidate others */
117 #define N_EVENT                 5
118
119 struct dev_data {
120         spinlock_t                      lock;
121         atomic_t                        count;
122         enum ep0_state                  state;
123         struct usb_gadgetfs_event       event [N_EVENT];
124         unsigned                        ev_next;
125         struct fasync_struct            *fasync;
126         u8                              current_config;
127
128         /* drivers reading ep0 MUST handle control requests (SETUP)
129          * reported that way; else the host will time out.
130          */
131         unsigned                        usermode_setup : 1,
132                                         setup_in : 1,
133                                         setup_can_stall : 1,
134                                         setup_out_ready : 1,
135                                         setup_out_error : 1,
136                                         setup_abort : 1;
137
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;
144         void                            *buf;
145         wait_queue_head_t               wait;
146         struct super_block              *sb;
147         struct dentry                   *dentry;
148
149         /* except this scratch i/o buffer for ep0 */
150         u8                              rbuf [256];
151 };
152
153 static inline void get_dev (struct dev_data *data)
154 {
155         atomic_inc (&data->count);
156 }
157
158 static void put_dev (struct dev_data *data)
159 {
160         if (likely (!atomic_dec_and_test (&data->count)))
161                 return;
162         /* needs no more cleanup */
163         BUG_ON (waitqueue_active (&data->wait));
164         kfree (data);
165 }
166
167 static struct dev_data *dev_new (void)
168 {
169         struct dev_data         *dev;
170
171         dev = kmalloc (sizeof *dev, GFP_KERNEL);
172         if (!dev)
173                 return 0;
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);
180         return dev;
181 }
182
183 /*----------------------------------------------------------------------*/
184
185 /* other /dev/gadget/$ENDPOINT files represent endpoints */
186 enum ep_state {
187         STATE_EP_DISABLED = 0,
188         STATE_EP_READY,
189         STATE_EP_DEFER_ENABLE,
190         STATE_EP_ENABLED,
191         STATE_EP_UNBOUND,
192 };
193
194 struct ep_data {
195         struct semaphore                lock;
196         enum ep_state                   state;
197         atomic_t                        count;
198         struct dev_data                 *dev;
199         /* must hold dev->lock before accessing ep or req */
200         struct usb_ep                   *ep;
201         struct usb_request              *req;
202         ssize_t                         status;
203         char                            name [16];
204         struct usb_endpoint_descriptor  desc, hs_desc;
205         struct list_head                epfiles;
206         wait_queue_head_t               wait;
207         struct dentry                   *dentry;
208         struct inode                    *inode;
209 };
210
211 static inline void get_ep (struct ep_data *data)
212 {
213         atomic_inc (&data->count);
214 }
215
216 static void put_ep (struct ep_data *data)
217 {
218         if (likely (!atomic_dec_and_test (&data->count)))
219                 return;
220         put_dev (data->dev);
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);
225         kfree (data);
226 }
227
228 /*----------------------------------------------------------------------*/
229
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.
233  */
234
235 #ifdef  CONFIG_USB_GADGET_DUMMY_HCD
236 /* act (mostly) like a net2280 */
237 #define CONFIG_USB_GADGET_NET2280
238 #endif
239
240 #ifdef  CONFIG_USB_GADGET_NET2280
241 #define CHIP                    "net2280"
242 #define HIGHSPEED
243 #endif
244
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
249 #endif
250
251 #ifdef  CONFIG_USB_GADGET_GOKU
252 #define CHIP                    "goku_udc"
253 #endif
254
255 #ifdef  CONFIG_USB_GADGET_SA1100
256 #define CHIP                    "sa1100"
257 #endif
258
259 /*----------------------------------------------------------------------*/
260
261 /* NOTE:  don't use dev_printk calls before binding to the gadget
262  * at the end of ep0 configuration, or after unbind.
263  */
264
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)
268
269 #ifdef DEBUG
270 #define DBG(dev,fmt,args...) \
271         xprintk(dev , KERN_DEBUG , fmt , ## args)
272 #else
273 #define DBG(dev,fmt,args...) \
274         do { } while (0)
275 #endif /* DEBUG */
276
277 #ifdef VERBOSE
278 #define VDEBUG  DBG
279 #else
280 #define VDEBUG(dev,fmt,args...) \
281         do { } while (0)
282 #endif /* DEBUG */
283
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)
290
291
292 /*----------------------------------------------------------------------*/
293
294 /* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
295  *
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.
299  */
300
301 static void epio_complete (struct usb_ep *ep, struct usb_request *req)
302 {
303         struct ep_data  *epdata = ep->driver_data;
304
305         if (!req->context)
306                 return;
307         if (req->status)
308                 epdata->status = req->status;
309         else
310                 epdata->status = req->actual;
311         complete ((struct completion *)req->context);
312 }
313
314 /* tasklock endpoint, returning when it's connected.
315  * still need dev->lock to use epdata->ep.
316  */
317 static int
318 get_ready_ep (unsigned f_flags, struct ep_data *epdata)
319 {
320         int     val;
321
322         if (f_flags & O_NONBLOCK) {
323                 if (down_trylock (&epdata->lock) != 0)
324                         goto nonblock;
325                 if (epdata->state != STATE_EP_ENABLED) {
326                         up (&epdata->lock);
327 nonblock:
328                         val = -EAGAIN;
329                 } else
330                         val = 0;
331                 return val;
332         }
333
334         if ((val = down_interruptible (&epdata->lock)) < 0)
335                 return val;
336 newstate:
337         switch (epdata->state) {
338         case STATE_EP_ENABLED:
339                 break;
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
345                                 )) < 0)
346                         goto fail;
347                 goto newstate;
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);
353                 // FALLTHROUGH
354         case STATE_EP_UNBOUND:                  /* clean disconnect */
355                 val = -ENODEV;
356 fail:
357                 up (&epdata->lock);
358         }
359         return val;
360 }
361
362 static ssize_t
363 ep_io (struct ep_data *epdata, void *buf, unsigned len)
364 {
365         DECLARE_COMPLETION (done);
366         int value;
367
368         spin_lock_irq (&epdata->dev->lock);
369         if (likely (epdata->ep != NULL)) {
370                 struct usb_request      *req = epdata->req;
371
372                 req->context = &done;
373                 req->complete = epio_complete;
374                 req->buf = buf;
375                 req->length = len;
376                 value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
377         } else
378                 value = -ENODEV;
379         spin_unlock_irq (&epdata->dev->lock);
380
381         if (likely (value == 0)) {
382                 value = wait_event_interruptible (done.wait, done.done);
383                 if (value != 0) {
384                         spin_lock_irq (&epdata->dev->lock);
385                         if (likely (epdata->ep != NULL)) {
386                                 DBG (epdata->dev, "%s i/o interrupted\n",
387                                                 epdata->name);
388                                 usb_ep_dequeue (epdata->ep, epdata->req);
389                                 spin_unlock_irq (&epdata->dev->lock);
390
391                                 wait_event (done.wait, done.done);
392                                 if (epdata->status == -ECONNRESET)
393                                         epdata->status = -EINTR;
394                         } else {
395                                 spin_unlock_irq (&epdata->dev->lock);
396
397                                 DBG (epdata->dev, "endpoint gone\n");
398                                 epdata->status = -ENODEV;
399                         }
400                 }
401                 return epdata->status;
402         }
403         return value;
404 }
405
406
407 /* handle a synchronous OUT bulk/intr/iso transfer */
408 static ssize_t
409 ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
410 {
411         struct ep_data          *data = fd->private_data;
412         void                    *kbuf;
413         ssize_t                 value;
414
415         if ((value = get_ready_ep (fd->f_flags, data)) < 0)
416                 return value;
417
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)
422                         return -EINVAL;
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);
428                 up (&data->lock);
429                 return -EBADMSG;
430         }
431
432         /* FIXME readahead for O_NONBLOCK and poll(); careful with ZLPs */
433
434         value = -ENOMEM;
435         kbuf = kmalloc (len, SLAB_KERNEL);
436         if (unlikely (!kbuf))
437                 goto free1;
438
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))
443                 value = -EFAULT;
444
445 free1:
446         up (&data->lock);
447         kfree (kbuf);
448         return value;
449 }
450
451 /* handle a synchronous IN bulk/intr/iso transfer */
452 static ssize_t
453 ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
454 {
455         struct ep_data          *data = fd->private_data;
456         void                    *kbuf;
457         ssize_t                 value;
458
459         if ((value = get_ready_ep (fd->f_flags, data)) < 0)
460                 return value;
461
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)
466                         return -EINVAL;
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);
472                 up (&data->lock);
473                 return -EBADMSG;
474         }
475
476         /* FIXME writebehind for O_NONBLOCK and poll(), qlen = 1 */
477
478         value = -ENOMEM;
479         kbuf = kmalloc (len, SLAB_KERNEL);
480         if (!kbuf)
481                 goto free1;
482         if (copy_from_user (kbuf, buf, len)) {
483                 value = -EFAULT;
484                 goto free1;
485         }
486
487         value = ep_io (data, kbuf, len);
488         VDEBUG (data->dev, "%s write %d IN, status %d\n",
489                 data->name, len, value);
490 free1:
491         up (&data->lock);
492         kfree (kbuf);
493         return value;
494 }
495
496 static int
497 ep_release (struct inode *inode, struct file *fd)
498 {
499         struct ep_data          *data = fd->private_data;
500
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;
506         }
507         put_ep (data);
508         return 0;
509 }
510
511 static int ep_ioctl (struct inode *inode, struct file *fd,
512                 unsigned code, unsigned long value)
513 {
514         struct ep_data          *data = fd->private_data;
515         int                     status;
516
517         if ((status = get_ready_ep (fd->f_flags, data)) < 0)
518                 return status;
519
520         spin_lock_irq (&data->dev->lock);
521         if (likely (data->ep != NULL)) {
522                 switch (code) {
523                 case GADGETFS_FIFO_STATUS:
524                         status = usb_ep_fifo_status (data->ep);
525                         break;
526                 case GADGETFS_FIFO_FLUSH:
527                         usb_ep_fifo_flush (data->ep);
528                         break;
529                 case GADGETFS_CLEAR_HALT:
530                         status = usb_ep_clear_halt (data->ep);
531                         break;
532                 default:
533                         status = -ENOTTY;
534                 }
535         } else
536                 status = -ENODEV;
537         spin_unlock_irq (&data->dev->lock);
538         up (&data->lock);
539         return status;
540 }
541
542 /* used after endpoint configuration */
543 static struct file_operations ep_io_operations = {
544         .owner =        THIS_MODULE,
545         .read =         ep_read,
546         .write =        ep_write,
547         .ioctl =        ep_ioctl,
548         .release =      ep_release,
549
550         // .aio_read =  ep_aio_read,
551         // .aio_write = ep_aio_write,
552 };
553
554 /* ENDPOINT INITIALIZATION
555  *
556  *     fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
557  *     status = write (fd, descriptors, sizeof descriptors)
558  *
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.
562  *
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.
566  */
567 static ssize_t
568 ep_config (struct file *fd, const char *buf, size_t len, loff_t *ptr)
569 {
570         struct ep_data          *data = fd->private_data;
571         struct usb_ep           *ep;
572         u32                     tag;
573         int                     value;
574
575         if ((value = down_interruptible (&data->lock)) < 0)
576                 return value;
577
578         if (data->state != STATE_EP_READY) {
579                 value = -EL2HLT;
580                 goto fail;
581         }
582
583         value = len;
584         if (len < USB_DT_ENDPOINT_SIZE + 4)
585                 goto fail0;
586
587         /* we might need to change message format someday */
588         if (copy_from_user (&tag, buf, 4)) {
589                 goto fail1;
590         }
591         if (tag != 1) {
592                 DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
593                 goto fail0;
594         }
595         buf += 4;
596         len -= 4;
597
598         /* NOTE:  audio endpoint extensions not accepted here;
599          * just don't include the extra bytes.
600          */
601
602         /* full/low speed descriptor, then high speed */
603         if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
604                 goto fail1;
605         }
606         if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
607                         || data->desc.bDescriptorType != USB_DT_ENDPOINT)
608                 goto fail0;
609         if (len != USB_DT_ENDPOINT_SIZE) {
610                 if (len != 2 * USB_DT_ENDPOINT_SIZE)
611                         goto fail0;
612                 if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
613                                         USB_DT_ENDPOINT_SIZE)) {
614                         goto fail1;
615                 }
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",
620                                         data->name);
621                         goto fail0;
622                 }
623         }
624         value = len;
625
626         spin_lock_irq (&data->dev->lock);
627         if (data->dev->state == STATE_DEV_UNBOUND) {
628                 value = -ENOENT;
629                 goto gone;
630         } else if ((ep = data->ep) == NULL) {
631                 value = -ENODEV;
632                 goto gone;
633         }
634         switch (data->dev->gadget->speed) {
635         case USB_SPEED_LOW:
636         case USB_SPEED_FULL:
637                 value = usb_ep_enable (ep, &data->desc);
638                 if (value == 0)
639                         data->state = STATE_EP_ENABLED;
640                 break;
641 #ifdef  HIGHSPEED
642         case USB_SPEED_HIGH:
643                 /* fails if caller didn't provide that descriptor... */
644                 value = usb_ep_enable (ep, &data->hs_desc);
645                 if (value == 0)
646                         data->state = STATE_EP_ENABLED;
647                 break;
648 #endif
649         default:
650                 DBG (data->dev, "unconnected, %s init deferred\n",
651                                 data->name);
652                 data->state = STATE_EP_DEFER_ENABLE;
653         }
654         if (value == 0)
655                 fd->f_op = &ep_io_operations;
656 gone:
657         spin_unlock_irq (&data->dev->lock);
658         if (value < 0) {
659 fail:
660                 data->desc.bDescriptorType = 0;
661                 data->hs_desc.bDescriptorType = 0;
662         }
663         up (&data->lock);
664         return value;
665 fail0:
666         value = -EINVAL;
667         goto fail;
668 fail1:
669         value = -EFAULT;
670         goto fail;
671 }
672
673 static int
674 ep_open (struct inode *inode, struct file *fd)
675 {
676         struct ep_data          *data = inode->u.generic_ip;
677         int                     value = -EBUSY;
678
679         if (down_interruptible (&data->lock) != 0)
680                 return -EINTR;
681         spin_lock_irq (&data->dev->lock);
682         if (data->dev->state == STATE_DEV_UNBOUND)
683                 value = -ENOENT;
684         else if (data->state == STATE_EP_DISABLED) {
685                 value = 0;
686                 data->state = STATE_EP_READY;
687                 get_ep (data);
688                 fd->private_data = data;
689                 VDEBUG (data->dev, "%s ready\n", data->name);
690         } else
691                 DBG (data->dev, "%s state %d\n",
692                         data->name, data->state);
693         spin_unlock_irq (&data->dev->lock);
694         up (&data->lock);
695         return value;
696 }
697
698 /* used before endpoint configuration */
699 static struct file_operations ep_config_operations = {
700         .owner =        THIS_MODULE,
701         .open =         ep_open,
702         .write =        ep_config,
703         .release =      ep_release,
704 };
705
706 /*----------------------------------------------------------------------*/
707
708 /* EP0 IMPLEMENTATION can be partly in userspace.
709  *
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.
713  */
714
715 static inline void ep0_readable (struct dev_data *dev)
716 {
717         wake_up (&dev->wait);
718         kill_fasync (&dev->fasync, SIGIO, POLL_IN);
719 }
720
721 static void clean_req (struct usb_ep *ep, struct usb_request *req)
722 {
723         struct dev_data         *dev = ep->driver_data;
724
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;
729         }
730         req->complete = epio_complete;
731         dev->setup_out_ready = 0;
732 }
733
734 static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
735 {
736         struct dev_data         *dev = ep->driver_data;
737         int                     free = 1;
738
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)
743                         free = 0;
744                 dev->setup_out_ready = 1;
745                 ep0_readable (dev);
746         } else if (dev->state == STATE_SETUP)
747                 dev->state = STATE_CONNECTED;
748
749         /* clean up as appropriate */
750         if (free && req->buf != &dev->rbuf)
751                 clean_req (ep, req);
752         req->complete = epio_complete;
753 }
754
755 static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
756 {
757         struct dev_data *dev = ep->driver_data;
758
759         if (dev->setup_out_ready) {
760                 DBG (dev, "ep0 request busy!\n");
761                 return -EBUSY;
762         }
763         if (len > sizeof (dev->rbuf))
764                 req->buf = usb_ep_alloc_buffer (ep, len, &req->dma, GFP_ATOMIC);
765         if (req->buf == 0) {
766                 req->buf = dev->rbuf;
767                 return -ENOMEM;
768         }
769         req->complete = ep0_complete;
770         req->length = len;
771         return 0;
772 }
773
774 static ssize_t
775 ep0_read (struct file *fd, char *buf, size_t len, loff_t *ptr)
776 {
777         struct dev_data                 *dev = fd->private_data;
778         ssize_t                         retval;
779         enum ep0_state                  state;
780
781         spin_lock_irq (&dev->lock);
782
783         /* report fd mode change before acting on it */
784         if (dev->setup_abort) {
785                 dev->setup_abort = 0;
786                 retval = -EIDRM;
787                 goto done;
788         }
789
790         /* control DATA stage */
791         if ((state = dev->state) == STATE_SETUP) {
792
793                 if (dev->setup_in) {            /* stall IN */
794                         VDEBUG(dev, "ep0in stall\n");
795                         (void) usb_ep_set_halt (dev->gadget->ep0);
796                         retval = -EL2HLT;
797                         dev->state = STATE_CONNECTED;
798
799                 } else if (len == 0) {          /* ack SET_CONFIGURATION etc */
800                         struct usb_ep           *ep = dev->gadget->ep0;
801                         struct usb_request      *req = dev->req;
802
803                         if ((retval = setup_req (ep, req, 0)) == 0)
804                                 retval = usb_ep_queue (ep, req, GFP_ATOMIC);
805                         dev->state = STATE_CONNECTED;
806
807                 } else {                        /* collect OUT data */
808                         if ((fd->f_flags & O_NONBLOCK) != 0
809                                         && !dev->setup_out_ready) {
810                                 retval = -EAGAIN;
811                                 goto done;
812                         }
813                         spin_unlock_irq (&dev->lock);
814                         retval = wait_event_interruptible (dev->wait,
815                                         dev->setup_out_ready != 0);
816
817                         /* FIXME state could change from under us */
818                         spin_lock_irq (&dev->lock);
819                         if (retval)
820                                 goto done;
821                         if (dev->setup_out_error)
822                                 retval = -EIO;
823                         else {
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))
827                                         retval = -EFAULT;
828                                 clean_req (dev->gadget->ep0, dev->req);
829                                 /* NOTE userspace can't yet choose to stall */
830                         }
831                 }
832                 goto done;
833         }
834
835         /* else normal: return event data */
836         if (len < sizeof dev->event [0]) {
837                 retval = -EINVAL;
838                 goto done;
839         }
840         len -= len % sizeof (struct usb_gadgetfs_event);
841         dev->usermode_setup = 1;
842
843 scan:
844         /* return queued events right away */
845         if (dev->ev_next != 0) {
846                 unsigned                i, n;
847                 int                     tmp = dev->ev_next;
848
849                 len = min (len, tmp * sizeof (struct usb_gadgetfs_event));
850                 n = len / sizeof (struct usb_gadgetfs_event);
851
852                 /* ep0 can't deliver events when STATE_SETUP */
853                 for (i = 0; i < n; i++) {
854                         if (dev->event [i].type == GADGETFS_SETUP) {
855                                 len = n = i + 1;
856                                 len *= sizeof (struct usb_gadgetfs_event);
857                                 n = 0;
858                                 break;
859                         }
860                 }
861                 spin_unlock_irq (&dev->lock);
862                 if (copy_to_user (buf, &dev->event, len))
863                         retval = -EFAULT;
864                 else
865                         retval = len;
866                 if (len > 0) {
867                         len /= sizeof (struct usb_gadgetfs_event);
868
869                         /* NOTE this doesn't guard against broken drivers;
870                          * concurrent ep0 readers may lose events.
871                          */
872                         spin_lock_irq (&dev->lock);
873                         dev->ev_next -= len;
874                         if (dev->ev_next != 0)
875                                 memmove (&dev->event, &dev->event [len],
876                                         sizeof (struct usb_gadgetfs_event)
877                                                 * (tmp - len));
878                         if (n == 0)
879                                 dev->state = STATE_SETUP;
880                         spin_unlock_irq (&dev->lock);
881                 }
882                 return retval;
883         }
884         if (fd->f_flags & O_NONBLOCK) {
885                 retval = -EAGAIN;
886                 goto done;
887         }
888
889         switch (state) {
890         default:
891                 DBG (dev, "fail %s, state %d\n", __FUNCTION__, state);
892                 retval = -ESRCH;
893                 break;
894         case STATE_UNCONNECTED:
895         case STATE_CONNECTED:
896                 spin_unlock_irq (&dev->lock);
897                 DBG (dev, "%s wait\n", __FUNCTION__);
898
899                 /* wait for events */
900                 retval = wait_event_interruptible (dev->wait,
901                                 dev->ev_next != 0);
902                 if (retval < 0)
903                         return retval;
904                 spin_lock_irq (&dev->lock);
905                 goto scan;
906         }
907
908 done:
909         spin_unlock_irq (&dev->lock);
910         return retval;
911 }
912
913 static struct usb_gadgetfs_event *
914 next_event (struct dev_data *dev, enum usb_gadgetfs_event_type type)
915 {
916         struct usb_gadgetfs_event       *event;
917         unsigned                        i;
918
919         switch (type) {
920         /* these events purge the queue */
921         case GADGETFS_DISCONNECT:
922                 if (dev->state == STATE_SETUP)
923                         dev->setup_abort = 1;
924                 // FALL THROUGH
925         case GADGETFS_CONNECT:
926                 dev->ev_next = 0;
927                 break;
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)
933                                 continue;
934                         DBG (dev, "discard old event %d\n", type);
935                         dev->ev_next--;
936                         if (i == dev->ev_next)
937                                 break;
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));
942                 }
943                 break;
944         default:
945                 BUG ();
946         }
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);
951         event->type = type;
952         return event;
953 }
954
955 static ssize_t
956 ep0_write (struct file *fd, const char *buf, size_t len, loff_t *ptr)
957 {
958         struct dev_data         *dev = fd->private_data;
959         ssize_t                 retval = -ESRCH;
960
961         spin_lock_irq (&dev->lock);
962
963         /* report fd mode change before acting on it */
964         if (dev->setup_abort) {
965                 dev->setup_abort = 0;
966                 retval = -EIDRM;
967
968         /* data and/or status stage for control request */
969         } else if (dev->state == STATE_SETUP) {
970
971                 /* IN DATA+STATUS caller makes len <= wLength */
972                 if (dev->setup_in) {
973                         retval = setup_req (dev->gadget->ep0, dev->req, len);
974                         if (retval == 0) {
975                                 spin_unlock_irq (&dev->lock);
976                                 if (copy_from_user (dev->req->buf, buf, len))
977                                         retval = -EFAULT;
978                                 else
979                                         retval = usb_ep_queue (
980                                                 dev->gadget->ep0, dev->req,
981                                                 GFP_KERNEL);
982                                 if (retval < 0) {
983                                         spin_lock_irq (&dev->lock);
984                                         clean_req (dev->gadget->ep0, dev->req);
985                                         spin_unlock_irq (&dev->lock);
986                                 } else
987                                         retval = len;
988
989                                 return retval;
990                         }
991
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);
996                         retval = -EL2HLT;
997                         dev->state = STATE_CONNECTED;
998                 } else {
999                         DBG(dev, "bogus ep0out stall!\n");
1000                 }
1001         } else
1002                 DBG (dev, "fail %s, state %d\n", __FUNCTION__, dev->state);
1003
1004         spin_unlock_irq (&dev->lock);
1005         return retval;
1006 }
1007
1008 static int
1009 ep0_fasync (int f, struct file *fd, int on)
1010 {
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);
1015 }
1016
1017 static struct usb_gadget_driver gadgetfs_driver;
1018
1019 static int
1020 dev_release (struct inode *inode, struct file *fd)
1021 {
1022         struct dev_data         *dev = fd->private_data;
1023
1024         /* closing ep0 === shutdown all */
1025
1026         usb_gadget_unregister_driver (&gadgetfs_driver);
1027
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.
1031          */
1032
1033         fasync_helper (-1, fd, 0, &dev->fasync);
1034         kfree (dev->buf);
1035         dev->buf = 0;
1036         put_dev (dev);
1037
1038         /* other endpoints were all decoupled from this device */
1039         dev->state = STATE_DEV_DISABLED;
1040         return 0;
1041 }
1042
1043 static int dev_ioctl (struct inode *inode, struct file *fd,
1044                 unsigned code, unsigned long value)
1045 {
1046         struct dev_data         *dev = fd->private_data;
1047         struct usb_gadget       *gadget = dev->gadget;
1048
1049         if (gadget->ops->ioctl)
1050                 return gadget->ops->ioctl (gadget, code, value);
1051         return -ENOTTY;
1052 }
1053
1054 /* used after device configuration */
1055 static struct file_operations ep0_io_operations = {
1056         .owner =        THIS_MODULE,
1057         .read =         ep0_read,
1058         .write =        ep0_write,
1059         .fasync =       ep0_fasync,
1060         // .poll =      ep0_poll,
1061         .ioctl =        dev_ioctl,
1062         .release =      dev_release,
1063 };
1064
1065 /*----------------------------------------------------------------------*/
1066
1067 /* The in-kernel gadget driver handles most ep0 issues, in particular
1068  * enumerating the single configuration (as provided from user space).
1069  *
1070  * Unrecognized ep0 requests may be handled in user space.
1071  */
1072
1073 #ifdef  HIGHSPEED
1074 static void make_qualifier (struct dev_data *dev)
1075 {
1076         struct usb_qualifier_descriptor         qual;
1077         struct usb_device_descriptor            *desc;
1078
1079         qual.bLength = sizeof qual;
1080         qual.bDescriptorType = USB_DT_DEVICE_QUALIFIER;
1081         qual.bcdUSB = __constant_cpu_to_le16 (0x0200);
1082
1083         desc = dev->dev;
1084         qual.bDeviceClass = desc->bDeviceClass;
1085         qual.bDeviceSubClass = desc->bDeviceSubClass;
1086         qual.bDeviceProtocol = desc->bDeviceProtocol;
1087
1088         /* assumes ep0 uses the same value for both speeds ... */
1089         qual.bMaxPacketSize0 = desc->bMaxPacketSize0;
1090
1091         qual.bNumConfigurations = 1;
1092         qual.bRESERVED = 0;
1093
1094         memcpy (dev->rbuf, &qual, sizeof qual);
1095 }
1096 #endif
1097
1098 static int
1099 config_buf (struct dev_data *dev, u8 type, unsigned index)
1100 {
1101         int             len;
1102 #ifdef HIGHSPEED
1103         int             hs;
1104 #endif
1105
1106         /* only one configuration */
1107         if (index > 0)
1108                 return -EINVAL;
1109
1110 #ifdef HIGHSPEED
1111         hs = (dev->gadget->speed == USB_SPEED_HIGH);
1112         if (type == USB_DT_OTHER_SPEED_CONFIG)
1113                 hs = !hs;
1114         if (hs) {
1115                 dev->req->buf = dev->hs_config;
1116                 len = le16_to_cpup (&dev->hs_config->wTotalLength);
1117         } else
1118 #endif
1119         {
1120                 dev->req->buf = dev->config;
1121                 len = le16_to_cpup (&dev->config->wTotalLength);
1122         }
1123         ((u8 *)dev->req->buf) [1] = type;
1124         return len;
1125 }
1126
1127 static int
1128 gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1129 {
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;
1134
1135         spin_lock (&dev->lock);
1136         dev->setup_abort = 0;
1137         if (dev->state == STATE_UNCONNECTED) {
1138                 struct usb_ep   *ep;
1139                 struct ep_data  *data;
1140
1141                 dev->state = STATE_CONNECTED;
1142                 dev->dev->bMaxPacketSize0 = gadget->ep0->maxpacket;
1143
1144 #ifdef  HIGHSPEED
1145                 if (gadget->speed == USB_SPEED_HIGH && dev->hs_config == 0) {
1146                         ERROR (dev, "no high speed config??\n");
1147                         return -EINVAL;
1148                 }
1149 #endif  /* HIGHSPEED */
1150
1151                 INFO (dev, "connected\n");
1152                 event = next_event (dev, GADGETFS_CONNECT);
1153                 event->u.speed = gadget->speed;
1154                 ep0_readable (dev);
1155
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)
1160                                 continue;
1161 #ifdef  HIGHSPEED
1162                         if (gadget->speed == USB_SPEED_HIGH)
1163                                 value = usb_ep_enable (ep, &data->hs_desc);
1164                         else
1165 #endif  /* HIGHSPEED */
1166                                 value = usb_ep_enable (ep, &data->desc);
1167                         if (value) {
1168                                 ERROR (dev, "deferred %s enable --> %d\n",
1169                                         data->name, value);
1170                                 continue;
1171                         }
1172                         data->state = STATE_EP_ENABLED;
1173                         wake_up (&data->wait);
1174                         DBG (dev, "woke up %s waiters\n", data->name);
1175                 }
1176
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.
1181          */
1182         } else if (dev->state == STATE_SETUP)
1183                 dev->setup_abort = 1;
1184
1185         req->buf = dev->rbuf;
1186         req->dma = DMA_ADDR_INVALID;
1187         req->context = 0;
1188         value = -EOPNOTSUPP;
1189         switch (ctrl->bRequest) {
1190
1191         case USB_REQ_GET_DESCRIPTOR:
1192                 if (ctrl->bRequestType != USB_DIR_IN)
1193                         goto unrecognized;
1194                 switch (ctrl->wValue >> 8) {
1195
1196                 case USB_DT_DEVICE:
1197                         value = min (ctrl->wLength, (u16) sizeof *dev->dev);
1198                         req->buf = dev->dev;
1199                         break;
1200 #ifdef  HIGHSPEED
1201                 case USB_DT_DEVICE_QUALIFIER:
1202                         if (!dev->hs_config)
1203                                 break;
1204                         value = min (ctrl->wLength, (u16)
1205                                 sizeof (struct usb_qualifier_descriptor));
1206                         make_qualifier (dev);
1207                         break;
1208                 case USB_DT_OTHER_SPEED_CONFIG:
1209                         // FALLTHROUGH
1210 #endif
1211                 case USB_DT_CONFIG:
1212                         value = config_buf (dev,
1213                                         ctrl->wValue >> 8,
1214                                         ctrl->wValue & 0xff);
1215                         if (value >= 0)
1216                                 value = min (ctrl->wLength, (u16) value);
1217                         break;
1218                 case USB_DT_STRING:
1219                         goto unrecognized;
1220
1221                 default:                // all others are errors
1222                         break;
1223                 }
1224                 break;
1225
1226         /* currently one config, two speeds */
1227         case USB_REQ_SET_CONFIGURATION:
1228                 if (ctrl->bRequestType != 0)
1229                         break;
1230                 if (0 == (u8) ctrl->wValue) {
1231                         value = 0;
1232                         dev->current_config = 0;
1233                         // user mode expected to disable endpoints
1234                 } else {
1235                         u8      config;
1236 #ifdef  HIGHSPEED
1237                         if (gadget->speed == USB_SPEED_HIGH)
1238                                 config = dev->hs_config->bConfigurationValue;
1239                         else
1240 #endif
1241                                 config = dev->config->bConfigurationValue;
1242
1243                         if (config == (u8) ctrl->wValue) {
1244                                 value = 0;
1245                                 dev->current_config = config;
1246                         }
1247                 }
1248
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.
1253                  *
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.
1257                  */
1258                 if (value == 0) {
1259                         INFO (dev, "configuration #%d\n", dev->current_config);
1260                         if (dev->usermode_setup) {
1261                                 dev->setup_can_stall = 0;
1262                                 goto delegate;
1263                         }
1264                 }
1265                 break;
1266
1267 #ifndef CONFIG_USB_GADGETFS_PXA2XX
1268         /* PXA automagically handles this request too */
1269         case USB_REQ_GET_CONFIGURATION:
1270                 if (ctrl->bRequestType != 0x80)
1271                         break;
1272                 *(u8 *)req->buf = dev->current_config;
1273                 value = min (ctrl->wLength, (u16) 1);
1274                 break;
1275 #endif
1276
1277         default:
1278 unrecognized:
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);
1283
1284                 /* if there's an ep0 reader, don't stall */
1285                 if (dev->usermode_setup) {
1286                         dev->setup_can_stall = 1;
1287 delegate:
1288                         dev->setup_in = (ctrl->bRequestType & USB_DIR_IN)
1289                                                 ? 1 : 0;
1290                         dev->setup_out_ready = 0;
1291                         dev->setup_out_error = 0;
1292                         value = 0;
1293
1294                         /* read DATA stage for OUT right away */
1295                         if (unlikely (!dev->setup_in && ctrl->wLength)) {
1296                                 value = setup_req (gadget->ep0, dev->req,
1297                                                         ctrl->wLength);
1298                                 if (value < 0)
1299                                         break;
1300                                 value = usb_ep_queue (gadget->ep0, dev->req,
1301                                                         GFP_ATOMIC);
1302                                 if (value < 0) {
1303                                         clean_req (gadget->ep0, dev->req);
1304                                         break;
1305                                 }
1306
1307                                 /* we can't currently stall these */
1308                                 dev->setup_can_stall = 0;
1309                         }
1310
1311                         /* state changes when reader collects event */
1312                         event = next_event (dev, GADGETFS_SETUP);
1313                         event->u.setup = *ctrl;
1314                         ep0_readable (dev);
1315                         spin_unlock (&dev->lock);
1316                         return 0;
1317                 }
1318         }
1319
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);
1324                 if (value < 0) {
1325                         DBG (dev, "ep_queue --> %d\n", value);
1326                         req->status = 0;
1327                 }
1328         }
1329
1330         /* device stalls when value < 0 */
1331         spin_unlock (&dev->lock);
1332         return value;
1333 }
1334
1335 static void destroy_ep_files (struct dev_data *dev)
1336 {
1337         struct list_head        *entry, *tmp;
1338
1339         DBG (dev, "%s %d\n", __FUNCTION__, dev->state);
1340
1341         /* dev->state must prevent interference */
1342 restart:
1343         spin_lock_irq (&dev->lock);
1344         list_for_each_safe (entry, tmp, &dev->epfiles) {
1345                 struct ep_data  *ep;
1346                 struct inode    *parent;
1347                 struct dentry   *dentry;
1348
1349                 /* break link to FS */
1350                 ep = list_entry (entry, struct ep_data, epfiles);
1351                 list_del_init (&ep->epfiles);
1352                 dentry = ep->dentry;
1353                 ep->dentry = 0;
1354                 parent = dentry->d_parent->d_inode;
1355
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);
1361                 ep->ep = 0;
1362                 wake_up (&ep->wait);
1363                 put_ep (ep);
1364
1365                 spin_unlock_irq (&dev->lock);
1366
1367                 /* break link to dcache */
1368                 down (&parent->i_sem);
1369                 d_delete (dentry);
1370                 dput (dentry);
1371                 up (&parent->i_sem);
1372
1373                 /* fds may still be open */
1374                 goto restart;
1375         }
1376         spin_unlock_irq (&dev->lock);
1377 }
1378
1379
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);
1384
1385 static int activate_ep_files (struct dev_data *dev)
1386 {
1387         struct usb_ep   *ep;
1388
1389         gadget_for_each_ep (ep, dev->gadget) {
1390                 struct ep_data  *data;
1391
1392                 data = kmalloc (sizeof *data, GFP_KERNEL);
1393                 if (!data)
1394                         goto enomem;
1395                 memset (data, 0, sizeof data);
1396                 data->state = STATE_EP_DISABLED;
1397                 init_MUTEX (&data->lock);
1398                 init_waitqueue_head (&data->wait);
1399
1400                 strncpy (data->name, ep->name, sizeof (data->name) - 1);
1401                 atomic_set (&data->count, 1);
1402                 data->dev = dev;
1403                 get_dev (dev);
1404
1405                 data->ep = ep;
1406                 ep->driver_data = data;
1407
1408                 data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1409                 if (!data->req)
1410                         goto enomem;
1411
1412                 data->inode = gadgetfs_create_file (dev->sb, data->name,
1413                                 data, &ep_config_operations,
1414                                 &data->dentry);
1415                 if (!data->inode) {
1416                         kfree (data);
1417                         goto enomem;
1418                 }
1419                 list_add_tail (&data->epfiles, &dev->epfiles);
1420         }
1421         return 0;
1422
1423 enomem:
1424         DBG (dev, "%s enomem\n", __FUNCTION__);
1425         destroy_ep_files (dev);
1426         return -ENOMEM;
1427 }
1428
1429 static void
1430 gadgetfs_unbind (struct usb_gadget *gadget)
1431 {
1432         struct dev_data         *dev = get_gadget_data (gadget);
1433
1434         DBG (dev, "%s\n", __FUNCTION__);
1435
1436         spin_lock_irq (&dev->lock);
1437         dev->state = STATE_DEV_UNBOUND;
1438         spin_unlock_irq (&dev->lock);
1439
1440         destroy_ep_files (dev);
1441         gadget->ep0->driver_data = 0;
1442         set_gadget_data (gadget, 0);
1443
1444         /* we've already been disconnected ... no i/o is active */
1445         if (dev->req)
1446                 usb_ep_free_request (gadget->ep0, dev->req);
1447         DBG (dev, "%s done\n", __FUNCTION__);
1448         put_dev (dev);
1449 }
1450
1451 static struct dev_data          *the_device;
1452
1453 static int
1454 gadgetfs_bind (struct usb_gadget *gadget)
1455 {
1456         struct dev_data         *dev = the_device;
1457
1458         if (!dev)
1459                 return -ESRCH;
1460         if (0 != strcmp (CHIP, gadget->name)) {
1461                 printk (KERN_ERR "%s expected " CHIP " controller not %s\n",
1462                         shortname, gadget->name);
1463                 return -ENODEV;
1464         }
1465
1466         set_gadget_data (gadget, dev);
1467         dev->gadget = gadget;
1468         gadget->ep0->driver_data = dev;
1469         dev->dev->bMaxPacketSize0 = gadget->ep0->maxpacket;
1470
1471         /* preallocate control response and buffer */
1472         dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1473         if (!dev->req)
1474                 goto enomem;
1475         dev->req->context = 0;
1476         dev->req->complete = epio_complete;
1477
1478         if (activate_ep_files (dev) < 0)
1479                 goto enomem;
1480
1481         INFO (dev, "bound to %s driver\n", gadget->name);
1482         dev->state = STATE_UNCONNECTED;
1483         get_dev (dev);
1484         return 0;
1485
1486 enomem:
1487         gadgetfs_unbind (gadget);
1488         return -ENOMEM;
1489 }
1490
1491 static void
1492 gadgetfs_disconnect (struct usb_gadget *gadget)
1493 {
1494         struct dev_data         *dev = get_gadget_data (gadget);
1495
1496         if (dev->state == STATE_UNCONNECTED) {
1497                 DBG (dev, "already unconnected\n");
1498                 return;
1499         }
1500         dev->state = STATE_UNCONNECTED;
1501
1502         INFO (dev, "disconnected\n");
1503         spin_lock (&dev->lock);
1504         next_event (dev, GADGETFS_DISCONNECT);
1505         ep0_readable (dev);
1506         spin_unlock (&dev->lock);
1507 }
1508
1509 static void
1510 gadgetfs_suspend (struct usb_gadget *gadget)
1511 {
1512         struct dev_data         *dev = get_gadget_data (gadget);
1513
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);
1521                 ep0_readable (dev);
1522                 /* FALLTHROUGH */
1523         default:
1524                 break;
1525         }
1526         spin_unlock (&dev->lock);
1527 }
1528
1529 static struct usb_gadget_driver gadgetfs_driver = {
1530 #ifdef  HIGHSPEED
1531         .speed          = USB_SPEED_HIGH,
1532 #else
1533         .speed          = USB_SPEED_FULL,
1534 #endif
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,
1541
1542         .driver         = {
1543                 .name           = (char *) shortname,
1544                 // .shutdown = ...
1545                 // .suspend = ...
1546                 // .resume = ...
1547         },
1548 };
1549
1550 /*----------------------------------------------------------------------*/
1551
1552 /* DEVICE INITIALIZATION
1553  *
1554  *     fd = open ("/dev/gadget/$CHIP", O_RDWR)
1555  *     status = write (fd, descriptors, sizeof descriptors)
1556  *
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:
1560  *
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
1568  *
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.
1574  *
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.
1579  */
1580
1581 static int is_valid_config (struct usb_config_descriptor *config)
1582 {
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 */
1589 }
1590
1591 static ssize_t
1592 dev_config (struct file *fd, const char *buf, size_t len, loff_t *ptr)
1593 {
1594         struct dev_data         *dev = fd->private_data;
1595         ssize_t                 value = len, length = len;
1596         unsigned                total;
1597         u32                     tag;
1598         char                    *kbuf;
1599
1600         if (dev->state != STATE_OPENED)
1601                 return -EEXIST;
1602
1603         if (len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4))
1604                 return -EINVAL;
1605
1606         /* we might need to change message format someday */
1607         if (copy_from_user (&tag, buf, 4))
1608                 return -EFAULT;
1609         if (tag != 0)
1610                 return -EINVAL;
1611         buf += 4;
1612         length -= 4;
1613
1614         kbuf = kmalloc (length, SLAB_KERNEL);
1615         if (!kbuf)
1616                 return -ENOMEM;
1617         if (copy_from_user (kbuf, buf, length)) {
1618                 kfree (kbuf);
1619                 return -EFAULT;
1620         }
1621
1622         spin_lock_irq (&dev->lock);
1623         value = -EINVAL;
1624         if (dev->buf)
1625                 goto fail;
1626         dev->buf = kbuf;
1627
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)
1632                 goto fail;
1633         kbuf += total;
1634         length -= total;
1635
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)
1641                         goto fail;
1642                 kbuf += total;
1643                 length -= total;
1644         }
1645
1646         /* could support multiple configs, using another encoding! */
1647
1648         /* device descriptor (tweaked for paranoia) */
1649         if (length != USB_DT_DEVICE_SIZE)
1650                 goto fail;
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)
1655                 goto fail;
1656         dev->dev->bNumConfigurations = 1;
1657         dev->dev->bcdUSB = __constant_cpu_to_le16 (0x0200);
1658
1659         /* triggers gadgetfs_bind(); then we can enumerate. */
1660         spin_unlock_irq (&dev->lock);
1661         value = usb_gadget_register_driver (&gadgetfs_driver);
1662         if (value != 0) {
1663                 kfree (dev->buf);
1664                 dev->buf = 0;
1665         } else {
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.
1669                  *
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.
1674                  */
1675                 fd->f_op = &ep0_io_operations;
1676                 value = len;
1677         }
1678         return value;
1679
1680 fail:
1681         spin_unlock_irq (&dev->lock);
1682         pr_debug ("%s: %s fail %Zd, %p\n", shortname, __FUNCTION__, value, dev);
1683         kfree (dev->buf);
1684         dev->buf = 0;
1685         return value;
1686 }
1687
1688 static int
1689 dev_open (struct inode *inode, struct file *fd)
1690 {
1691         struct dev_data         *dev = inode->u.generic_ip;
1692         int                     value = -EBUSY;
1693
1694         if (dev->state == STATE_DEV_DISABLED) {
1695                 dev->ev_next = 0;
1696                 dev->state = STATE_OPENED;
1697                 fd->private_data = dev;
1698                 get_dev (dev);
1699                 value = 0;
1700         }
1701         return value;
1702 }
1703
1704 static struct file_operations dev_init_operations = {
1705         .owner =        THIS_MODULE,
1706         .open =         dev_open,
1707         .write =        dev_config,
1708         .fasync =       ep0_fasync,
1709         .ioctl =        dev_ioctl,
1710         .release =      dev_release,
1711 };
1712
1713 /*----------------------------------------------------------------------*/
1714
1715 /* FILESYSTEM AND SUPERBLOCK OPERATIONS
1716  *
1717  * Mounting the filesystem creates a controller file, used first for
1718  * device configuration then later for event monitoring.
1719  */
1720
1721
1722 /* FIXME PAM etc could set this security policy without mount options
1723  * if epfiles inherited ownership and permissons from ep0 ...
1724  */
1725
1726 static unsigned default_uid;
1727 static unsigned default_gid;
1728 static unsigned default_perm = S_IRUSR | S_IWUSR;
1729
1730 module_param (default_uid, uint, 0644);
1731 module_param (default_gid, uint, 0644);
1732 module_param (default_perm, uint, 0644);
1733
1734
1735 static struct inode *
1736 gadgetfs_make_inode (struct super_block *sb,
1737                 void *data, struct file_operations *fops,
1738                 int mode)
1739 {
1740         struct inode *inode = new_inode (sb);
1741
1742         if (inode) {
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
1749                                 = CURRENT_TIME;
1750                 inode->u.generic_ip = data;
1751                 inode->i_fop = fops;
1752         }
1753         return inode;
1754 }
1755
1756 /* creates in fs root directory, so non-renamable and non-linkable.
1757  * so inode and dentry are paired, until device reconfig.
1758  */
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)
1763 {
1764         struct dentry   *dentry;
1765         struct inode    *inode;
1766         struct qstr     qname;
1767
1768         qname.name = name;
1769         qname.len = strlen (name);
1770         qname.hash = full_name_hash (qname.name, qname.len);
1771         dentry = d_alloc (sb->s_root, &qname);
1772         if (!dentry)
1773                 return 0;
1774
1775         inode = gadgetfs_make_inode (sb, data, fops,
1776                         S_IFREG | (default_perm & S_IRWXUGO));
1777         if (!inode) {
1778                 dput(dentry);
1779                 return 0;
1780         }
1781         d_add (dentry, inode);
1782         *dentry_p = dentry;
1783         return inode;
1784 }
1785
1786 static struct super_operations gadget_fs_operations = {
1787         .statfs =       simple_statfs,
1788         .drop_inode =   generic_delete_inode,
1789 };
1790
1791 static int
1792 gadgetfs_fill_super (struct super_block *sb, void *opts, int silent)
1793 {
1794         struct inode    *inode;
1795         struct dentry   *d;
1796         struct dev_data *dev;
1797
1798         if (the_device)
1799                 return -ESRCH;
1800
1801         /* superblock */
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;
1806
1807         /* root inode */
1808         inode = gadgetfs_make_inode (sb,
1809                         0, &simple_dir_operations,
1810                         S_IFDIR | S_IRUGO | S_IXUGO);
1811         if (!inode)
1812                 return -ENOMEM;
1813         inode->i_op = &simple_dir_inode_operations;
1814         if (!(d = d_alloc_root (inode))) {
1815                 iput (inode);
1816                 return -ENOMEM;
1817         }
1818         sb->s_root = d;
1819
1820         /* the ep0 file is named after the controller we expect;
1821          * user mode code can use it for sanity checks, like we do.
1822          */
1823         dev = dev_new ();
1824         if (!dev)
1825                 return -ENOMEM;
1826
1827         dev->sb = sb;
1828         if (!(inode = gadgetfs_create_file (sb, CHIP,
1829                                 dev, &dev_init_operations,
1830                                 &dev->dentry))) {
1831                 put_dev(dev);
1832                 return -ENOMEM;
1833         }
1834
1835         /* other endpoint files are available after hardware setup,
1836          * from binding to a controller.
1837          */
1838         the_device = dev;
1839         return 0;
1840 }
1841
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)
1846 {
1847         return get_sb_single (t, flags, opts, gadgetfs_fill_super);
1848 }
1849
1850 static void
1851 gadgetfs_kill_sb (struct super_block *sb)
1852 {
1853         kill_litter_super (sb);
1854         if (the_device) {
1855                 put_dev (the_device);
1856                 the_device = 0;
1857         }
1858 }
1859
1860 /*----------------------------------------------------------------------*/
1861
1862 static struct file_system_type gadgetfs_type = {
1863         .owner          = THIS_MODULE,
1864         .name           = shortname,
1865         .get_sb         = gadgetfs_get_sb,
1866         .kill_sb        = gadgetfs_kill_sb,
1867 };
1868
1869 /*----------------------------------------------------------------------*/
1870
1871 static int __init init (void)
1872 {
1873         int status;
1874
1875         status = register_filesystem (&gadgetfs_type);
1876         if (status == 0)
1877                 pr_info ("%s: %s, version " DRIVER_VERSION "\n",
1878                         shortname, driver_desc);
1879         return status;
1880 }
1881 module_init (init);
1882
1883 static void __exit cleanup (void)
1884 {
1885         pr_debug ("unregister %s\n", shortname);
1886         unregister_filesystem (&gadgetfs_type);
1887 }
1888 module_exit (cleanup);
1889