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