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