]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/usb/gadget/f_fs.c
make vfree() safe to call from interrupt contexts
[karo-tx-linux.git] / drivers / usb / gadget / f_fs.c
1 /*
2  * f_fs.c -- user mode file system API for USB composite function controllers
3  *
4  * Copyright (C) 2010 Samsung Electronics
5  * Author: Michal Nazarewicz <mina86@mina86.com>
6  *
7  * Based on inode.c (GadgetFS) which was:
8  * Copyright (C) 2003-2004 David Brownell
9  * Copyright (C) 2003 Agilent Technologies
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  */
16
17
18 /* #define DEBUG */
19 /* #define VERBOSE_DEBUG */
20
21 #include <linux/blkdev.h>
22 #include <linux/pagemap.h>
23 #include <linux/export.h>
24 #include <linux/hid.h>
25 #include <asm/unaligned.h>
26
27 #include <linux/usb/composite.h>
28 #include <linux/usb/functionfs.h>
29
30
31 #define FUNCTIONFS_MAGIC        0xa647361 /* Chosen by a honest dice roll ;) */
32
33
34 /* Debugging ****************************************************************/
35
36 #ifdef VERBOSE_DEBUG
37 #ifndef pr_vdebug
38 #  define pr_vdebug pr_debug
39 #endif /* pr_vdebug */
40 #  define ffs_dump_mem(prefix, ptr, len) \
41         print_hex_dump_bytes(pr_fmt(prefix ": "), DUMP_PREFIX_NONE, ptr, len)
42 #else
43 #ifndef pr_vdebug
44 #  define pr_vdebug(...)                 do { } while (0)
45 #endif /* pr_vdebug */
46 #  define ffs_dump_mem(prefix, ptr, len) do { } while (0)
47 #endif /* VERBOSE_DEBUG */
48
49 #define ENTER()    pr_vdebug("%s()\n", __func__)
50
51
52 /* The data structure and setup file ****************************************/
53
54 enum ffs_state {
55         /*
56          * Waiting for descriptors and strings.
57          *
58          * In this state no open(2), read(2) or write(2) on epfiles
59          * may succeed (which should not be the problem as there
60          * should be no such files opened in the first place).
61          */
62         FFS_READ_DESCRIPTORS,
63         FFS_READ_STRINGS,
64
65         /*
66          * We've got descriptors and strings.  We are or have called
67          * functionfs_ready_callback().  functionfs_bind() may have
68          * been called but we don't know.
69          *
70          * This is the only state in which operations on epfiles may
71          * succeed.
72          */
73         FFS_ACTIVE,
74
75         /*
76          * All endpoints have been closed.  This state is also set if
77          * we encounter an unrecoverable error.  The only
78          * unrecoverable error is situation when after reading strings
79          * from user space we fail to initialise epfiles or
80          * functionfs_ready_callback() returns with error (<0).
81          *
82          * In this state no open(2), read(2) or write(2) (both on ep0
83          * as well as epfile) may succeed (at this point epfiles are
84          * unlinked and all closed so this is not a problem; ep0 is
85          * also closed but ep0 file exists and so open(2) on ep0 must
86          * fail).
87          */
88         FFS_CLOSING
89 };
90
91
92 enum ffs_setup_state {
93         /* There is no setup request pending. */
94         FFS_NO_SETUP,
95         /*
96          * User has read events and there was a setup request event
97          * there.  The next read/write on ep0 will handle the
98          * request.
99          */
100         FFS_SETUP_PENDING,
101         /*
102          * There was event pending but before user space handled it
103          * some other event was introduced which canceled existing
104          * setup.  If this state is set read/write on ep0 return
105          * -EIDRM.  This state is only set when adding event.
106          */
107         FFS_SETUP_CANCELED
108 };
109
110
111
112 struct ffs_epfile;
113 struct ffs_function;
114
115 struct ffs_data {
116         struct usb_gadget               *gadget;
117
118         /*
119          * Protect access read/write operations, only one read/write
120          * at a time.  As a consequence protects ep0req and company.
121          * While setup request is being processed (queued) this is
122          * held.
123          */
124         struct mutex                    mutex;
125
126         /*
127          * Protect access to endpoint related structures (basically
128          * usb_ep_queue(), usb_ep_dequeue(), etc. calls) except for
129          * endpoint zero.
130          */
131         spinlock_t                      eps_lock;
132
133         /*
134          * XXX REVISIT do we need our own request? Since we are not
135          * handling setup requests immediately user space may be so
136          * slow that another setup will be sent to the gadget but this
137          * time not to us but another function and then there could be
138          * a race.  Is that the case? Or maybe we can use cdev->req
139          * after all, maybe we just need some spinlock for that?
140          */
141         struct usb_request              *ep0req;                /* P: mutex */
142         struct completion               ep0req_completion;      /* P: mutex */
143         int                             ep0req_status;          /* P: mutex */
144
145         /* reference counter */
146         atomic_t                        ref;
147         /* how many files are opened (EP0 and others) */
148         atomic_t                        opened;
149
150         /* EP0 state */
151         enum ffs_state                  state;
152
153         /*
154          * Possible transitions:
155          * + FFS_NO_SETUP       -> FFS_SETUP_PENDING  -- P: ev.waitq.lock
156          *               happens only in ep0 read which is P: mutex
157          * + FFS_SETUP_PENDING  -> FFS_NO_SETUP       -- P: ev.waitq.lock
158          *               happens only in ep0 i/o  which is P: mutex
159          * + FFS_SETUP_PENDING  -> FFS_SETUP_CANCELED -- P: ev.waitq.lock
160          * + FFS_SETUP_CANCELED -> FFS_NO_SETUP       -- cmpxchg
161          */
162         enum ffs_setup_state            setup_state;
163
164 #define FFS_SETUP_STATE(ffs)                                    \
165         ((enum ffs_setup_state)cmpxchg(&(ffs)->setup_state,     \
166                                        FFS_SETUP_CANCELED, FFS_NO_SETUP))
167
168         /* Events & such. */
169         struct {
170                 u8                              types[4];
171                 unsigned short                  count;
172                 /* XXX REVISIT need to update it in some places, or do we? */
173                 unsigned short                  can_stall;
174                 struct usb_ctrlrequest          setup;
175
176                 wait_queue_head_t               waitq;
177         } ev; /* the whole structure, P: ev.waitq.lock */
178
179         /* Flags */
180         unsigned long                   flags;
181 #define FFS_FL_CALL_CLOSED_CALLBACK 0
182 #define FFS_FL_BOUND                1
183
184         /* Active function */
185         struct ffs_function             *func;
186
187         /*
188          * Device name, write once when file system is mounted.
189          * Intended for user to read if she wants.
190          */
191         const char                      *dev_name;
192         /* Private data for our user (ie. gadget).  Managed by user. */
193         void                            *private_data;
194
195         /* filled by __ffs_data_got_descs() */
196         /*
197          * Real descriptors are 16 bytes after raw_descs (so you need
198          * to skip 16 bytes (ie. ffs->raw_descs + 16) to get to the
199          * first full speed descriptor).  raw_descs_length and
200          * raw_fs_descs_length do not have those 16 bytes added.
201          */
202         const void                      *raw_descs;
203         unsigned                        raw_descs_length;
204         unsigned                        raw_fs_descs_length;
205         unsigned                        fs_descs_count;
206         unsigned                        hs_descs_count;
207
208         unsigned short                  strings_count;
209         unsigned short                  interfaces_count;
210         unsigned short                  eps_count;
211         unsigned short                  _pad1;
212
213         /* filled by __ffs_data_got_strings() */
214         /* ids in stringtabs are set in functionfs_bind() */
215         const void                      *raw_strings;
216         struct usb_gadget_strings       **stringtabs;
217
218         /*
219          * File system's super block, write once when file system is
220          * mounted.
221          */
222         struct super_block              *sb;
223
224         /* File permissions, written once when fs is mounted */
225         struct ffs_file_perms {
226                 umode_t                         mode;
227                 kuid_t                          uid;
228                 kgid_t                          gid;
229         }                               file_perms;
230
231         /*
232          * The endpoint files, filled by ffs_epfiles_create(),
233          * destroyed by ffs_epfiles_destroy().
234          */
235         struct ffs_epfile               *epfiles;
236 };
237
238 /* Reference counter handling */
239 static void ffs_data_get(struct ffs_data *ffs);
240 static void ffs_data_put(struct ffs_data *ffs);
241 /* Creates new ffs_data object. */
242 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
243
244 /* Opened counter handling. */
245 static void ffs_data_opened(struct ffs_data *ffs);
246 static void ffs_data_closed(struct ffs_data *ffs);
247
248 /* Called with ffs->mutex held; take over ownership of data. */
249 static int __must_check
250 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
251 static int __must_check
252 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
253
254
255 /* The function structure ***************************************************/
256
257 struct ffs_ep;
258
259 struct ffs_function {
260         struct usb_configuration        *conf;
261         struct usb_gadget               *gadget;
262         struct ffs_data                 *ffs;
263
264         struct ffs_ep                   *eps;
265         u8                              eps_revmap[16];
266         short                           *interfaces_nums;
267
268         struct usb_function             function;
269 };
270
271
272 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
273 {
274         return container_of(f, struct ffs_function, function);
275 }
276
277 static void ffs_func_free(struct ffs_function *func);
278
279 static void ffs_func_eps_disable(struct ffs_function *func);
280 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
281
282 static int ffs_func_bind(struct usb_configuration *,
283                          struct usb_function *);
284 static void ffs_func_unbind(struct usb_configuration *,
285                             struct usb_function *);
286 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
287 static void ffs_func_disable(struct usb_function *);
288 static int ffs_func_setup(struct usb_function *,
289                           const struct usb_ctrlrequest *);
290 static void ffs_func_suspend(struct usb_function *);
291 static void ffs_func_resume(struct usb_function *);
292
293
294 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
295 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
296
297
298 /* The endpoints structures *************************************************/
299
300 struct ffs_ep {
301         struct usb_ep                   *ep;    /* P: ffs->eps_lock */
302         struct usb_request              *req;   /* P: epfile->mutex */
303
304         /* [0]: full speed, [1]: high speed */
305         struct usb_endpoint_descriptor  *descs[2];
306
307         u8                              num;
308
309         int                             status; /* P: epfile->mutex */
310 };
311
312 struct ffs_epfile {
313         /* Protects ep->ep and ep->req. */
314         struct mutex                    mutex;
315         wait_queue_head_t               wait;
316
317         struct ffs_data                 *ffs;
318         struct ffs_ep                   *ep;    /* P: ffs->eps_lock */
319
320         struct dentry                   *dentry;
321
322         char                            name[5];
323
324         unsigned char                   in;     /* P: ffs->eps_lock */
325         unsigned char                   isoc;   /* P: ffs->eps_lock */
326
327         unsigned char                   _pad;
328 };
329
330 static int  __must_check ffs_epfiles_create(struct ffs_data *ffs);
331 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
332
333 static struct inode *__must_check
334 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
335                    const struct file_operations *fops,
336                    struct dentry **dentry_p);
337
338
339 /* Misc helper functions ****************************************************/
340
341 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
342         __attribute__((warn_unused_result, nonnull));
343 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
344         __attribute__((warn_unused_result, nonnull));
345
346
347 /* Control file aka ep0 *****************************************************/
348
349 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
350 {
351         struct ffs_data *ffs = req->context;
352
353         complete_all(&ffs->ep0req_completion);
354 }
355
356 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
357 {
358         struct usb_request *req = ffs->ep0req;
359         int ret;
360
361         req->zero     = len < le16_to_cpu(ffs->ev.setup.wLength);
362
363         spin_unlock_irq(&ffs->ev.waitq.lock);
364
365         req->buf      = data;
366         req->length   = len;
367
368         /*
369          * UDC layer requires to provide a buffer even for ZLP, but should
370          * not use it at all. Let's provide some poisoned pointer to catch
371          * possible bug in the driver.
372          */
373         if (req->buf == NULL)
374                 req->buf = (void *)0xDEADBABE;
375
376         INIT_COMPLETION(ffs->ep0req_completion);
377
378         ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
379         if (unlikely(ret < 0))
380                 return ret;
381
382         ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
383         if (unlikely(ret)) {
384                 usb_ep_dequeue(ffs->gadget->ep0, req);
385                 return -EINTR;
386         }
387
388         ffs->setup_state = FFS_NO_SETUP;
389         return ffs->ep0req_status;
390 }
391
392 static int __ffs_ep0_stall(struct ffs_data *ffs)
393 {
394         if (ffs->ev.can_stall) {
395                 pr_vdebug("ep0 stall\n");
396                 usb_ep_set_halt(ffs->gadget->ep0);
397                 ffs->setup_state = FFS_NO_SETUP;
398                 return -EL2HLT;
399         } else {
400                 pr_debug("bogus ep0 stall!\n");
401                 return -ESRCH;
402         }
403 }
404
405 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
406                              size_t len, loff_t *ptr)
407 {
408         struct ffs_data *ffs = file->private_data;
409         ssize_t ret;
410         char *data;
411
412         ENTER();
413
414         /* Fast check if setup was canceled */
415         if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
416                 return -EIDRM;
417
418         /* Acquire mutex */
419         ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
420         if (unlikely(ret < 0))
421                 return ret;
422
423         /* Check state */
424         switch (ffs->state) {
425         case FFS_READ_DESCRIPTORS:
426         case FFS_READ_STRINGS:
427                 /* Copy data */
428                 if (unlikely(len < 16)) {
429                         ret = -EINVAL;
430                         break;
431                 }
432
433                 data = ffs_prepare_buffer(buf, len);
434                 if (IS_ERR(data)) {
435                         ret = PTR_ERR(data);
436                         break;
437                 }
438
439                 /* Handle data */
440                 if (ffs->state == FFS_READ_DESCRIPTORS) {
441                         pr_info("read descriptors\n");
442                         ret = __ffs_data_got_descs(ffs, data, len);
443                         if (unlikely(ret < 0))
444                                 break;
445
446                         ffs->state = FFS_READ_STRINGS;
447                         ret = len;
448                 } else {
449                         pr_info("read strings\n");
450                         ret = __ffs_data_got_strings(ffs, data, len);
451                         if (unlikely(ret < 0))
452                                 break;
453
454                         ret = ffs_epfiles_create(ffs);
455                         if (unlikely(ret)) {
456                                 ffs->state = FFS_CLOSING;
457                                 break;
458                         }
459
460                         ffs->state = FFS_ACTIVE;
461                         mutex_unlock(&ffs->mutex);
462
463                         ret = functionfs_ready_callback(ffs);
464                         if (unlikely(ret < 0)) {
465                                 ffs->state = FFS_CLOSING;
466                                 return ret;
467                         }
468
469                         set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
470                         return len;
471                 }
472                 break;
473
474         case FFS_ACTIVE:
475                 data = NULL;
476                 /*
477                  * We're called from user space, we can use _irq
478                  * rather then _irqsave
479                  */
480                 spin_lock_irq(&ffs->ev.waitq.lock);
481                 switch (FFS_SETUP_STATE(ffs)) {
482                 case FFS_SETUP_CANCELED:
483                         ret = -EIDRM;
484                         goto done_spin;
485
486                 case FFS_NO_SETUP:
487                         ret = -ESRCH;
488                         goto done_spin;
489
490                 case FFS_SETUP_PENDING:
491                         break;
492                 }
493
494                 /* FFS_SETUP_PENDING */
495                 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
496                         spin_unlock_irq(&ffs->ev.waitq.lock);
497                         ret = __ffs_ep0_stall(ffs);
498                         break;
499                 }
500
501                 /* FFS_SETUP_PENDING and not stall */
502                 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
503
504                 spin_unlock_irq(&ffs->ev.waitq.lock);
505
506                 data = ffs_prepare_buffer(buf, len);
507                 if (IS_ERR(data)) {
508                         ret = PTR_ERR(data);
509                         break;
510                 }
511
512                 spin_lock_irq(&ffs->ev.waitq.lock);
513
514                 /*
515                  * We are guaranteed to be still in FFS_ACTIVE state
516                  * but the state of setup could have changed from
517                  * FFS_SETUP_PENDING to FFS_SETUP_CANCELED so we need
518                  * to check for that.  If that happened we copied data
519                  * from user space in vain but it's unlikely.
520                  *
521                  * For sure we are not in FFS_NO_SETUP since this is
522                  * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
523                  * transition can be performed and it's protected by
524                  * mutex.
525                  */
526                 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
527                         ret = -EIDRM;
528 done_spin:
529                         spin_unlock_irq(&ffs->ev.waitq.lock);
530                 } else {
531                         /* unlocks spinlock */
532                         ret = __ffs_ep0_queue_wait(ffs, data, len);
533                 }
534                 kfree(data);
535                 break;
536
537         default:
538                 ret = -EBADFD;
539                 break;
540         }
541
542         mutex_unlock(&ffs->mutex);
543         return ret;
544 }
545
546 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
547                                      size_t n)
548 {
549         /*
550          * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
551          * to release them.
552          */
553         struct usb_functionfs_event events[n];
554         unsigned i = 0;
555
556         memset(events, 0, sizeof events);
557
558         do {
559                 events[i].type = ffs->ev.types[i];
560                 if (events[i].type == FUNCTIONFS_SETUP) {
561                         events[i].u.setup = ffs->ev.setup;
562                         ffs->setup_state = FFS_SETUP_PENDING;
563                 }
564         } while (++i < n);
565
566         if (n < ffs->ev.count) {
567                 ffs->ev.count -= n;
568                 memmove(ffs->ev.types, ffs->ev.types + n,
569                         ffs->ev.count * sizeof *ffs->ev.types);
570         } else {
571                 ffs->ev.count = 0;
572         }
573
574         spin_unlock_irq(&ffs->ev.waitq.lock);
575         mutex_unlock(&ffs->mutex);
576
577         return unlikely(__copy_to_user(buf, events, sizeof events))
578                 ? -EFAULT : sizeof events;
579 }
580
581 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
582                             size_t len, loff_t *ptr)
583 {
584         struct ffs_data *ffs = file->private_data;
585         char *data = NULL;
586         size_t n;
587         int ret;
588
589         ENTER();
590
591         /* Fast check if setup was canceled */
592         if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
593                 return -EIDRM;
594
595         /* Acquire mutex */
596         ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
597         if (unlikely(ret < 0))
598                 return ret;
599
600         /* Check state */
601         if (ffs->state != FFS_ACTIVE) {
602                 ret = -EBADFD;
603                 goto done_mutex;
604         }
605
606         /*
607          * We're called from user space, we can use _irq rather then
608          * _irqsave
609          */
610         spin_lock_irq(&ffs->ev.waitq.lock);
611
612         switch (FFS_SETUP_STATE(ffs)) {
613         case FFS_SETUP_CANCELED:
614                 ret = -EIDRM;
615                 break;
616
617         case FFS_NO_SETUP:
618                 n = len / sizeof(struct usb_functionfs_event);
619                 if (unlikely(!n)) {
620                         ret = -EINVAL;
621                         break;
622                 }
623
624                 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
625                         ret = -EAGAIN;
626                         break;
627                 }
628
629                 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
630                                                         ffs->ev.count)) {
631                         ret = -EINTR;
632                         break;
633                 }
634
635                 return __ffs_ep0_read_events(ffs, buf,
636                                              min(n, (size_t)ffs->ev.count));
637
638         case FFS_SETUP_PENDING:
639                 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
640                         spin_unlock_irq(&ffs->ev.waitq.lock);
641                         ret = __ffs_ep0_stall(ffs);
642                         goto done_mutex;
643                 }
644
645                 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
646
647                 spin_unlock_irq(&ffs->ev.waitq.lock);
648
649                 if (likely(len)) {
650                         data = kmalloc(len, GFP_KERNEL);
651                         if (unlikely(!data)) {
652                                 ret = -ENOMEM;
653                                 goto done_mutex;
654                         }
655                 }
656
657                 spin_lock_irq(&ffs->ev.waitq.lock);
658
659                 /* See ffs_ep0_write() */
660                 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
661                         ret = -EIDRM;
662                         break;
663                 }
664
665                 /* unlocks spinlock */
666                 ret = __ffs_ep0_queue_wait(ffs, data, len);
667                 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
668                         ret = -EFAULT;
669                 goto done_mutex;
670
671         default:
672                 ret = -EBADFD;
673                 break;
674         }
675
676         spin_unlock_irq(&ffs->ev.waitq.lock);
677 done_mutex:
678         mutex_unlock(&ffs->mutex);
679         kfree(data);
680         return ret;
681 }
682
683 static int ffs_ep0_open(struct inode *inode, struct file *file)
684 {
685         struct ffs_data *ffs = inode->i_private;
686
687         ENTER();
688
689         if (unlikely(ffs->state == FFS_CLOSING))
690                 return -EBUSY;
691
692         file->private_data = ffs;
693         ffs_data_opened(ffs);
694
695         return 0;
696 }
697
698 static int ffs_ep0_release(struct inode *inode, struct file *file)
699 {
700         struct ffs_data *ffs = file->private_data;
701
702         ENTER();
703
704         ffs_data_closed(ffs);
705
706         return 0;
707 }
708
709 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
710 {
711         struct ffs_data *ffs = file->private_data;
712         struct usb_gadget *gadget = ffs->gadget;
713         long ret;
714
715         ENTER();
716
717         if (code == FUNCTIONFS_INTERFACE_REVMAP) {
718                 struct ffs_function *func = ffs->func;
719                 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
720         } else if (gadget && gadget->ops->ioctl) {
721                 ret = gadget->ops->ioctl(gadget, code, value);
722         } else {
723                 ret = -ENOTTY;
724         }
725
726         return ret;
727 }
728
729 static const struct file_operations ffs_ep0_operations = {
730         .owner =        THIS_MODULE,
731         .llseek =       no_llseek,
732
733         .open =         ffs_ep0_open,
734         .write =        ffs_ep0_write,
735         .read =         ffs_ep0_read,
736         .release =      ffs_ep0_release,
737         .unlocked_ioctl =       ffs_ep0_ioctl,
738 };
739
740
741 /* "Normal" endpoints operations ********************************************/
742
743 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
744 {
745         ENTER();
746         if (likely(req->context)) {
747                 struct ffs_ep *ep = _ep->driver_data;
748                 ep->status = req->status ? req->status : req->actual;
749                 complete(req->context);
750         }
751 }
752
753 static ssize_t ffs_epfile_io(struct file *file,
754                              char __user *buf, size_t len, int read)
755 {
756         struct ffs_epfile *epfile = file->private_data;
757         struct ffs_ep *ep;
758         char *data = NULL;
759         ssize_t ret;
760         int halt;
761
762         goto first_try;
763         do {
764                 spin_unlock_irq(&epfile->ffs->eps_lock);
765                 mutex_unlock(&epfile->mutex);
766
767 first_try:
768                 /* Are we still active? */
769                 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
770                         ret = -ENODEV;
771                         goto error;
772                 }
773
774                 /* Wait for endpoint to be enabled */
775                 ep = epfile->ep;
776                 if (!ep) {
777                         if (file->f_flags & O_NONBLOCK) {
778                                 ret = -EAGAIN;
779                                 goto error;
780                         }
781
782                         if (wait_event_interruptible(epfile->wait,
783                                                      (ep = epfile->ep))) {
784                                 ret = -EINTR;
785                                 goto error;
786                         }
787                 }
788
789                 /* Do we halt? */
790                 halt = !read == !epfile->in;
791                 if (halt && epfile->isoc) {
792                         ret = -EINVAL;
793                         goto error;
794                 }
795
796                 /* Allocate & copy */
797                 if (!halt && !data) {
798                         data = kzalloc(len, GFP_KERNEL);
799                         if (unlikely(!data))
800                                 return -ENOMEM;
801
802                         if (!read &&
803                             unlikely(__copy_from_user(data, buf, len))) {
804                                 ret = -EFAULT;
805                                 goto error;
806                         }
807                 }
808
809                 /* We will be using request */
810                 ret = ffs_mutex_lock(&epfile->mutex,
811                                      file->f_flags & O_NONBLOCK);
812                 if (unlikely(ret))
813                         goto error;
814
815                 /*
816                  * We're called from user space, we can use _irq rather then
817                  * _irqsave
818                  */
819                 spin_lock_irq(&epfile->ffs->eps_lock);
820
821                 /*
822                  * While we were acquiring mutex endpoint got disabled
823                  * or changed?
824                  */
825         } while (unlikely(epfile->ep != ep));
826
827         /* Halt */
828         if (unlikely(halt)) {
829                 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
830                         usb_ep_set_halt(ep->ep);
831                 spin_unlock_irq(&epfile->ffs->eps_lock);
832                 ret = -EBADMSG;
833         } else {
834                 /* Fire the request */
835                 DECLARE_COMPLETION_ONSTACK(done);
836
837                 struct usb_request *req = ep->req;
838                 req->context  = &done;
839                 req->complete = ffs_epfile_io_complete;
840                 req->buf      = data;
841                 req->length   = len;
842
843                 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
844
845                 spin_unlock_irq(&epfile->ffs->eps_lock);
846
847                 if (unlikely(ret < 0)) {
848                         /* nop */
849                 } else if (unlikely(wait_for_completion_interruptible(&done))) {
850                         ret = -EINTR;
851                         usb_ep_dequeue(ep->ep, req);
852                 } else {
853                         ret = ep->status;
854                         if (read && ret > 0 &&
855                             unlikely(copy_to_user(buf, data, ret)))
856                                 ret = -EFAULT;
857                 }
858         }
859
860         mutex_unlock(&epfile->mutex);
861 error:
862         kfree(data);
863         return ret;
864 }
865
866 static ssize_t
867 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
868                  loff_t *ptr)
869 {
870         ENTER();
871
872         return ffs_epfile_io(file, (char __user *)buf, len, 0);
873 }
874
875 static ssize_t
876 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
877 {
878         ENTER();
879
880         return ffs_epfile_io(file, buf, len, 1);
881 }
882
883 static int
884 ffs_epfile_open(struct inode *inode, struct file *file)
885 {
886         struct ffs_epfile *epfile = inode->i_private;
887
888         ENTER();
889
890         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
891                 return -ENODEV;
892
893         file->private_data = epfile;
894         ffs_data_opened(epfile->ffs);
895
896         return 0;
897 }
898
899 static int
900 ffs_epfile_release(struct inode *inode, struct file *file)
901 {
902         struct ffs_epfile *epfile = inode->i_private;
903
904         ENTER();
905
906         ffs_data_closed(epfile->ffs);
907
908         return 0;
909 }
910
911 static long ffs_epfile_ioctl(struct file *file, unsigned code,
912                              unsigned long value)
913 {
914         struct ffs_epfile *epfile = file->private_data;
915         int ret;
916
917         ENTER();
918
919         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
920                 return -ENODEV;
921
922         spin_lock_irq(&epfile->ffs->eps_lock);
923         if (likely(epfile->ep)) {
924                 switch (code) {
925                 case FUNCTIONFS_FIFO_STATUS:
926                         ret = usb_ep_fifo_status(epfile->ep->ep);
927                         break;
928                 case FUNCTIONFS_FIFO_FLUSH:
929                         usb_ep_fifo_flush(epfile->ep->ep);
930                         ret = 0;
931                         break;
932                 case FUNCTIONFS_CLEAR_HALT:
933                         ret = usb_ep_clear_halt(epfile->ep->ep);
934                         break;
935                 case FUNCTIONFS_ENDPOINT_REVMAP:
936                         ret = epfile->ep->num;
937                         break;
938                 default:
939                         ret = -ENOTTY;
940                 }
941         } else {
942                 ret = -ENODEV;
943         }
944         spin_unlock_irq(&epfile->ffs->eps_lock);
945
946         return ret;
947 }
948
949 static const struct file_operations ffs_epfile_operations = {
950         .owner =        THIS_MODULE,
951         .llseek =       no_llseek,
952
953         .open =         ffs_epfile_open,
954         .write =        ffs_epfile_write,
955         .read =         ffs_epfile_read,
956         .release =      ffs_epfile_release,
957         .unlocked_ioctl =       ffs_epfile_ioctl,
958 };
959
960
961 /* File system and super block operations ***********************************/
962
963 /*
964  * Mounting the file system creates a controller file, used first for
965  * function configuration then later for event monitoring.
966  */
967
968 static struct inode *__must_check
969 ffs_sb_make_inode(struct super_block *sb, void *data,
970                   const struct file_operations *fops,
971                   const struct inode_operations *iops,
972                   struct ffs_file_perms *perms)
973 {
974         struct inode *inode;
975
976         ENTER();
977
978         inode = new_inode(sb);
979
980         if (likely(inode)) {
981                 struct timespec current_time = CURRENT_TIME;
982
983                 inode->i_ino     = get_next_ino();
984                 inode->i_mode    = perms->mode;
985                 inode->i_uid     = perms->uid;
986                 inode->i_gid     = perms->gid;
987                 inode->i_atime   = current_time;
988                 inode->i_mtime   = current_time;
989                 inode->i_ctime   = current_time;
990                 inode->i_private = data;
991                 if (fops)
992                         inode->i_fop = fops;
993                 if (iops)
994                         inode->i_op  = iops;
995         }
996
997         return inode;
998 }
999
1000 /* Create "regular" file */
1001 static struct inode *ffs_sb_create_file(struct super_block *sb,
1002                                         const char *name, void *data,
1003                                         const struct file_operations *fops,
1004                                         struct dentry **dentry_p)
1005 {
1006         struct ffs_data *ffs = sb->s_fs_info;
1007         struct dentry   *dentry;
1008         struct inode    *inode;
1009
1010         ENTER();
1011
1012         dentry = d_alloc_name(sb->s_root, name);
1013         if (unlikely(!dentry))
1014                 return NULL;
1015
1016         inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1017         if (unlikely(!inode)) {
1018                 dput(dentry);
1019                 return NULL;
1020         }
1021
1022         d_add(dentry, inode);
1023         if (dentry_p)
1024                 *dentry_p = dentry;
1025
1026         return inode;
1027 }
1028
1029 /* Super block */
1030 static const struct super_operations ffs_sb_operations = {
1031         .statfs =       simple_statfs,
1032         .drop_inode =   generic_delete_inode,
1033 };
1034
1035 struct ffs_sb_fill_data {
1036         struct ffs_file_perms perms;
1037         umode_t root_mode;
1038         const char *dev_name;
1039         union {
1040                 /* set by ffs_fs_mount(), read by ffs_sb_fill() */
1041                 void *private_data;
1042                 /* set by ffs_sb_fill(), read by ffs_fs_mount */
1043                 struct ffs_data *ffs_data;
1044         };
1045 };
1046
1047 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1048 {
1049         struct ffs_sb_fill_data *data = _data;
1050         struct inode    *inode;
1051         struct ffs_data *ffs;
1052
1053         ENTER();
1054
1055         /* Initialise data */
1056         ffs = ffs_data_new();
1057         if (unlikely(!ffs))
1058                 goto Enomem;
1059
1060         ffs->sb              = sb;
1061         ffs->dev_name        = kstrdup(data->dev_name, GFP_KERNEL);
1062         if (unlikely(!ffs->dev_name))
1063                 goto Enomem;
1064         ffs->file_perms      = data->perms;
1065         ffs->private_data    = data->private_data;
1066
1067         /* used by the caller of this function */
1068         data->ffs_data       = ffs;
1069
1070         sb->s_fs_info        = ffs;
1071         sb->s_blocksize      = PAGE_CACHE_SIZE;
1072         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1073         sb->s_magic          = FUNCTIONFS_MAGIC;
1074         sb->s_op             = &ffs_sb_operations;
1075         sb->s_time_gran      = 1;
1076
1077         /* Root inode */
1078         data->perms.mode = data->root_mode;
1079         inode = ffs_sb_make_inode(sb, NULL,
1080                                   &simple_dir_operations,
1081                                   &simple_dir_inode_operations,
1082                                   &data->perms);
1083         sb->s_root = d_make_root(inode);
1084         if (unlikely(!sb->s_root))
1085                 goto Enomem;
1086
1087         /* EP0 file */
1088         if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1089                                          &ffs_ep0_operations, NULL)))
1090                 goto Enomem;
1091
1092         return 0;
1093
1094 Enomem:
1095         return -ENOMEM;
1096 }
1097
1098 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1099 {
1100         ENTER();
1101
1102         if (!opts || !*opts)
1103                 return 0;
1104
1105         for (;;) {
1106                 unsigned long value;
1107                 char *eq, *comma;
1108
1109                 /* Option limit */
1110                 comma = strchr(opts, ',');
1111                 if (comma)
1112                         *comma = 0;
1113
1114                 /* Value limit */
1115                 eq = strchr(opts, '=');
1116                 if (unlikely(!eq)) {
1117                         pr_err("'=' missing in %s\n", opts);
1118                         return -EINVAL;
1119                 }
1120                 *eq = 0;
1121
1122                 /* Parse value */
1123                 if (kstrtoul(eq + 1, 0, &value)) {
1124                         pr_err("%s: invalid value: %s\n", opts, eq + 1);
1125                         return -EINVAL;
1126                 }
1127
1128                 /* Interpret option */
1129                 switch (eq - opts) {
1130                 case 5:
1131                         if (!memcmp(opts, "rmode", 5))
1132                                 data->root_mode  = (value & 0555) | S_IFDIR;
1133                         else if (!memcmp(opts, "fmode", 5))
1134                                 data->perms.mode = (value & 0666) | S_IFREG;
1135                         else
1136                                 goto invalid;
1137                         break;
1138
1139                 case 4:
1140                         if (!memcmp(opts, "mode", 4)) {
1141                                 data->root_mode  = (value & 0555) | S_IFDIR;
1142                                 data->perms.mode = (value & 0666) | S_IFREG;
1143                         } else {
1144                                 goto invalid;
1145                         }
1146                         break;
1147
1148                 case 3:
1149                         if (!memcmp(opts, "uid", 3)) {
1150                                 data->perms.uid = make_kuid(current_user_ns(), value);
1151                                 if (!uid_valid(data->perms.uid)) {
1152                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1153                                         return -EINVAL;
1154                                 }
1155                         } else if (!memcmp(opts, "gid", 3)) {
1156                                 data->perms.gid = make_kgid(current_user_ns(), value);
1157                                 if (!gid_valid(data->perms.gid)) {
1158                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1159                                         return -EINVAL;
1160                                 }
1161                         } else {
1162                                 goto invalid;
1163                         }
1164                         break;
1165
1166                 default:
1167 invalid:
1168                         pr_err("%s: invalid option\n", opts);
1169                         return -EINVAL;
1170                 }
1171
1172                 /* Next iteration */
1173                 if (!comma)
1174                         break;
1175                 opts = comma + 1;
1176         }
1177
1178         return 0;
1179 }
1180
1181 /* "mount -t functionfs dev_name /dev/function" ends up here */
1182
1183 static struct dentry *
1184 ffs_fs_mount(struct file_system_type *t, int flags,
1185               const char *dev_name, void *opts)
1186 {
1187         struct ffs_sb_fill_data data = {
1188                 .perms = {
1189                         .mode = S_IFREG | 0600,
1190                         .uid = GLOBAL_ROOT_UID,
1191                         .gid = GLOBAL_ROOT_GID,
1192                 },
1193                 .root_mode = S_IFDIR | 0500,
1194         };
1195         struct dentry *rv;
1196         int ret;
1197         void *ffs_dev;
1198
1199         ENTER();
1200
1201         ret = ffs_fs_parse_opts(&data, opts);
1202         if (unlikely(ret < 0))
1203                 return ERR_PTR(ret);
1204
1205         ffs_dev = functionfs_acquire_dev_callback(dev_name);
1206         if (IS_ERR(ffs_dev))
1207                 return ffs_dev;
1208
1209         data.dev_name = dev_name;
1210         data.private_data = ffs_dev;
1211         rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1212
1213         /* data.ffs_data is set by ffs_sb_fill */
1214         if (IS_ERR(rv))
1215                 functionfs_release_dev_callback(data.ffs_data);
1216
1217         return rv;
1218 }
1219
1220 static void
1221 ffs_fs_kill_sb(struct super_block *sb)
1222 {
1223         ENTER();
1224
1225         kill_litter_super(sb);
1226         if (sb->s_fs_info) {
1227                 functionfs_release_dev_callback(sb->s_fs_info);
1228                 ffs_data_put(sb->s_fs_info);
1229         }
1230 }
1231
1232 static struct file_system_type ffs_fs_type = {
1233         .owner          = THIS_MODULE,
1234         .name           = "functionfs",
1235         .mount          = ffs_fs_mount,
1236         .kill_sb        = ffs_fs_kill_sb,
1237 };
1238
1239
1240 /* Driver's main init/cleanup functions *************************************/
1241
1242 static int functionfs_init(void)
1243 {
1244         int ret;
1245
1246         ENTER();
1247
1248         ret = register_filesystem(&ffs_fs_type);
1249         if (likely(!ret))
1250                 pr_info("file system registered\n");
1251         else
1252                 pr_err("failed registering file system (%d)\n", ret);
1253
1254         return ret;
1255 }
1256
1257 static void functionfs_cleanup(void)
1258 {
1259         ENTER();
1260
1261         pr_info("unloading\n");
1262         unregister_filesystem(&ffs_fs_type);
1263 }
1264
1265
1266 /* ffs_data and ffs_function construction and destruction code **************/
1267
1268 static void ffs_data_clear(struct ffs_data *ffs);
1269 static void ffs_data_reset(struct ffs_data *ffs);
1270
1271 static void ffs_data_get(struct ffs_data *ffs)
1272 {
1273         ENTER();
1274
1275         atomic_inc(&ffs->ref);
1276 }
1277
1278 static void ffs_data_opened(struct ffs_data *ffs)
1279 {
1280         ENTER();
1281
1282         atomic_inc(&ffs->ref);
1283         atomic_inc(&ffs->opened);
1284 }
1285
1286 static void ffs_data_put(struct ffs_data *ffs)
1287 {
1288         ENTER();
1289
1290         if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1291                 pr_info("%s(): freeing\n", __func__);
1292                 ffs_data_clear(ffs);
1293                 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1294                        waitqueue_active(&ffs->ep0req_completion.wait));
1295                 kfree(ffs->dev_name);
1296                 kfree(ffs);
1297         }
1298 }
1299
1300 static void ffs_data_closed(struct ffs_data *ffs)
1301 {
1302         ENTER();
1303
1304         if (atomic_dec_and_test(&ffs->opened)) {
1305                 ffs->state = FFS_CLOSING;
1306                 ffs_data_reset(ffs);
1307         }
1308
1309         ffs_data_put(ffs);
1310 }
1311
1312 static struct ffs_data *ffs_data_new(void)
1313 {
1314         struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1315         if (unlikely(!ffs))
1316                 return 0;
1317
1318         ENTER();
1319
1320         atomic_set(&ffs->ref, 1);
1321         atomic_set(&ffs->opened, 0);
1322         ffs->state = FFS_READ_DESCRIPTORS;
1323         mutex_init(&ffs->mutex);
1324         spin_lock_init(&ffs->eps_lock);
1325         init_waitqueue_head(&ffs->ev.waitq);
1326         init_completion(&ffs->ep0req_completion);
1327
1328         /* XXX REVISIT need to update it in some places, or do we? */
1329         ffs->ev.can_stall = 1;
1330
1331         return ffs;
1332 }
1333
1334 static void ffs_data_clear(struct ffs_data *ffs)
1335 {
1336         ENTER();
1337
1338         if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1339                 functionfs_closed_callback(ffs);
1340
1341         BUG_ON(ffs->gadget);
1342
1343         if (ffs->epfiles)
1344                 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1345
1346         kfree(ffs->raw_descs);
1347         kfree(ffs->raw_strings);
1348         kfree(ffs->stringtabs);
1349 }
1350
1351 static void ffs_data_reset(struct ffs_data *ffs)
1352 {
1353         ENTER();
1354
1355         ffs_data_clear(ffs);
1356
1357         ffs->epfiles = NULL;
1358         ffs->raw_descs = NULL;
1359         ffs->raw_strings = NULL;
1360         ffs->stringtabs = NULL;
1361
1362         ffs->raw_descs_length = 0;
1363         ffs->raw_fs_descs_length = 0;
1364         ffs->fs_descs_count = 0;
1365         ffs->hs_descs_count = 0;
1366
1367         ffs->strings_count = 0;
1368         ffs->interfaces_count = 0;
1369         ffs->eps_count = 0;
1370
1371         ffs->ev.count = 0;
1372
1373         ffs->state = FFS_READ_DESCRIPTORS;
1374         ffs->setup_state = FFS_NO_SETUP;
1375         ffs->flags = 0;
1376 }
1377
1378
1379 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1380 {
1381         struct usb_gadget_strings **lang;
1382         int first_id;
1383
1384         ENTER();
1385
1386         if (WARN_ON(ffs->state != FFS_ACTIVE
1387                  || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1388                 return -EBADFD;
1389
1390         first_id = usb_string_ids_n(cdev, ffs->strings_count);
1391         if (unlikely(first_id < 0))
1392                 return first_id;
1393
1394         ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1395         if (unlikely(!ffs->ep0req))
1396                 return -ENOMEM;
1397         ffs->ep0req->complete = ffs_ep0_complete;
1398         ffs->ep0req->context = ffs;
1399
1400         lang = ffs->stringtabs;
1401         for (lang = ffs->stringtabs; *lang; ++lang) {
1402                 struct usb_string *str = (*lang)->strings;
1403                 int id = first_id;
1404                 for (; str->s; ++id, ++str)
1405                         str->id = id;
1406         }
1407
1408         ffs->gadget = cdev->gadget;
1409         ffs_data_get(ffs);
1410         return 0;
1411 }
1412
1413 static void functionfs_unbind(struct ffs_data *ffs)
1414 {
1415         ENTER();
1416
1417         if (!WARN_ON(!ffs->gadget)) {
1418                 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1419                 ffs->ep0req = NULL;
1420                 ffs->gadget = NULL;
1421                 ffs_data_put(ffs);
1422                 clear_bit(FFS_FL_BOUND, &ffs->flags);
1423         }
1424 }
1425
1426 static int ffs_epfiles_create(struct ffs_data *ffs)
1427 {
1428         struct ffs_epfile *epfile, *epfiles;
1429         unsigned i, count;
1430
1431         ENTER();
1432
1433         count = ffs->eps_count;
1434         epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1435         if (!epfiles)
1436                 return -ENOMEM;
1437
1438         epfile = epfiles;
1439         for (i = 1; i <= count; ++i, ++epfile) {
1440                 epfile->ffs = ffs;
1441                 mutex_init(&epfile->mutex);
1442                 init_waitqueue_head(&epfile->wait);
1443                 sprintf(epfiles->name, "ep%u",  i);
1444                 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1445                                                  &ffs_epfile_operations,
1446                                                  &epfile->dentry))) {
1447                         ffs_epfiles_destroy(epfiles, i - 1);
1448                         return -ENOMEM;
1449                 }
1450         }
1451
1452         ffs->epfiles = epfiles;
1453         return 0;
1454 }
1455
1456 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1457 {
1458         struct ffs_epfile *epfile = epfiles;
1459
1460         ENTER();
1461
1462         for (; count; --count, ++epfile) {
1463                 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1464                        waitqueue_active(&epfile->wait));
1465                 if (epfile->dentry) {
1466                         d_delete(epfile->dentry);
1467                         dput(epfile->dentry);
1468                         epfile->dentry = NULL;
1469                 }
1470         }
1471
1472         kfree(epfiles);
1473 }
1474
1475 static int functionfs_bind_config(struct usb_composite_dev *cdev,
1476                                   struct usb_configuration *c,
1477                                   struct ffs_data *ffs)
1478 {
1479         struct ffs_function *func;
1480         int ret;
1481
1482         ENTER();
1483
1484         func = kzalloc(sizeof *func, GFP_KERNEL);
1485         if (unlikely(!func))
1486                 return -ENOMEM;
1487
1488         func->function.name    = "Function FS Gadget";
1489         func->function.strings = ffs->stringtabs;
1490
1491         func->function.bind    = ffs_func_bind;
1492         func->function.unbind  = ffs_func_unbind;
1493         func->function.set_alt = ffs_func_set_alt;
1494         func->function.disable = ffs_func_disable;
1495         func->function.setup   = ffs_func_setup;
1496         func->function.suspend = ffs_func_suspend;
1497         func->function.resume  = ffs_func_resume;
1498
1499         func->conf   = c;
1500         func->gadget = cdev->gadget;
1501         func->ffs = ffs;
1502         ffs_data_get(ffs);
1503
1504         ret = usb_add_function(c, &func->function);
1505         if (unlikely(ret))
1506                 ffs_func_free(func);
1507
1508         return ret;
1509 }
1510
1511 static void ffs_func_free(struct ffs_function *func)
1512 {
1513         struct ffs_ep *ep         = func->eps;
1514         unsigned count            = func->ffs->eps_count;
1515         unsigned long flags;
1516
1517         ENTER();
1518
1519         /* cleanup after autoconfig */
1520         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1521         do {
1522                 if (ep->ep && ep->req)
1523                         usb_ep_free_request(ep->ep, ep->req);
1524                 ep->req = NULL;
1525                 ++ep;
1526         } while (--count);
1527         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1528
1529         ffs_data_put(func->ffs);
1530
1531         kfree(func->eps);
1532         /*
1533          * eps and interfaces_nums are allocated in the same chunk so
1534          * only one free is required.  Descriptors are also allocated
1535          * in the same chunk.
1536          */
1537
1538         kfree(func);
1539 }
1540
1541 static void ffs_func_eps_disable(struct ffs_function *func)
1542 {
1543         struct ffs_ep *ep         = func->eps;
1544         struct ffs_epfile *epfile = func->ffs->epfiles;
1545         unsigned count            = func->ffs->eps_count;
1546         unsigned long flags;
1547
1548         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1549         do {
1550                 /* pending requests get nuked */
1551                 if (likely(ep->ep))
1552                         usb_ep_disable(ep->ep);
1553                 epfile->ep = NULL;
1554
1555                 ++ep;
1556                 ++epfile;
1557         } while (--count);
1558         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1559 }
1560
1561 static int ffs_func_eps_enable(struct ffs_function *func)
1562 {
1563         struct ffs_data *ffs      = func->ffs;
1564         struct ffs_ep *ep         = func->eps;
1565         struct ffs_epfile *epfile = ffs->epfiles;
1566         unsigned count            = ffs->eps_count;
1567         unsigned long flags;
1568         int ret = 0;
1569
1570         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1571         do {
1572                 struct usb_endpoint_descriptor *ds;
1573                 ds = ep->descs[ep->descs[1] ? 1 : 0];
1574
1575                 ep->ep->driver_data = ep;
1576                 ep->ep->desc = ds;
1577                 ret = usb_ep_enable(ep->ep);
1578                 if (likely(!ret)) {
1579                         epfile->ep = ep;
1580                         epfile->in = usb_endpoint_dir_in(ds);
1581                         epfile->isoc = usb_endpoint_xfer_isoc(ds);
1582                 } else {
1583                         break;
1584                 }
1585
1586                 wake_up(&epfile->wait);
1587
1588                 ++ep;
1589                 ++epfile;
1590         } while (--count);
1591         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1592
1593         return ret;
1594 }
1595
1596
1597 /* Parsing and building descriptors and strings *****************************/
1598
1599 /*
1600  * This validates if data pointed by data is a valid USB descriptor as
1601  * well as record how many interfaces, endpoints and strings are
1602  * required by given configuration.  Returns address after the
1603  * descriptor or NULL if data is invalid.
1604  */
1605
1606 enum ffs_entity_type {
1607         FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1608 };
1609
1610 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1611                                    u8 *valuep,
1612                                    struct usb_descriptor_header *desc,
1613                                    void *priv);
1614
1615 static int __must_check ffs_do_desc(char *data, unsigned len,
1616                                     ffs_entity_callback entity, void *priv)
1617 {
1618         struct usb_descriptor_header *_ds = (void *)data;
1619         u8 length;
1620         int ret;
1621
1622         ENTER();
1623
1624         /* At least two bytes are required: length and type */
1625         if (len < 2) {
1626                 pr_vdebug("descriptor too short\n");
1627                 return -EINVAL;
1628         }
1629
1630         /* If we have at least as many bytes as the descriptor takes? */
1631         length = _ds->bLength;
1632         if (len < length) {
1633                 pr_vdebug("descriptor longer then available data\n");
1634                 return -EINVAL;
1635         }
1636
1637 #define __entity_check_INTERFACE(val)  1
1638 #define __entity_check_STRING(val)     (val)
1639 #define __entity_check_ENDPOINT(val)   ((val) & USB_ENDPOINT_NUMBER_MASK)
1640 #define __entity(type, val) do {                                        \
1641                 pr_vdebug("entity " #type "(%02x)\n", (val));           \
1642                 if (unlikely(!__entity_check_ ##type(val))) {           \
1643                         pr_vdebug("invalid entity's value\n");          \
1644                         return -EINVAL;                                 \
1645                 }                                                       \
1646                 ret = entity(FFS_ ##type, &val, _ds, priv);             \
1647                 if (unlikely(ret < 0)) {                                \
1648                         pr_debug("entity " #type "(%02x); ret = %d\n",  \
1649                                  (val), ret);                           \
1650                         return ret;                                     \
1651                 }                                                       \
1652         } while (0)
1653
1654         /* Parse descriptor depending on type. */
1655         switch (_ds->bDescriptorType) {
1656         case USB_DT_DEVICE:
1657         case USB_DT_CONFIG:
1658         case USB_DT_STRING:
1659         case USB_DT_DEVICE_QUALIFIER:
1660                 /* function can't have any of those */
1661                 pr_vdebug("descriptor reserved for gadget: %d\n",
1662                       _ds->bDescriptorType);
1663                 return -EINVAL;
1664
1665         case USB_DT_INTERFACE: {
1666                 struct usb_interface_descriptor *ds = (void *)_ds;
1667                 pr_vdebug("interface descriptor\n");
1668                 if (length != sizeof *ds)
1669                         goto inv_length;
1670
1671                 __entity(INTERFACE, ds->bInterfaceNumber);
1672                 if (ds->iInterface)
1673                         __entity(STRING, ds->iInterface);
1674         }
1675                 break;
1676
1677         case USB_DT_ENDPOINT: {
1678                 struct usb_endpoint_descriptor *ds = (void *)_ds;
1679                 pr_vdebug("endpoint descriptor\n");
1680                 if (length != USB_DT_ENDPOINT_SIZE &&
1681                     length != USB_DT_ENDPOINT_AUDIO_SIZE)
1682                         goto inv_length;
1683                 __entity(ENDPOINT, ds->bEndpointAddress);
1684         }
1685                 break;
1686
1687         case HID_DT_HID:
1688                 pr_vdebug("hid descriptor\n");
1689                 if (length != sizeof(struct hid_descriptor))
1690                         goto inv_length;
1691                 break;
1692
1693         case USB_DT_OTG:
1694                 if (length != sizeof(struct usb_otg_descriptor))
1695                         goto inv_length;
1696                 break;
1697
1698         case USB_DT_INTERFACE_ASSOCIATION: {
1699                 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1700                 pr_vdebug("interface association descriptor\n");
1701                 if (length != sizeof *ds)
1702                         goto inv_length;
1703                 if (ds->iFunction)
1704                         __entity(STRING, ds->iFunction);
1705         }
1706                 break;
1707
1708         case USB_DT_OTHER_SPEED_CONFIG:
1709         case USB_DT_INTERFACE_POWER:
1710         case USB_DT_DEBUG:
1711         case USB_DT_SECURITY:
1712         case USB_DT_CS_RADIO_CONTROL:
1713                 /* TODO */
1714                 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1715                 return -EINVAL;
1716
1717         default:
1718                 /* We should never be here */
1719                 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1720                 return -EINVAL;
1721
1722 inv_length:
1723                 pr_vdebug("invalid length: %d (descriptor %d)\n",
1724                           _ds->bLength, _ds->bDescriptorType);
1725                 return -EINVAL;
1726         }
1727
1728 #undef __entity
1729 #undef __entity_check_DESCRIPTOR
1730 #undef __entity_check_INTERFACE
1731 #undef __entity_check_STRING
1732 #undef __entity_check_ENDPOINT
1733
1734         return length;
1735 }
1736
1737 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1738                                      ffs_entity_callback entity, void *priv)
1739 {
1740         const unsigned _len = len;
1741         unsigned long num = 0;
1742
1743         ENTER();
1744
1745         for (;;) {
1746                 int ret;
1747
1748                 if (num == count)
1749                         data = NULL;
1750
1751                 /* Record "descriptor" entity */
1752                 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1753                 if (unlikely(ret < 0)) {
1754                         pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1755                                  num, ret);
1756                         return ret;
1757                 }
1758
1759                 if (!data)
1760                         return _len - len;
1761
1762                 ret = ffs_do_desc(data, len, entity, priv);
1763                 if (unlikely(ret < 0)) {
1764                         pr_debug("%s returns %d\n", __func__, ret);
1765                         return ret;
1766                 }
1767
1768                 len -= ret;
1769                 data += ret;
1770                 ++num;
1771         }
1772 }
1773
1774 static int __ffs_data_do_entity(enum ffs_entity_type type,
1775                                 u8 *valuep, struct usb_descriptor_header *desc,
1776                                 void *priv)
1777 {
1778         struct ffs_data *ffs = priv;
1779
1780         ENTER();
1781
1782         switch (type) {
1783         case FFS_DESCRIPTOR:
1784                 break;
1785
1786         case FFS_INTERFACE:
1787                 /*
1788                  * Interfaces are indexed from zero so if we
1789                  * encountered interface "n" then there are at least
1790                  * "n+1" interfaces.
1791                  */
1792                 if (*valuep >= ffs->interfaces_count)
1793                         ffs->interfaces_count = *valuep + 1;
1794                 break;
1795
1796         case FFS_STRING:
1797                 /*
1798                  * Strings are indexed from 1 (0 is magic ;) reserved
1799                  * for languages list or some such)
1800                  */
1801                 if (*valuep > ffs->strings_count)
1802                         ffs->strings_count = *valuep;
1803                 break;
1804
1805         case FFS_ENDPOINT:
1806                 /* Endpoints are indexed from 1 as well. */
1807                 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1808                         ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1809                 break;
1810         }
1811
1812         return 0;
1813 }
1814
1815 static int __ffs_data_got_descs(struct ffs_data *ffs,
1816                                 char *const _data, size_t len)
1817 {
1818         unsigned fs_count, hs_count;
1819         int fs_len, ret = -EINVAL;
1820         char *data = _data;
1821
1822         ENTER();
1823
1824         if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
1825                      get_unaligned_le32(data + 4) != len))
1826                 goto error;
1827         fs_count = get_unaligned_le32(data +  8);
1828         hs_count = get_unaligned_le32(data + 12);
1829
1830         if (!fs_count && !hs_count)
1831                 goto einval;
1832
1833         data += 16;
1834         len  -= 16;
1835
1836         if (likely(fs_count)) {
1837                 fs_len = ffs_do_descs(fs_count, data, len,
1838                                       __ffs_data_do_entity, ffs);
1839                 if (unlikely(fs_len < 0)) {
1840                         ret = fs_len;
1841                         goto error;
1842                 }
1843
1844                 data += fs_len;
1845                 len  -= fs_len;
1846         } else {
1847                 fs_len = 0;
1848         }
1849
1850         if (likely(hs_count)) {
1851                 ret = ffs_do_descs(hs_count, data, len,
1852                                    __ffs_data_do_entity, ffs);
1853                 if (unlikely(ret < 0))
1854                         goto error;
1855         } else {
1856                 ret = 0;
1857         }
1858
1859         if (unlikely(len != ret))
1860                 goto einval;
1861
1862         ffs->raw_fs_descs_length = fs_len;
1863         ffs->raw_descs_length    = fs_len + ret;
1864         ffs->raw_descs           = _data;
1865         ffs->fs_descs_count      = fs_count;
1866         ffs->hs_descs_count      = hs_count;
1867
1868         return 0;
1869
1870 einval:
1871         ret = -EINVAL;
1872 error:
1873         kfree(_data);
1874         return ret;
1875 }
1876
1877 static int __ffs_data_got_strings(struct ffs_data *ffs,
1878                                   char *const _data, size_t len)
1879 {
1880         u32 str_count, needed_count, lang_count;
1881         struct usb_gadget_strings **stringtabs, *t;
1882         struct usb_string *strings, *s;
1883         const char *data = _data;
1884
1885         ENTER();
1886
1887         if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1888                      get_unaligned_le32(data + 4) != len))
1889                 goto error;
1890         str_count  = get_unaligned_le32(data + 8);
1891         lang_count = get_unaligned_le32(data + 12);
1892
1893         /* if one is zero the other must be zero */
1894         if (unlikely(!str_count != !lang_count))
1895                 goto error;
1896
1897         /* Do we have at least as many strings as descriptors need? */
1898         needed_count = ffs->strings_count;
1899         if (unlikely(str_count < needed_count))
1900                 goto error;
1901
1902         /*
1903          * If we don't need any strings just return and free all
1904          * memory.
1905          */
1906         if (!needed_count) {
1907                 kfree(_data);
1908                 return 0;
1909         }
1910
1911         /* Allocate everything in one chunk so there's less maintenance. */
1912         {
1913                 struct {
1914                         struct usb_gadget_strings *stringtabs[lang_count + 1];
1915                         struct usb_gadget_strings stringtab[lang_count];
1916                         struct usb_string strings[lang_count*(needed_count+1)];
1917                 } *d;
1918                 unsigned i = 0;
1919
1920                 d = kmalloc(sizeof *d, GFP_KERNEL);
1921                 if (unlikely(!d)) {
1922                         kfree(_data);
1923                         return -ENOMEM;
1924                 }
1925
1926                 stringtabs = d->stringtabs;
1927                 t = d->stringtab;
1928                 i = lang_count;
1929                 do {
1930                         *stringtabs++ = t++;
1931                 } while (--i);
1932                 *stringtabs = NULL;
1933
1934                 stringtabs = d->stringtabs;
1935                 t = d->stringtab;
1936                 s = d->strings;
1937                 strings = s;
1938         }
1939
1940         /* For each language */
1941         data += 16;
1942         len -= 16;
1943
1944         do { /* lang_count > 0 so we can use do-while */
1945                 unsigned needed = needed_count;
1946
1947                 if (unlikely(len < 3))
1948                         goto error_free;
1949                 t->language = get_unaligned_le16(data);
1950                 t->strings  = s;
1951                 ++t;
1952
1953                 data += 2;
1954                 len -= 2;
1955
1956                 /* For each string */
1957                 do { /* str_count > 0 so we can use do-while */
1958                         size_t length = strnlen(data, len);
1959
1960                         if (unlikely(length == len))
1961                                 goto error_free;
1962
1963                         /*
1964                          * User may provide more strings then we need,
1965                          * if that's the case we simply ignore the
1966                          * rest
1967                          */
1968                         if (likely(needed)) {
1969                                 /*
1970                                  * s->id will be set while adding
1971                                  * function to configuration so for
1972                                  * now just leave garbage here.
1973                                  */
1974                                 s->s = data;
1975                                 --needed;
1976                                 ++s;
1977                         }
1978
1979                         data += length + 1;
1980                         len -= length + 1;
1981                 } while (--str_count);
1982
1983                 s->id = 0;   /* terminator */
1984                 s->s = NULL;
1985                 ++s;
1986
1987         } while (--lang_count);
1988
1989         /* Some garbage left? */
1990         if (unlikely(len))
1991                 goto error_free;
1992
1993         /* Done! */
1994         ffs->stringtabs = stringtabs;
1995         ffs->raw_strings = _data;
1996
1997         return 0;
1998
1999 error_free:
2000         kfree(stringtabs);
2001 error:
2002         kfree(_data);
2003         return -EINVAL;
2004 }
2005
2006
2007 /* Events handling and management *******************************************/
2008
2009 static void __ffs_event_add(struct ffs_data *ffs,
2010                             enum usb_functionfs_event_type type)
2011 {
2012         enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2013         int neg = 0;
2014
2015         /*
2016          * Abort any unhandled setup
2017          *
2018          * We do not need to worry about some cmpxchg() changing value
2019          * of ffs->setup_state without holding the lock because when
2020          * state is FFS_SETUP_PENDING cmpxchg() in several places in
2021          * the source does nothing.
2022          */
2023         if (ffs->setup_state == FFS_SETUP_PENDING)
2024                 ffs->setup_state = FFS_SETUP_CANCELED;
2025
2026         switch (type) {
2027         case FUNCTIONFS_RESUME:
2028                 rem_type2 = FUNCTIONFS_SUSPEND;
2029                 /* FALL THROUGH */
2030         case FUNCTIONFS_SUSPEND:
2031         case FUNCTIONFS_SETUP:
2032                 rem_type1 = type;
2033                 /* Discard all similar events */
2034                 break;
2035
2036         case FUNCTIONFS_BIND:
2037         case FUNCTIONFS_UNBIND:
2038         case FUNCTIONFS_DISABLE:
2039         case FUNCTIONFS_ENABLE:
2040                 /* Discard everything other then power management. */
2041                 rem_type1 = FUNCTIONFS_SUSPEND;
2042                 rem_type2 = FUNCTIONFS_RESUME;
2043                 neg = 1;
2044                 break;
2045
2046         default:
2047                 BUG();
2048         }
2049
2050         {
2051                 u8 *ev  = ffs->ev.types, *out = ev;
2052                 unsigned n = ffs->ev.count;
2053                 for (; n; --n, ++ev)
2054                         if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2055                                 *out++ = *ev;
2056                         else
2057                                 pr_vdebug("purging event %d\n", *ev);
2058                 ffs->ev.count = out - ffs->ev.types;
2059         }
2060
2061         pr_vdebug("adding event %d\n", type);
2062         ffs->ev.types[ffs->ev.count++] = type;
2063         wake_up_locked(&ffs->ev.waitq);
2064 }
2065
2066 static void ffs_event_add(struct ffs_data *ffs,
2067                           enum usb_functionfs_event_type type)
2068 {
2069         unsigned long flags;
2070         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2071         __ffs_event_add(ffs, type);
2072         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2073 }
2074
2075
2076 /* Bind/unbind USB function hooks *******************************************/
2077
2078 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2079                                     struct usb_descriptor_header *desc,
2080                                     void *priv)
2081 {
2082         struct usb_endpoint_descriptor *ds = (void *)desc;
2083         struct ffs_function *func = priv;
2084         struct ffs_ep *ffs_ep;
2085
2086         /*
2087          * If hs_descriptors is not NULL then we are reading hs
2088          * descriptors now
2089          */
2090         const int isHS = func->function.hs_descriptors != NULL;
2091         unsigned idx;
2092
2093         if (type != FFS_DESCRIPTOR)
2094                 return 0;
2095
2096         if (isHS)
2097                 func->function.hs_descriptors[(long)valuep] = desc;
2098         else
2099                 func->function.fs_descriptors[(long)valuep]    = desc;
2100
2101         if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2102                 return 0;
2103
2104         idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2105         ffs_ep = func->eps + idx;
2106
2107         if (unlikely(ffs_ep->descs[isHS])) {
2108                 pr_vdebug("two %sspeed descriptors for EP %d\n",
2109                           isHS ? "high" : "full",
2110                           ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2111                 return -EINVAL;
2112         }
2113         ffs_ep->descs[isHS] = ds;
2114
2115         ffs_dump_mem(": Original  ep desc", ds, ds->bLength);
2116         if (ffs_ep->ep) {
2117                 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2118                 if (!ds->wMaxPacketSize)
2119                         ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2120         } else {
2121                 struct usb_request *req;
2122                 struct usb_ep *ep;
2123
2124                 pr_vdebug("autoconfig\n");
2125                 ep = usb_ep_autoconfig(func->gadget, ds);
2126                 if (unlikely(!ep))
2127                         return -ENOTSUPP;
2128                 ep->driver_data = func->eps + idx;
2129
2130                 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2131                 if (unlikely(!req))
2132                         return -ENOMEM;
2133
2134                 ffs_ep->ep  = ep;
2135                 ffs_ep->req = req;
2136                 func->eps_revmap[ds->bEndpointAddress &
2137                                  USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2138         }
2139         ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2140
2141         return 0;
2142 }
2143
2144 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2145                                    struct usb_descriptor_header *desc,
2146                                    void *priv)
2147 {
2148         struct ffs_function *func = priv;
2149         unsigned idx;
2150         u8 newValue;
2151
2152         switch (type) {
2153         default:
2154         case FFS_DESCRIPTOR:
2155                 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2156                 return 0;
2157
2158         case FFS_INTERFACE:
2159                 idx = *valuep;
2160                 if (func->interfaces_nums[idx] < 0) {
2161                         int id = usb_interface_id(func->conf, &func->function);
2162                         if (unlikely(id < 0))
2163                                 return id;
2164                         func->interfaces_nums[idx] = id;
2165                 }
2166                 newValue = func->interfaces_nums[idx];
2167                 break;
2168
2169         case FFS_STRING:
2170                 /* String' IDs are allocated when fsf_data is bound to cdev */
2171                 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2172                 break;
2173
2174         case FFS_ENDPOINT:
2175                 /*
2176                  * USB_DT_ENDPOINT are handled in
2177                  * __ffs_func_bind_do_descs().
2178                  */
2179                 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2180                         return 0;
2181
2182                 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2183                 if (unlikely(!func->eps[idx].ep))
2184                         return -EINVAL;
2185
2186                 {
2187                         struct usb_endpoint_descriptor **descs;
2188                         descs = func->eps[idx].descs;
2189                         newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2190                 }
2191                 break;
2192         }
2193
2194         pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2195         *valuep = newValue;
2196         return 0;
2197 }
2198
2199 static int ffs_func_bind(struct usb_configuration *c,
2200                          struct usb_function *f)
2201 {
2202         struct ffs_function *func = ffs_func_from_usb(f);
2203         struct ffs_data *ffs = func->ffs;
2204
2205         const int full = !!func->ffs->fs_descs_count;
2206         const int high = gadget_is_dualspeed(func->gadget) &&
2207                 func->ffs->hs_descs_count;
2208
2209         int ret;
2210
2211         /* Make it a single chunk, less management later on */
2212         struct {
2213                 struct ffs_ep eps[ffs->eps_count];
2214                 struct usb_descriptor_header
2215                         *fs_descs[full ? ffs->fs_descs_count + 1 : 0];
2216                 struct usb_descriptor_header
2217                         *hs_descs[high ? ffs->hs_descs_count + 1 : 0];
2218                 short inums[ffs->interfaces_count];
2219                 char raw_descs[high ? ffs->raw_descs_length
2220                                     : ffs->raw_fs_descs_length];
2221         } *data;
2222
2223         ENTER();
2224
2225         /* Only high speed but not supported by gadget? */
2226         if (unlikely(!(full | high)))
2227                 return -ENOTSUPP;
2228
2229         /* Allocate */
2230         data = kmalloc(sizeof *data, GFP_KERNEL);
2231         if (unlikely(!data))
2232                 return -ENOMEM;
2233
2234         /* Zero */
2235         memset(data->eps, 0, sizeof data->eps);
2236         memcpy(data->raw_descs, ffs->raw_descs + 16, sizeof data->raw_descs);
2237         memset(data->inums, 0xff, sizeof data->inums);
2238         for (ret = ffs->eps_count; ret; --ret)
2239                 data->eps[ret].num = -1;
2240
2241         /* Save pointers */
2242         func->eps             = data->eps;
2243         func->interfaces_nums = data->inums;
2244
2245         /*
2246          * Go through all the endpoint descriptors and allocate
2247          * endpoints first, so that later we can rewrite the endpoint
2248          * numbers without worrying that it may be described later on.
2249          */
2250         if (likely(full)) {
2251                 func->function.fs_descriptors = data->fs_descs;
2252                 ret = ffs_do_descs(ffs->fs_descs_count,
2253                                    data->raw_descs,
2254                                    sizeof data->raw_descs,
2255                                    __ffs_func_bind_do_descs, func);
2256                 if (unlikely(ret < 0))
2257                         goto error;
2258         } else {
2259                 ret = 0;
2260         }
2261
2262         if (likely(high)) {
2263                 func->function.hs_descriptors = data->hs_descs;
2264                 ret = ffs_do_descs(ffs->hs_descs_count,
2265                                    data->raw_descs + ret,
2266                                    (sizeof data->raw_descs) - ret,
2267                                    __ffs_func_bind_do_descs, func);
2268         }
2269
2270         /*
2271          * Now handle interface numbers allocation and interface and
2272          * endpoint numbers rewriting.  We can do that in one go
2273          * now.
2274          */
2275         ret = ffs_do_descs(ffs->fs_descs_count +
2276                            (high ? ffs->hs_descs_count : 0),
2277                            data->raw_descs, sizeof data->raw_descs,
2278                            __ffs_func_bind_do_nums, func);
2279         if (unlikely(ret < 0))
2280                 goto error;
2281
2282         /* And we're done */
2283         ffs_event_add(ffs, FUNCTIONFS_BIND);
2284         return 0;
2285
2286 error:
2287         /* XXX Do we need to release all claimed endpoints here? */
2288         return ret;
2289 }
2290
2291
2292 /* Other USB function hooks *************************************************/
2293
2294 static void ffs_func_unbind(struct usb_configuration *c,
2295                             struct usb_function *f)
2296 {
2297         struct ffs_function *func = ffs_func_from_usb(f);
2298         struct ffs_data *ffs = func->ffs;
2299
2300         ENTER();
2301
2302         if (ffs->func == func) {
2303                 ffs_func_eps_disable(func);
2304                 ffs->func = NULL;
2305         }
2306
2307         ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2308
2309         ffs_func_free(func);
2310 }
2311
2312 static int ffs_func_set_alt(struct usb_function *f,
2313                             unsigned interface, unsigned alt)
2314 {
2315         struct ffs_function *func = ffs_func_from_usb(f);
2316         struct ffs_data *ffs = func->ffs;
2317         int ret = 0, intf;
2318
2319         if (alt != (unsigned)-1) {
2320                 intf = ffs_func_revmap_intf(func, interface);
2321                 if (unlikely(intf < 0))
2322                         return intf;
2323         }
2324
2325         if (ffs->func)
2326                 ffs_func_eps_disable(ffs->func);
2327
2328         if (ffs->state != FFS_ACTIVE)
2329                 return -ENODEV;
2330
2331         if (alt == (unsigned)-1) {
2332                 ffs->func = NULL;
2333                 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2334                 return 0;
2335         }
2336
2337         ffs->func = func;
2338         ret = ffs_func_eps_enable(func);
2339         if (likely(ret >= 0))
2340                 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2341         return ret;
2342 }
2343
2344 static void ffs_func_disable(struct usb_function *f)
2345 {
2346         ffs_func_set_alt(f, 0, (unsigned)-1);
2347 }
2348
2349 static int ffs_func_setup(struct usb_function *f,
2350                           const struct usb_ctrlrequest *creq)
2351 {
2352         struct ffs_function *func = ffs_func_from_usb(f);
2353         struct ffs_data *ffs = func->ffs;
2354         unsigned long flags;
2355         int ret;
2356
2357         ENTER();
2358
2359         pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2360         pr_vdebug("creq->bRequest     = %02x\n", creq->bRequest);
2361         pr_vdebug("creq->wValue       = %04x\n", le16_to_cpu(creq->wValue));
2362         pr_vdebug("creq->wIndex       = %04x\n", le16_to_cpu(creq->wIndex));
2363         pr_vdebug("creq->wLength      = %04x\n", le16_to_cpu(creq->wLength));
2364
2365         /*
2366          * Most requests directed to interface go through here
2367          * (notable exceptions are set/get interface) so we need to
2368          * handle them.  All other either handled by composite or
2369          * passed to usb_configuration->setup() (if one is set).  No
2370          * matter, we will handle requests directed to endpoint here
2371          * as well (as it's straightforward) but what to do with any
2372          * other request?
2373          */
2374         if (ffs->state != FFS_ACTIVE)
2375                 return -ENODEV;
2376
2377         switch (creq->bRequestType & USB_RECIP_MASK) {
2378         case USB_RECIP_INTERFACE:
2379                 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2380                 if (unlikely(ret < 0))
2381                         return ret;
2382                 break;
2383
2384         case USB_RECIP_ENDPOINT:
2385                 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2386                 if (unlikely(ret < 0))
2387                         return ret;
2388                 break;
2389
2390         default:
2391                 return -EOPNOTSUPP;
2392         }
2393
2394         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2395         ffs->ev.setup = *creq;
2396         ffs->ev.setup.wIndex = cpu_to_le16(ret);
2397         __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2398         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2399
2400         return 0;
2401 }
2402
2403 static void ffs_func_suspend(struct usb_function *f)
2404 {
2405         ENTER();
2406         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2407 }
2408
2409 static void ffs_func_resume(struct usb_function *f)
2410 {
2411         ENTER();
2412         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2413 }
2414
2415
2416 /* Endpoint and interface numbers reverse mapping ***************************/
2417
2418 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2419 {
2420         num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2421         return num ? num : -EDOM;
2422 }
2423
2424 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2425 {
2426         short *nums = func->interfaces_nums;
2427         unsigned count = func->ffs->interfaces_count;
2428
2429         for (; count; --count, ++nums) {
2430                 if (*nums >= 0 && *nums == intf)
2431                         return nums - func->interfaces_nums;
2432         }
2433
2434         return -EDOM;
2435 }
2436
2437
2438 /* Misc helper functions ****************************************************/
2439
2440 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2441 {
2442         return nonblock
2443                 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2444                 : mutex_lock_interruptible(mutex);
2445 }
2446
2447 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
2448 {
2449         char *data;
2450
2451         if (unlikely(!len))
2452                 return NULL;
2453
2454         data = kmalloc(len, GFP_KERNEL);
2455         if (unlikely(!data))
2456                 return ERR_PTR(-ENOMEM);
2457
2458         if (unlikely(__copy_from_user(data, buf, len))) {
2459                 kfree(data);
2460                 return ERR_PTR(-EFAULT);
2461         }
2462
2463         pr_vdebug("Buffer from user space:\n");
2464         ffs_dump_mem("", data, len);
2465
2466         return data;
2467 }