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