GNU Linux-libre 4.9.328-gnu1
[releases.git] / drivers / usb / gadget / legacy / inode.c
1 /*
2  * inode.c -- user mode filesystem api for usb gadget controllers
3  *
4  * Copyright (C) 2003-2004 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
13
14 /* #define VERBOSE_DEBUG */
15
16 #include <linux/init.h>
17 #include <linux/module.h>
18 #include <linux/fs.h>
19 #include <linux/pagemap.h>
20 #include <linux/uts.h>
21 #include <linux/wait.h>
22 #include <linux/compiler.h>
23 #include <asm/uaccess.h>
24 #include <linux/sched.h>
25 #include <linux/slab.h>
26 #include <linux/poll.h>
27 #include <linux/mmu_context.h>
28 #include <linux/aio.h>
29 #include <linux/uio.h>
30 #include <linux/delay.h>
31 #include <linux/device.h>
32 #include <linux/moduleparam.h>
33
34 #include <linux/usb/gadgetfs.h>
35 #include <linux/usb/gadget.h>
36
37
38 /*
39  * The gadgetfs API maps each endpoint to a file descriptor so that you
40  * can use standard synchronous read/write calls for I/O.  There's some
41  * O_NONBLOCK and O_ASYNC/FASYNC style i/o support.  Example usermode
42  * drivers show how this works in practice.  You can also use AIO to
43  * eliminate I/O gaps between requests, to help when streaming data.
44  *
45  * Key parts that must be USB-specific are protocols defining how the
46  * read/write operations relate to the hardware state machines.  There
47  * are two types of files.  One type is for the device, implementing ep0.
48  * The other type is for each IN or OUT endpoint.  In both cases, the
49  * user mode driver must configure the hardware before using it.
50  *
51  * - First, dev_config() is called when /dev/gadget/$CHIP is configured
52  *   (by writing configuration and device descriptors).  Afterwards it
53  *   may serve as a source of device events, used to handle all control
54  *   requests other than basic enumeration.
55  *
56  * - Then, after a SET_CONFIGURATION control request, ep_config() is
57  *   called when each /dev/gadget/ep* file is configured (by writing
58  *   endpoint descriptors).  Afterwards these files are used to write()
59  *   IN data or to read() OUT data.  To halt the endpoint, a "wrong
60  *   direction" request is issued (like reading an IN endpoint).
61  *
62  * Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe
63  * not possible on all hardware.  For example, precise fault handling with
64  * respect to data left in endpoint fifos after aborted operations; or
65  * selective clearing of endpoint halts, to implement SET_INTERFACE.
66  */
67
68 #define DRIVER_DESC     "USB Gadget filesystem"
69 #define DRIVER_VERSION  "24 Aug 2004"
70
71 static const char driver_desc [] = DRIVER_DESC;
72 static const char shortname [] = "gadgetfs";
73
74 MODULE_DESCRIPTION (DRIVER_DESC);
75 MODULE_AUTHOR ("David Brownell");
76 MODULE_LICENSE ("GPL");
77
78 static int ep_open(struct inode *, struct file *);
79
80
81 /*----------------------------------------------------------------------*/
82
83 #define GADGETFS_MAGIC          0xaee71ee7
84
85 /* /dev/gadget/$CHIP represents ep0 and the whole device */
86 enum ep0_state {
87         /* DISBLED is the initial state.
88          */
89         STATE_DEV_DISABLED = 0,
90
91         /* Only one open() of /dev/gadget/$CHIP; only one file tracks
92          * ep0/device i/o modes and binding to the controller.  Driver
93          * must always write descriptors to initialize the device, then
94          * the device becomes UNCONNECTED until enumeration.
95          */
96         STATE_DEV_OPENED,
97
98         /* From then on, ep0 fd is in either of two basic modes:
99          * - (UN)CONNECTED: read usb_gadgetfs_event(s) from it
100          * - SETUP: read/write will transfer control data and succeed;
101          *   or if "wrong direction", performs protocol stall
102          */
103         STATE_DEV_UNCONNECTED,
104         STATE_DEV_CONNECTED,
105         STATE_DEV_SETUP,
106
107         /* UNBOUND means the driver closed ep0, so the device won't be
108          * accessible again (DEV_DISABLED) until all fds are closed.
109          */
110         STATE_DEV_UNBOUND,
111 };
112
113 /* enough for the whole queue: most events invalidate others */
114 #define N_EVENT                 5
115
116 #define RBUF_SIZE               256
117
118 struct dev_data {
119         spinlock_t                      lock;
120         atomic_t                        count;
121         int                             udc_usage;
122         enum ep0_state                  state;          /* P: lock */
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                                         gadget_registered : 1;
138         unsigned                        setup_wLength;
139
140         /* the rest is basically write-once */
141         struct usb_config_descriptor    *config, *hs_config;
142         struct usb_device_descriptor    *dev;
143         struct usb_request              *req;
144         struct usb_gadget               *gadget;
145         struct list_head                epfiles;
146         void                            *buf;
147         wait_queue_head_t               wait;
148         struct super_block              *sb;
149         struct dentry                   *dentry;
150
151         /* except this scratch i/o buffer for ep0 */
152         u8                              rbuf[RBUF_SIZE];
153 };
154
155 static inline void get_dev (struct dev_data *data)
156 {
157         atomic_inc (&data->count);
158 }
159
160 static void put_dev (struct dev_data *data)
161 {
162         if (likely (!atomic_dec_and_test (&data->count)))
163                 return;
164         /* needs no more cleanup */
165         BUG_ON (waitqueue_active (&data->wait));
166         kfree (data);
167 }
168
169 static struct dev_data *dev_new (void)
170 {
171         struct dev_data         *dev;
172
173         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
174         if (!dev)
175                 return NULL;
176         dev->state = STATE_DEV_DISABLED;
177         atomic_set (&dev->count, 1);
178         spin_lock_init (&dev->lock);
179         INIT_LIST_HEAD (&dev->epfiles);
180         init_waitqueue_head (&dev->wait);
181         return dev;
182 }
183
184 /*----------------------------------------------------------------------*/
185
186 /* other /dev/gadget/$ENDPOINT files represent endpoints */
187 enum ep_state {
188         STATE_EP_DISABLED = 0,
189         STATE_EP_READY,
190         STATE_EP_ENABLED,
191         STATE_EP_UNBOUND,
192 };
193
194 struct ep_data {
195         struct mutex                    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 };
209
210 static inline void get_ep (struct ep_data *data)
211 {
212         atomic_inc (&data->count);
213 }
214
215 static void put_ep (struct ep_data *data)
216 {
217         if (likely (!atomic_dec_and_test (&data->count)))
218                 return;
219         put_dev (data->dev);
220         /* needs no more cleanup */
221         BUG_ON (!list_empty (&data->epfiles));
222         BUG_ON (waitqueue_active (&data->wait));
223         kfree (data);
224 }
225
226 /*----------------------------------------------------------------------*/
227
228 /* most "how to use the hardware" policy choices are in userspace:
229  * mapping endpoint roles (which the driver needs) to the capabilities
230  * which the usb controller has.  most of those capabilities are exposed
231  * implicitly, starting with the driver name and then endpoint names.
232  */
233
234 static const char *CHIP;
235
236 /*----------------------------------------------------------------------*/
237
238 /* NOTE:  don't use dev_printk calls before binding to the gadget
239  * at the end of ep0 configuration, or after unbind.
240  */
241
242 /* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */
243 #define xprintk(d,level,fmt,args...) \
244         printk(level "%s: " fmt , shortname , ## args)
245
246 #ifdef DEBUG
247 #define DBG(dev,fmt,args...) \
248         xprintk(dev , KERN_DEBUG , fmt , ## args)
249 #else
250 #define DBG(dev,fmt,args...) \
251         do { } while (0)
252 #endif /* DEBUG */
253
254 #ifdef VERBOSE_DEBUG
255 #define VDEBUG  DBG
256 #else
257 #define VDEBUG(dev,fmt,args...) \
258         do { } while (0)
259 #endif /* DEBUG */
260
261 #define ERROR(dev,fmt,args...) \
262         xprintk(dev , KERN_ERR , fmt , ## args)
263 #define INFO(dev,fmt,args...) \
264         xprintk(dev , KERN_INFO , fmt , ## args)
265
266
267 /*----------------------------------------------------------------------*/
268
269 /* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
270  *
271  * After opening, configure non-control endpoints.  Then use normal
272  * stream read() and write() requests; and maybe ioctl() to get more
273  * precise FIFO status when recovering from cancellation.
274  */
275
276 static void epio_complete (struct usb_ep *ep, struct usb_request *req)
277 {
278         struct ep_data  *epdata = ep->driver_data;
279
280         if (!req->context)
281                 return;
282         if (req->status)
283                 epdata->status = req->status;
284         else
285                 epdata->status = req->actual;
286         complete ((struct completion *)req->context);
287 }
288
289 /* tasklock endpoint, returning when it's connected.
290  * still need dev->lock to use epdata->ep.
291  */
292 static int
293 get_ready_ep (unsigned f_flags, struct ep_data *epdata, bool is_write)
294 {
295         int     val;
296
297         if (f_flags & O_NONBLOCK) {
298                 if (!mutex_trylock(&epdata->lock))
299                         goto nonblock;
300                 if (epdata->state != STATE_EP_ENABLED &&
301                     (!is_write || epdata->state != STATE_EP_READY)) {
302                         mutex_unlock(&epdata->lock);
303 nonblock:
304                         val = -EAGAIN;
305                 } else
306                         val = 0;
307                 return val;
308         }
309
310         val = mutex_lock_interruptible(&epdata->lock);
311         if (val < 0)
312                 return val;
313
314         switch (epdata->state) {
315         case STATE_EP_ENABLED:
316                 return 0;
317         case STATE_EP_READY:                    /* not configured yet */
318                 if (is_write)
319                         return 0;
320                 // FALLTHRU
321         case STATE_EP_UNBOUND:                  /* clean disconnect */
322                 break;
323         // case STATE_EP_DISABLED:              /* "can't happen" */
324         default:                                /* error! */
325                 pr_debug ("%s: ep %p not available, state %d\n",
326                                 shortname, epdata, epdata->state);
327         }
328         mutex_unlock(&epdata->lock);
329         return -ENODEV;
330 }
331
332 static ssize_t
333 ep_io (struct ep_data *epdata, void *buf, unsigned len)
334 {
335         DECLARE_COMPLETION_ONSTACK (done);
336         int value;
337
338         spin_lock_irq (&epdata->dev->lock);
339         if (likely (epdata->ep != NULL)) {
340                 struct usb_request      *req = epdata->req;
341
342                 req->context = &done;
343                 req->complete = epio_complete;
344                 req->buf = buf;
345                 req->length = len;
346                 value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
347         } else
348                 value = -ENODEV;
349         spin_unlock_irq (&epdata->dev->lock);
350
351         if (likely (value == 0)) {
352                 value = wait_event_interruptible (done.wait, done.done);
353                 if (value != 0) {
354                         spin_lock_irq (&epdata->dev->lock);
355                         if (likely (epdata->ep != NULL)) {
356                                 DBG (epdata->dev, "%s i/o interrupted\n",
357                                                 epdata->name);
358                                 usb_ep_dequeue (epdata->ep, epdata->req);
359                                 spin_unlock_irq (&epdata->dev->lock);
360
361                                 wait_event (done.wait, done.done);
362                                 if (epdata->status == -ECONNRESET)
363                                         epdata->status = -EINTR;
364                         } else {
365                                 spin_unlock_irq (&epdata->dev->lock);
366
367                                 DBG (epdata->dev, "endpoint gone\n");
368                                 wait_for_completion(&done);
369                                 epdata->status = -ENODEV;
370                         }
371                 }
372                 return epdata->status;
373         }
374         return value;
375 }
376
377 static int
378 ep_release (struct inode *inode, struct file *fd)
379 {
380         struct ep_data          *data = fd->private_data;
381         int value;
382
383         value = mutex_lock_interruptible(&data->lock);
384         if (value < 0)
385                 return value;
386
387         /* clean up if this can be reopened */
388         if (data->state != STATE_EP_UNBOUND) {
389                 data->state = STATE_EP_DISABLED;
390                 data->desc.bDescriptorType = 0;
391                 data->hs_desc.bDescriptorType = 0;
392                 usb_ep_disable(data->ep);
393         }
394         mutex_unlock(&data->lock);
395         put_ep (data);
396         return 0;
397 }
398
399 static long ep_ioctl(struct file *fd, unsigned code, unsigned long value)
400 {
401         struct ep_data          *data = fd->private_data;
402         int                     status;
403
404         if ((status = get_ready_ep (fd->f_flags, data, false)) < 0)
405                 return status;
406
407         spin_lock_irq (&data->dev->lock);
408         if (likely (data->ep != NULL)) {
409                 switch (code) {
410                 case GADGETFS_FIFO_STATUS:
411                         status = usb_ep_fifo_status (data->ep);
412                         break;
413                 case GADGETFS_FIFO_FLUSH:
414                         usb_ep_fifo_flush (data->ep);
415                         break;
416                 case GADGETFS_CLEAR_HALT:
417                         status = usb_ep_clear_halt (data->ep);
418                         break;
419                 default:
420                         status = -ENOTTY;
421                 }
422         } else
423                 status = -ENODEV;
424         spin_unlock_irq (&data->dev->lock);
425         mutex_unlock(&data->lock);
426         return status;
427 }
428
429 /*----------------------------------------------------------------------*/
430
431 /* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */
432
433 struct kiocb_priv {
434         struct usb_request      *req;
435         struct ep_data          *epdata;
436         struct kiocb            *iocb;
437         struct mm_struct        *mm;
438         struct work_struct      work;
439         void                    *buf;
440         struct iov_iter         to;
441         const void              *to_free;
442         unsigned                actual;
443 };
444
445 static int ep_aio_cancel(struct kiocb *iocb)
446 {
447         struct kiocb_priv       *priv = iocb->private;
448         struct ep_data          *epdata;
449         int                     value;
450
451         local_irq_disable();
452         epdata = priv->epdata;
453         // spin_lock(&epdata->dev->lock);
454         if (likely(epdata && epdata->ep && priv->req))
455                 value = usb_ep_dequeue (epdata->ep, priv->req);
456         else
457                 value = -EINVAL;
458         // spin_unlock(&epdata->dev->lock);
459         local_irq_enable();
460
461         return value;
462 }
463
464 static void ep_user_copy_worker(struct work_struct *work)
465 {
466         struct kiocb_priv *priv = container_of(work, struct kiocb_priv, work);
467         struct mm_struct *mm = priv->mm;
468         struct kiocb *iocb = priv->iocb;
469         size_t ret;
470
471         use_mm(mm);
472         ret = copy_to_iter(priv->buf, priv->actual, &priv->to);
473         unuse_mm(mm);
474         if (!ret)
475                 ret = -EFAULT;
476
477         /* completing the iocb can drop the ctx and mm, don't touch mm after */
478         iocb->ki_complete(iocb, ret, ret);
479
480         kfree(priv->buf);
481         kfree(priv->to_free);
482         kfree(priv);
483 }
484
485 static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req)
486 {
487         struct kiocb            *iocb = req->context;
488         struct kiocb_priv       *priv = iocb->private;
489         struct ep_data          *epdata = priv->epdata;
490
491         /* lock against disconnect (and ideally, cancel) */
492         spin_lock(&epdata->dev->lock);
493         priv->req = NULL;
494         priv->epdata = NULL;
495
496         /* if this was a write or a read returning no data then we
497          * don't need to copy anything to userspace, so we can
498          * complete the aio request immediately.
499          */
500         if (priv->to_free == NULL || unlikely(req->actual == 0)) {
501                 kfree(req->buf);
502                 kfree(priv->to_free);
503                 kfree(priv);
504                 iocb->private = NULL;
505                 /* aio_complete() reports bytes-transferred _and_ faults */
506
507                 iocb->ki_complete(iocb, req->actual ? req->actual : req->status,
508                                 req->status);
509         } else {
510                 /* ep_copy_to_user() won't report both; we hide some faults */
511                 if (unlikely(0 != req->status))
512                         DBG(epdata->dev, "%s fault %d len %d\n",
513                                 ep->name, req->status, req->actual);
514
515                 priv->buf = req->buf;
516                 priv->actual = req->actual;
517                 INIT_WORK(&priv->work, ep_user_copy_worker);
518                 schedule_work(&priv->work);
519         }
520
521         usb_ep_free_request(ep, req);
522         spin_unlock(&epdata->dev->lock);
523         put_ep(epdata);
524 }
525
526 static ssize_t ep_aio(struct kiocb *iocb,
527                       struct kiocb_priv *priv,
528                       struct ep_data *epdata,
529                       char *buf,
530                       size_t len)
531 {
532         struct usb_request *req;
533         ssize_t value;
534
535         iocb->private = priv;
536         priv->iocb = iocb;
537
538         kiocb_set_cancel_fn(iocb, ep_aio_cancel);
539         get_ep(epdata);
540         priv->epdata = epdata;
541         priv->actual = 0;
542         priv->mm = current->mm; /* mm teardown waits for iocbs in exit_aio() */
543
544         /* each kiocb is coupled to one usb_request, but we can't
545          * allocate or submit those if the host disconnected.
546          */
547         spin_lock_irq(&epdata->dev->lock);
548         value = -ENODEV;
549         if (unlikely(epdata->ep == NULL))
550                 goto fail;
551
552         req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC);
553         value = -ENOMEM;
554         if (unlikely(!req))
555                 goto fail;
556
557         priv->req = req;
558         req->buf = buf;
559         req->length = len;
560         req->complete = ep_aio_complete;
561         req->context = iocb;
562         value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC);
563         if (unlikely(0 != value)) {
564                 usb_ep_free_request(epdata->ep, req);
565                 goto fail;
566         }
567         spin_unlock_irq(&epdata->dev->lock);
568         return -EIOCBQUEUED;
569
570 fail:
571         spin_unlock_irq(&epdata->dev->lock);
572         kfree(priv->to_free);
573         kfree(priv);
574         put_ep(epdata);
575         return value;
576 }
577
578 static ssize_t
579 ep_read_iter(struct kiocb *iocb, struct iov_iter *to)
580 {
581         struct file *file = iocb->ki_filp;
582         struct ep_data *epdata = file->private_data;
583         size_t len = iov_iter_count(to);
584         ssize_t value;
585         char *buf;
586
587         if ((value = get_ready_ep(file->f_flags, epdata, false)) < 0)
588                 return value;
589
590         /* halt any endpoint by doing a "wrong direction" i/o call */
591         if (usb_endpoint_dir_in(&epdata->desc)) {
592                 if (usb_endpoint_xfer_isoc(&epdata->desc) ||
593                     !is_sync_kiocb(iocb)) {
594                         mutex_unlock(&epdata->lock);
595                         return -EINVAL;
596                 }
597                 DBG (epdata->dev, "%s halt\n", epdata->name);
598                 spin_lock_irq(&epdata->dev->lock);
599                 if (likely(epdata->ep != NULL))
600                         usb_ep_set_halt(epdata->ep);
601                 spin_unlock_irq(&epdata->dev->lock);
602                 mutex_unlock(&epdata->lock);
603                 return -EBADMSG;
604         }
605
606         buf = kmalloc(len, GFP_KERNEL);
607         if (unlikely(!buf)) {
608                 mutex_unlock(&epdata->lock);
609                 return -ENOMEM;
610         }
611         if (is_sync_kiocb(iocb)) {
612                 value = ep_io(epdata, buf, len);
613                 if (value >= 0 && (copy_to_iter(buf, value, to) != value))
614                         value = -EFAULT;
615         } else {
616                 struct kiocb_priv *priv = kzalloc(sizeof *priv, GFP_KERNEL);
617                 value = -ENOMEM;
618                 if (!priv)
619                         goto fail;
620                 priv->to_free = dup_iter(&priv->to, to, GFP_KERNEL);
621                 if (!priv->to_free) {
622                         kfree(priv);
623                         goto fail;
624                 }
625                 value = ep_aio(iocb, priv, epdata, buf, len);
626                 if (value == -EIOCBQUEUED)
627                         buf = NULL;
628         }
629 fail:
630         kfree(buf);
631         mutex_unlock(&epdata->lock);
632         return value;
633 }
634
635 static ssize_t ep_config(struct ep_data *, const char *, size_t);
636
637 static ssize_t
638 ep_write_iter(struct kiocb *iocb, struct iov_iter *from)
639 {
640         struct file *file = iocb->ki_filp;
641         struct ep_data *epdata = file->private_data;
642         size_t len = iov_iter_count(from);
643         bool configured;
644         ssize_t value;
645         char *buf;
646
647         if ((value = get_ready_ep(file->f_flags, epdata, true)) < 0)
648                 return value;
649
650         configured = epdata->state == STATE_EP_ENABLED;
651
652         /* halt any endpoint by doing a "wrong direction" i/o call */
653         if (configured && !usb_endpoint_dir_in(&epdata->desc)) {
654                 if (usb_endpoint_xfer_isoc(&epdata->desc) ||
655                     !is_sync_kiocb(iocb)) {
656                         mutex_unlock(&epdata->lock);
657                         return -EINVAL;
658                 }
659                 DBG (epdata->dev, "%s halt\n", epdata->name);
660                 spin_lock_irq(&epdata->dev->lock);
661                 if (likely(epdata->ep != NULL))
662                         usb_ep_set_halt(epdata->ep);
663                 spin_unlock_irq(&epdata->dev->lock);
664                 mutex_unlock(&epdata->lock);
665                 return -EBADMSG;
666         }
667
668         buf = kmalloc(len, GFP_KERNEL);
669         if (unlikely(!buf)) {
670                 mutex_unlock(&epdata->lock);
671                 return -ENOMEM;
672         }
673
674         if (unlikely(copy_from_iter(buf, len, from) != len)) {
675                 value = -EFAULT;
676                 goto out;
677         }
678
679         if (unlikely(!configured)) {
680                 value = ep_config(epdata, buf, len);
681         } else if (is_sync_kiocb(iocb)) {
682                 value = ep_io(epdata, buf, len);
683         } else {
684                 struct kiocb_priv *priv = kzalloc(sizeof *priv, GFP_KERNEL);
685                 value = -ENOMEM;
686                 if (priv) {
687                         value = ep_aio(iocb, priv, epdata, buf, len);
688                         if (value == -EIOCBQUEUED)
689                                 buf = NULL;
690                 }
691         }
692 out:
693         kfree(buf);
694         mutex_unlock(&epdata->lock);
695         return value;
696 }
697
698 /*----------------------------------------------------------------------*/
699
700 /* used after endpoint configuration */
701 static const struct file_operations ep_io_operations = {
702         .owner =        THIS_MODULE,
703
704         .open =         ep_open,
705         .release =      ep_release,
706         .llseek =       no_llseek,
707         .unlocked_ioctl = ep_ioctl,
708         .read_iter =    ep_read_iter,
709         .write_iter =   ep_write_iter,
710 };
711
712 /* ENDPOINT INITIALIZATION
713  *
714  *     fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
715  *     status = write (fd, descriptors, sizeof descriptors)
716  *
717  * That write establishes the endpoint configuration, configuring
718  * the controller to process bulk, interrupt, or isochronous transfers
719  * at the right maxpacket size, and so on.
720  *
721  * The descriptors are message type 1, identified by a host order u32
722  * at the beginning of what's written.  Descriptor order is: full/low
723  * speed descriptor, then optional high speed descriptor.
724  */
725 static ssize_t
726 ep_config (struct ep_data *data, const char *buf, size_t len)
727 {
728         struct usb_ep           *ep;
729         u32                     tag;
730         int                     value, length = len;
731
732         if (data->state != STATE_EP_READY) {
733                 value = -EL2HLT;
734                 goto fail;
735         }
736
737         value = len;
738         if (len < USB_DT_ENDPOINT_SIZE + 4)
739                 goto fail0;
740
741         /* we might need to change message format someday */
742         memcpy(&tag, buf, 4);
743         if (tag != 1) {
744                 DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
745                 goto fail0;
746         }
747         buf += 4;
748         len -= 4;
749
750         /* NOTE:  audio endpoint extensions not accepted here;
751          * just don't include the extra bytes.
752          */
753
754         /* full/low speed descriptor, then high speed */
755         memcpy(&data->desc, buf, USB_DT_ENDPOINT_SIZE);
756         if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
757                         || data->desc.bDescriptorType != USB_DT_ENDPOINT)
758                 goto fail0;
759         if (len != USB_DT_ENDPOINT_SIZE) {
760                 if (len != 2 * USB_DT_ENDPOINT_SIZE)
761                         goto fail0;
762                 memcpy(&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
763                         USB_DT_ENDPOINT_SIZE);
764                 if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
765                                 || data->hs_desc.bDescriptorType
766                                         != USB_DT_ENDPOINT) {
767                         DBG(data->dev, "config %s, bad hs length or type\n",
768                                         data->name);
769                         goto fail0;
770                 }
771         }
772
773         spin_lock_irq (&data->dev->lock);
774         if (data->dev->state == STATE_DEV_UNBOUND) {
775                 value = -ENOENT;
776                 goto gone;
777         } else {
778                 ep = data->ep;
779                 if (ep == NULL) {
780                         value = -ENODEV;
781                         goto gone;
782                 }
783         }
784         switch (data->dev->gadget->speed) {
785         case USB_SPEED_LOW:
786         case USB_SPEED_FULL:
787                 ep->desc = &data->desc;
788                 break;
789         case USB_SPEED_HIGH:
790                 /* fails if caller didn't provide that descriptor... */
791                 ep->desc = &data->hs_desc;
792                 break;
793         default:
794                 DBG(data->dev, "unconnected, %s init abandoned\n",
795                                 data->name);
796                 value = -EINVAL;
797                 goto gone;
798         }
799         value = usb_ep_enable(ep);
800         if (value == 0) {
801                 data->state = STATE_EP_ENABLED;
802                 value = length;
803         }
804 gone:
805         spin_unlock_irq (&data->dev->lock);
806         if (value < 0) {
807 fail:
808                 data->desc.bDescriptorType = 0;
809                 data->hs_desc.bDescriptorType = 0;
810         }
811         return value;
812 fail0:
813         value = -EINVAL;
814         goto fail;
815 }
816
817 static int
818 ep_open (struct inode *inode, struct file *fd)
819 {
820         struct ep_data          *data = inode->i_private;
821         int                     value = -EBUSY;
822
823         if (mutex_lock_interruptible(&data->lock) != 0)
824                 return -EINTR;
825         spin_lock_irq (&data->dev->lock);
826         if (data->dev->state == STATE_DEV_UNBOUND)
827                 value = -ENOENT;
828         else if (data->state == STATE_EP_DISABLED) {
829                 value = 0;
830                 data->state = STATE_EP_READY;
831                 get_ep (data);
832                 fd->private_data = data;
833                 VDEBUG (data->dev, "%s ready\n", data->name);
834         } else
835                 DBG (data->dev, "%s state %d\n",
836                         data->name, data->state);
837         spin_unlock_irq (&data->dev->lock);
838         mutex_unlock(&data->lock);
839         return value;
840 }
841
842 /*----------------------------------------------------------------------*/
843
844 /* EP0 IMPLEMENTATION can be partly in userspace.
845  *
846  * Drivers that use this facility receive various events, including
847  * control requests the kernel doesn't handle.  Drivers that don't
848  * use this facility may be too simple-minded for real applications.
849  */
850
851 static inline void ep0_readable (struct dev_data *dev)
852 {
853         wake_up (&dev->wait);
854         kill_fasync (&dev->fasync, SIGIO, POLL_IN);
855 }
856
857 static void clean_req (struct usb_ep *ep, struct usb_request *req)
858 {
859         struct dev_data         *dev = ep->driver_data;
860
861         if (req->buf != dev->rbuf) {
862                 kfree(req->buf);
863                 req->buf = dev->rbuf;
864         }
865         req->complete = epio_complete;
866         dev->setup_out_ready = 0;
867 }
868
869 static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
870 {
871         struct dev_data         *dev = ep->driver_data;
872         unsigned long           flags;
873         int                     free = 1;
874
875         /* for control OUT, data must still get to userspace */
876         spin_lock_irqsave(&dev->lock, flags);
877         if (!dev->setup_in) {
878                 dev->setup_out_error = (req->status != 0);
879                 if (!dev->setup_out_error)
880                         free = 0;
881                 dev->setup_out_ready = 1;
882                 ep0_readable (dev);
883         }
884
885         /* clean up as appropriate */
886         if (free && req->buf != &dev->rbuf)
887                 clean_req (ep, req);
888         req->complete = epio_complete;
889         spin_unlock_irqrestore(&dev->lock, flags);
890 }
891
892 static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
893 {
894         struct dev_data *dev = ep->driver_data;
895
896         if (dev->setup_out_ready) {
897                 DBG (dev, "ep0 request busy!\n");
898                 return -EBUSY;
899         }
900         if (len > sizeof (dev->rbuf))
901                 req->buf = kmalloc(len, GFP_ATOMIC);
902         if (req->buf == NULL) {
903                 req->buf = dev->rbuf;
904                 return -ENOMEM;
905         }
906         req->complete = ep0_complete;
907         req->length = len;
908         req->zero = 0;
909         return 0;
910 }
911
912 static ssize_t
913 ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
914 {
915         struct dev_data                 *dev = fd->private_data;
916         ssize_t                         retval;
917         enum ep0_state                  state;
918
919         spin_lock_irq (&dev->lock);
920         if (dev->state <= STATE_DEV_OPENED) {
921                 retval = -EINVAL;
922                 goto done;
923         }
924
925         /* report fd mode change before acting on it */
926         if (dev->setup_abort) {
927                 dev->setup_abort = 0;
928                 retval = -EIDRM;
929                 goto done;
930         }
931
932         /* control DATA stage */
933         if ((state = dev->state) == STATE_DEV_SETUP) {
934
935                 if (dev->setup_in) {            /* stall IN */
936                         VDEBUG(dev, "ep0in stall\n");
937                         (void) usb_ep_set_halt (dev->gadget->ep0);
938                         retval = -EL2HLT;
939                         dev->state = STATE_DEV_CONNECTED;
940
941                 } else if (len == 0) {          /* ack SET_CONFIGURATION etc */
942                         struct usb_ep           *ep = dev->gadget->ep0;
943                         struct usb_request      *req = dev->req;
944
945                         if ((retval = setup_req (ep, req, 0)) == 0) {
946                                 ++dev->udc_usage;
947                                 spin_unlock_irq (&dev->lock);
948                                 retval = usb_ep_queue (ep, req, GFP_KERNEL);
949                                 spin_lock_irq (&dev->lock);
950                                 --dev->udc_usage;
951                         }
952                         dev->state = STATE_DEV_CONNECTED;
953
954                         /* assume that was SET_CONFIGURATION */
955                         if (dev->current_config) {
956                                 unsigned power;
957
958                                 if (gadget_is_dualspeed(dev->gadget)
959                                                 && (dev->gadget->speed
960                                                         == USB_SPEED_HIGH))
961                                         power = dev->hs_config->bMaxPower;
962                                 else
963                                         power = dev->config->bMaxPower;
964                                 usb_gadget_vbus_draw(dev->gadget, 2 * power);
965                         }
966
967                 } else {                        /* collect OUT data */
968                         if ((fd->f_flags & O_NONBLOCK) != 0
969                                         && !dev->setup_out_ready) {
970                                 retval = -EAGAIN;
971                                 goto done;
972                         }
973                         spin_unlock_irq (&dev->lock);
974                         retval = wait_event_interruptible (dev->wait,
975                                         dev->setup_out_ready != 0);
976
977                         /* FIXME state could change from under us */
978                         spin_lock_irq (&dev->lock);
979                         if (retval)
980                                 goto done;
981
982                         if (dev->state != STATE_DEV_SETUP) {
983                                 retval = -ECANCELED;
984                                 goto done;
985                         }
986                         dev->state = STATE_DEV_CONNECTED;
987
988                         if (dev->setup_out_error)
989                                 retval = -EIO;
990                         else {
991                                 len = min (len, (size_t)dev->req->actual);
992                                 ++dev->udc_usage;
993                                 spin_unlock_irq(&dev->lock);
994                                 if (copy_to_user (buf, dev->req->buf, len))
995                                         retval = -EFAULT;
996                                 else
997                                         retval = len;
998                                 spin_lock_irq(&dev->lock);
999                                 --dev->udc_usage;
1000                                 clean_req (dev->gadget->ep0, dev->req);
1001                                 /* NOTE userspace can't yet choose to stall */
1002                         }
1003                 }
1004                 goto done;
1005         }
1006
1007         /* else normal: return event data */
1008         if (len < sizeof dev->event [0]) {
1009                 retval = -EINVAL;
1010                 goto done;
1011         }
1012         len -= len % sizeof (struct usb_gadgetfs_event);
1013         dev->usermode_setup = 1;
1014
1015 scan:
1016         /* return queued events right away */
1017         if (dev->ev_next != 0) {
1018                 unsigned                i, n;
1019
1020                 n = len / sizeof (struct usb_gadgetfs_event);
1021                 if (dev->ev_next < n)
1022                         n = dev->ev_next;
1023
1024                 /* ep0 i/o has special semantics during STATE_DEV_SETUP */
1025                 for (i = 0; i < n; i++) {
1026                         if (dev->event [i].type == GADGETFS_SETUP) {
1027                                 dev->state = STATE_DEV_SETUP;
1028                                 n = i + 1;
1029                                 break;
1030                         }
1031                 }
1032                 spin_unlock_irq (&dev->lock);
1033                 len = n * sizeof (struct usb_gadgetfs_event);
1034                 if (copy_to_user (buf, &dev->event, len))
1035                         retval = -EFAULT;
1036                 else
1037                         retval = len;
1038                 if (len > 0) {
1039                         /* NOTE this doesn't guard against broken drivers;
1040                          * concurrent ep0 readers may lose events.
1041                          */
1042                         spin_lock_irq (&dev->lock);
1043                         if (dev->ev_next > n) {
1044                                 memmove(&dev->event[0], &dev->event[n],
1045                                         sizeof (struct usb_gadgetfs_event)
1046                                                 * (dev->ev_next - n));
1047                         }
1048                         dev->ev_next -= n;
1049                         spin_unlock_irq (&dev->lock);
1050                 }
1051                 return retval;
1052         }
1053         if (fd->f_flags & O_NONBLOCK) {
1054                 retval = -EAGAIN;
1055                 goto done;
1056         }
1057
1058         switch (state) {
1059         default:
1060                 DBG (dev, "fail %s, state %d\n", __func__, state);
1061                 retval = -ESRCH;
1062                 break;
1063         case STATE_DEV_UNCONNECTED:
1064         case STATE_DEV_CONNECTED:
1065                 spin_unlock_irq (&dev->lock);
1066                 DBG (dev, "%s wait\n", __func__);
1067
1068                 /* wait for events */
1069                 retval = wait_event_interruptible (dev->wait,
1070                                 dev->ev_next != 0);
1071                 if (retval < 0)
1072                         return retval;
1073                 spin_lock_irq (&dev->lock);
1074                 goto scan;
1075         }
1076
1077 done:
1078         spin_unlock_irq (&dev->lock);
1079         return retval;
1080 }
1081
1082 static struct usb_gadgetfs_event *
1083 next_event (struct dev_data *dev, enum usb_gadgetfs_event_type type)
1084 {
1085         struct usb_gadgetfs_event       *event;
1086         unsigned                        i;
1087
1088         switch (type) {
1089         /* these events purge the queue */
1090         case GADGETFS_DISCONNECT:
1091                 if (dev->state == STATE_DEV_SETUP)
1092                         dev->setup_abort = 1;
1093                 // FALL THROUGH
1094         case GADGETFS_CONNECT:
1095                 dev->ev_next = 0;
1096                 break;
1097         case GADGETFS_SETUP:            /* previous request timed out */
1098         case GADGETFS_SUSPEND:          /* same effect */
1099                 /* these events can't be repeated */
1100                 for (i = 0; i != dev->ev_next; i++) {
1101                         if (dev->event [i].type != type)
1102                                 continue;
1103                         DBG(dev, "discard old event[%d] %d\n", i, type);
1104                         dev->ev_next--;
1105                         if (i == dev->ev_next)
1106                                 break;
1107                         /* indices start at zero, for simplicity */
1108                         memmove (&dev->event [i], &dev->event [i + 1],
1109                                 sizeof (struct usb_gadgetfs_event)
1110                                         * (dev->ev_next - i));
1111                 }
1112                 break;
1113         default:
1114                 BUG ();
1115         }
1116         VDEBUG(dev, "event[%d] = %d\n", dev->ev_next, type);
1117         event = &dev->event [dev->ev_next++];
1118         BUG_ON (dev->ev_next > N_EVENT);
1119         memset (event, 0, sizeof *event);
1120         event->type = type;
1121         return event;
1122 }
1123
1124 static ssize_t
1125 ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1126 {
1127         struct dev_data         *dev = fd->private_data;
1128         ssize_t                 retval = -ESRCH;
1129
1130         /* report fd mode change before acting on it */
1131         if (dev->setup_abort) {
1132                 dev->setup_abort = 0;
1133                 retval = -EIDRM;
1134
1135         /* data and/or status stage for control request */
1136         } else if (dev->state == STATE_DEV_SETUP) {
1137
1138                 len = min_t(size_t, len, dev->setup_wLength);
1139                 if (dev->setup_in) {
1140                         retval = setup_req (dev->gadget->ep0, dev->req, len);
1141                         if (retval == 0) {
1142                                 dev->state = STATE_DEV_CONNECTED;
1143                                 ++dev->udc_usage;
1144                                 spin_unlock_irq (&dev->lock);
1145                                 if (copy_from_user (dev->req->buf, buf, len))
1146                                         retval = -EFAULT;
1147                                 else {
1148                                         if (len < dev->setup_wLength)
1149                                                 dev->req->zero = 1;
1150                                         retval = usb_ep_queue (
1151                                                 dev->gadget->ep0, dev->req,
1152                                                 GFP_KERNEL);
1153                                 }
1154                                 spin_lock_irq(&dev->lock);
1155                                 --dev->udc_usage;
1156                                 if (retval < 0) {
1157                                         clean_req (dev->gadget->ep0, dev->req);
1158                                 } else
1159                                         retval = len;
1160
1161                                 return retval;
1162                         }
1163
1164                 /* can stall some OUT transfers */
1165                 } else if (dev->setup_can_stall) {
1166                         VDEBUG(dev, "ep0out stall\n");
1167                         (void) usb_ep_set_halt (dev->gadget->ep0);
1168                         retval = -EL2HLT;
1169                         dev->state = STATE_DEV_CONNECTED;
1170                 } else {
1171                         DBG(dev, "bogus ep0out stall!\n");
1172                 }
1173         } else
1174                 DBG (dev, "fail %s, state %d\n", __func__, dev->state);
1175
1176         return retval;
1177 }
1178
1179 static int
1180 ep0_fasync (int f, struct file *fd, int on)
1181 {
1182         struct dev_data         *dev = fd->private_data;
1183         // caller must F_SETOWN before signal delivery happens
1184         VDEBUG (dev, "%s %s\n", __func__, on ? "on" : "off");
1185         return fasync_helper (f, fd, on, &dev->fasync);
1186 }
1187
1188 static struct usb_gadget_driver gadgetfs_driver;
1189
1190 static int
1191 dev_release (struct inode *inode, struct file *fd)
1192 {
1193         struct dev_data         *dev = fd->private_data;
1194
1195         /* closing ep0 === shutdown all */
1196
1197         if (dev->gadget_registered) {
1198                 usb_gadget_unregister_driver (&gadgetfs_driver);
1199                 dev->gadget_registered = false;
1200         }
1201
1202         /* at this point "good" hardware has disconnected the
1203          * device from USB; the host won't see it any more.
1204          * alternatively, all host requests will time out.
1205          */
1206
1207         kfree (dev->buf);
1208         dev->buf = NULL;
1209
1210         /* other endpoints were all decoupled from this device */
1211         spin_lock_irq(&dev->lock);
1212         dev->state = STATE_DEV_DISABLED;
1213         spin_unlock_irq(&dev->lock);
1214
1215         put_dev (dev);
1216         return 0;
1217 }
1218
1219 static unsigned int
1220 ep0_poll (struct file *fd, poll_table *wait)
1221 {
1222        struct dev_data         *dev = fd->private_data;
1223        int                     mask = 0;
1224
1225         if (dev->state <= STATE_DEV_OPENED)
1226                 return DEFAULT_POLLMASK;
1227
1228        poll_wait(fd, &dev->wait, wait);
1229
1230        spin_lock_irq (&dev->lock);
1231
1232        /* report fd mode change before acting on it */
1233        if (dev->setup_abort) {
1234                dev->setup_abort = 0;
1235                mask = POLLHUP;
1236                goto out;
1237        }
1238
1239        if (dev->state == STATE_DEV_SETUP) {
1240                if (dev->setup_in || dev->setup_can_stall)
1241                        mask = POLLOUT;
1242        } else {
1243                if (dev->ev_next != 0)
1244                        mask = POLLIN;
1245        }
1246 out:
1247        spin_unlock_irq(&dev->lock);
1248        return mask;
1249 }
1250
1251 static long dev_ioctl (struct file *fd, unsigned code, unsigned long value)
1252 {
1253         struct dev_data         *dev = fd->private_data;
1254         struct usb_gadget       *gadget = dev->gadget;
1255         long ret = -ENOTTY;
1256
1257         spin_lock_irq(&dev->lock);
1258         if (dev->state == STATE_DEV_OPENED ||
1259                         dev->state == STATE_DEV_UNBOUND) {
1260                 /* Not bound to a UDC */
1261         } else if (gadget->ops->ioctl) {
1262                 ++dev->udc_usage;
1263                 spin_unlock_irq(&dev->lock);
1264
1265                 ret = gadget->ops->ioctl (gadget, code, value);
1266
1267                 spin_lock_irq(&dev->lock);
1268                 --dev->udc_usage;
1269         }
1270         spin_unlock_irq(&dev->lock);
1271
1272         return ret;
1273 }
1274
1275 /*----------------------------------------------------------------------*/
1276
1277 /* The in-kernel gadget driver handles most ep0 issues, in particular
1278  * enumerating the single configuration (as provided from user space).
1279  *
1280  * Unrecognized ep0 requests may be handled in user space.
1281  */
1282
1283 static void make_qualifier (struct dev_data *dev)
1284 {
1285         struct usb_qualifier_descriptor         qual;
1286         struct usb_device_descriptor            *desc;
1287
1288         qual.bLength = sizeof qual;
1289         qual.bDescriptorType = USB_DT_DEVICE_QUALIFIER;
1290         qual.bcdUSB = cpu_to_le16 (0x0200);
1291
1292         desc = dev->dev;
1293         qual.bDeviceClass = desc->bDeviceClass;
1294         qual.bDeviceSubClass = desc->bDeviceSubClass;
1295         qual.bDeviceProtocol = desc->bDeviceProtocol;
1296
1297         /* assumes ep0 uses the same value for both speeds ... */
1298         qual.bMaxPacketSize0 = dev->gadget->ep0->maxpacket;
1299
1300         qual.bNumConfigurations = 1;
1301         qual.bRESERVED = 0;
1302
1303         memcpy (dev->rbuf, &qual, sizeof qual);
1304 }
1305
1306 static int
1307 config_buf (struct dev_data *dev, u8 type, unsigned index)
1308 {
1309         int             len;
1310         int             hs = 0;
1311
1312         /* only one configuration */
1313         if (index > 0)
1314                 return -EINVAL;
1315
1316         if (gadget_is_dualspeed(dev->gadget)) {
1317                 hs = (dev->gadget->speed == USB_SPEED_HIGH);
1318                 if (type == USB_DT_OTHER_SPEED_CONFIG)
1319                         hs = !hs;
1320         }
1321         if (hs) {
1322                 dev->req->buf = dev->hs_config;
1323                 len = le16_to_cpu(dev->hs_config->wTotalLength);
1324         } else {
1325                 dev->req->buf = dev->config;
1326                 len = le16_to_cpu(dev->config->wTotalLength);
1327         }
1328         ((u8 *)dev->req->buf) [1] = type;
1329         return len;
1330 }
1331
1332 static int
1333 gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1334 {
1335         struct dev_data                 *dev = get_gadget_data (gadget);
1336         struct usb_request              *req = dev->req;
1337         int                             value = -EOPNOTSUPP;
1338         struct usb_gadgetfs_event       *event;
1339         u16                             w_value = le16_to_cpu(ctrl->wValue);
1340         u16                             w_length = le16_to_cpu(ctrl->wLength);
1341
1342         if (w_length > RBUF_SIZE) {
1343                 if (ctrl->bRequestType & USB_DIR_IN) {
1344                         /* Cast away the const, we are going to overwrite on purpose. */
1345                         __le16 *temp = (__le16 *)&ctrl->wLength;
1346
1347                         *temp = cpu_to_le16(RBUF_SIZE);
1348                         w_length = RBUF_SIZE;
1349                 } else {
1350                         return value;
1351                 }
1352         }
1353
1354         spin_lock (&dev->lock);
1355         dev->setup_abort = 0;
1356         if (dev->state == STATE_DEV_UNCONNECTED) {
1357                 if (gadget_is_dualspeed(gadget)
1358                                 && gadget->speed == USB_SPEED_HIGH
1359                                 && dev->hs_config == NULL) {
1360                         spin_unlock(&dev->lock);
1361                         ERROR (dev, "no high speed config??\n");
1362                         return -EINVAL;
1363                 }
1364
1365                 dev->state = STATE_DEV_CONNECTED;
1366
1367                 INFO (dev, "connected\n");
1368                 event = next_event (dev, GADGETFS_CONNECT);
1369                 event->u.speed = gadget->speed;
1370                 ep0_readable (dev);
1371
1372         /* host may have given up waiting for response.  we can miss control
1373          * requests handled lower down (device/endpoint status and features);
1374          * then ep0_{read,write} will report the wrong status. controller
1375          * driver will have aborted pending i/o.
1376          */
1377         } else if (dev->state == STATE_DEV_SETUP)
1378                 dev->setup_abort = 1;
1379
1380         req->buf = dev->rbuf;
1381         req->context = NULL;
1382         switch (ctrl->bRequest) {
1383
1384         case USB_REQ_GET_DESCRIPTOR:
1385                 if (ctrl->bRequestType != USB_DIR_IN)
1386                         goto unrecognized;
1387                 switch (w_value >> 8) {
1388
1389                 case USB_DT_DEVICE:
1390                         value = min (w_length, (u16) sizeof *dev->dev);
1391                         dev->dev->bMaxPacketSize0 = dev->gadget->ep0->maxpacket;
1392                         req->buf = dev->dev;
1393                         break;
1394                 case USB_DT_DEVICE_QUALIFIER:
1395                         if (!dev->hs_config)
1396                                 break;
1397                         value = min (w_length, (u16)
1398                                 sizeof (struct usb_qualifier_descriptor));
1399                         make_qualifier (dev);
1400                         break;
1401                 case USB_DT_OTHER_SPEED_CONFIG:
1402                         // FALLTHROUGH
1403                 case USB_DT_CONFIG:
1404                         value = config_buf (dev,
1405                                         w_value >> 8,
1406                                         w_value & 0xff);
1407                         if (value >= 0)
1408                                 value = min (w_length, (u16) value);
1409                         break;
1410                 case USB_DT_STRING:
1411                         goto unrecognized;
1412
1413                 default:                // all others are errors
1414                         break;
1415                 }
1416                 break;
1417
1418         /* currently one config, two speeds */
1419         case USB_REQ_SET_CONFIGURATION:
1420                 if (ctrl->bRequestType != 0)
1421                         goto unrecognized;
1422                 if (0 == (u8) w_value) {
1423                         value = 0;
1424                         dev->current_config = 0;
1425                         usb_gadget_vbus_draw(gadget, 8 /* mA */ );
1426                         // user mode expected to disable endpoints
1427                 } else {
1428                         u8      config, power;
1429
1430                         if (gadget_is_dualspeed(gadget)
1431                                         && gadget->speed == USB_SPEED_HIGH) {
1432                                 config = dev->hs_config->bConfigurationValue;
1433                                 power = dev->hs_config->bMaxPower;
1434                         } else {
1435                                 config = dev->config->bConfigurationValue;
1436                                 power = dev->config->bMaxPower;
1437                         }
1438
1439                         if (config == (u8) w_value) {
1440                                 value = 0;
1441                                 dev->current_config = config;
1442                                 usb_gadget_vbus_draw(gadget, 2 * power);
1443                         }
1444                 }
1445
1446                 /* report SET_CONFIGURATION like any other control request,
1447                  * except that usermode may not stall this.  the next
1448                  * request mustn't be allowed start until this finishes:
1449                  * endpoints and threads set up, etc.
1450                  *
1451                  * NOTE:  older PXA hardware (before PXA 255: without UDCCFR)
1452                  * has bad/racey automagic that prevents synchronizing here.
1453                  * even kernel mode drivers often miss them.
1454                  */
1455                 if (value == 0) {
1456                         INFO (dev, "configuration #%d\n", dev->current_config);
1457                         usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
1458                         if (dev->usermode_setup) {
1459                                 dev->setup_can_stall = 0;
1460                                 goto delegate;
1461                         }
1462                 }
1463                 break;
1464
1465 #ifndef CONFIG_USB_PXA25X
1466         /* PXA automagically handles this request too */
1467         case USB_REQ_GET_CONFIGURATION:
1468                 if (ctrl->bRequestType != 0x80)
1469                         goto unrecognized;
1470                 *(u8 *)req->buf = dev->current_config;
1471                 value = min (w_length, (u16) 1);
1472                 break;
1473 #endif
1474
1475         default:
1476 unrecognized:
1477                 VDEBUG (dev, "%s req%02x.%02x v%04x i%04x l%d\n",
1478                         dev->usermode_setup ? "delegate" : "fail",
1479                         ctrl->bRequestType, ctrl->bRequest,
1480                         w_value, le16_to_cpu(ctrl->wIndex), w_length);
1481
1482                 /* if there's an ep0 reader, don't stall */
1483                 if (dev->usermode_setup) {
1484                         dev->setup_can_stall = 1;
1485 delegate:
1486                         dev->setup_in = (ctrl->bRequestType & USB_DIR_IN)
1487                                                 ? 1 : 0;
1488                         dev->setup_wLength = w_length;
1489                         dev->setup_out_ready = 0;
1490                         dev->setup_out_error = 0;
1491                         value = 0;
1492
1493                         /* read DATA stage for OUT right away */
1494                         if (unlikely (!dev->setup_in && w_length)) {
1495                                 value = setup_req (gadget->ep0, dev->req,
1496                                                         w_length);
1497                                 if (value < 0)
1498                                         break;
1499
1500                                 ++dev->udc_usage;
1501                                 spin_unlock (&dev->lock);
1502                                 value = usb_ep_queue (gadget->ep0, dev->req,
1503                                                         GFP_KERNEL);
1504                                 spin_lock (&dev->lock);
1505                                 --dev->udc_usage;
1506                                 if (value < 0) {
1507                                         clean_req (gadget->ep0, dev->req);
1508                                         break;
1509                                 }
1510
1511                                 /* we can't currently stall these */
1512                                 dev->setup_can_stall = 0;
1513                         }
1514
1515                         /* state changes when reader collects event */
1516                         event = next_event (dev, GADGETFS_SETUP);
1517                         event->u.setup = *ctrl;
1518                         ep0_readable (dev);
1519                         spin_unlock (&dev->lock);
1520                         return 0;
1521                 }
1522         }
1523
1524         /* proceed with data transfer and status phases? */
1525         if (value >= 0 && dev->state != STATE_DEV_SETUP) {
1526                 req->length = value;
1527                 req->zero = value < w_length;
1528
1529                 ++dev->udc_usage;
1530                 spin_unlock (&dev->lock);
1531                 value = usb_ep_queue (gadget->ep0, req, GFP_KERNEL);
1532                 spin_lock(&dev->lock);
1533                 --dev->udc_usage;
1534                 spin_unlock(&dev->lock);
1535                 if (value < 0) {
1536                         DBG (dev, "ep_queue --> %d\n", value);
1537                         req->status = 0;
1538                 }
1539                 return value;
1540         }
1541
1542         /* device stalls when value < 0 */
1543         spin_unlock (&dev->lock);
1544         return value;
1545 }
1546
1547 static void destroy_ep_files (struct dev_data *dev)
1548 {
1549         DBG (dev, "%s %d\n", __func__, dev->state);
1550
1551         /* dev->state must prevent interference */
1552         spin_lock_irq (&dev->lock);
1553         while (!list_empty(&dev->epfiles)) {
1554                 struct ep_data  *ep;
1555                 struct inode    *parent;
1556                 struct dentry   *dentry;
1557
1558                 /* break link to FS */
1559                 ep = list_first_entry (&dev->epfiles, struct ep_data, epfiles);
1560                 list_del_init (&ep->epfiles);
1561                 spin_unlock_irq (&dev->lock);
1562
1563                 dentry = ep->dentry;
1564                 ep->dentry = NULL;
1565                 parent = d_inode(dentry->d_parent);
1566
1567                 /* break link to controller */
1568                 mutex_lock(&ep->lock);
1569                 if (ep->state == STATE_EP_ENABLED)
1570                         (void) usb_ep_disable (ep->ep);
1571                 ep->state = STATE_EP_UNBOUND;
1572                 usb_ep_free_request (ep->ep, ep->req);
1573                 ep->ep = NULL;
1574                 mutex_unlock(&ep->lock);
1575
1576                 wake_up (&ep->wait);
1577                 put_ep (ep);
1578
1579                 /* break link to dcache */
1580                 inode_lock(parent);
1581                 d_delete (dentry);
1582                 dput (dentry);
1583                 inode_unlock(parent);
1584
1585                 spin_lock_irq (&dev->lock);
1586         }
1587         spin_unlock_irq (&dev->lock);
1588 }
1589
1590
1591 static struct dentry *
1592 gadgetfs_create_file (struct super_block *sb, char const *name,
1593                 void *data, const struct file_operations *fops);
1594
1595 static int activate_ep_files (struct dev_data *dev)
1596 {
1597         struct usb_ep   *ep;
1598         struct ep_data  *data;
1599
1600         gadget_for_each_ep (ep, dev->gadget) {
1601
1602                 data = kzalloc(sizeof(*data), GFP_KERNEL);
1603                 if (!data)
1604                         goto enomem0;
1605                 data->state = STATE_EP_DISABLED;
1606                 mutex_init(&data->lock);
1607                 init_waitqueue_head (&data->wait);
1608
1609                 strncpy (data->name, ep->name, sizeof (data->name) - 1);
1610                 atomic_set (&data->count, 1);
1611                 data->dev = dev;
1612                 get_dev (dev);
1613
1614                 data->ep = ep;
1615                 ep->driver_data = data;
1616
1617                 data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1618                 if (!data->req)
1619                         goto enomem1;
1620
1621                 data->dentry = gadgetfs_create_file (dev->sb, data->name,
1622                                 data, &ep_io_operations);
1623                 if (!data->dentry)
1624                         goto enomem2;
1625                 list_add_tail (&data->epfiles, &dev->epfiles);
1626         }
1627         return 0;
1628
1629 enomem2:
1630         usb_ep_free_request (ep, data->req);
1631 enomem1:
1632         put_dev (dev);
1633         kfree (data);
1634 enomem0:
1635         DBG (dev, "%s enomem\n", __func__);
1636         destroy_ep_files (dev);
1637         return -ENOMEM;
1638 }
1639
1640 static void
1641 gadgetfs_unbind (struct usb_gadget *gadget)
1642 {
1643         struct dev_data         *dev = get_gadget_data (gadget);
1644
1645         DBG (dev, "%s\n", __func__);
1646
1647         spin_lock_irq (&dev->lock);
1648         dev->state = STATE_DEV_UNBOUND;
1649         while (dev->udc_usage > 0) {
1650                 spin_unlock_irq(&dev->lock);
1651                 usleep_range(1000, 2000);
1652                 spin_lock_irq(&dev->lock);
1653         }
1654         spin_unlock_irq (&dev->lock);
1655
1656         destroy_ep_files (dev);
1657         gadget->ep0->driver_data = NULL;
1658         set_gadget_data (gadget, NULL);
1659
1660         /* we've already been disconnected ... no i/o is active */
1661         if (dev->req)
1662                 usb_ep_free_request (gadget->ep0, dev->req);
1663         DBG (dev, "%s done\n", __func__);
1664         put_dev (dev);
1665 }
1666
1667 static struct dev_data          *the_device;
1668
1669 static int gadgetfs_bind(struct usb_gadget *gadget,
1670                 struct usb_gadget_driver *driver)
1671 {
1672         struct dev_data         *dev = the_device;
1673
1674         if (!dev)
1675                 return -ESRCH;
1676         if (0 != strcmp (CHIP, gadget->name)) {
1677                 pr_err("%s expected %s controller not %s\n",
1678                         shortname, CHIP, gadget->name);
1679                 return -ENODEV;
1680         }
1681
1682         set_gadget_data (gadget, dev);
1683         dev->gadget = gadget;
1684         gadget->ep0->driver_data = dev;
1685
1686         /* preallocate control response and buffer */
1687         dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1688         if (!dev->req)
1689                 goto enomem;
1690         dev->req->context = NULL;
1691         dev->req->complete = epio_complete;
1692
1693         if (activate_ep_files (dev) < 0)
1694                 goto enomem;
1695
1696         INFO (dev, "bound to %s driver\n", gadget->name);
1697         spin_lock_irq(&dev->lock);
1698         dev->state = STATE_DEV_UNCONNECTED;
1699         spin_unlock_irq(&dev->lock);
1700         get_dev (dev);
1701         return 0;
1702
1703 enomem:
1704         gadgetfs_unbind (gadget);
1705         return -ENOMEM;
1706 }
1707
1708 static void
1709 gadgetfs_disconnect (struct usb_gadget *gadget)
1710 {
1711         struct dev_data         *dev = get_gadget_data (gadget);
1712         unsigned long           flags;
1713
1714         spin_lock_irqsave (&dev->lock, flags);
1715         if (dev->state == STATE_DEV_UNCONNECTED)
1716                 goto exit;
1717         dev->state = STATE_DEV_UNCONNECTED;
1718
1719         INFO (dev, "disconnected\n");
1720         next_event (dev, GADGETFS_DISCONNECT);
1721         ep0_readable (dev);
1722 exit:
1723         spin_unlock_irqrestore (&dev->lock, flags);
1724 }
1725
1726 static void
1727 gadgetfs_suspend (struct usb_gadget *gadget)
1728 {
1729         struct dev_data         *dev = get_gadget_data (gadget);
1730         unsigned long           flags;
1731
1732         INFO (dev, "suspended from state %d\n", dev->state);
1733         spin_lock_irqsave(&dev->lock, flags);
1734         switch (dev->state) {
1735         case STATE_DEV_SETUP:           // VERY odd... host died??
1736         case STATE_DEV_CONNECTED:
1737         case STATE_DEV_UNCONNECTED:
1738                 next_event (dev, GADGETFS_SUSPEND);
1739                 ep0_readable (dev);
1740                 /* FALLTHROUGH */
1741         default:
1742                 break;
1743         }
1744         spin_unlock_irqrestore(&dev->lock, flags);
1745 }
1746
1747 static struct usb_gadget_driver gadgetfs_driver = {
1748         .function       = (char *) driver_desc,
1749         .bind           = gadgetfs_bind,
1750         .unbind         = gadgetfs_unbind,
1751         .setup          = gadgetfs_setup,
1752         .reset          = gadgetfs_disconnect,
1753         .disconnect     = gadgetfs_disconnect,
1754         .suspend        = gadgetfs_suspend,
1755
1756         .driver = {
1757                 .name           = (char *) shortname,
1758         },
1759 };
1760
1761 /*----------------------------------------------------------------------*/
1762 /* DEVICE INITIALIZATION
1763  *
1764  *     fd = open ("/dev/gadget/$CHIP", O_RDWR)
1765  *     status = write (fd, descriptors, sizeof descriptors)
1766  *
1767  * That write establishes the device configuration, so the kernel can
1768  * bind to the controller ... guaranteeing it can handle enumeration
1769  * at all necessary speeds.  Descriptor order is:
1770  *
1771  * . message tag (u32, host order) ... for now, must be zero; it
1772  *      would change to support features like multi-config devices
1773  * . full/low speed config ... all wTotalLength bytes (with interface,
1774  *      class, altsetting, endpoint, and other descriptors)
1775  * . high speed config ... all descriptors, for high speed operation;
1776  *      this one's optional except for high-speed hardware
1777  * . device descriptor
1778  *
1779  * Endpoints are not yet enabled. Drivers must wait until device
1780  * configuration and interface altsetting changes create
1781  * the need to configure (or unconfigure) them.
1782  *
1783  * After initialization, the device stays active for as long as that
1784  * $CHIP file is open.  Events must then be read from that descriptor,
1785  * such as configuration notifications.
1786  */
1787
1788 static int is_valid_config(struct usb_config_descriptor *config,
1789                 unsigned int total)
1790 {
1791         return config->bDescriptorType == USB_DT_CONFIG
1792                 && config->bLength == USB_DT_CONFIG_SIZE
1793                 && total >= USB_DT_CONFIG_SIZE
1794                 && config->bConfigurationValue != 0
1795                 && (config->bmAttributes & USB_CONFIG_ATT_ONE) != 0
1796                 && (config->bmAttributes & USB_CONFIG_ATT_WAKEUP) == 0;
1797         /* FIXME if gadget->is_otg, _must_ include an otg descriptor */
1798         /* FIXME check lengths: walk to end */
1799 }
1800
1801 static ssize_t
1802 dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1803 {
1804         struct dev_data         *dev = fd->private_data;
1805         ssize_t                 value, length = len;
1806         unsigned                total;
1807         u32                     tag;
1808         char                    *kbuf;
1809
1810         spin_lock_irq(&dev->lock);
1811         if (dev->state > STATE_DEV_OPENED) {
1812                 value = ep0_write(fd, buf, len, ptr);
1813                 spin_unlock_irq(&dev->lock);
1814                 return value;
1815         }
1816         spin_unlock_irq(&dev->lock);
1817
1818         if ((len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4)) ||
1819             (len > PAGE_SIZE * 4))
1820                 return -EINVAL;
1821
1822         /* we might need to change message format someday */
1823         if (copy_from_user (&tag, buf, 4))
1824                 return -EFAULT;
1825         if (tag != 0)
1826                 return -EINVAL;
1827         buf += 4;
1828         length -= 4;
1829
1830         kbuf = memdup_user(buf, length);
1831         if (IS_ERR(kbuf))
1832                 return PTR_ERR(kbuf);
1833
1834         spin_lock_irq (&dev->lock);
1835         value = -EINVAL;
1836         if (dev->buf) {
1837                 spin_unlock_irq(&dev->lock);
1838                 kfree(kbuf);
1839                 return value;
1840         }
1841         dev->buf = kbuf;
1842
1843         /* full or low speed config */
1844         dev->config = (void *) kbuf;
1845         total = le16_to_cpu(dev->config->wTotalLength);
1846         if (!is_valid_config(dev->config, total) ||
1847                         total > length - USB_DT_DEVICE_SIZE)
1848                 goto fail;
1849         kbuf += total;
1850         length -= total;
1851
1852         /* optional high speed config */
1853         if (kbuf [1] == USB_DT_CONFIG) {
1854                 dev->hs_config = (void *) kbuf;
1855                 total = le16_to_cpu(dev->hs_config->wTotalLength);
1856                 if (!is_valid_config(dev->hs_config, total) ||
1857                                 total > length - USB_DT_DEVICE_SIZE)
1858                         goto fail;
1859                 kbuf += total;
1860                 length -= total;
1861         } else {
1862                 dev->hs_config = NULL;
1863         }
1864
1865         /* could support multiple configs, using another encoding! */
1866
1867         /* device descriptor (tweaked for paranoia) */
1868         if (length != USB_DT_DEVICE_SIZE)
1869                 goto fail;
1870         dev->dev = (void *)kbuf;
1871         if (dev->dev->bLength != USB_DT_DEVICE_SIZE
1872                         || dev->dev->bDescriptorType != USB_DT_DEVICE
1873                         || dev->dev->bNumConfigurations != 1)
1874                 goto fail;
1875         dev->dev->bNumConfigurations = 1;
1876         dev->dev->bcdUSB = cpu_to_le16 (0x0200);
1877
1878         /* triggers gadgetfs_bind(); then we can enumerate. */
1879         spin_unlock_irq (&dev->lock);
1880         if (dev->hs_config)
1881                 gadgetfs_driver.max_speed = USB_SPEED_HIGH;
1882         else
1883                 gadgetfs_driver.max_speed = USB_SPEED_FULL;
1884
1885         value = usb_gadget_probe_driver(&gadgetfs_driver);
1886         if (value != 0) {
1887                 spin_lock_irq(&dev->lock);
1888                 goto fail;
1889         } else {
1890                 /* at this point "good" hardware has for the first time
1891                  * let the USB the host see us.  alternatively, if users
1892                  * unplug/replug that will clear all the error state.
1893                  *
1894                  * note:  everything running before here was guaranteed
1895                  * to choke driver model style diagnostics.  from here
1896                  * on, they can work ... except in cleanup paths that
1897                  * kick in after the ep0 descriptor is closed.
1898                  */
1899                 value = len;
1900                 dev->gadget_registered = true;
1901         }
1902         return value;
1903
1904 fail:
1905         dev->config = NULL;
1906         dev->hs_config = NULL;
1907         dev->dev = NULL;
1908         spin_unlock_irq (&dev->lock);
1909         pr_debug ("%s: %s fail %Zd, %p\n", shortname, __func__, value, dev);
1910         kfree (dev->buf);
1911         dev->buf = NULL;
1912         return value;
1913 }
1914
1915 static int
1916 dev_open (struct inode *inode, struct file *fd)
1917 {
1918         struct dev_data         *dev = inode->i_private;
1919         int                     value = -EBUSY;
1920
1921         spin_lock_irq(&dev->lock);
1922         if (dev->state == STATE_DEV_DISABLED) {
1923                 dev->ev_next = 0;
1924                 dev->state = STATE_DEV_OPENED;
1925                 fd->private_data = dev;
1926                 get_dev (dev);
1927                 value = 0;
1928         }
1929         spin_unlock_irq(&dev->lock);
1930         return value;
1931 }
1932
1933 static const struct file_operations ep0_operations = {
1934         .llseek =       no_llseek,
1935
1936         .open =         dev_open,
1937         .read =         ep0_read,
1938         .write =        dev_config,
1939         .fasync =       ep0_fasync,
1940         .poll =         ep0_poll,
1941         .unlocked_ioctl = dev_ioctl,
1942         .release =      dev_release,
1943 };
1944
1945 /*----------------------------------------------------------------------*/
1946
1947 /* FILESYSTEM AND SUPERBLOCK OPERATIONS
1948  *
1949  * Mounting the filesystem creates a controller file, used first for
1950  * device configuration then later for event monitoring.
1951  */
1952
1953
1954 /* FIXME PAM etc could set this security policy without mount options
1955  * if epfiles inherited ownership and permissons from ep0 ...
1956  */
1957
1958 static unsigned default_uid;
1959 static unsigned default_gid;
1960 static unsigned default_perm = S_IRUSR | S_IWUSR;
1961
1962 module_param (default_uid, uint, 0644);
1963 module_param (default_gid, uint, 0644);
1964 module_param (default_perm, uint, 0644);
1965
1966
1967 static struct inode *
1968 gadgetfs_make_inode (struct super_block *sb,
1969                 void *data, const struct file_operations *fops,
1970                 int mode)
1971 {
1972         struct inode *inode = new_inode (sb);
1973
1974         if (inode) {
1975                 inode->i_ino = get_next_ino();
1976                 inode->i_mode = mode;
1977                 inode->i_uid = make_kuid(&init_user_ns, default_uid);
1978                 inode->i_gid = make_kgid(&init_user_ns, default_gid);
1979                 inode->i_atime = inode->i_mtime = inode->i_ctime
1980                                 = current_time(inode);
1981                 inode->i_private = data;
1982                 inode->i_fop = fops;
1983         }
1984         return inode;
1985 }
1986
1987 /* creates in fs root directory, so non-renamable and non-linkable.
1988  * so inode and dentry are paired, until device reconfig.
1989  */
1990 static struct dentry *
1991 gadgetfs_create_file (struct super_block *sb, char const *name,
1992                 void *data, const struct file_operations *fops)
1993 {
1994         struct dentry   *dentry;
1995         struct inode    *inode;
1996
1997         dentry = d_alloc_name(sb->s_root, name);
1998         if (!dentry)
1999                 return NULL;
2000
2001         inode = gadgetfs_make_inode (sb, data, fops,
2002                         S_IFREG | (default_perm & S_IRWXUGO));
2003         if (!inode) {
2004                 dput(dentry);
2005                 return NULL;
2006         }
2007         d_add (dentry, inode);
2008         return dentry;
2009 }
2010
2011 static const struct super_operations gadget_fs_operations = {
2012         .statfs =       simple_statfs,
2013         .drop_inode =   generic_delete_inode,
2014 };
2015
2016 static int
2017 gadgetfs_fill_super (struct super_block *sb, void *opts, int silent)
2018 {
2019         struct inode    *inode;
2020         struct dev_data *dev;
2021
2022         if (the_device)
2023                 return -ESRCH;
2024
2025         CHIP = usb_get_gadget_udc_name();
2026         if (!CHIP)
2027                 return -ENODEV;
2028
2029         /* superblock */
2030         sb->s_blocksize = PAGE_SIZE;
2031         sb->s_blocksize_bits = PAGE_SHIFT;
2032         sb->s_magic = GADGETFS_MAGIC;
2033         sb->s_op = &gadget_fs_operations;
2034         sb->s_time_gran = 1;
2035
2036         /* root inode */
2037         inode = gadgetfs_make_inode (sb,
2038                         NULL, &simple_dir_operations,
2039                         S_IFDIR | S_IRUGO | S_IXUGO);
2040         if (!inode)
2041                 goto Enomem;
2042         inode->i_op = &simple_dir_inode_operations;
2043         if (!(sb->s_root = d_make_root (inode)))
2044                 goto Enomem;
2045
2046         /* the ep0 file is named after the controller we expect;
2047          * user mode code can use it for sanity checks, like we do.
2048          */
2049         dev = dev_new ();
2050         if (!dev)
2051                 goto Enomem;
2052
2053         dev->sb = sb;
2054         dev->dentry = gadgetfs_create_file(sb, CHIP, dev, &ep0_operations);
2055         if (!dev->dentry) {
2056                 put_dev(dev);
2057                 goto Enomem;
2058         }
2059
2060         /* other endpoint files are available after hardware setup,
2061          * from binding to a controller.
2062          */
2063         the_device = dev;
2064         return 0;
2065
2066 Enomem:
2067         kfree(CHIP);
2068         CHIP = NULL;
2069
2070         return -ENOMEM;
2071 }
2072
2073 /* "mount -t gadgetfs path /dev/gadget" ends up here */
2074 static struct dentry *
2075 gadgetfs_mount (struct file_system_type *t, int flags,
2076                 const char *path, void *opts)
2077 {
2078         return mount_single (t, flags, opts, gadgetfs_fill_super);
2079 }
2080
2081 static void
2082 gadgetfs_kill_sb (struct super_block *sb)
2083 {
2084         kill_litter_super (sb);
2085         if (the_device) {
2086                 put_dev (the_device);
2087                 the_device = NULL;
2088         }
2089         kfree(CHIP);
2090         CHIP = NULL;
2091 }
2092
2093 /*----------------------------------------------------------------------*/
2094
2095 static struct file_system_type gadgetfs_type = {
2096         .owner          = THIS_MODULE,
2097         .name           = shortname,
2098         .mount          = gadgetfs_mount,
2099         .kill_sb        = gadgetfs_kill_sb,
2100 };
2101 MODULE_ALIAS_FS("gadgetfs");
2102
2103 /*----------------------------------------------------------------------*/
2104
2105 static int __init init (void)
2106 {
2107         int status;
2108
2109         status = register_filesystem (&gadgetfs_type);
2110         if (status == 0)
2111                 pr_info ("%s: %s, version " DRIVER_VERSION "\n",
2112                         shortname, driver_desc);
2113         return status;
2114 }
2115 module_init (init);
2116
2117 static void __exit cleanup (void)
2118 {
2119         pr_debug ("unregister %s\n", shortname);
2120         unregister_filesystem (&gadgetfs_type);
2121 }
2122 module_exit (cleanup);
2123