Merge remote-tracking branches 'asoc/fix/adsp', 'asoc/fix/arizona', 'asoc/fix/atmel...
[linux-drm-fsl-dcu.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         reinit_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         .llseek =       no_llseek,
731
732         .open =         ffs_ep0_open,
733         .write =        ffs_ep0_write,
734         .read =         ffs_ep0_read,
735         .release =      ffs_ep0_release,
736         .unlocked_ioctl =       ffs_ep0_ioctl,
737 };
738
739
740 /* "Normal" endpoints operations ********************************************/
741
742 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
743 {
744         ENTER();
745         if (likely(req->context)) {
746                 struct ffs_ep *ep = _ep->driver_data;
747                 ep->status = req->status ? req->status : req->actual;
748                 complete(req->context);
749         }
750 }
751
752 static ssize_t ffs_epfile_io(struct file *file,
753                              char __user *buf, size_t len, int read)
754 {
755         struct ffs_epfile *epfile = file->private_data;
756         struct ffs_ep *ep;
757         char *data = NULL;
758         ssize_t ret;
759         int halt;
760
761         goto first_try;
762         do {
763                 spin_unlock_irq(&epfile->ffs->eps_lock);
764                 mutex_unlock(&epfile->mutex);
765
766 first_try:
767                 /* Are we still active? */
768                 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
769                         ret = -ENODEV;
770                         goto error;
771                 }
772
773                 /* Wait for endpoint to be enabled */
774                 ep = epfile->ep;
775                 if (!ep) {
776                         if (file->f_flags & O_NONBLOCK) {
777                                 ret = -EAGAIN;
778                                 goto error;
779                         }
780
781                         if (wait_event_interruptible(epfile->wait,
782                                                      (ep = epfile->ep))) {
783                                 ret = -EINTR;
784                                 goto error;
785                         }
786                 }
787
788                 /* Do we halt? */
789                 halt = !read == !epfile->in;
790                 if (halt && epfile->isoc) {
791                         ret = -EINVAL;
792                         goto error;
793                 }
794
795                 /* Allocate & copy */
796                 if (!halt && !data) {
797                         data = kzalloc(len, GFP_KERNEL);
798                         if (unlikely(!data))
799                                 return -ENOMEM;
800
801                         if (!read &&
802                             unlikely(__copy_from_user(data, buf, len))) {
803                                 ret = -EFAULT;
804                                 goto error;
805                         }
806                 }
807
808                 /* We will be using request */
809                 ret = ffs_mutex_lock(&epfile->mutex,
810                                      file->f_flags & O_NONBLOCK);
811                 if (unlikely(ret))
812                         goto error;
813
814                 /*
815                  * We're called from user space, we can use _irq rather then
816                  * _irqsave
817                  */
818                 spin_lock_irq(&epfile->ffs->eps_lock);
819
820                 /*
821                  * While we were acquiring mutex endpoint got disabled
822                  * or changed?
823                  */
824         } while (unlikely(epfile->ep != ep));
825
826         /* Halt */
827         if (unlikely(halt)) {
828                 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
829                         usb_ep_set_halt(ep->ep);
830                 spin_unlock_irq(&epfile->ffs->eps_lock);
831                 ret = -EBADMSG;
832         } else {
833                 /* Fire the request */
834                 DECLARE_COMPLETION_ONSTACK(done);
835
836                 struct usb_request *req = ep->req;
837                 req->context  = &done;
838                 req->complete = ffs_epfile_io_complete;
839                 req->buf      = data;
840                 req->length   = len;
841
842                 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
843
844                 spin_unlock_irq(&epfile->ffs->eps_lock);
845
846                 if (unlikely(ret < 0)) {
847                         /* nop */
848                 } else if (unlikely(wait_for_completion_interruptible(&done))) {
849                         ret = -EINTR;
850                         usb_ep_dequeue(ep->ep, req);
851                 } else {
852                         ret = ep->status;
853                         if (read && ret > 0 &&
854                             unlikely(copy_to_user(buf, data, ret)))
855                                 ret = -EFAULT;
856                 }
857         }
858
859         mutex_unlock(&epfile->mutex);
860 error:
861         kfree(data);
862         return ret;
863 }
864
865 static ssize_t
866 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
867                  loff_t *ptr)
868 {
869         ENTER();
870
871         return ffs_epfile_io(file, (char __user *)buf, len, 0);
872 }
873
874 static ssize_t
875 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
876 {
877         ENTER();
878
879         return ffs_epfile_io(file, buf, len, 1);
880 }
881
882 static int
883 ffs_epfile_open(struct inode *inode, struct file *file)
884 {
885         struct ffs_epfile *epfile = inode->i_private;
886
887         ENTER();
888
889         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
890                 return -ENODEV;
891
892         file->private_data = epfile;
893         ffs_data_opened(epfile->ffs);
894
895         return 0;
896 }
897
898 static int
899 ffs_epfile_release(struct inode *inode, struct file *file)
900 {
901         struct ffs_epfile *epfile = inode->i_private;
902
903         ENTER();
904
905         ffs_data_closed(epfile->ffs);
906
907         return 0;
908 }
909
910 static long ffs_epfile_ioctl(struct file *file, unsigned code,
911                              unsigned long value)
912 {
913         struct ffs_epfile *epfile = file->private_data;
914         int ret;
915
916         ENTER();
917
918         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
919                 return -ENODEV;
920
921         spin_lock_irq(&epfile->ffs->eps_lock);
922         if (likely(epfile->ep)) {
923                 switch (code) {
924                 case FUNCTIONFS_FIFO_STATUS:
925                         ret = usb_ep_fifo_status(epfile->ep->ep);
926                         break;
927                 case FUNCTIONFS_FIFO_FLUSH:
928                         usb_ep_fifo_flush(epfile->ep->ep);
929                         ret = 0;
930                         break;
931                 case FUNCTIONFS_CLEAR_HALT:
932                         ret = usb_ep_clear_halt(epfile->ep->ep);
933                         break;
934                 case FUNCTIONFS_ENDPOINT_REVMAP:
935                         ret = epfile->ep->num;
936                         break;
937                 default:
938                         ret = -ENOTTY;
939                 }
940         } else {
941                 ret = -ENODEV;
942         }
943         spin_unlock_irq(&epfile->ffs->eps_lock);
944
945         return ret;
946 }
947
948 static const struct file_operations ffs_epfile_operations = {
949         .llseek =       no_llseek,
950
951         .open =         ffs_epfile_open,
952         .write =        ffs_epfile_write,
953         .read =         ffs_epfile_read,
954         .release =      ffs_epfile_release,
955         .unlocked_ioctl =       ffs_epfile_ioctl,
956 };
957
958
959 /* File system and super block operations ***********************************/
960
961 /*
962  * Mounting the file system creates a controller file, used first for
963  * function configuration then later for event monitoring.
964  */
965
966 static struct inode *__must_check
967 ffs_sb_make_inode(struct super_block *sb, void *data,
968                   const struct file_operations *fops,
969                   const struct inode_operations *iops,
970                   struct ffs_file_perms *perms)
971 {
972         struct inode *inode;
973
974         ENTER();
975
976         inode = new_inode(sb);
977
978         if (likely(inode)) {
979                 struct timespec current_time = CURRENT_TIME;
980
981                 inode->i_ino     = get_next_ino();
982                 inode->i_mode    = perms->mode;
983                 inode->i_uid     = perms->uid;
984                 inode->i_gid     = perms->gid;
985                 inode->i_atime   = current_time;
986                 inode->i_mtime   = current_time;
987                 inode->i_ctime   = current_time;
988                 inode->i_private = data;
989                 if (fops)
990                         inode->i_fop = fops;
991                 if (iops)
992                         inode->i_op  = iops;
993         }
994
995         return inode;
996 }
997
998 /* Create "regular" file */
999 static struct inode *ffs_sb_create_file(struct super_block *sb,
1000                                         const char *name, void *data,
1001                                         const struct file_operations *fops,
1002                                         struct dentry **dentry_p)
1003 {
1004         struct ffs_data *ffs = sb->s_fs_info;
1005         struct dentry   *dentry;
1006         struct inode    *inode;
1007
1008         ENTER();
1009
1010         dentry = d_alloc_name(sb->s_root, name);
1011         if (unlikely(!dentry))
1012                 return NULL;
1013
1014         inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1015         if (unlikely(!inode)) {
1016                 dput(dentry);
1017                 return NULL;
1018         }
1019
1020         d_add(dentry, inode);
1021         if (dentry_p)
1022                 *dentry_p = dentry;
1023
1024         return inode;
1025 }
1026
1027 /* Super block */
1028 static const struct super_operations ffs_sb_operations = {
1029         .statfs =       simple_statfs,
1030         .drop_inode =   generic_delete_inode,
1031 };
1032
1033 struct ffs_sb_fill_data {
1034         struct ffs_file_perms perms;
1035         umode_t root_mode;
1036         const char *dev_name;
1037         struct ffs_data *ffs_data;
1038 };
1039
1040 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1041 {
1042         struct ffs_sb_fill_data *data = _data;
1043         struct inode    *inode;
1044         struct ffs_data *ffs = data->ffs_data;
1045
1046         ENTER();
1047
1048         ffs->sb              = sb;
1049         data->ffs_data       = NULL;
1050         sb->s_fs_info        = ffs;
1051         sb->s_blocksize      = PAGE_CACHE_SIZE;
1052         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1053         sb->s_magic          = FUNCTIONFS_MAGIC;
1054         sb->s_op             = &ffs_sb_operations;
1055         sb->s_time_gran      = 1;
1056
1057         /* Root inode */
1058         data->perms.mode = data->root_mode;
1059         inode = ffs_sb_make_inode(sb, NULL,
1060                                   &simple_dir_operations,
1061                                   &simple_dir_inode_operations,
1062                                   &data->perms);
1063         sb->s_root = d_make_root(inode);
1064         if (unlikely(!sb->s_root))
1065                 return -ENOMEM;
1066
1067         /* EP0 file */
1068         if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1069                                          &ffs_ep0_operations, NULL)))
1070                 return -ENOMEM;
1071
1072         return 0;
1073 }
1074
1075 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1076 {
1077         ENTER();
1078
1079         if (!opts || !*opts)
1080                 return 0;
1081
1082         for (;;) {
1083                 unsigned long value;
1084                 char *eq, *comma;
1085
1086                 /* Option limit */
1087                 comma = strchr(opts, ',');
1088                 if (comma)
1089                         *comma = 0;
1090
1091                 /* Value limit */
1092                 eq = strchr(opts, '=');
1093                 if (unlikely(!eq)) {
1094                         pr_err("'=' missing in %s\n", opts);
1095                         return -EINVAL;
1096                 }
1097                 *eq = 0;
1098
1099                 /* Parse value */
1100                 if (kstrtoul(eq + 1, 0, &value)) {
1101                         pr_err("%s: invalid value: %s\n", opts, eq + 1);
1102                         return -EINVAL;
1103                 }
1104
1105                 /* Interpret option */
1106                 switch (eq - opts) {
1107                 case 5:
1108                         if (!memcmp(opts, "rmode", 5))
1109                                 data->root_mode  = (value & 0555) | S_IFDIR;
1110                         else if (!memcmp(opts, "fmode", 5))
1111                                 data->perms.mode = (value & 0666) | S_IFREG;
1112                         else
1113                                 goto invalid;
1114                         break;
1115
1116                 case 4:
1117                         if (!memcmp(opts, "mode", 4)) {
1118                                 data->root_mode  = (value & 0555) | S_IFDIR;
1119                                 data->perms.mode = (value & 0666) | S_IFREG;
1120                         } else {
1121                                 goto invalid;
1122                         }
1123                         break;
1124
1125                 case 3:
1126                         if (!memcmp(opts, "uid", 3)) {
1127                                 data->perms.uid = make_kuid(current_user_ns(), value);
1128                                 if (!uid_valid(data->perms.uid)) {
1129                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1130                                         return -EINVAL;
1131                                 }
1132                         } else if (!memcmp(opts, "gid", 3)) {
1133                                 data->perms.gid = make_kgid(current_user_ns(), value);
1134                                 if (!gid_valid(data->perms.gid)) {
1135                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1136                                         return -EINVAL;
1137                                 }
1138                         } else {
1139                                 goto invalid;
1140                         }
1141                         break;
1142
1143                 default:
1144 invalid:
1145                         pr_err("%s: invalid option\n", opts);
1146                         return -EINVAL;
1147                 }
1148
1149                 /* Next iteration */
1150                 if (!comma)
1151                         break;
1152                 opts = comma + 1;
1153         }
1154
1155         return 0;
1156 }
1157
1158 /* "mount -t functionfs dev_name /dev/function" ends up here */
1159
1160 static struct dentry *
1161 ffs_fs_mount(struct file_system_type *t, int flags,
1162               const char *dev_name, void *opts)
1163 {
1164         struct ffs_sb_fill_data data = {
1165                 .perms = {
1166                         .mode = S_IFREG | 0600,
1167                         .uid = GLOBAL_ROOT_UID,
1168                         .gid = GLOBAL_ROOT_GID,
1169                 },
1170                 .root_mode = S_IFDIR | 0500,
1171         };
1172         struct dentry *rv;
1173         int ret;
1174         void *ffs_dev;
1175         struct ffs_data *ffs;
1176
1177         ENTER();
1178
1179         ret = ffs_fs_parse_opts(&data, opts);
1180         if (unlikely(ret < 0))
1181                 return ERR_PTR(ret);
1182
1183         ffs = ffs_data_new();
1184         if (unlikely(!ffs))
1185                 return ERR_PTR(-ENOMEM);
1186         ffs->file_perms = data.perms;
1187
1188         ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1189         if (unlikely(!ffs->dev_name)) {
1190                 ffs_data_put(ffs);
1191                 return ERR_PTR(-ENOMEM);
1192         }
1193
1194         ffs_dev = functionfs_acquire_dev_callback(dev_name);
1195         if (IS_ERR(ffs_dev)) {
1196                 ffs_data_put(ffs);
1197                 return ERR_CAST(ffs_dev);
1198         }
1199         ffs->private_data = ffs_dev;
1200         data.ffs_data = ffs;
1201
1202         rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1203         if (IS_ERR(rv) && data.ffs_data) {
1204                 functionfs_release_dev_callback(data.ffs_data);
1205                 ffs_data_put(data.ffs_data);
1206         }
1207         return rv;
1208 }
1209
1210 static void
1211 ffs_fs_kill_sb(struct super_block *sb)
1212 {
1213         ENTER();
1214
1215         kill_litter_super(sb);
1216         if (sb->s_fs_info) {
1217                 functionfs_release_dev_callback(sb->s_fs_info);
1218                 ffs_data_put(sb->s_fs_info);
1219         }
1220 }
1221
1222 static struct file_system_type ffs_fs_type = {
1223         .owner          = THIS_MODULE,
1224         .name           = "functionfs",
1225         .mount          = ffs_fs_mount,
1226         .kill_sb        = ffs_fs_kill_sb,
1227 };
1228 MODULE_ALIAS_FS("functionfs");
1229
1230
1231 /* Driver's main init/cleanup functions *************************************/
1232
1233 static int functionfs_init(void)
1234 {
1235         int ret;
1236
1237         ENTER();
1238
1239         ret = register_filesystem(&ffs_fs_type);
1240         if (likely(!ret))
1241                 pr_info("file system registered\n");
1242         else
1243                 pr_err("failed registering file system (%d)\n", ret);
1244
1245         return ret;
1246 }
1247
1248 static void functionfs_cleanup(void)
1249 {
1250         ENTER();
1251
1252         pr_info("unloading\n");
1253         unregister_filesystem(&ffs_fs_type);
1254 }
1255
1256
1257 /* ffs_data and ffs_function construction and destruction code **************/
1258
1259 static void ffs_data_clear(struct ffs_data *ffs);
1260 static void ffs_data_reset(struct ffs_data *ffs);
1261
1262 static void ffs_data_get(struct ffs_data *ffs)
1263 {
1264         ENTER();
1265
1266         atomic_inc(&ffs->ref);
1267 }
1268
1269 static void ffs_data_opened(struct ffs_data *ffs)
1270 {
1271         ENTER();
1272
1273         atomic_inc(&ffs->ref);
1274         atomic_inc(&ffs->opened);
1275 }
1276
1277 static void ffs_data_put(struct ffs_data *ffs)
1278 {
1279         ENTER();
1280
1281         if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1282                 pr_info("%s(): freeing\n", __func__);
1283                 ffs_data_clear(ffs);
1284                 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1285                        waitqueue_active(&ffs->ep0req_completion.wait));
1286                 kfree(ffs->dev_name);
1287                 kfree(ffs);
1288         }
1289 }
1290
1291 static void ffs_data_closed(struct ffs_data *ffs)
1292 {
1293         ENTER();
1294
1295         if (atomic_dec_and_test(&ffs->opened)) {
1296                 ffs->state = FFS_CLOSING;
1297                 ffs_data_reset(ffs);
1298         }
1299
1300         ffs_data_put(ffs);
1301 }
1302
1303 static struct ffs_data *ffs_data_new(void)
1304 {
1305         struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1306         if (unlikely(!ffs))
1307                 return NULL;
1308
1309         ENTER();
1310
1311         atomic_set(&ffs->ref, 1);
1312         atomic_set(&ffs->opened, 0);
1313         ffs->state = FFS_READ_DESCRIPTORS;
1314         mutex_init(&ffs->mutex);
1315         spin_lock_init(&ffs->eps_lock);
1316         init_waitqueue_head(&ffs->ev.waitq);
1317         init_completion(&ffs->ep0req_completion);
1318
1319         /* XXX REVISIT need to update it in some places, or do we? */
1320         ffs->ev.can_stall = 1;
1321
1322         return ffs;
1323 }
1324
1325 static void ffs_data_clear(struct ffs_data *ffs)
1326 {
1327         ENTER();
1328
1329         if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1330                 functionfs_closed_callback(ffs);
1331
1332         BUG_ON(ffs->gadget);
1333
1334         if (ffs->epfiles)
1335                 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1336
1337         kfree(ffs->raw_descs);
1338         kfree(ffs->raw_strings);
1339         kfree(ffs->stringtabs);
1340 }
1341
1342 static void ffs_data_reset(struct ffs_data *ffs)
1343 {
1344         ENTER();
1345
1346         ffs_data_clear(ffs);
1347
1348         ffs->epfiles = NULL;
1349         ffs->raw_descs = NULL;
1350         ffs->raw_strings = NULL;
1351         ffs->stringtabs = NULL;
1352
1353         ffs->raw_descs_length = 0;
1354         ffs->raw_fs_descs_length = 0;
1355         ffs->fs_descs_count = 0;
1356         ffs->hs_descs_count = 0;
1357
1358         ffs->strings_count = 0;
1359         ffs->interfaces_count = 0;
1360         ffs->eps_count = 0;
1361
1362         ffs->ev.count = 0;
1363
1364         ffs->state = FFS_READ_DESCRIPTORS;
1365         ffs->setup_state = FFS_NO_SETUP;
1366         ffs->flags = 0;
1367 }
1368
1369
1370 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1371 {
1372         struct usb_gadget_strings **lang;
1373         int first_id;
1374
1375         ENTER();
1376
1377         if (WARN_ON(ffs->state != FFS_ACTIVE
1378                  || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1379                 return -EBADFD;
1380
1381         first_id = usb_string_ids_n(cdev, ffs->strings_count);
1382         if (unlikely(first_id < 0))
1383                 return first_id;
1384
1385         ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1386         if (unlikely(!ffs->ep0req))
1387                 return -ENOMEM;
1388         ffs->ep0req->complete = ffs_ep0_complete;
1389         ffs->ep0req->context = ffs;
1390
1391         lang = ffs->stringtabs;
1392         for (lang = ffs->stringtabs; *lang; ++lang) {
1393                 struct usb_string *str = (*lang)->strings;
1394                 int id = first_id;
1395                 for (; str->s; ++id, ++str)
1396                         str->id = id;
1397         }
1398
1399         ffs->gadget = cdev->gadget;
1400         ffs_data_get(ffs);
1401         return 0;
1402 }
1403
1404 static void functionfs_unbind(struct ffs_data *ffs)
1405 {
1406         ENTER();
1407
1408         if (!WARN_ON(!ffs->gadget)) {
1409                 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1410                 ffs->ep0req = NULL;
1411                 ffs->gadget = NULL;
1412                 clear_bit(FFS_FL_BOUND, &ffs->flags);
1413                 ffs_data_put(ffs);
1414         }
1415 }
1416
1417 static int ffs_epfiles_create(struct ffs_data *ffs)
1418 {
1419         struct ffs_epfile *epfile, *epfiles;
1420         unsigned i, count;
1421
1422         ENTER();
1423
1424         count = ffs->eps_count;
1425         epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1426         if (!epfiles)
1427                 return -ENOMEM;
1428
1429         epfile = epfiles;
1430         for (i = 1; i <= count; ++i, ++epfile) {
1431                 epfile->ffs = ffs;
1432                 mutex_init(&epfile->mutex);
1433                 init_waitqueue_head(&epfile->wait);
1434                 sprintf(epfiles->name, "ep%u",  i);
1435                 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1436                                                  &ffs_epfile_operations,
1437                                                  &epfile->dentry))) {
1438                         ffs_epfiles_destroy(epfiles, i - 1);
1439                         return -ENOMEM;
1440                 }
1441         }
1442
1443         ffs->epfiles = epfiles;
1444         return 0;
1445 }
1446
1447 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1448 {
1449         struct ffs_epfile *epfile = epfiles;
1450
1451         ENTER();
1452
1453         for (; count; --count, ++epfile) {
1454                 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1455                        waitqueue_active(&epfile->wait));
1456                 if (epfile->dentry) {
1457                         d_delete(epfile->dentry);
1458                         dput(epfile->dentry);
1459                         epfile->dentry = NULL;
1460                 }
1461         }
1462
1463         kfree(epfiles);
1464 }
1465
1466 static int functionfs_bind_config(struct usb_composite_dev *cdev,
1467                                   struct usb_configuration *c,
1468                                   struct ffs_data *ffs)
1469 {
1470         struct ffs_function *func;
1471         int ret;
1472
1473         ENTER();
1474
1475         func = kzalloc(sizeof *func, GFP_KERNEL);
1476         if (unlikely(!func))
1477                 return -ENOMEM;
1478
1479         func->function.name    = "Function FS Gadget";
1480         func->function.strings = ffs->stringtabs;
1481
1482         func->function.bind    = ffs_func_bind;
1483         func->function.unbind  = ffs_func_unbind;
1484         func->function.set_alt = ffs_func_set_alt;
1485         func->function.disable = ffs_func_disable;
1486         func->function.setup   = ffs_func_setup;
1487         func->function.suspend = ffs_func_suspend;
1488         func->function.resume  = ffs_func_resume;
1489
1490         func->conf   = c;
1491         func->gadget = cdev->gadget;
1492         func->ffs = ffs;
1493         ffs_data_get(ffs);
1494
1495         ret = usb_add_function(c, &func->function);
1496         if (unlikely(ret))
1497                 ffs_func_free(func);
1498
1499         return ret;
1500 }
1501
1502 static void ffs_func_free(struct ffs_function *func)
1503 {
1504         struct ffs_ep *ep         = func->eps;
1505         unsigned count            = func->ffs->eps_count;
1506         unsigned long flags;
1507
1508         ENTER();
1509
1510         /* cleanup after autoconfig */
1511         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1512         do {
1513                 if (ep->ep && ep->req)
1514                         usb_ep_free_request(ep->ep, ep->req);
1515                 ep->req = NULL;
1516                 ++ep;
1517         } while (--count);
1518         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1519
1520         ffs_data_put(func->ffs);
1521
1522         kfree(func->eps);
1523         /*
1524          * eps and interfaces_nums are allocated in the same chunk so
1525          * only one free is required.  Descriptors are also allocated
1526          * in the same chunk.
1527          */
1528
1529         kfree(func);
1530 }
1531
1532 static void ffs_func_eps_disable(struct ffs_function *func)
1533 {
1534         struct ffs_ep *ep         = func->eps;
1535         struct ffs_epfile *epfile = func->ffs->epfiles;
1536         unsigned count            = func->ffs->eps_count;
1537         unsigned long flags;
1538
1539         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1540         do {
1541                 /* pending requests get nuked */
1542                 if (likely(ep->ep))
1543                         usb_ep_disable(ep->ep);
1544                 epfile->ep = NULL;
1545
1546                 ++ep;
1547                 ++epfile;
1548         } while (--count);
1549         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1550 }
1551
1552 static int ffs_func_eps_enable(struct ffs_function *func)
1553 {
1554         struct ffs_data *ffs      = func->ffs;
1555         struct ffs_ep *ep         = func->eps;
1556         struct ffs_epfile *epfile = ffs->epfiles;
1557         unsigned count            = ffs->eps_count;
1558         unsigned long flags;
1559         int ret = 0;
1560
1561         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1562         do {
1563                 struct usb_endpoint_descriptor *ds;
1564                 ds = ep->descs[ep->descs[1] ? 1 : 0];
1565
1566                 ep->ep->driver_data = ep;
1567                 ep->ep->desc = ds;
1568                 ret = usb_ep_enable(ep->ep);
1569                 if (likely(!ret)) {
1570                         epfile->ep = ep;
1571                         epfile->in = usb_endpoint_dir_in(ds);
1572                         epfile->isoc = usb_endpoint_xfer_isoc(ds);
1573                 } else {
1574                         break;
1575                 }
1576
1577                 wake_up(&epfile->wait);
1578
1579                 ++ep;
1580                 ++epfile;
1581         } while (--count);
1582         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1583
1584         return ret;
1585 }
1586
1587
1588 /* Parsing and building descriptors and strings *****************************/
1589
1590 /*
1591  * This validates if data pointed by data is a valid USB descriptor as
1592  * well as record how many interfaces, endpoints and strings are
1593  * required by given configuration.  Returns address after the
1594  * descriptor or NULL if data is invalid.
1595  */
1596
1597 enum ffs_entity_type {
1598         FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1599 };
1600
1601 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1602                                    u8 *valuep,
1603                                    struct usb_descriptor_header *desc,
1604                                    void *priv);
1605
1606 static int __must_check ffs_do_desc(char *data, unsigned len,
1607                                     ffs_entity_callback entity, void *priv)
1608 {
1609         struct usb_descriptor_header *_ds = (void *)data;
1610         u8 length;
1611         int ret;
1612
1613         ENTER();
1614
1615         /* At least two bytes are required: length and type */
1616         if (len < 2) {
1617                 pr_vdebug("descriptor too short\n");
1618                 return -EINVAL;
1619         }
1620
1621         /* If we have at least as many bytes as the descriptor takes? */
1622         length = _ds->bLength;
1623         if (len < length) {
1624                 pr_vdebug("descriptor longer then available data\n");
1625                 return -EINVAL;
1626         }
1627
1628 #define __entity_check_INTERFACE(val)  1
1629 #define __entity_check_STRING(val)     (val)
1630 #define __entity_check_ENDPOINT(val)   ((val) & USB_ENDPOINT_NUMBER_MASK)
1631 #define __entity(type, val) do {                                        \
1632                 pr_vdebug("entity " #type "(%02x)\n", (val));           \
1633                 if (unlikely(!__entity_check_ ##type(val))) {           \
1634                         pr_vdebug("invalid entity's value\n");          \
1635                         return -EINVAL;                                 \
1636                 }                                                       \
1637                 ret = entity(FFS_ ##type, &val, _ds, priv);             \
1638                 if (unlikely(ret < 0)) {                                \
1639                         pr_debug("entity " #type "(%02x); ret = %d\n",  \
1640                                  (val), ret);                           \
1641                         return ret;                                     \
1642                 }                                                       \
1643         } while (0)
1644
1645         /* Parse descriptor depending on type. */
1646         switch (_ds->bDescriptorType) {
1647         case USB_DT_DEVICE:
1648         case USB_DT_CONFIG:
1649         case USB_DT_STRING:
1650         case USB_DT_DEVICE_QUALIFIER:
1651                 /* function can't have any of those */
1652                 pr_vdebug("descriptor reserved for gadget: %d\n",
1653                       _ds->bDescriptorType);
1654                 return -EINVAL;
1655
1656         case USB_DT_INTERFACE: {
1657                 struct usb_interface_descriptor *ds = (void *)_ds;
1658                 pr_vdebug("interface descriptor\n");
1659                 if (length != sizeof *ds)
1660                         goto inv_length;
1661
1662                 __entity(INTERFACE, ds->bInterfaceNumber);
1663                 if (ds->iInterface)
1664                         __entity(STRING, ds->iInterface);
1665         }
1666                 break;
1667
1668         case USB_DT_ENDPOINT: {
1669                 struct usb_endpoint_descriptor *ds = (void *)_ds;
1670                 pr_vdebug("endpoint descriptor\n");
1671                 if (length != USB_DT_ENDPOINT_SIZE &&
1672                     length != USB_DT_ENDPOINT_AUDIO_SIZE)
1673                         goto inv_length;
1674                 __entity(ENDPOINT, ds->bEndpointAddress);
1675         }
1676                 break;
1677
1678         case HID_DT_HID:
1679                 pr_vdebug("hid descriptor\n");
1680                 if (length != sizeof(struct hid_descriptor))
1681                         goto inv_length;
1682                 break;
1683
1684         case USB_DT_OTG:
1685                 if (length != sizeof(struct usb_otg_descriptor))
1686                         goto inv_length;
1687                 break;
1688
1689         case USB_DT_INTERFACE_ASSOCIATION: {
1690                 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1691                 pr_vdebug("interface association descriptor\n");
1692                 if (length != sizeof *ds)
1693                         goto inv_length;
1694                 if (ds->iFunction)
1695                         __entity(STRING, ds->iFunction);
1696         }
1697                 break;
1698
1699         case USB_DT_OTHER_SPEED_CONFIG:
1700         case USB_DT_INTERFACE_POWER:
1701         case USB_DT_DEBUG:
1702         case USB_DT_SECURITY:
1703         case USB_DT_CS_RADIO_CONTROL:
1704                 /* TODO */
1705                 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1706                 return -EINVAL;
1707
1708         default:
1709                 /* We should never be here */
1710                 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1711                 return -EINVAL;
1712
1713 inv_length:
1714                 pr_vdebug("invalid length: %d (descriptor %d)\n",
1715                           _ds->bLength, _ds->bDescriptorType);
1716                 return -EINVAL;
1717         }
1718
1719 #undef __entity
1720 #undef __entity_check_DESCRIPTOR
1721 #undef __entity_check_INTERFACE
1722 #undef __entity_check_STRING
1723 #undef __entity_check_ENDPOINT
1724
1725         return length;
1726 }
1727
1728 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1729                                      ffs_entity_callback entity, void *priv)
1730 {
1731         const unsigned _len = len;
1732         unsigned long num = 0;
1733
1734         ENTER();
1735
1736         for (;;) {
1737                 int ret;
1738
1739                 if (num == count)
1740                         data = NULL;
1741
1742                 /* Record "descriptor" entity */
1743                 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1744                 if (unlikely(ret < 0)) {
1745                         pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1746                                  num, ret);
1747                         return ret;
1748                 }
1749
1750                 if (!data)
1751                         return _len - len;
1752
1753                 ret = ffs_do_desc(data, len, entity, priv);
1754                 if (unlikely(ret < 0)) {
1755                         pr_debug("%s returns %d\n", __func__, ret);
1756                         return ret;
1757                 }
1758
1759                 len -= ret;
1760                 data += ret;
1761                 ++num;
1762         }
1763 }
1764
1765 static int __ffs_data_do_entity(enum ffs_entity_type type,
1766                                 u8 *valuep, struct usb_descriptor_header *desc,
1767                                 void *priv)
1768 {
1769         struct ffs_data *ffs = priv;
1770
1771         ENTER();
1772
1773         switch (type) {
1774         case FFS_DESCRIPTOR:
1775                 break;
1776
1777         case FFS_INTERFACE:
1778                 /*
1779                  * Interfaces are indexed from zero so if we
1780                  * encountered interface "n" then there are at least
1781                  * "n+1" interfaces.
1782                  */
1783                 if (*valuep >= ffs->interfaces_count)
1784                         ffs->interfaces_count = *valuep + 1;
1785                 break;
1786
1787         case FFS_STRING:
1788                 /*
1789                  * Strings are indexed from 1 (0 is magic ;) reserved
1790                  * for languages list or some such)
1791                  */
1792                 if (*valuep > ffs->strings_count)
1793                         ffs->strings_count = *valuep;
1794                 break;
1795
1796         case FFS_ENDPOINT:
1797                 /* Endpoints are indexed from 1 as well. */
1798                 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1799                         ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1800                 break;
1801         }
1802
1803         return 0;
1804 }
1805
1806 static int __ffs_data_got_descs(struct ffs_data *ffs,
1807                                 char *const _data, size_t len)
1808 {
1809         unsigned fs_count, hs_count;
1810         int fs_len, ret = -EINVAL;
1811         char *data = _data;
1812
1813         ENTER();
1814
1815         if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
1816                      get_unaligned_le32(data + 4) != len))
1817                 goto error;
1818         fs_count = get_unaligned_le32(data +  8);
1819         hs_count = get_unaligned_le32(data + 12);
1820
1821         if (!fs_count && !hs_count)
1822                 goto einval;
1823
1824         data += 16;
1825         len  -= 16;
1826
1827         if (likely(fs_count)) {
1828                 fs_len = ffs_do_descs(fs_count, data, len,
1829                                       __ffs_data_do_entity, ffs);
1830                 if (unlikely(fs_len < 0)) {
1831                         ret = fs_len;
1832                         goto error;
1833                 }
1834
1835                 data += fs_len;
1836                 len  -= fs_len;
1837         } else {
1838                 fs_len = 0;
1839         }
1840
1841         if (likely(hs_count)) {
1842                 ret = ffs_do_descs(hs_count, data, len,
1843                                    __ffs_data_do_entity, ffs);
1844                 if (unlikely(ret < 0))
1845                         goto error;
1846         } else {
1847                 ret = 0;
1848         }
1849
1850         if (unlikely(len != ret))
1851                 goto einval;
1852
1853         ffs->raw_fs_descs_length = fs_len;
1854         ffs->raw_descs_length    = fs_len + ret;
1855         ffs->raw_descs           = _data;
1856         ffs->fs_descs_count      = fs_count;
1857         ffs->hs_descs_count      = hs_count;
1858
1859         return 0;
1860
1861 einval:
1862         ret = -EINVAL;
1863 error:
1864         kfree(_data);
1865         return ret;
1866 }
1867
1868 static int __ffs_data_got_strings(struct ffs_data *ffs,
1869                                   char *const _data, size_t len)
1870 {
1871         u32 str_count, needed_count, lang_count;
1872         struct usb_gadget_strings **stringtabs, *t;
1873         struct usb_string *strings, *s;
1874         const char *data = _data;
1875
1876         ENTER();
1877
1878         if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1879                      get_unaligned_le32(data + 4) != len))
1880                 goto error;
1881         str_count  = get_unaligned_le32(data + 8);
1882         lang_count = get_unaligned_le32(data + 12);
1883
1884         /* if one is zero the other must be zero */
1885         if (unlikely(!str_count != !lang_count))
1886                 goto error;
1887
1888         /* Do we have at least as many strings as descriptors need? */
1889         needed_count = ffs->strings_count;
1890         if (unlikely(str_count < needed_count))
1891                 goto error;
1892
1893         /*
1894          * If we don't need any strings just return and free all
1895          * memory.
1896          */
1897         if (!needed_count) {
1898                 kfree(_data);
1899                 return 0;
1900         }
1901
1902         /* Allocate everything in one chunk so there's less maintenance. */
1903         {
1904                 struct {
1905                         struct usb_gadget_strings *stringtabs[lang_count + 1];
1906                         struct usb_gadget_strings stringtab[lang_count];
1907                         struct usb_string strings[lang_count*(needed_count+1)];
1908                 } *d;
1909                 unsigned i = 0;
1910
1911                 d = kmalloc(sizeof *d, GFP_KERNEL);
1912                 if (unlikely(!d)) {
1913                         kfree(_data);
1914                         return -ENOMEM;
1915                 }
1916
1917                 stringtabs = d->stringtabs;
1918                 t = d->stringtab;
1919                 i = lang_count;
1920                 do {
1921                         *stringtabs++ = t++;
1922                 } while (--i);
1923                 *stringtabs = NULL;
1924
1925                 stringtabs = d->stringtabs;
1926                 t = d->stringtab;
1927                 s = d->strings;
1928                 strings = s;
1929         }
1930
1931         /* For each language */
1932         data += 16;
1933         len -= 16;
1934
1935         do { /* lang_count > 0 so we can use do-while */
1936                 unsigned needed = needed_count;
1937
1938                 if (unlikely(len < 3))
1939                         goto error_free;
1940                 t->language = get_unaligned_le16(data);
1941                 t->strings  = s;
1942                 ++t;
1943
1944                 data += 2;
1945                 len -= 2;
1946
1947                 /* For each string */
1948                 do { /* str_count > 0 so we can use do-while */
1949                         size_t length = strnlen(data, len);
1950
1951                         if (unlikely(length == len))
1952                                 goto error_free;
1953
1954                         /*
1955                          * User may provide more strings then we need,
1956                          * if that's the case we simply ignore the
1957                          * rest
1958                          */
1959                         if (likely(needed)) {
1960                                 /*
1961                                  * s->id will be set while adding
1962                                  * function to configuration so for
1963                                  * now just leave garbage here.
1964                                  */
1965                                 s->s = data;
1966                                 --needed;
1967                                 ++s;
1968                         }
1969
1970                         data += length + 1;
1971                         len -= length + 1;
1972                 } while (--str_count);
1973
1974                 s->id = 0;   /* terminator */
1975                 s->s = NULL;
1976                 ++s;
1977
1978         } while (--lang_count);
1979
1980         /* Some garbage left? */
1981         if (unlikely(len))
1982                 goto error_free;
1983
1984         /* Done! */
1985         ffs->stringtabs = stringtabs;
1986         ffs->raw_strings = _data;
1987
1988         return 0;
1989
1990 error_free:
1991         kfree(stringtabs);
1992 error:
1993         kfree(_data);
1994         return -EINVAL;
1995 }
1996
1997
1998 /* Events handling and management *******************************************/
1999
2000 static void __ffs_event_add(struct ffs_data *ffs,
2001                             enum usb_functionfs_event_type type)
2002 {
2003         enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2004         int neg = 0;
2005
2006         /*
2007          * Abort any unhandled setup
2008          *
2009          * We do not need to worry about some cmpxchg() changing value
2010          * of ffs->setup_state without holding the lock because when
2011          * state is FFS_SETUP_PENDING cmpxchg() in several places in
2012          * the source does nothing.
2013          */
2014         if (ffs->setup_state == FFS_SETUP_PENDING)
2015                 ffs->setup_state = FFS_SETUP_CANCELED;
2016
2017         switch (type) {
2018         case FUNCTIONFS_RESUME:
2019                 rem_type2 = FUNCTIONFS_SUSPEND;
2020                 /* FALL THROUGH */
2021         case FUNCTIONFS_SUSPEND:
2022         case FUNCTIONFS_SETUP:
2023                 rem_type1 = type;
2024                 /* Discard all similar events */
2025                 break;
2026
2027         case FUNCTIONFS_BIND:
2028         case FUNCTIONFS_UNBIND:
2029         case FUNCTIONFS_DISABLE:
2030         case FUNCTIONFS_ENABLE:
2031                 /* Discard everything other then power management. */
2032                 rem_type1 = FUNCTIONFS_SUSPEND;
2033                 rem_type2 = FUNCTIONFS_RESUME;
2034                 neg = 1;
2035                 break;
2036
2037         default:
2038                 BUG();
2039         }
2040
2041         {
2042                 u8 *ev  = ffs->ev.types, *out = ev;
2043                 unsigned n = ffs->ev.count;
2044                 for (; n; --n, ++ev)
2045                         if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2046                                 *out++ = *ev;
2047                         else
2048                                 pr_vdebug("purging event %d\n", *ev);
2049                 ffs->ev.count = out - ffs->ev.types;
2050         }
2051
2052         pr_vdebug("adding event %d\n", type);
2053         ffs->ev.types[ffs->ev.count++] = type;
2054         wake_up_locked(&ffs->ev.waitq);
2055 }
2056
2057 static void ffs_event_add(struct ffs_data *ffs,
2058                           enum usb_functionfs_event_type type)
2059 {
2060         unsigned long flags;
2061         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2062         __ffs_event_add(ffs, type);
2063         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2064 }
2065
2066
2067 /* Bind/unbind USB function hooks *******************************************/
2068
2069 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2070                                     struct usb_descriptor_header *desc,
2071                                     void *priv)
2072 {
2073         struct usb_endpoint_descriptor *ds = (void *)desc;
2074         struct ffs_function *func = priv;
2075         struct ffs_ep *ffs_ep;
2076
2077         /*
2078          * If hs_descriptors is not NULL then we are reading hs
2079          * descriptors now
2080          */
2081         const int isHS = func->function.hs_descriptors != NULL;
2082         unsigned idx;
2083
2084         if (type != FFS_DESCRIPTOR)
2085                 return 0;
2086
2087         if (isHS)
2088                 func->function.hs_descriptors[(long)valuep] = desc;
2089         else
2090                 func->function.fs_descriptors[(long)valuep]    = desc;
2091
2092         if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2093                 return 0;
2094
2095         idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2096         ffs_ep = func->eps + idx;
2097
2098         if (unlikely(ffs_ep->descs[isHS])) {
2099                 pr_vdebug("two %sspeed descriptors for EP %d\n",
2100                           isHS ? "high" : "full",
2101                           ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2102                 return -EINVAL;
2103         }
2104         ffs_ep->descs[isHS] = ds;
2105
2106         ffs_dump_mem(": Original  ep desc", ds, ds->bLength);
2107         if (ffs_ep->ep) {
2108                 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2109                 if (!ds->wMaxPacketSize)
2110                         ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2111         } else {
2112                 struct usb_request *req;
2113                 struct usb_ep *ep;
2114
2115                 pr_vdebug("autoconfig\n");
2116                 ep = usb_ep_autoconfig(func->gadget, ds);
2117                 if (unlikely(!ep))
2118                         return -ENOTSUPP;
2119                 ep->driver_data = func->eps + idx;
2120
2121                 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2122                 if (unlikely(!req))
2123                         return -ENOMEM;
2124
2125                 ffs_ep->ep  = ep;
2126                 ffs_ep->req = req;
2127                 func->eps_revmap[ds->bEndpointAddress &
2128                                  USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2129         }
2130         ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2131
2132         return 0;
2133 }
2134
2135 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2136                                    struct usb_descriptor_header *desc,
2137                                    void *priv)
2138 {
2139         struct ffs_function *func = priv;
2140         unsigned idx;
2141         u8 newValue;
2142
2143         switch (type) {
2144         default:
2145         case FFS_DESCRIPTOR:
2146                 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2147                 return 0;
2148
2149         case FFS_INTERFACE:
2150                 idx = *valuep;
2151                 if (func->interfaces_nums[idx] < 0) {
2152                         int id = usb_interface_id(func->conf, &func->function);
2153                         if (unlikely(id < 0))
2154                                 return id;
2155                         func->interfaces_nums[idx] = id;
2156                 }
2157                 newValue = func->interfaces_nums[idx];
2158                 break;
2159
2160         case FFS_STRING:
2161                 /* String' IDs are allocated when fsf_data is bound to cdev */
2162                 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2163                 break;
2164
2165         case FFS_ENDPOINT:
2166                 /*
2167                  * USB_DT_ENDPOINT are handled in
2168                  * __ffs_func_bind_do_descs().
2169                  */
2170                 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2171                         return 0;
2172
2173                 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2174                 if (unlikely(!func->eps[idx].ep))
2175                         return -EINVAL;
2176
2177                 {
2178                         struct usb_endpoint_descriptor **descs;
2179                         descs = func->eps[idx].descs;
2180                         newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2181                 }
2182                 break;
2183         }
2184
2185         pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2186         *valuep = newValue;
2187         return 0;
2188 }
2189
2190 static int ffs_func_bind(struct usb_configuration *c,
2191                          struct usb_function *f)
2192 {
2193         struct ffs_function *func = ffs_func_from_usb(f);
2194         struct ffs_data *ffs = func->ffs;
2195
2196         const int full = !!func->ffs->fs_descs_count;
2197         const int high = gadget_is_dualspeed(func->gadget) &&
2198                 func->ffs->hs_descs_count;
2199
2200         int ret;
2201
2202         /* Make it a single chunk, less management later on */
2203         struct {
2204                 struct ffs_ep eps[ffs->eps_count];
2205                 struct usb_descriptor_header
2206                         *fs_descs[full ? ffs->fs_descs_count + 1 : 0];
2207                 struct usb_descriptor_header
2208                         *hs_descs[high ? ffs->hs_descs_count + 1 : 0];
2209                 short inums[ffs->interfaces_count];
2210                 char raw_descs[high ? ffs->raw_descs_length
2211                                     : ffs->raw_fs_descs_length];
2212         } *data;
2213
2214         ENTER();
2215
2216         /* Only high speed but not supported by gadget? */
2217         if (unlikely(!(full | high)))
2218                 return -ENOTSUPP;
2219
2220         /* Allocate */
2221         data = kmalloc(sizeof *data, GFP_KERNEL);
2222         if (unlikely(!data))
2223                 return -ENOMEM;
2224
2225         /* Zero */
2226         memset(data->eps, 0, sizeof data->eps);
2227         memcpy(data->raw_descs, ffs->raw_descs + 16, sizeof data->raw_descs);
2228         memset(data->inums, 0xff, sizeof data->inums);
2229         for (ret = ffs->eps_count; ret; --ret)
2230                 data->eps[ret].num = -1;
2231
2232         /* Save pointers */
2233         func->eps             = data->eps;
2234         func->interfaces_nums = data->inums;
2235
2236         /*
2237          * Go through all the endpoint descriptors and allocate
2238          * endpoints first, so that later we can rewrite the endpoint
2239          * numbers without worrying that it may be described later on.
2240          */
2241         if (likely(full)) {
2242                 func->function.fs_descriptors = data->fs_descs;
2243                 ret = ffs_do_descs(ffs->fs_descs_count,
2244                                    data->raw_descs,
2245                                    sizeof data->raw_descs,
2246                                    __ffs_func_bind_do_descs, func);
2247                 if (unlikely(ret < 0))
2248                         goto error;
2249         } else {
2250                 ret = 0;
2251         }
2252
2253         if (likely(high)) {
2254                 func->function.hs_descriptors = data->hs_descs;
2255                 ret = ffs_do_descs(ffs->hs_descs_count,
2256                                    data->raw_descs + ret,
2257                                    (sizeof data->raw_descs) - ret,
2258                                    __ffs_func_bind_do_descs, func);
2259                 if (unlikely(ret < 0))
2260                         goto error;
2261         }
2262
2263         /*
2264          * Now handle interface numbers allocation and interface and
2265          * endpoint numbers rewriting.  We can do that in one go
2266          * now.
2267          */
2268         ret = ffs_do_descs(ffs->fs_descs_count +
2269                            (high ? ffs->hs_descs_count : 0),
2270                            data->raw_descs, sizeof data->raw_descs,
2271                            __ffs_func_bind_do_nums, func);
2272         if (unlikely(ret < 0))
2273                 goto error;
2274
2275         /* And we're done */
2276         ffs_event_add(ffs, FUNCTIONFS_BIND);
2277         return 0;
2278
2279 error:
2280         /* XXX Do we need to release all claimed endpoints here? */
2281         return ret;
2282 }
2283
2284
2285 /* Other USB function hooks *************************************************/
2286
2287 static void ffs_func_unbind(struct usb_configuration *c,
2288                             struct usb_function *f)
2289 {
2290         struct ffs_function *func = ffs_func_from_usb(f);
2291         struct ffs_data *ffs = func->ffs;
2292
2293         ENTER();
2294
2295         if (ffs->func == func) {
2296                 ffs_func_eps_disable(func);
2297                 ffs->func = NULL;
2298         }
2299
2300         ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2301
2302         ffs_func_free(func);
2303 }
2304
2305 static int ffs_func_set_alt(struct usb_function *f,
2306                             unsigned interface, unsigned alt)
2307 {
2308         struct ffs_function *func = ffs_func_from_usb(f);
2309         struct ffs_data *ffs = func->ffs;
2310         int ret = 0, intf;
2311
2312         if (alt != (unsigned)-1) {
2313                 intf = ffs_func_revmap_intf(func, interface);
2314                 if (unlikely(intf < 0))
2315                         return intf;
2316         }
2317
2318         if (ffs->func)
2319                 ffs_func_eps_disable(ffs->func);
2320
2321         if (ffs->state != FFS_ACTIVE)
2322                 return -ENODEV;
2323
2324         if (alt == (unsigned)-1) {
2325                 ffs->func = NULL;
2326                 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2327                 return 0;
2328         }
2329
2330         ffs->func = func;
2331         ret = ffs_func_eps_enable(func);
2332         if (likely(ret >= 0))
2333                 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2334         return ret;
2335 }
2336
2337 static void ffs_func_disable(struct usb_function *f)
2338 {
2339         ffs_func_set_alt(f, 0, (unsigned)-1);
2340 }
2341
2342 static int ffs_func_setup(struct usb_function *f,
2343                           const struct usb_ctrlrequest *creq)
2344 {
2345         struct ffs_function *func = ffs_func_from_usb(f);
2346         struct ffs_data *ffs = func->ffs;
2347         unsigned long flags;
2348         int ret;
2349
2350         ENTER();
2351
2352         pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2353         pr_vdebug("creq->bRequest     = %02x\n", creq->bRequest);
2354         pr_vdebug("creq->wValue       = %04x\n", le16_to_cpu(creq->wValue));
2355         pr_vdebug("creq->wIndex       = %04x\n", le16_to_cpu(creq->wIndex));
2356         pr_vdebug("creq->wLength      = %04x\n", le16_to_cpu(creq->wLength));
2357
2358         /*
2359          * Most requests directed to interface go through here
2360          * (notable exceptions are set/get interface) so we need to
2361          * handle them.  All other either handled by composite or
2362          * passed to usb_configuration->setup() (if one is set).  No
2363          * matter, we will handle requests directed to endpoint here
2364          * as well (as it's straightforward) but what to do with any
2365          * other request?
2366          */
2367         if (ffs->state != FFS_ACTIVE)
2368                 return -ENODEV;
2369
2370         switch (creq->bRequestType & USB_RECIP_MASK) {
2371         case USB_RECIP_INTERFACE:
2372                 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2373                 if (unlikely(ret < 0))
2374                         return ret;
2375                 break;
2376
2377         case USB_RECIP_ENDPOINT:
2378                 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2379                 if (unlikely(ret < 0))
2380                         return ret;
2381                 break;
2382
2383         default:
2384                 return -EOPNOTSUPP;
2385         }
2386
2387         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2388         ffs->ev.setup = *creq;
2389         ffs->ev.setup.wIndex = cpu_to_le16(ret);
2390         __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2391         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2392
2393         return 0;
2394 }
2395
2396 static void ffs_func_suspend(struct usb_function *f)
2397 {
2398         ENTER();
2399         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2400 }
2401
2402 static void ffs_func_resume(struct usb_function *f)
2403 {
2404         ENTER();
2405         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2406 }
2407
2408
2409 /* Endpoint and interface numbers reverse mapping ***************************/
2410
2411 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2412 {
2413         num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2414         return num ? num : -EDOM;
2415 }
2416
2417 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2418 {
2419         short *nums = func->interfaces_nums;
2420         unsigned count = func->ffs->interfaces_count;
2421
2422         for (; count; --count, ++nums) {
2423                 if (*nums >= 0 && *nums == intf)
2424                         return nums - func->interfaces_nums;
2425         }
2426
2427         return -EDOM;
2428 }
2429
2430
2431 /* Misc helper functions ****************************************************/
2432
2433 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2434 {
2435         return nonblock
2436                 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2437                 : mutex_lock_interruptible(mutex);
2438 }
2439
2440 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
2441 {
2442         char *data;
2443
2444         if (unlikely(!len))
2445                 return NULL;
2446
2447         data = kmalloc(len, GFP_KERNEL);
2448         if (unlikely(!data))
2449                 return ERR_PTR(-ENOMEM);
2450
2451         if (unlikely(__copy_from_user(data, buf, len))) {
2452                 kfree(data);
2453                 return ERR_PTR(-EFAULT);
2454         }
2455
2456         pr_vdebug("Buffer from user space:\n");
2457         ffs_dump_mem("", data, len);
2458
2459         return data;
2460 }