]> git.karo-electronics.de Git - linux-beck.git/blob - drivers/usb/gadget/f_fs.c
phy: ti-pipe3: Add SATA compatible to Documentation binding
[linux-beck.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, [2]: super speed */
138         struct usb_endpoint_descriptor  *descs[3];
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
843                                  * here.  Since data_len (i.e. req->length) may
844                                  * be bigger than len (after being rounded up
845                                  * to maxpacketsize), we may end up with more
846                                  * data then user space has space for.
847                                  */
848                                 ret = ep->status;
849                                 if (io_data->read && ret > 0) {
850                                         ret = min_t(size_t, ret, io_data->len);
851
852                                         if (unlikely(copy_to_user(io_data->buf,
853                                                 data, ret)))
854                                                 ret = -EFAULT;
855                                 }
856                         }
857                         kfree(data);
858                 }
859         }
860
861         mutex_unlock(&epfile->mutex);
862         return ret;
863 error:
864         kfree(data);
865         return ret;
866 }
867
868 static ssize_t
869 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
870                  loff_t *ptr)
871 {
872         struct ffs_io_data io_data;
873
874         ENTER();
875
876         io_data.aio = false;
877         io_data.read = false;
878         io_data.buf = (char * __user)buf;
879         io_data.len = len;
880
881         return ffs_epfile_io(file, &io_data);
882 }
883
884 static ssize_t
885 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
886 {
887         struct ffs_io_data io_data;
888
889         ENTER();
890
891         io_data.aio = false;
892         io_data.read = true;
893         io_data.buf = buf;
894         io_data.len = len;
895
896         return ffs_epfile_io(file, &io_data);
897 }
898
899 static int
900 ffs_epfile_open(struct inode *inode, struct file *file)
901 {
902         struct ffs_epfile *epfile = inode->i_private;
903
904         ENTER();
905
906         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
907                 return -ENODEV;
908
909         file->private_data = epfile;
910         ffs_data_opened(epfile->ffs);
911
912         return 0;
913 }
914
915 static int ffs_aio_cancel(struct kiocb *kiocb)
916 {
917         struct ffs_io_data *io_data = kiocb->private;
918         struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
919         int value;
920
921         ENTER();
922
923         spin_lock_irq(&epfile->ffs->eps_lock);
924
925         if (likely(io_data && io_data->ep && io_data->req))
926                 value = usb_ep_dequeue(io_data->ep, io_data->req);
927         else
928                 value = -EINVAL;
929
930         spin_unlock_irq(&epfile->ffs->eps_lock);
931
932         return value;
933 }
934
935 static ssize_t ffs_epfile_aio_write(struct kiocb *kiocb,
936                                     const struct iovec *iovec,
937                                     unsigned long nr_segs, loff_t loff)
938 {
939         struct ffs_io_data *io_data;
940
941         ENTER();
942
943         io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
944         if (unlikely(!io_data))
945                 return -ENOMEM;
946
947         io_data->aio = true;
948         io_data->read = false;
949         io_data->kiocb = kiocb;
950         io_data->iovec = iovec;
951         io_data->nr_segs = nr_segs;
952         io_data->len = kiocb->ki_nbytes;
953         io_data->mm = current->mm;
954
955         kiocb->private = io_data;
956
957         kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
958
959         return ffs_epfile_io(kiocb->ki_filp, io_data);
960 }
961
962 static ssize_t ffs_epfile_aio_read(struct kiocb *kiocb,
963                                    const struct iovec *iovec,
964                                    unsigned long nr_segs, loff_t loff)
965 {
966         struct ffs_io_data *io_data;
967         struct iovec *iovec_copy;
968
969         ENTER();
970
971         iovec_copy = kmalloc_array(nr_segs, sizeof(*iovec_copy), GFP_KERNEL);
972         if (unlikely(!iovec_copy))
973                 return -ENOMEM;
974
975         memcpy(iovec_copy, iovec, sizeof(struct iovec)*nr_segs);
976
977         io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
978         if (unlikely(!io_data)) {
979                 kfree(iovec_copy);
980                 return -ENOMEM;
981         }
982
983         io_data->aio = true;
984         io_data->read = true;
985         io_data->kiocb = kiocb;
986         io_data->iovec = iovec_copy;
987         io_data->nr_segs = nr_segs;
988         io_data->len = kiocb->ki_nbytes;
989         io_data->mm = current->mm;
990
991         kiocb->private = io_data;
992
993         kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
994
995         return ffs_epfile_io(kiocb->ki_filp, io_data);
996 }
997
998 static int
999 ffs_epfile_release(struct inode *inode, struct file *file)
1000 {
1001         struct ffs_epfile *epfile = inode->i_private;
1002
1003         ENTER();
1004
1005         ffs_data_closed(epfile->ffs);
1006
1007         return 0;
1008 }
1009
1010 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1011                              unsigned long value)
1012 {
1013         struct ffs_epfile *epfile = file->private_data;
1014         int ret;
1015
1016         ENTER();
1017
1018         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1019                 return -ENODEV;
1020
1021         spin_lock_irq(&epfile->ffs->eps_lock);
1022         if (likely(epfile->ep)) {
1023                 switch (code) {
1024                 case FUNCTIONFS_FIFO_STATUS:
1025                         ret = usb_ep_fifo_status(epfile->ep->ep);
1026                         break;
1027                 case FUNCTIONFS_FIFO_FLUSH:
1028                         usb_ep_fifo_flush(epfile->ep->ep);
1029                         ret = 0;
1030                         break;
1031                 case FUNCTIONFS_CLEAR_HALT:
1032                         ret = usb_ep_clear_halt(epfile->ep->ep);
1033                         break;
1034                 case FUNCTIONFS_ENDPOINT_REVMAP:
1035                         ret = epfile->ep->num;
1036                         break;
1037                 default:
1038                         ret = -ENOTTY;
1039                 }
1040         } else {
1041                 ret = -ENODEV;
1042         }
1043         spin_unlock_irq(&epfile->ffs->eps_lock);
1044
1045         return ret;
1046 }
1047
1048 static const struct file_operations ffs_epfile_operations = {
1049         .llseek =       no_llseek,
1050
1051         .open =         ffs_epfile_open,
1052         .write =        ffs_epfile_write,
1053         .read =         ffs_epfile_read,
1054         .aio_write =    ffs_epfile_aio_write,
1055         .aio_read =     ffs_epfile_aio_read,
1056         .release =      ffs_epfile_release,
1057         .unlocked_ioctl =       ffs_epfile_ioctl,
1058 };
1059
1060
1061 /* File system and super block operations ***********************************/
1062
1063 /*
1064  * Mounting the file system creates a controller file, used first for
1065  * function configuration then later for event monitoring.
1066  */
1067
1068 static struct inode *__must_check
1069 ffs_sb_make_inode(struct super_block *sb, void *data,
1070                   const struct file_operations *fops,
1071                   const struct inode_operations *iops,
1072                   struct ffs_file_perms *perms)
1073 {
1074         struct inode *inode;
1075
1076         ENTER();
1077
1078         inode = new_inode(sb);
1079
1080         if (likely(inode)) {
1081                 struct timespec current_time = CURRENT_TIME;
1082
1083                 inode->i_ino     = get_next_ino();
1084                 inode->i_mode    = perms->mode;
1085                 inode->i_uid     = perms->uid;
1086                 inode->i_gid     = perms->gid;
1087                 inode->i_atime   = current_time;
1088                 inode->i_mtime   = current_time;
1089                 inode->i_ctime   = current_time;
1090                 inode->i_private = data;
1091                 if (fops)
1092                         inode->i_fop = fops;
1093                 if (iops)
1094                         inode->i_op  = iops;
1095         }
1096
1097         return inode;
1098 }
1099
1100 /* Create "regular" file */
1101 static struct inode *ffs_sb_create_file(struct super_block *sb,
1102                                         const char *name, void *data,
1103                                         const struct file_operations *fops,
1104                                         struct dentry **dentry_p)
1105 {
1106         struct ffs_data *ffs = sb->s_fs_info;
1107         struct dentry   *dentry;
1108         struct inode    *inode;
1109
1110         ENTER();
1111
1112         dentry = d_alloc_name(sb->s_root, name);
1113         if (unlikely(!dentry))
1114                 return NULL;
1115
1116         inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1117         if (unlikely(!inode)) {
1118                 dput(dentry);
1119                 return NULL;
1120         }
1121
1122         d_add(dentry, inode);
1123         if (dentry_p)
1124                 *dentry_p = dentry;
1125
1126         return inode;
1127 }
1128
1129 /* Super block */
1130 static const struct super_operations ffs_sb_operations = {
1131         .statfs =       simple_statfs,
1132         .drop_inode =   generic_delete_inode,
1133 };
1134
1135 struct ffs_sb_fill_data {
1136         struct ffs_file_perms perms;
1137         umode_t root_mode;
1138         const char *dev_name;
1139         struct ffs_data *ffs_data;
1140 };
1141
1142 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1143 {
1144         struct ffs_sb_fill_data *data = _data;
1145         struct inode    *inode;
1146         struct ffs_data *ffs = data->ffs_data;
1147
1148         ENTER();
1149
1150         ffs->sb              = sb;
1151         data->ffs_data       = NULL;
1152         sb->s_fs_info        = ffs;
1153         sb->s_blocksize      = PAGE_CACHE_SIZE;
1154         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1155         sb->s_magic          = FUNCTIONFS_MAGIC;
1156         sb->s_op             = &ffs_sb_operations;
1157         sb->s_time_gran      = 1;
1158
1159         /* Root inode */
1160         data->perms.mode = data->root_mode;
1161         inode = ffs_sb_make_inode(sb, NULL,
1162                                   &simple_dir_operations,
1163                                   &simple_dir_inode_operations,
1164                                   &data->perms);
1165         sb->s_root = d_make_root(inode);
1166         if (unlikely(!sb->s_root))
1167                 return -ENOMEM;
1168
1169         /* EP0 file */
1170         if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1171                                          &ffs_ep0_operations, NULL)))
1172                 return -ENOMEM;
1173
1174         return 0;
1175 }
1176
1177 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1178 {
1179         ENTER();
1180
1181         if (!opts || !*opts)
1182                 return 0;
1183
1184         for (;;) {
1185                 unsigned long value;
1186                 char *eq, *comma;
1187
1188                 /* Option limit */
1189                 comma = strchr(opts, ',');
1190                 if (comma)
1191                         *comma = 0;
1192
1193                 /* Value limit */
1194                 eq = strchr(opts, '=');
1195                 if (unlikely(!eq)) {
1196                         pr_err("'=' missing in %s\n", opts);
1197                         return -EINVAL;
1198                 }
1199                 *eq = 0;
1200
1201                 /* Parse value */
1202                 if (kstrtoul(eq + 1, 0, &value)) {
1203                         pr_err("%s: invalid value: %s\n", opts, eq + 1);
1204                         return -EINVAL;
1205                 }
1206
1207                 /* Interpret option */
1208                 switch (eq - opts) {
1209                 case 5:
1210                         if (!memcmp(opts, "rmode", 5))
1211                                 data->root_mode  = (value & 0555) | S_IFDIR;
1212                         else if (!memcmp(opts, "fmode", 5))
1213                                 data->perms.mode = (value & 0666) | S_IFREG;
1214                         else
1215                                 goto invalid;
1216                         break;
1217
1218                 case 4:
1219                         if (!memcmp(opts, "mode", 4)) {
1220                                 data->root_mode  = (value & 0555) | S_IFDIR;
1221                                 data->perms.mode = (value & 0666) | S_IFREG;
1222                         } else {
1223                                 goto invalid;
1224                         }
1225                         break;
1226
1227                 case 3:
1228                         if (!memcmp(opts, "uid", 3)) {
1229                                 data->perms.uid = make_kuid(current_user_ns(), value);
1230                                 if (!uid_valid(data->perms.uid)) {
1231                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1232                                         return -EINVAL;
1233                                 }
1234                         } else if (!memcmp(opts, "gid", 3)) {
1235                                 data->perms.gid = make_kgid(current_user_ns(), value);
1236                                 if (!gid_valid(data->perms.gid)) {
1237                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1238                                         return -EINVAL;
1239                                 }
1240                         } else {
1241                                 goto invalid;
1242                         }
1243                         break;
1244
1245                 default:
1246 invalid:
1247                         pr_err("%s: invalid option\n", opts);
1248                         return -EINVAL;
1249                 }
1250
1251                 /* Next iteration */
1252                 if (!comma)
1253                         break;
1254                 opts = comma + 1;
1255         }
1256
1257         return 0;
1258 }
1259
1260 /* "mount -t functionfs dev_name /dev/function" ends up here */
1261
1262 static struct dentry *
1263 ffs_fs_mount(struct file_system_type *t, int flags,
1264               const char *dev_name, void *opts)
1265 {
1266         struct ffs_sb_fill_data data = {
1267                 .perms = {
1268                         .mode = S_IFREG | 0600,
1269                         .uid = GLOBAL_ROOT_UID,
1270                         .gid = GLOBAL_ROOT_GID,
1271                 },
1272                 .root_mode = S_IFDIR | 0500,
1273         };
1274         struct dentry *rv;
1275         int ret;
1276         void *ffs_dev;
1277         struct ffs_data *ffs;
1278
1279         ENTER();
1280
1281         ret = ffs_fs_parse_opts(&data, opts);
1282         if (unlikely(ret < 0))
1283                 return ERR_PTR(ret);
1284
1285         ffs = ffs_data_new();
1286         if (unlikely(!ffs))
1287                 return ERR_PTR(-ENOMEM);
1288         ffs->file_perms = data.perms;
1289
1290         ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1291         if (unlikely(!ffs->dev_name)) {
1292                 ffs_data_put(ffs);
1293                 return ERR_PTR(-ENOMEM);
1294         }
1295
1296         ffs_dev = ffs_acquire_dev(dev_name);
1297         if (IS_ERR(ffs_dev)) {
1298                 ffs_data_put(ffs);
1299                 return ERR_CAST(ffs_dev);
1300         }
1301         ffs->private_data = ffs_dev;
1302         data.ffs_data = ffs;
1303
1304         rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1305         if (IS_ERR(rv) && data.ffs_data) {
1306                 ffs_release_dev(data.ffs_data);
1307                 ffs_data_put(data.ffs_data);
1308         }
1309         return rv;
1310 }
1311
1312 static void
1313 ffs_fs_kill_sb(struct super_block *sb)
1314 {
1315         ENTER();
1316
1317         kill_litter_super(sb);
1318         if (sb->s_fs_info) {
1319                 ffs_release_dev(sb->s_fs_info);
1320                 ffs_data_put(sb->s_fs_info);
1321         }
1322 }
1323
1324 static struct file_system_type ffs_fs_type = {
1325         .owner          = THIS_MODULE,
1326         .name           = "functionfs",
1327         .mount          = ffs_fs_mount,
1328         .kill_sb        = ffs_fs_kill_sb,
1329 };
1330 MODULE_ALIAS_FS("functionfs");
1331
1332
1333 /* Driver's main init/cleanup functions *************************************/
1334
1335 static int functionfs_init(void)
1336 {
1337         int ret;
1338
1339         ENTER();
1340
1341         ret = register_filesystem(&ffs_fs_type);
1342         if (likely(!ret))
1343                 pr_info("file system registered\n");
1344         else
1345                 pr_err("failed registering file system (%d)\n", ret);
1346
1347         return ret;
1348 }
1349
1350 static void functionfs_cleanup(void)
1351 {
1352         ENTER();
1353
1354         pr_info("unloading\n");
1355         unregister_filesystem(&ffs_fs_type);
1356 }
1357
1358
1359 /* ffs_data and ffs_function construction and destruction code **************/
1360
1361 static void ffs_data_clear(struct ffs_data *ffs);
1362 static void ffs_data_reset(struct ffs_data *ffs);
1363
1364 static void ffs_data_get(struct ffs_data *ffs)
1365 {
1366         ENTER();
1367
1368         atomic_inc(&ffs->ref);
1369 }
1370
1371 static void ffs_data_opened(struct ffs_data *ffs)
1372 {
1373         ENTER();
1374
1375         atomic_inc(&ffs->ref);
1376         atomic_inc(&ffs->opened);
1377 }
1378
1379 static void ffs_data_put(struct ffs_data *ffs)
1380 {
1381         ENTER();
1382
1383         if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1384                 pr_info("%s(): freeing\n", __func__);
1385                 ffs_data_clear(ffs);
1386                 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1387                        waitqueue_active(&ffs->ep0req_completion.wait));
1388                 kfree(ffs->dev_name);
1389                 kfree(ffs);
1390         }
1391 }
1392
1393 static void ffs_data_closed(struct ffs_data *ffs)
1394 {
1395         ENTER();
1396
1397         if (atomic_dec_and_test(&ffs->opened)) {
1398                 ffs->state = FFS_CLOSING;
1399                 ffs_data_reset(ffs);
1400         }
1401
1402         ffs_data_put(ffs);
1403 }
1404
1405 static struct ffs_data *ffs_data_new(void)
1406 {
1407         struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1408         if (unlikely(!ffs))
1409                 return NULL;
1410
1411         ENTER();
1412
1413         atomic_set(&ffs->ref, 1);
1414         atomic_set(&ffs->opened, 0);
1415         ffs->state = FFS_READ_DESCRIPTORS;
1416         mutex_init(&ffs->mutex);
1417         spin_lock_init(&ffs->eps_lock);
1418         init_waitqueue_head(&ffs->ev.waitq);
1419         init_completion(&ffs->ep0req_completion);
1420
1421         /* XXX REVISIT need to update it in some places, or do we? */
1422         ffs->ev.can_stall = 1;
1423
1424         return ffs;
1425 }
1426
1427 static void ffs_data_clear(struct ffs_data *ffs)
1428 {
1429         ENTER();
1430
1431         if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1432                 ffs_closed(ffs);
1433
1434         BUG_ON(ffs->gadget);
1435
1436         if (ffs->epfiles)
1437                 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1438
1439         kfree(ffs->raw_descs_data);
1440         kfree(ffs->raw_strings);
1441         kfree(ffs->stringtabs);
1442 }
1443
1444 static void ffs_data_reset(struct ffs_data *ffs)
1445 {
1446         ENTER();
1447
1448         ffs_data_clear(ffs);
1449
1450         ffs->epfiles = NULL;
1451         ffs->raw_descs_data = NULL;
1452         ffs->raw_descs = NULL;
1453         ffs->raw_strings = NULL;
1454         ffs->stringtabs = NULL;
1455
1456         ffs->raw_descs_length = 0;
1457         ffs->fs_descs_count = 0;
1458         ffs->hs_descs_count = 0;
1459         ffs->ss_descs_count = 0;
1460
1461         ffs->strings_count = 0;
1462         ffs->interfaces_count = 0;
1463         ffs->eps_count = 0;
1464
1465         ffs->ev.count = 0;
1466
1467         ffs->state = FFS_READ_DESCRIPTORS;
1468         ffs->setup_state = FFS_NO_SETUP;
1469         ffs->flags = 0;
1470 }
1471
1472
1473 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1474 {
1475         struct usb_gadget_strings **lang;
1476         int first_id;
1477
1478         ENTER();
1479
1480         if (WARN_ON(ffs->state != FFS_ACTIVE
1481                  || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1482                 return -EBADFD;
1483
1484         first_id = usb_string_ids_n(cdev, ffs->strings_count);
1485         if (unlikely(first_id < 0))
1486                 return first_id;
1487
1488         ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1489         if (unlikely(!ffs->ep0req))
1490                 return -ENOMEM;
1491         ffs->ep0req->complete = ffs_ep0_complete;
1492         ffs->ep0req->context = ffs;
1493
1494         lang = ffs->stringtabs;
1495         for (lang = ffs->stringtabs; *lang; ++lang) {
1496                 struct usb_string *str = (*lang)->strings;
1497                 int id = first_id;
1498                 for (; str->s; ++id, ++str)
1499                         str->id = id;
1500         }
1501
1502         ffs->gadget = cdev->gadget;
1503         ffs_data_get(ffs);
1504         return 0;
1505 }
1506
1507 static void functionfs_unbind(struct ffs_data *ffs)
1508 {
1509         ENTER();
1510
1511         if (!WARN_ON(!ffs->gadget)) {
1512                 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1513                 ffs->ep0req = NULL;
1514                 ffs->gadget = NULL;
1515                 clear_bit(FFS_FL_BOUND, &ffs->flags);
1516                 ffs_data_put(ffs);
1517         }
1518 }
1519
1520 static int ffs_epfiles_create(struct ffs_data *ffs)
1521 {
1522         struct ffs_epfile *epfile, *epfiles;
1523         unsigned i, count;
1524
1525         ENTER();
1526
1527         count = ffs->eps_count;
1528         epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1529         if (!epfiles)
1530                 return -ENOMEM;
1531
1532         epfile = epfiles;
1533         for (i = 1; i <= count; ++i, ++epfile) {
1534                 epfile->ffs = ffs;
1535                 mutex_init(&epfile->mutex);
1536                 init_waitqueue_head(&epfile->wait);
1537                 sprintf(epfiles->name, "ep%u",  i);
1538                 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1539                                                  &ffs_epfile_operations,
1540                                                  &epfile->dentry))) {
1541                         ffs_epfiles_destroy(epfiles, i - 1);
1542                         return -ENOMEM;
1543                 }
1544         }
1545
1546         ffs->epfiles = epfiles;
1547         return 0;
1548 }
1549
1550 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1551 {
1552         struct ffs_epfile *epfile = epfiles;
1553
1554         ENTER();
1555
1556         for (; count; --count, ++epfile) {
1557                 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1558                        waitqueue_active(&epfile->wait));
1559                 if (epfile->dentry) {
1560                         d_delete(epfile->dentry);
1561                         dput(epfile->dentry);
1562                         epfile->dentry = NULL;
1563                 }
1564         }
1565
1566         kfree(epfiles);
1567 }
1568
1569
1570 static void ffs_func_eps_disable(struct ffs_function *func)
1571 {
1572         struct ffs_ep *ep         = func->eps;
1573         struct ffs_epfile *epfile = func->ffs->epfiles;
1574         unsigned count            = func->ffs->eps_count;
1575         unsigned long flags;
1576
1577         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1578         do {
1579                 /* pending requests get nuked */
1580                 if (likely(ep->ep))
1581                         usb_ep_disable(ep->ep);
1582                 epfile->ep = NULL;
1583
1584                 ++ep;
1585                 ++epfile;
1586         } while (--count);
1587         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1588 }
1589
1590 static int ffs_func_eps_enable(struct ffs_function *func)
1591 {
1592         struct ffs_data *ffs      = func->ffs;
1593         struct ffs_ep *ep         = func->eps;
1594         struct ffs_epfile *epfile = ffs->epfiles;
1595         unsigned count            = ffs->eps_count;
1596         unsigned long flags;
1597         int ret = 0;
1598
1599         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1600         do {
1601                 struct usb_endpoint_descriptor *ds;
1602                 int desc_idx;
1603
1604                 if (ffs->gadget->speed == USB_SPEED_SUPER)
1605                         desc_idx = 2;
1606                 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1607                         desc_idx = 1;
1608                 else
1609                         desc_idx = 0;
1610
1611                 /* fall-back to lower speed if desc missing for current speed */
1612                 do {
1613                         ds = ep->descs[desc_idx];
1614                 } while (!ds && --desc_idx >= 0);
1615
1616                 if (!ds) {
1617                         ret = -EINVAL;
1618                         break;
1619                 }
1620
1621                 ep->ep->driver_data = ep;
1622                 ep->ep->desc = ds;
1623                 ret = usb_ep_enable(ep->ep);
1624                 if (likely(!ret)) {
1625                         epfile->ep = ep;
1626                         epfile->in = usb_endpoint_dir_in(ds);
1627                         epfile->isoc = usb_endpoint_xfer_isoc(ds);
1628                 } else {
1629                         break;
1630                 }
1631
1632                 wake_up(&epfile->wait);
1633
1634                 ++ep;
1635                 ++epfile;
1636         } while (--count);
1637         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1638
1639         return ret;
1640 }
1641
1642
1643 /* Parsing and building descriptors and strings *****************************/
1644
1645 /*
1646  * This validates if data pointed by data is a valid USB descriptor as
1647  * well as record how many interfaces, endpoints and strings are
1648  * required by given configuration.  Returns address after the
1649  * descriptor or NULL if data is invalid.
1650  */
1651
1652 enum ffs_entity_type {
1653         FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1654 };
1655
1656 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1657                                    u8 *valuep,
1658                                    struct usb_descriptor_header *desc,
1659                                    void *priv);
1660
1661 static int __must_check ffs_do_desc(char *data, unsigned len,
1662                                     ffs_entity_callback entity, void *priv)
1663 {
1664         struct usb_descriptor_header *_ds = (void *)data;
1665         u8 length;
1666         int ret;
1667
1668         ENTER();
1669
1670         /* At least two bytes are required: length and type */
1671         if (len < 2) {
1672                 pr_vdebug("descriptor too short\n");
1673                 return -EINVAL;
1674         }
1675
1676         /* If we have at least as many bytes as the descriptor takes? */
1677         length = _ds->bLength;
1678         if (len < length) {
1679                 pr_vdebug("descriptor longer then available data\n");
1680                 return -EINVAL;
1681         }
1682
1683 #define __entity_check_INTERFACE(val)  1
1684 #define __entity_check_STRING(val)     (val)
1685 #define __entity_check_ENDPOINT(val)   ((val) & USB_ENDPOINT_NUMBER_MASK)
1686 #define __entity(type, val) do {                                        \
1687                 pr_vdebug("entity " #type "(%02x)\n", (val));           \
1688                 if (unlikely(!__entity_check_ ##type(val))) {           \
1689                         pr_vdebug("invalid entity's value\n");          \
1690                         return -EINVAL;                                 \
1691                 }                                                       \
1692                 ret = entity(FFS_ ##type, &val, _ds, priv);             \
1693                 if (unlikely(ret < 0)) {                                \
1694                         pr_debug("entity " #type "(%02x); ret = %d\n",  \
1695                                  (val), ret);                           \
1696                         return ret;                                     \
1697                 }                                                       \
1698         } while (0)
1699
1700         /* Parse descriptor depending on type. */
1701         switch (_ds->bDescriptorType) {
1702         case USB_DT_DEVICE:
1703         case USB_DT_CONFIG:
1704         case USB_DT_STRING:
1705         case USB_DT_DEVICE_QUALIFIER:
1706                 /* function can't have any of those */
1707                 pr_vdebug("descriptor reserved for gadget: %d\n",
1708                       _ds->bDescriptorType);
1709                 return -EINVAL;
1710
1711         case USB_DT_INTERFACE: {
1712                 struct usb_interface_descriptor *ds = (void *)_ds;
1713                 pr_vdebug("interface descriptor\n");
1714                 if (length != sizeof *ds)
1715                         goto inv_length;
1716
1717                 __entity(INTERFACE, ds->bInterfaceNumber);
1718                 if (ds->iInterface)
1719                         __entity(STRING, ds->iInterface);
1720         }
1721                 break;
1722
1723         case USB_DT_ENDPOINT: {
1724                 struct usb_endpoint_descriptor *ds = (void *)_ds;
1725                 pr_vdebug("endpoint descriptor\n");
1726                 if (length != USB_DT_ENDPOINT_SIZE &&
1727                     length != USB_DT_ENDPOINT_AUDIO_SIZE)
1728                         goto inv_length;
1729                 __entity(ENDPOINT, ds->bEndpointAddress);
1730         }
1731                 break;
1732
1733         case HID_DT_HID:
1734                 pr_vdebug("hid descriptor\n");
1735                 if (length != sizeof(struct hid_descriptor))
1736                         goto inv_length;
1737                 break;
1738
1739         case USB_DT_OTG:
1740                 if (length != sizeof(struct usb_otg_descriptor))
1741                         goto inv_length;
1742                 break;
1743
1744         case USB_DT_INTERFACE_ASSOCIATION: {
1745                 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1746                 pr_vdebug("interface association descriptor\n");
1747                 if (length != sizeof *ds)
1748                         goto inv_length;
1749                 if (ds->iFunction)
1750                         __entity(STRING, ds->iFunction);
1751         }
1752                 break;
1753
1754         case USB_DT_SS_ENDPOINT_COMP:
1755                 pr_vdebug("EP SS companion descriptor\n");
1756                 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1757                         goto inv_length;
1758                 break;
1759
1760         case USB_DT_OTHER_SPEED_CONFIG:
1761         case USB_DT_INTERFACE_POWER:
1762         case USB_DT_DEBUG:
1763         case USB_DT_SECURITY:
1764         case USB_DT_CS_RADIO_CONTROL:
1765                 /* TODO */
1766                 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1767                 return -EINVAL;
1768
1769         default:
1770                 /* We should never be here */
1771                 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1772                 return -EINVAL;
1773
1774 inv_length:
1775                 pr_vdebug("invalid length: %d (descriptor %d)\n",
1776                           _ds->bLength, _ds->bDescriptorType);
1777                 return -EINVAL;
1778         }
1779
1780 #undef __entity
1781 #undef __entity_check_DESCRIPTOR
1782 #undef __entity_check_INTERFACE
1783 #undef __entity_check_STRING
1784 #undef __entity_check_ENDPOINT
1785
1786         return length;
1787 }
1788
1789 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1790                                      ffs_entity_callback entity, void *priv)
1791 {
1792         const unsigned _len = len;
1793         unsigned long num = 0;
1794
1795         ENTER();
1796
1797         for (;;) {
1798                 int ret;
1799
1800                 if (num == count)
1801                         data = NULL;
1802
1803                 /* Record "descriptor" entity */
1804                 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1805                 if (unlikely(ret < 0)) {
1806                         pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1807                                  num, ret);
1808                         return ret;
1809                 }
1810
1811                 if (!data)
1812                         return _len - len;
1813
1814                 ret = ffs_do_desc(data, len, entity, priv);
1815                 if (unlikely(ret < 0)) {
1816                         pr_debug("%s returns %d\n", __func__, ret);
1817                         return ret;
1818                 }
1819
1820                 len -= ret;
1821                 data += ret;
1822                 ++num;
1823         }
1824 }
1825
1826 static int __ffs_data_do_entity(enum ffs_entity_type type,
1827                                 u8 *valuep, struct usb_descriptor_header *desc,
1828                                 void *priv)
1829 {
1830         struct ffs_data *ffs = priv;
1831
1832         ENTER();
1833
1834         switch (type) {
1835         case FFS_DESCRIPTOR:
1836                 break;
1837
1838         case FFS_INTERFACE:
1839                 /*
1840                  * Interfaces are indexed from zero so if we
1841                  * encountered interface "n" then there are at least
1842                  * "n+1" interfaces.
1843                  */
1844                 if (*valuep >= ffs->interfaces_count)
1845                         ffs->interfaces_count = *valuep + 1;
1846                 break;
1847
1848         case FFS_STRING:
1849                 /*
1850                  * Strings are indexed from 1 (0 is magic ;) reserved
1851                  * for languages list or some such)
1852                  */
1853                 if (*valuep > ffs->strings_count)
1854                         ffs->strings_count = *valuep;
1855                 break;
1856
1857         case FFS_ENDPOINT:
1858                 /* Endpoints are indexed from 1 as well. */
1859                 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1860                         ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1861                 break;
1862         }
1863
1864         return 0;
1865 }
1866
1867 static int __ffs_data_got_descs(struct ffs_data *ffs,
1868                                 char *const _data, size_t len)
1869 {
1870         char *data = _data, *raw_descs;
1871         unsigned counts[3], flags;
1872         int ret = -EINVAL, i;
1873
1874         ENTER();
1875
1876         if (get_unaligned_le32(data + 4) != len)
1877                 goto error;
1878
1879         switch (get_unaligned_le32(data)) {
1880         case FUNCTIONFS_DESCRIPTORS_MAGIC:
1881                 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
1882                 data += 8;
1883                 len  -= 8;
1884                 break;
1885         case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
1886                 flags = get_unaligned_le32(data + 8);
1887                 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
1888                               FUNCTIONFS_HAS_HS_DESC |
1889                               FUNCTIONFS_HAS_SS_DESC)) {
1890                         ret = -ENOSYS;
1891                         goto error;
1892                 }
1893                 data += 12;
1894                 len  -= 12;
1895                 break;
1896         default:
1897                 goto error;
1898         }
1899
1900         /* Read fs_count, hs_count and ss_count (if present) */
1901         for (i = 0; i < 3; ++i) {
1902                 if (!(flags & (1 << i))) {
1903                         counts[i] = 0;
1904                 } else if (len < 4) {
1905                         goto error;
1906                 } else {
1907                         counts[i] = get_unaligned_le32(data);
1908                         data += 4;
1909                         len  -= 4;
1910                 }
1911         }
1912
1913         /* Read descriptors */
1914         raw_descs = data;
1915         for (i = 0; i < 3; ++i) {
1916                 if (!counts[i])
1917                         continue;
1918                 ret = ffs_do_descs(counts[i], data, len,
1919                                    __ffs_data_do_entity, ffs);
1920                 if (ret < 0)
1921                         goto error;
1922                 data += ret;
1923                 len  -= ret;
1924         }
1925
1926         if (raw_descs == data || len) {
1927                 ret = -EINVAL;
1928                 goto error;
1929         }
1930
1931         ffs->raw_descs_data     = _data;
1932         ffs->raw_descs          = raw_descs;
1933         ffs->raw_descs_length   = data - raw_descs;
1934         ffs->fs_descs_count     = counts[0];
1935         ffs->hs_descs_count     = counts[1];
1936         ffs->ss_descs_count     = counts[2];
1937
1938         return 0;
1939
1940 error:
1941         kfree(_data);
1942         return ret;
1943 }
1944
1945 static int __ffs_data_got_strings(struct ffs_data *ffs,
1946                                   char *const _data, size_t len)
1947 {
1948         u32 str_count, needed_count, lang_count;
1949         struct usb_gadget_strings **stringtabs, *t;
1950         struct usb_string *strings, *s;
1951         const char *data = _data;
1952
1953         ENTER();
1954
1955         if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1956                      get_unaligned_le32(data + 4) != len))
1957                 goto error;
1958         str_count  = get_unaligned_le32(data + 8);
1959         lang_count = get_unaligned_le32(data + 12);
1960
1961         /* if one is zero the other must be zero */
1962         if (unlikely(!str_count != !lang_count))
1963                 goto error;
1964
1965         /* Do we have at least as many strings as descriptors need? */
1966         needed_count = ffs->strings_count;
1967         if (unlikely(str_count < needed_count))
1968                 goto error;
1969
1970         /*
1971          * If we don't need any strings just return and free all
1972          * memory.
1973          */
1974         if (!needed_count) {
1975                 kfree(_data);
1976                 return 0;
1977         }
1978
1979         /* Allocate everything in one chunk so there's less maintenance. */
1980         {
1981                 unsigned i = 0;
1982                 vla_group(d);
1983                 vla_item(d, struct usb_gadget_strings *, stringtabs,
1984                         lang_count + 1);
1985                 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
1986                 vla_item(d, struct usb_string, strings,
1987                         lang_count*(needed_count+1));
1988
1989                 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
1990
1991                 if (unlikely(!vlabuf)) {
1992                         kfree(_data);
1993                         return -ENOMEM;
1994                 }
1995
1996                 /* Initialize the VLA pointers */
1997                 stringtabs = vla_ptr(vlabuf, d, stringtabs);
1998                 t = vla_ptr(vlabuf, d, stringtab);
1999                 i = lang_count;
2000                 do {
2001                         *stringtabs++ = t++;
2002                 } while (--i);
2003                 *stringtabs = NULL;
2004
2005                 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2006                 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2007                 t = vla_ptr(vlabuf, d, stringtab);
2008                 s = vla_ptr(vlabuf, d, strings);
2009                 strings = s;
2010         }
2011
2012         /* For each language */
2013         data += 16;
2014         len -= 16;
2015
2016         do { /* lang_count > 0 so we can use do-while */
2017                 unsigned needed = needed_count;
2018
2019                 if (unlikely(len < 3))
2020                         goto error_free;
2021                 t->language = get_unaligned_le16(data);
2022                 t->strings  = s;
2023                 ++t;
2024
2025                 data += 2;
2026                 len -= 2;
2027
2028                 /* For each string */
2029                 do { /* str_count > 0 so we can use do-while */
2030                         size_t length = strnlen(data, len);
2031
2032                         if (unlikely(length == len))
2033                                 goto error_free;
2034
2035                         /*
2036                          * User may provide more strings then we need,
2037                          * if that's the case we simply ignore the
2038                          * rest
2039                          */
2040                         if (likely(needed)) {
2041                                 /*
2042                                  * s->id will be set while adding
2043                                  * function to configuration so for
2044                                  * now just leave garbage here.
2045                                  */
2046                                 s->s = data;
2047                                 --needed;
2048                                 ++s;
2049                         }
2050
2051                         data += length + 1;
2052                         len -= length + 1;
2053                 } while (--str_count);
2054
2055                 s->id = 0;   /* terminator */
2056                 s->s = NULL;
2057                 ++s;
2058
2059         } while (--lang_count);
2060
2061         /* Some garbage left? */
2062         if (unlikely(len))
2063                 goto error_free;
2064
2065         /* Done! */
2066         ffs->stringtabs = stringtabs;
2067         ffs->raw_strings = _data;
2068
2069         return 0;
2070
2071 error_free:
2072         kfree(stringtabs);
2073 error:
2074         kfree(_data);
2075         return -EINVAL;
2076 }
2077
2078
2079 /* Events handling and management *******************************************/
2080
2081 static void __ffs_event_add(struct ffs_data *ffs,
2082                             enum usb_functionfs_event_type type)
2083 {
2084         enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2085         int neg = 0;
2086
2087         /*
2088          * Abort any unhandled setup
2089          *
2090          * We do not need to worry about some cmpxchg() changing value
2091          * of ffs->setup_state without holding the lock because when
2092          * state is FFS_SETUP_PENDING cmpxchg() in several places in
2093          * the source does nothing.
2094          */
2095         if (ffs->setup_state == FFS_SETUP_PENDING)
2096                 ffs->setup_state = FFS_SETUP_CANCELLED;
2097
2098         switch (type) {
2099         case FUNCTIONFS_RESUME:
2100                 rem_type2 = FUNCTIONFS_SUSPEND;
2101                 /* FALL THROUGH */
2102         case FUNCTIONFS_SUSPEND:
2103         case FUNCTIONFS_SETUP:
2104                 rem_type1 = type;
2105                 /* Discard all similar events */
2106                 break;
2107
2108         case FUNCTIONFS_BIND:
2109         case FUNCTIONFS_UNBIND:
2110         case FUNCTIONFS_DISABLE:
2111         case FUNCTIONFS_ENABLE:
2112                 /* Discard everything other then power management. */
2113                 rem_type1 = FUNCTIONFS_SUSPEND;
2114                 rem_type2 = FUNCTIONFS_RESUME;
2115                 neg = 1;
2116                 break;
2117
2118         default:
2119                 BUG();
2120         }
2121
2122         {
2123                 u8 *ev  = ffs->ev.types, *out = ev;
2124                 unsigned n = ffs->ev.count;
2125                 for (; n; --n, ++ev)
2126                         if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2127                                 *out++ = *ev;
2128                         else
2129                                 pr_vdebug("purging event %d\n", *ev);
2130                 ffs->ev.count = out - ffs->ev.types;
2131         }
2132
2133         pr_vdebug("adding event %d\n", type);
2134         ffs->ev.types[ffs->ev.count++] = type;
2135         wake_up_locked(&ffs->ev.waitq);
2136 }
2137
2138 static void ffs_event_add(struct ffs_data *ffs,
2139                           enum usb_functionfs_event_type type)
2140 {
2141         unsigned long flags;
2142         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2143         __ffs_event_add(ffs, type);
2144         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2145 }
2146
2147
2148 /* Bind/unbind USB function hooks *******************************************/
2149
2150 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2151                                     struct usb_descriptor_header *desc,
2152                                     void *priv)
2153 {
2154         struct usb_endpoint_descriptor *ds = (void *)desc;
2155         struct ffs_function *func = priv;
2156         struct ffs_ep *ffs_ep;
2157         unsigned ep_desc_id, idx;
2158         static const char *speed_names[] = { "full", "high", "super" };
2159
2160         if (type != FFS_DESCRIPTOR)
2161                 return 0;
2162
2163         /*
2164          * If ss_descriptors is not NULL, we are reading super speed
2165          * descriptors; if hs_descriptors is not NULL, we are reading high
2166          * speed descriptors; otherwise, we are reading full speed
2167          * descriptors.
2168          */
2169         if (func->function.ss_descriptors) {
2170                 ep_desc_id = 2;
2171                 func->function.ss_descriptors[(long)valuep] = desc;
2172         } else if (func->function.hs_descriptors) {
2173                 ep_desc_id = 1;
2174                 func->function.hs_descriptors[(long)valuep] = desc;
2175         } else {
2176                 ep_desc_id = 0;
2177                 func->function.fs_descriptors[(long)valuep]    = desc;
2178         }
2179
2180         if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2181                 return 0;
2182
2183         idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2184         ffs_ep = func->eps + idx;
2185
2186         if (unlikely(ffs_ep->descs[ep_desc_id])) {
2187                 pr_err("two %sspeed descriptors for EP %d\n",
2188                           speed_names[ep_desc_id],
2189                           ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2190                 return -EINVAL;
2191         }
2192         ffs_ep->descs[ep_desc_id] = ds;
2193
2194         ffs_dump_mem(": Original  ep desc", ds, ds->bLength);
2195         if (ffs_ep->ep) {
2196                 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2197                 if (!ds->wMaxPacketSize)
2198                         ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2199         } else {
2200                 struct usb_request *req;
2201                 struct usb_ep *ep;
2202
2203                 pr_vdebug("autoconfig\n");
2204                 ep = usb_ep_autoconfig(func->gadget, ds);
2205                 if (unlikely(!ep))
2206                         return -ENOTSUPP;
2207                 ep->driver_data = func->eps + idx;
2208
2209                 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2210                 if (unlikely(!req))
2211                         return -ENOMEM;
2212
2213                 ffs_ep->ep  = ep;
2214                 ffs_ep->req = req;
2215                 func->eps_revmap[ds->bEndpointAddress &
2216                                  USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2217         }
2218         ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2219
2220         return 0;
2221 }
2222
2223 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2224                                    struct usb_descriptor_header *desc,
2225                                    void *priv)
2226 {
2227         struct ffs_function *func = priv;
2228         unsigned idx;
2229         u8 newValue;
2230
2231         switch (type) {
2232         default:
2233         case FFS_DESCRIPTOR:
2234                 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2235                 return 0;
2236
2237         case FFS_INTERFACE:
2238                 idx = *valuep;
2239                 if (func->interfaces_nums[idx] < 0) {
2240                         int id = usb_interface_id(func->conf, &func->function);
2241                         if (unlikely(id < 0))
2242                                 return id;
2243                         func->interfaces_nums[idx] = id;
2244                 }
2245                 newValue = func->interfaces_nums[idx];
2246                 break;
2247
2248         case FFS_STRING:
2249                 /* String' IDs are allocated when fsf_data is bound to cdev */
2250                 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2251                 break;
2252
2253         case FFS_ENDPOINT:
2254                 /*
2255                  * USB_DT_ENDPOINT are handled in
2256                  * __ffs_func_bind_do_descs().
2257                  */
2258                 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2259                         return 0;
2260
2261                 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2262                 if (unlikely(!func->eps[idx].ep))
2263                         return -EINVAL;
2264
2265                 {
2266                         struct usb_endpoint_descriptor **descs;
2267                         descs = func->eps[idx].descs;
2268                         newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2269                 }
2270                 break;
2271         }
2272
2273         pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2274         *valuep = newValue;
2275         return 0;
2276 }
2277
2278 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2279                                                 struct usb_configuration *c)
2280 {
2281         struct ffs_function *func = ffs_func_from_usb(f);
2282         struct f_fs_opts *ffs_opts =
2283                 container_of(f->fi, struct f_fs_opts, func_inst);
2284         int ret;
2285
2286         ENTER();
2287
2288         /*
2289          * Legacy gadget triggers binding in functionfs_ready_callback,
2290          * which already uses locking; taking the same lock here would
2291          * cause a deadlock.
2292          *
2293          * Configfs-enabled gadgets however do need ffs_dev_lock.
2294          */
2295         if (!ffs_opts->no_configfs)
2296                 ffs_dev_lock();
2297         ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2298         func->ffs = ffs_opts->dev->ffs_data;
2299         if (!ffs_opts->no_configfs)
2300                 ffs_dev_unlock();
2301         if (ret)
2302                 return ERR_PTR(ret);
2303
2304         func->conf = c;
2305         func->gadget = c->cdev->gadget;
2306
2307         ffs_data_get(func->ffs);
2308
2309         /*
2310          * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2311          * configurations are bound in sequence with list_for_each_entry,
2312          * in each configuration its functions are bound in sequence
2313          * with list_for_each_entry, so we assume no race condition
2314          * with regard to ffs_opts->bound access
2315          */
2316         if (!ffs_opts->refcnt) {
2317                 ret = functionfs_bind(func->ffs, c->cdev);
2318                 if (ret)
2319                         return ERR_PTR(ret);
2320         }
2321         ffs_opts->refcnt++;
2322         func->function.strings = func->ffs->stringtabs;
2323
2324         return ffs_opts;
2325 }
2326
2327 static int _ffs_func_bind(struct usb_configuration *c,
2328                           struct usb_function *f)
2329 {
2330         struct ffs_function *func = ffs_func_from_usb(f);
2331         struct ffs_data *ffs = func->ffs;
2332
2333         const int full = !!func->ffs->fs_descs_count;
2334         const int high = gadget_is_dualspeed(func->gadget) &&
2335                 func->ffs->hs_descs_count;
2336         const int super = gadget_is_superspeed(func->gadget) &&
2337                 func->ffs->ss_descs_count;
2338
2339         int fs_len, hs_len, ret;
2340
2341         /* Make it a single chunk, less management later on */
2342         vla_group(d);
2343         vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2344         vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2345                 full ? ffs->fs_descs_count + 1 : 0);
2346         vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2347                 high ? ffs->hs_descs_count + 1 : 0);
2348         vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2349                 super ? ffs->ss_descs_count + 1 : 0);
2350         vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2351         vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2352         char *vlabuf;
2353
2354         ENTER();
2355
2356         /* Has descriptors only for speeds gadget does not support */
2357         if (unlikely(!(full | high | super)))
2358                 return -ENOTSUPP;
2359
2360         /* Allocate a single chunk, less management later on */
2361         vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2362         if (unlikely(!vlabuf))
2363                 return -ENOMEM;
2364
2365         /* Zero */
2366         memset(vla_ptr(vlabuf, d, eps), 0, d_eps__sz);
2367         /* Copy descriptors  */
2368         memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2369                ffs->raw_descs_length);
2370
2371         memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2372         for (ret = ffs->eps_count; ret; --ret) {
2373                 struct ffs_ep *ptr;
2374
2375                 ptr = vla_ptr(vlabuf, d, eps);
2376                 ptr[ret].num = -1;
2377         }
2378
2379         /* Save pointers
2380          * d_eps == vlabuf, func->eps used to kfree vlabuf later
2381         */
2382         func->eps             = vla_ptr(vlabuf, d, eps);
2383         func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2384
2385         /*
2386          * Go through all the endpoint descriptors and allocate
2387          * endpoints first, so that later we can rewrite the endpoint
2388          * numbers without worrying that it may be described later on.
2389          */
2390         if (likely(full)) {
2391                 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2392                 fs_len = ffs_do_descs(ffs->fs_descs_count,
2393                                       vla_ptr(vlabuf, d, raw_descs),
2394                                       d_raw_descs__sz,
2395                                       __ffs_func_bind_do_descs, func);
2396                 if (unlikely(fs_len < 0)) {
2397                         ret = fs_len;
2398                         goto error;
2399                 }
2400         } else {
2401                 fs_len = 0;
2402         }
2403
2404         if (likely(high)) {
2405                 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2406                 hs_len = ffs_do_descs(ffs->hs_descs_count,
2407                                       vla_ptr(vlabuf, d, raw_descs) + fs_len,
2408                                       d_raw_descs__sz - fs_len,
2409                                       __ffs_func_bind_do_descs, func);
2410                 if (unlikely(hs_len < 0)) {
2411                         ret = hs_len;
2412                         goto error;
2413                 }
2414         } else {
2415                 hs_len = 0;
2416         }
2417
2418         if (likely(super)) {
2419                 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2420                 ret = ffs_do_descs(ffs->ss_descs_count,
2421                                 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2422                                 d_raw_descs__sz - fs_len - hs_len,
2423                                 __ffs_func_bind_do_descs, func);
2424                 if (unlikely(ret < 0))
2425                         goto error;
2426         }
2427
2428         /*
2429          * Now handle interface numbers allocation and interface and
2430          * endpoint numbers rewriting.  We can do that in one go
2431          * now.
2432          */
2433         ret = ffs_do_descs(ffs->fs_descs_count +
2434                            (high ? ffs->hs_descs_count : 0) +
2435                            (super ? ffs->ss_descs_count : 0),
2436                            vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2437                            __ffs_func_bind_do_nums, func);
2438         if (unlikely(ret < 0))
2439                 goto error;
2440
2441         /* And we're done */
2442         ffs_event_add(ffs, FUNCTIONFS_BIND);
2443         return 0;
2444
2445 error:
2446         /* XXX Do we need to release all claimed endpoints here? */
2447         return ret;
2448 }
2449
2450 static int ffs_func_bind(struct usb_configuration *c,
2451                          struct usb_function *f)
2452 {
2453         struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2454
2455         if (IS_ERR(ffs_opts))
2456                 return PTR_ERR(ffs_opts);
2457
2458         return _ffs_func_bind(c, f);
2459 }
2460
2461
2462 /* Other USB function hooks *************************************************/
2463
2464 static int ffs_func_set_alt(struct usb_function *f,
2465                             unsigned interface, unsigned alt)
2466 {
2467         struct ffs_function *func = ffs_func_from_usb(f);
2468         struct ffs_data *ffs = func->ffs;
2469         int ret = 0, intf;
2470
2471         if (alt != (unsigned)-1) {
2472                 intf = ffs_func_revmap_intf(func, interface);
2473                 if (unlikely(intf < 0))
2474                         return intf;
2475         }
2476
2477         if (ffs->func)
2478                 ffs_func_eps_disable(ffs->func);
2479
2480         if (ffs->state != FFS_ACTIVE)
2481                 return -ENODEV;
2482
2483         if (alt == (unsigned)-1) {
2484                 ffs->func = NULL;
2485                 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2486                 return 0;
2487         }
2488
2489         ffs->func = func;
2490         ret = ffs_func_eps_enable(func);
2491         if (likely(ret >= 0))
2492                 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2493         return ret;
2494 }
2495
2496 static void ffs_func_disable(struct usb_function *f)
2497 {
2498         ffs_func_set_alt(f, 0, (unsigned)-1);
2499 }
2500
2501 static int ffs_func_setup(struct usb_function *f,
2502                           const struct usb_ctrlrequest *creq)
2503 {
2504         struct ffs_function *func = ffs_func_from_usb(f);
2505         struct ffs_data *ffs = func->ffs;
2506         unsigned long flags;
2507         int ret;
2508
2509         ENTER();
2510
2511         pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2512         pr_vdebug("creq->bRequest     = %02x\n", creq->bRequest);
2513         pr_vdebug("creq->wValue       = %04x\n", le16_to_cpu(creq->wValue));
2514         pr_vdebug("creq->wIndex       = %04x\n", le16_to_cpu(creq->wIndex));
2515         pr_vdebug("creq->wLength      = %04x\n", le16_to_cpu(creq->wLength));
2516
2517         /*
2518          * Most requests directed to interface go through here
2519          * (notable exceptions are set/get interface) so we need to
2520          * handle them.  All other either handled by composite or
2521          * passed to usb_configuration->setup() (if one is set).  No
2522          * matter, we will handle requests directed to endpoint here
2523          * as well (as it's straightforward) but what to do with any
2524          * other request?
2525          */
2526         if (ffs->state != FFS_ACTIVE)
2527                 return -ENODEV;
2528
2529         switch (creq->bRequestType & USB_RECIP_MASK) {
2530         case USB_RECIP_INTERFACE:
2531                 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2532                 if (unlikely(ret < 0))
2533                         return ret;
2534                 break;
2535
2536         case USB_RECIP_ENDPOINT:
2537                 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2538                 if (unlikely(ret < 0))
2539                         return ret;
2540                 break;
2541
2542         default:
2543                 return -EOPNOTSUPP;
2544         }
2545
2546         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2547         ffs->ev.setup = *creq;
2548         ffs->ev.setup.wIndex = cpu_to_le16(ret);
2549         __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2550         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2551
2552         return 0;
2553 }
2554
2555 static void ffs_func_suspend(struct usb_function *f)
2556 {
2557         ENTER();
2558         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2559 }
2560
2561 static void ffs_func_resume(struct usb_function *f)
2562 {
2563         ENTER();
2564         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2565 }
2566
2567
2568 /* Endpoint and interface numbers reverse mapping ***************************/
2569
2570 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2571 {
2572         num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2573         return num ? num : -EDOM;
2574 }
2575
2576 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2577 {
2578         short *nums = func->interfaces_nums;
2579         unsigned count = func->ffs->interfaces_count;
2580
2581         for (; count; --count, ++nums) {
2582                 if (*nums >= 0 && *nums == intf)
2583                         return nums - func->interfaces_nums;
2584         }
2585
2586         return -EDOM;
2587 }
2588
2589
2590 /* Devices management *******************************************************/
2591
2592 static LIST_HEAD(ffs_devices);
2593
2594 static struct ffs_dev *_ffs_do_find_dev(const char *name)
2595 {
2596         struct ffs_dev *dev;
2597
2598         list_for_each_entry(dev, &ffs_devices, entry) {
2599                 if (!dev->name || !name)
2600                         continue;
2601                 if (strcmp(dev->name, name) == 0)
2602                         return dev;
2603         }
2604
2605         return NULL;
2606 }
2607
2608 /*
2609  * ffs_lock must be taken by the caller of this function
2610  */
2611 static struct ffs_dev *_ffs_get_single_dev(void)
2612 {
2613         struct ffs_dev *dev;
2614
2615         if (list_is_singular(&ffs_devices)) {
2616                 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
2617                 if (dev->single)
2618                         return dev;
2619         }
2620
2621         return NULL;
2622 }
2623
2624 /*
2625  * ffs_lock must be taken by the caller of this function
2626  */
2627 static struct ffs_dev *_ffs_find_dev(const char *name)
2628 {
2629         struct ffs_dev *dev;
2630
2631         dev = _ffs_get_single_dev();
2632         if (dev)
2633                 return dev;
2634
2635         return _ffs_do_find_dev(name);
2636 }
2637
2638 /* Configfs support *********************************************************/
2639
2640 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
2641 {
2642         return container_of(to_config_group(item), struct f_fs_opts,
2643                             func_inst.group);
2644 }
2645
2646 static void ffs_attr_release(struct config_item *item)
2647 {
2648         struct f_fs_opts *opts = to_ffs_opts(item);
2649
2650         usb_put_function_instance(&opts->func_inst);
2651 }
2652
2653 static struct configfs_item_operations ffs_item_ops = {
2654         .release        = ffs_attr_release,
2655 };
2656
2657 static struct config_item_type ffs_func_type = {
2658         .ct_item_ops    = &ffs_item_ops,
2659         .ct_owner       = THIS_MODULE,
2660 };
2661
2662
2663 /* Function registration interface ******************************************/
2664
2665 static void ffs_free_inst(struct usb_function_instance *f)
2666 {
2667         struct f_fs_opts *opts;
2668
2669         opts = to_f_fs_opts(f);
2670         ffs_dev_lock();
2671         _ffs_free_dev(opts->dev);
2672         ffs_dev_unlock();
2673         kfree(opts);
2674 }
2675
2676 #define MAX_INST_NAME_LEN       40
2677
2678 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
2679 {
2680         struct f_fs_opts *opts;
2681         char *ptr;
2682         const char *tmp;
2683         int name_len, ret;
2684
2685         name_len = strlen(name) + 1;
2686         if (name_len > MAX_INST_NAME_LEN)
2687                 return -ENAMETOOLONG;
2688
2689         ptr = kstrndup(name, name_len, GFP_KERNEL);
2690         if (!ptr)
2691                 return -ENOMEM;
2692
2693         opts = to_f_fs_opts(fi);
2694         tmp = NULL;
2695
2696         ffs_dev_lock();
2697
2698         tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
2699         ret = _ffs_name_dev(opts->dev, ptr);
2700         if (ret) {
2701                 kfree(ptr);
2702                 ffs_dev_unlock();
2703                 return ret;
2704         }
2705         opts->dev->name_allocated = true;
2706
2707         ffs_dev_unlock();
2708
2709         kfree(tmp);
2710
2711         return 0;
2712 }
2713
2714 static struct usb_function_instance *ffs_alloc_inst(void)
2715 {
2716         struct f_fs_opts *opts;
2717         struct ffs_dev *dev;
2718
2719         opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2720         if (!opts)
2721                 return ERR_PTR(-ENOMEM);
2722
2723         opts->func_inst.set_inst_name = ffs_set_inst_name;
2724         opts->func_inst.free_func_inst = ffs_free_inst;
2725         ffs_dev_lock();
2726         dev = _ffs_alloc_dev();
2727         ffs_dev_unlock();
2728         if (IS_ERR(dev)) {
2729                 kfree(opts);
2730                 return ERR_CAST(dev);
2731         }
2732         opts->dev = dev;
2733         dev->opts = opts;
2734
2735         config_group_init_type_name(&opts->func_inst.group, "",
2736                                     &ffs_func_type);
2737         return &opts->func_inst;
2738 }
2739
2740 static void ffs_free(struct usb_function *f)
2741 {
2742         kfree(ffs_func_from_usb(f));
2743 }
2744
2745 static void ffs_func_unbind(struct usb_configuration *c,
2746                             struct usb_function *f)
2747 {
2748         struct ffs_function *func = ffs_func_from_usb(f);
2749         struct ffs_data *ffs = func->ffs;
2750         struct f_fs_opts *opts =
2751                 container_of(f->fi, struct f_fs_opts, func_inst);
2752         struct ffs_ep *ep = func->eps;
2753         unsigned count = ffs->eps_count;
2754         unsigned long flags;
2755
2756         ENTER();
2757         if (ffs->func == func) {
2758                 ffs_func_eps_disable(func);
2759                 ffs->func = NULL;
2760         }
2761
2762         if (!--opts->refcnt)
2763                 functionfs_unbind(ffs);
2764
2765         /* cleanup after autoconfig */
2766         spin_lock_irqsave(&func->ffs->eps_lock, flags);
2767         do {
2768                 if (ep->ep && ep->req)
2769                         usb_ep_free_request(ep->ep, ep->req);
2770                 ep->req = NULL;
2771                 ++ep;
2772         } while (--count);
2773         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2774         kfree(func->eps);
2775         func->eps = NULL;
2776         /*
2777          * eps, descriptors and interfaces_nums are allocated in the
2778          * same chunk so only one free is required.
2779          */
2780         func->function.fs_descriptors = NULL;
2781         func->function.hs_descriptors = NULL;
2782         func->function.ss_descriptors = NULL;
2783         func->interfaces_nums = NULL;
2784
2785         ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2786 }
2787
2788 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
2789 {
2790         struct ffs_function *func;
2791
2792         ENTER();
2793
2794         func = kzalloc(sizeof(*func), GFP_KERNEL);
2795         if (unlikely(!func))
2796                 return ERR_PTR(-ENOMEM);
2797
2798         func->function.name    = "Function FS Gadget";
2799
2800         func->function.bind    = ffs_func_bind;
2801         func->function.unbind  = ffs_func_unbind;
2802         func->function.set_alt = ffs_func_set_alt;
2803         func->function.disable = ffs_func_disable;
2804         func->function.setup   = ffs_func_setup;
2805         func->function.suspend = ffs_func_suspend;
2806         func->function.resume  = ffs_func_resume;
2807         func->function.free_func = ffs_free;
2808
2809         return &func->function;
2810 }
2811
2812 /*
2813  * ffs_lock must be taken by the caller of this function
2814  */
2815 static struct ffs_dev *_ffs_alloc_dev(void)
2816 {
2817         struct ffs_dev *dev;
2818         int ret;
2819
2820         if (_ffs_get_single_dev())
2821                         return ERR_PTR(-EBUSY);
2822
2823         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2824         if (!dev)
2825                 return ERR_PTR(-ENOMEM);
2826
2827         if (list_empty(&ffs_devices)) {
2828                 ret = functionfs_init();
2829                 if (ret) {
2830                         kfree(dev);
2831                         return ERR_PTR(ret);
2832                 }
2833         }
2834
2835         list_add(&dev->entry, &ffs_devices);
2836
2837         return dev;
2838 }
2839
2840 /*
2841  * ffs_lock must be taken by the caller of this function
2842  * The caller is responsible for "name" being available whenever f_fs needs it
2843  */
2844 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
2845 {
2846         struct ffs_dev *existing;
2847
2848         existing = _ffs_do_find_dev(name);
2849         if (existing)
2850                 return -EBUSY;
2851
2852         dev->name = name;
2853
2854         return 0;
2855 }
2856
2857 /*
2858  * The caller is responsible for "name" being available whenever f_fs needs it
2859  */
2860 int ffs_name_dev(struct ffs_dev *dev, const char *name)
2861 {
2862         int ret;
2863
2864         ffs_dev_lock();
2865         ret = _ffs_name_dev(dev, name);
2866         ffs_dev_unlock();
2867
2868         return ret;
2869 }
2870 EXPORT_SYMBOL(ffs_name_dev);
2871
2872 int ffs_single_dev(struct ffs_dev *dev)
2873 {
2874         int ret;
2875
2876         ret = 0;
2877         ffs_dev_lock();
2878
2879         if (!list_is_singular(&ffs_devices))
2880                 ret = -EBUSY;
2881         else
2882                 dev->single = true;
2883
2884         ffs_dev_unlock();
2885         return ret;
2886 }
2887 EXPORT_SYMBOL(ffs_single_dev);
2888
2889 /*
2890  * ffs_lock must be taken by the caller of this function
2891  */
2892 static void _ffs_free_dev(struct ffs_dev *dev)
2893 {
2894         list_del(&dev->entry);
2895         if (dev->name_allocated)
2896                 kfree(dev->name);
2897         kfree(dev);
2898         if (list_empty(&ffs_devices))
2899                 functionfs_cleanup();
2900 }
2901
2902 static void *ffs_acquire_dev(const char *dev_name)
2903 {
2904         struct ffs_dev *ffs_dev;
2905
2906         ENTER();
2907         ffs_dev_lock();
2908
2909         ffs_dev = _ffs_find_dev(dev_name);
2910         if (!ffs_dev)
2911                 ffs_dev = ERR_PTR(-ENODEV);
2912         else if (ffs_dev->mounted)
2913                 ffs_dev = ERR_PTR(-EBUSY);
2914         else if (ffs_dev->ffs_acquire_dev_callback &&
2915             ffs_dev->ffs_acquire_dev_callback(ffs_dev))
2916                 ffs_dev = ERR_PTR(-ENODEV);
2917         else
2918                 ffs_dev->mounted = true;
2919
2920         ffs_dev_unlock();
2921         return ffs_dev;
2922 }
2923
2924 static void ffs_release_dev(struct ffs_data *ffs_data)
2925 {
2926         struct ffs_dev *ffs_dev;
2927
2928         ENTER();
2929         ffs_dev_lock();
2930
2931         ffs_dev = ffs_data->private_data;
2932         if (ffs_dev) {
2933                 ffs_dev->mounted = false;
2934
2935                 if (ffs_dev->ffs_release_dev_callback)
2936                         ffs_dev->ffs_release_dev_callback(ffs_dev);
2937         }
2938
2939         ffs_dev_unlock();
2940 }
2941
2942 static int ffs_ready(struct ffs_data *ffs)
2943 {
2944         struct ffs_dev *ffs_obj;
2945         int ret = 0;
2946
2947         ENTER();
2948         ffs_dev_lock();
2949
2950         ffs_obj = ffs->private_data;
2951         if (!ffs_obj) {
2952                 ret = -EINVAL;
2953                 goto done;
2954         }
2955         if (WARN_ON(ffs_obj->desc_ready)) {
2956                 ret = -EBUSY;
2957                 goto done;
2958         }
2959
2960         ffs_obj->desc_ready = true;
2961         ffs_obj->ffs_data = ffs;
2962
2963         if (ffs_obj->ffs_ready_callback)
2964                 ret = ffs_obj->ffs_ready_callback(ffs);
2965
2966 done:
2967         ffs_dev_unlock();
2968         return ret;
2969 }
2970
2971 static void ffs_closed(struct ffs_data *ffs)
2972 {
2973         struct ffs_dev *ffs_obj;
2974
2975         ENTER();
2976         ffs_dev_lock();
2977
2978         ffs_obj = ffs->private_data;
2979         if (!ffs_obj)
2980                 goto done;
2981
2982         ffs_obj->desc_ready = false;
2983
2984         if (ffs_obj->ffs_closed_callback)
2985                 ffs_obj->ffs_closed_callback(ffs);
2986
2987         if (!ffs_obj->opts || ffs_obj->opts->no_configfs
2988             || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
2989                 goto done;
2990
2991         unregister_gadget_item(ffs_obj->opts->
2992                                func_inst.group.cg_item.ci_parent->ci_parent);
2993 done:
2994         ffs_dev_unlock();
2995 }
2996
2997 /* Misc helper functions ****************************************************/
2998
2999 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3000 {
3001         return nonblock
3002                 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3003                 : mutex_lock_interruptible(mutex);
3004 }
3005
3006 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3007 {
3008         char *data;
3009
3010         if (unlikely(!len))
3011                 return NULL;
3012
3013         data = kmalloc(len, GFP_KERNEL);
3014         if (unlikely(!data))
3015                 return ERR_PTR(-ENOMEM);
3016
3017         if (unlikely(__copy_from_user(data, buf, len))) {
3018                 kfree(data);
3019                 return ERR_PTR(-EFAULT);
3020         }
3021
3022         pr_vdebug("Buffer from user space:\n");
3023         ffs_dump_mem("", data, len);
3024
3025         return data;
3026 }
3027
3028 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3029 MODULE_LICENSE("GPL");
3030 MODULE_AUTHOR("Michal Nazarewicz");