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