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