iwlwifi: pcie: fix polling in various places
[cascardo/linux.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                 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1561                         sprintf(epfiles->name, "ep%02x", ffs->eps_addrmap[i]);
1562                 else
1563                         sprintf(epfiles->name, "ep%u", i);
1564                 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1565                                                  &ffs_epfile_operations,
1566                                                  &epfile->dentry))) {
1567                         ffs_epfiles_destroy(epfiles, i - 1);
1568                         return -ENOMEM;
1569                 }
1570         }
1571
1572         ffs->epfiles = epfiles;
1573         return 0;
1574 }
1575
1576 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1577 {
1578         struct ffs_epfile *epfile = epfiles;
1579
1580         ENTER();
1581
1582         for (; count; --count, ++epfile) {
1583                 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1584                        waitqueue_active(&epfile->wait));
1585                 if (epfile->dentry) {
1586                         d_delete(epfile->dentry);
1587                         dput(epfile->dentry);
1588                         epfile->dentry = NULL;
1589                 }
1590         }
1591
1592         kfree(epfiles);
1593 }
1594
1595
1596 static void ffs_func_eps_disable(struct ffs_function *func)
1597 {
1598         struct ffs_ep *ep         = func->eps;
1599         struct ffs_epfile *epfile = func->ffs->epfiles;
1600         unsigned count            = func->ffs->eps_count;
1601         unsigned long flags;
1602
1603         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1604         do {
1605                 /* pending requests get nuked */
1606                 if (likely(ep->ep))
1607                         usb_ep_disable(ep->ep);
1608                 epfile->ep = NULL;
1609
1610                 ++ep;
1611                 ++epfile;
1612         } while (--count);
1613         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1614 }
1615
1616 static int ffs_func_eps_enable(struct ffs_function *func)
1617 {
1618         struct ffs_data *ffs      = func->ffs;
1619         struct ffs_ep *ep         = func->eps;
1620         struct ffs_epfile *epfile = ffs->epfiles;
1621         unsigned count            = ffs->eps_count;
1622         unsigned long flags;
1623         int ret = 0;
1624
1625         spin_lock_irqsave(&func->ffs->eps_lock, flags);
1626         do {
1627                 struct usb_endpoint_descriptor *ds;
1628                 int desc_idx;
1629
1630                 if (ffs->gadget->speed == USB_SPEED_SUPER)
1631                         desc_idx = 2;
1632                 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1633                         desc_idx = 1;
1634                 else
1635                         desc_idx = 0;
1636
1637                 /* fall-back to lower speed if desc missing for current speed */
1638                 do {
1639                         ds = ep->descs[desc_idx];
1640                 } while (!ds && --desc_idx >= 0);
1641
1642                 if (!ds) {
1643                         ret = -EINVAL;
1644                         break;
1645                 }
1646
1647                 ep->ep->driver_data = ep;
1648                 ep->ep->desc = ds;
1649                 ret = usb_ep_enable(ep->ep);
1650                 if (likely(!ret)) {
1651                         epfile->ep = ep;
1652                         epfile->in = usb_endpoint_dir_in(ds);
1653                         epfile->isoc = usb_endpoint_xfer_isoc(ds);
1654                 } else {
1655                         break;
1656                 }
1657
1658                 wake_up(&epfile->wait);
1659
1660                 ++ep;
1661                 ++epfile;
1662         } while (--count);
1663         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1664
1665         return ret;
1666 }
1667
1668
1669 /* Parsing and building descriptors and strings *****************************/
1670
1671 /*
1672  * This validates if data pointed by data is a valid USB descriptor as
1673  * well as record how many interfaces, endpoints and strings are
1674  * required by given configuration.  Returns address after the
1675  * descriptor or NULL if data is invalid.
1676  */
1677
1678 enum ffs_entity_type {
1679         FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1680 };
1681
1682 enum ffs_os_desc_type {
1683         FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1684 };
1685
1686 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1687                                    u8 *valuep,
1688                                    struct usb_descriptor_header *desc,
1689                                    void *priv);
1690
1691 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1692                                     struct usb_os_desc_header *h, void *data,
1693                                     unsigned len, void *priv);
1694
1695 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1696                                            ffs_entity_callback entity,
1697                                            void *priv)
1698 {
1699         struct usb_descriptor_header *_ds = (void *)data;
1700         u8 length;
1701         int ret;
1702
1703         ENTER();
1704
1705         /* At least two bytes are required: length and type */
1706         if (len < 2) {
1707                 pr_vdebug("descriptor too short\n");
1708                 return -EINVAL;
1709         }
1710
1711         /* If we have at least as many bytes as the descriptor takes? */
1712         length = _ds->bLength;
1713         if (len < length) {
1714                 pr_vdebug("descriptor longer then available data\n");
1715                 return -EINVAL;
1716         }
1717
1718 #define __entity_check_INTERFACE(val)  1
1719 #define __entity_check_STRING(val)     (val)
1720 #define __entity_check_ENDPOINT(val)   ((val) & USB_ENDPOINT_NUMBER_MASK)
1721 #define __entity(type, val) do {                                        \
1722                 pr_vdebug("entity " #type "(%02x)\n", (val));           \
1723                 if (unlikely(!__entity_check_ ##type(val))) {           \
1724                         pr_vdebug("invalid entity's value\n");          \
1725                         return -EINVAL;                                 \
1726                 }                                                       \
1727                 ret = entity(FFS_ ##type, &val, _ds, priv);             \
1728                 if (unlikely(ret < 0)) {                                \
1729                         pr_debug("entity " #type "(%02x); ret = %d\n",  \
1730                                  (val), ret);                           \
1731                         return ret;                                     \
1732                 }                                                       \
1733         } while (0)
1734
1735         /* Parse descriptor depending on type. */
1736         switch (_ds->bDescriptorType) {
1737         case USB_DT_DEVICE:
1738         case USB_DT_CONFIG:
1739         case USB_DT_STRING:
1740         case USB_DT_DEVICE_QUALIFIER:
1741                 /* function can't have any of those */
1742                 pr_vdebug("descriptor reserved for gadget: %d\n",
1743                       _ds->bDescriptorType);
1744                 return -EINVAL;
1745
1746         case USB_DT_INTERFACE: {
1747                 struct usb_interface_descriptor *ds = (void *)_ds;
1748                 pr_vdebug("interface descriptor\n");
1749                 if (length != sizeof *ds)
1750                         goto inv_length;
1751
1752                 __entity(INTERFACE, ds->bInterfaceNumber);
1753                 if (ds->iInterface)
1754                         __entity(STRING, ds->iInterface);
1755         }
1756                 break;
1757
1758         case USB_DT_ENDPOINT: {
1759                 struct usb_endpoint_descriptor *ds = (void *)_ds;
1760                 pr_vdebug("endpoint descriptor\n");
1761                 if (length != USB_DT_ENDPOINT_SIZE &&
1762                     length != USB_DT_ENDPOINT_AUDIO_SIZE)
1763                         goto inv_length;
1764                 __entity(ENDPOINT, ds->bEndpointAddress);
1765         }
1766                 break;
1767
1768         case HID_DT_HID:
1769                 pr_vdebug("hid descriptor\n");
1770                 if (length != sizeof(struct hid_descriptor))
1771                         goto inv_length;
1772                 break;
1773
1774         case USB_DT_OTG:
1775                 if (length != sizeof(struct usb_otg_descriptor))
1776                         goto inv_length;
1777                 break;
1778
1779         case USB_DT_INTERFACE_ASSOCIATION: {
1780                 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1781                 pr_vdebug("interface association descriptor\n");
1782                 if (length != sizeof *ds)
1783                         goto inv_length;
1784                 if (ds->iFunction)
1785                         __entity(STRING, ds->iFunction);
1786         }
1787                 break;
1788
1789         case USB_DT_SS_ENDPOINT_COMP:
1790                 pr_vdebug("EP SS companion descriptor\n");
1791                 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1792                         goto inv_length;
1793                 break;
1794
1795         case USB_DT_OTHER_SPEED_CONFIG:
1796         case USB_DT_INTERFACE_POWER:
1797         case USB_DT_DEBUG:
1798         case USB_DT_SECURITY:
1799         case USB_DT_CS_RADIO_CONTROL:
1800                 /* TODO */
1801                 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1802                 return -EINVAL;
1803
1804         default:
1805                 /* We should never be here */
1806                 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1807                 return -EINVAL;
1808
1809 inv_length:
1810                 pr_vdebug("invalid length: %d (descriptor %d)\n",
1811                           _ds->bLength, _ds->bDescriptorType);
1812                 return -EINVAL;
1813         }
1814
1815 #undef __entity
1816 #undef __entity_check_DESCRIPTOR
1817 #undef __entity_check_INTERFACE
1818 #undef __entity_check_STRING
1819 #undef __entity_check_ENDPOINT
1820
1821         return length;
1822 }
1823
1824 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1825                                      ffs_entity_callback entity, void *priv)
1826 {
1827         const unsigned _len = len;
1828         unsigned long num = 0;
1829
1830         ENTER();
1831
1832         for (;;) {
1833                 int ret;
1834
1835                 if (num == count)
1836                         data = NULL;
1837
1838                 /* Record "descriptor" entity */
1839                 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1840                 if (unlikely(ret < 0)) {
1841                         pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1842                                  num, ret);
1843                         return ret;
1844                 }
1845
1846                 if (!data)
1847                         return _len - len;
1848
1849                 ret = ffs_do_single_desc(data, len, entity, priv);
1850                 if (unlikely(ret < 0)) {
1851                         pr_debug("%s returns %d\n", __func__, ret);
1852                         return ret;
1853                 }
1854
1855                 len -= ret;
1856                 data += ret;
1857                 ++num;
1858         }
1859 }
1860
1861 static int __ffs_data_do_entity(enum ffs_entity_type type,
1862                                 u8 *valuep, struct usb_descriptor_header *desc,
1863                                 void *priv)
1864 {
1865         struct ffs_desc_helper *helper = priv;
1866         struct usb_endpoint_descriptor *d;
1867
1868         ENTER();
1869
1870         switch (type) {
1871         case FFS_DESCRIPTOR:
1872                 break;
1873
1874         case FFS_INTERFACE:
1875                 /*
1876                  * Interfaces are indexed from zero so if we
1877                  * encountered interface "n" then there are at least
1878                  * "n+1" interfaces.
1879                  */
1880                 if (*valuep >= helper->interfaces_count)
1881                         helper->interfaces_count = *valuep + 1;
1882                 break;
1883
1884         case FFS_STRING:
1885                 /*
1886                  * Strings are indexed from 1 (0 is magic ;) reserved
1887                  * for languages list or some such)
1888                  */
1889                 if (*valuep > helper->ffs->strings_count)
1890                         helper->ffs->strings_count = *valuep;
1891                 break;
1892
1893         case FFS_ENDPOINT:
1894                 d = (void *)desc;
1895                 helper->eps_count++;
1896                 if (helper->eps_count >= 15)
1897                         return -EINVAL;
1898                 /* Check if descriptors for any speed were already parsed */
1899                 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
1900                         helper->ffs->eps_addrmap[helper->eps_count] =
1901                                 d->bEndpointAddress;
1902                 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
1903                                 d->bEndpointAddress)
1904                         return -EINVAL;
1905                 break;
1906         }
1907
1908         return 0;
1909 }
1910
1911 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1912                                    struct usb_os_desc_header *desc)
1913 {
1914         u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1915         u16 w_index = le16_to_cpu(desc->wIndex);
1916
1917         if (bcd_version != 1) {
1918                 pr_vdebug("unsupported os descriptors version: %d",
1919                           bcd_version);
1920                 return -EINVAL;
1921         }
1922         switch (w_index) {
1923         case 0x4:
1924                 *next_type = FFS_OS_DESC_EXT_COMPAT;
1925                 break;
1926         case 0x5:
1927                 *next_type = FFS_OS_DESC_EXT_PROP;
1928                 break;
1929         default:
1930                 pr_vdebug("unsupported os descriptor type: %d", w_index);
1931                 return -EINVAL;
1932         }
1933
1934         return sizeof(*desc);
1935 }
1936
1937 /*
1938  * Process all extended compatibility/extended property descriptors
1939  * of a feature descriptor
1940  */
1941 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1942                                               enum ffs_os_desc_type type,
1943                                               u16 feature_count,
1944                                               ffs_os_desc_callback entity,
1945                                               void *priv,
1946                                               struct usb_os_desc_header *h)
1947 {
1948         int ret;
1949         const unsigned _len = len;
1950
1951         ENTER();
1952
1953         /* loop over all ext compat/ext prop descriptors */
1954         while (feature_count--) {
1955                 ret = entity(type, h, data, len, priv);
1956                 if (unlikely(ret < 0)) {
1957                         pr_debug("bad OS descriptor, type: %d\n", type);
1958                         return ret;
1959                 }
1960                 data += ret;
1961                 len -= ret;
1962         }
1963         return _len - len;
1964 }
1965
1966 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1967 static int __must_check ffs_do_os_descs(unsigned count,
1968                                         char *data, unsigned len,
1969                                         ffs_os_desc_callback entity, void *priv)
1970 {
1971         const unsigned _len = len;
1972         unsigned long num = 0;
1973
1974         ENTER();
1975
1976         for (num = 0; num < count; ++num) {
1977                 int ret;
1978                 enum ffs_os_desc_type type;
1979                 u16 feature_count;
1980                 struct usb_os_desc_header *desc = (void *)data;
1981
1982                 if (len < sizeof(*desc))
1983                         return -EINVAL;
1984
1985                 /*
1986                  * Record "descriptor" entity.
1987                  * Process dwLength, bcdVersion, wIndex, get b/wCount.
1988                  * Move the data pointer to the beginning of extended
1989                  * compatibilities proper or extended properties proper
1990                  * portions of the data
1991                  */
1992                 if (le32_to_cpu(desc->dwLength) > len)
1993                         return -EINVAL;
1994
1995                 ret = __ffs_do_os_desc_header(&type, desc);
1996                 if (unlikely(ret < 0)) {
1997                         pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
1998                                  num, ret);
1999                         return ret;
2000                 }
2001                 /*
2002                  * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2003                  */
2004                 feature_count = le16_to_cpu(desc->wCount);
2005                 if (type == FFS_OS_DESC_EXT_COMPAT &&
2006                     (feature_count > 255 || desc->Reserved))
2007                                 return -EINVAL;
2008                 len -= ret;
2009                 data += ret;
2010
2011                 /*
2012                  * Process all function/property descriptors
2013                  * of this Feature Descriptor
2014                  */
2015                 ret = ffs_do_single_os_desc(data, len, type,
2016                                             feature_count, entity, priv, desc);
2017                 if (unlikely(ret < 0)) {
2018                         pr_debug("%s returns %d\n", __func__, ret);
2019                         return ret;
2020                 }
2021
2022                 len -= ret;
2023                 data += ret;
2024         }
2025         return _len - len;
2026 }
2027
2028 /**
2029  * Validate contents of the buffer from userspace related to OS descriptors.
2030  */
2031 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2032                                  struct usb_os_desc_header *h, void *data,
2033                                  unsigned len, void *priv)
2034 {
2035         struct ffs_data *ffs = priv;
2036         u8 length;
2037
2038         ENTER();
2039
2040         switch (type) {
2041         case FFS_OS_DESC_EXT_COMPAT: {
2042                 struct usb_ext_compat_desc *d = data;
2043                 int i;
2044
2045                 if (len < sizeof(*d) ||
2046                     d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2047                     d->Reserved1)
2048                         return -EINVAL;
2049                 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2050                         if (d->Reserved2[i])
2051                                 return -EINVAL;
2052
2053                 length = sizeof(struct usb_ext_compat_desc);
2054         }
2055                 break;
2056         case FFS_OS_DESC_EXT_PROP: {
2057                 struct usb_ext_prop_desc *d = data;
2058                 u32 type, pdl;
2059                 u16 pnl;
2060
2061                 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2062                         return -EINVAL;
2063                 length = le32_to_cpu(d->dwSize);
2064                 type = le32_to_cpu(d->dwPropertyDataType);
2065                 if (type < USB_EXT_PROP_UNICODE ||
2066                     type > USB_EXT_PROP_UNICODE_MULTI) {
2067                         pr_vdebug("unsupported os descriptor property type: %d",
2068                                   type);
2069                         return -EINVAL;
2070                 }
2071                 pnl = le16_to_cpu(d->wPropertyNameLength);
2072                 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2073                 if (length != 14 + pnl + pdl) {
2074                         pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2075                                   length, pnl, pdl, type);
2076                         return -EINVAL;
2077                 }
2078                 ++ffs->ms_os_descs_ext_prop_count;
2079                 /* property name reported to the host as "WCHAR"s */
2080                 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2081                 ffs->ms_os_descs_ext_prop_data_len += pdl;
2082         }
2083                 break;
2084         default:
2085                 pr_vdebug("unknown descriptor: %d\n", type);
2086                 return -EINVAL;
2087         }
2088         return length;
2089 }
2090
2091 static int __ffs_data_got_descs(struct ffs_data *ffs,
2092                                 char *const _data, size_t len)
2093 {
2094         char *data = _data, *raw_descs;
2095         unsigned os_descs_count = 0, counts[3], flags;
2096         int ret = -EINVAL, i;
2097         struct ffs_desc_helper helper;
2098
2099         ENTER();
2100
2101         if (get_unaligned_le32(data + 4) != len)
2102                 goto error;
2103
2104         switch (get_unaligned_le32(data)) {
2105         case FUNCTIONFS_DESCRIPTORS_MAGIC:
2106                 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2107                 data += 8;
2108                 len  -= 8;
2109                 break;
2110         case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2111                 flags = get_unaligned_le32(data + 8);
2112                 ffs->user_flags = flags;
2113                 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2114                               FUNCTIONFS_HAS_HS_DESC |
2115                               FUNCTIONFS_HAS_SS_DESC |
2116                               FUNCTIONFS_HAS_MS_OS_DESC |
2117                               FUNCTIONFS_VIRTUAL_ADDR)) {
2118                         ret = -ENOSYS;
2119                         goto error;
2120                 }
2121                 data += 12;
2122                 len  -= 12;
2123                 break;
2124         default:
2125                 goto error;
2126         }
2127
2128         /* Read fs_count, hs_count and ss_count (if present) */
2129         for (i = 0; i < 3; ++i) {
2130                 if (!(flags & (1 << i))) {
2131                         counts[i] = 0;
2132                 } else if (len < 4) {
2133                         goto error;
2134                 } else {
2135                         counts[i] = get_unaligned_le32(data);
2136                         data += 4;
2137                         len  -= 4;
2138                 }
2139         }
2140         if (flags & (1 << i)) {
2141                 os_descs_count = get_unaligned_le32(data);
2142                 data += 4;
2143                 len -= 4;
2144         };
2145
2146         /* Read descriptors */
2147         raw_descs = data;
2148         helper.ffs = ffs;
2149         for (i = 0; i < 3; ++i) {
2150                 if (!counts[i])
2151                         continue;
2152                 helper.interfaces_count = 0;
2153                 helper.eps_count = 0;
2154                 ret = ffs_do_descs(counts[i], data, len,
2155                                    __ffs_data_do_entity, &helper);
2156                 if (ret < 0)
2157                         goto error;
2158                 if (!ffs->eps_count && !ffs->interfaces_count) {
2159                         ffs->eps_count = helper.eps_count;
2160                         ffs->interfaces_count = helper.interfaces_count;
2161                 } else {
2162                         if (ffs->eps_count != helper.eps_count) {
2163                                 ret = -EINVAL;
2164                                 goto error;
2165                         }
2166                         if (ffs->interfaces_count != helper.interfaces_count) {
2167                                 ret = -EINVAL;
2168                                 goto error;
2169                         }
2170                 }
2171                 data += ret;
2172                 len  -= ret;
2173         }
2174         if (os_descs_count) {
2175                 ret = ffs_do_os_descs(os_descs_count, data, len,
2176                                       __ffs_data_do_os_desc, ffs);
2177                 if (ret < 0)
2178                         goto error;
2179                 data += ret;
2180                 len -= ret;
2181         }
2182
2183         if (raw_descs == data || len) {
2184                 ret = -EINVAL;
2185                 goto error;
2186         }
2187
2188         ffs->raw_descs_data     = _data;
2189         ffs->raw_descs          = raw_descs;
2190         ffs->raw_descs_length   = data - raw_descs;
2191         ffs->fs_descs_count     = counts[0];
2192         ffs->hs_descs_count     = counts[1];
2193         ffs->ss_descs_count     = counts[2];
2194         ffs->ms_os_descs_count  = os_descs_count;
2195
2196         return 0;
2197
2198 error:
2199         kfree(_data);
2200         return ret;
2201 }
2202
2203 static int __ffs_data_got_strings(struct ffs_data *ffs,
2204                                   char *const _data, size_t len)
2205 {
2206         u32 str_count, needed_count, lang_count;
2207         struct usb_gadget_strings **stringtabs, *t;
2208         struct usb_string *strings, *s;
2209         const char *data = _data;
2210
2211         ENTER();
2212
2213         if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2214                      get_unaligned_le32(data + 4) != len))
2215                 goto error;
2216         str_count  = get_unaligned_le32(data + 8);
2217         lang_count = get_unaligned_le32(data + 12);
2218
2219         /* if one is zero the other must be zero */
2220         if (unlikely(!str_count != !lang_count))
2221                 goto error;
2222
2223         /* Do we have at least as many strings as descriptors need? */
2224         needed_count = ffs->strings_count;
2225         if (unlikely(str_count < needed_count))
2226                 goto error;
2227
2228         /*
2229          * If we don't need any strings just return and free all
2230          * memory.
2231          */
2232         if (!needed_count) {
2233                 kfree(_data);
2234                 return 0;
2235         }
2236
2237         /* Allocate everything in one chunk so there's less maintenance. */
2238         {
2239                 unsigned i = 0;
2240                 vla_group(d);
2241                 vla_item(d, struct usb_gadget_strings *, stringtabs,
2242                         lang_count + 1);
2243                 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2244                 vla_item(d, struct usb_string, strings,
2245                         lang_count*(needed_count+1));
2246
2247                 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2248
2249                 if (unlikely(!vlabuf)) {
2250                         kfree(_data);
2251                         return -ENOMEM;
2252                 }
2253
2254                 /* Initialize the VLA pointers */
2255                 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2256                 t = vla_ptr(vlabuf, d, stringtab);
2257                 i = lang_count;
2258                 do {
2259                         *stringtabs++ = t++;
2260                 } while (--i);
2261                 *stringtabs = NULL;
2262
2263                 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2264                 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2265                 t = vla_ptr(vlabuf, d, stringtab);
2266                 s = vla_ptr(vlabuf, d, strings);
2267                 strings = s;
2268         }
2269
2270         /* For each language */
2271         data += 16;
2272         len -= 16;
2273
2274         do { /* lang_count > 0 so we can use do-while */
2275                 unsigned needed = needed_count;
2276
2277                 if (unlikely(len < 3))
2278                         goto error_free;
2279                 t->language = get_unaligned_le16(data);
2280                 t->strings  = s;
2281                 ++t;
2282
2283                 data += 2;
2284                 len -= 2;
2285
2286                 /* For each string */
2287                 do { /* str_count > 0 so we can use do-while */
2288                         size_t length = strnlen(data, len);
2289
2290                         if (unlikely(length == len))
2291                                 goto error_free;
2292
2293                         /*
2294                          * User may provide more strings then we need,
2295                          * if that's the case we simply ignore the
2296                          * rest
2297                          */
2298                         if (likely(needed)) {
2299                                 /*
2300                                  * s->id will be set while adding
2301                                  * function to configuration so for
2302                                  * now just leave garbage here.
2303                                  */
2304                                 s->s = data;
2305                                 --needed;
2306                                 ++s;
2307                         }
2308
2309                         data += length + 1;
2310                         len -= length + 1;
2311                 } while (--str_count);
2312
2313                 s->id = 0;   /* terminator */
2314                 s->s = NULL;
2315                 ++s;
2316
2317         } while (--lang_count);
2318
2319         /* Some garbage left? */
2320         if (unlikely(len))
2321                 goto error_free;
2322
2323         /* Done! */
2324         ffs->stringtabs = stringtabs;
2325         ffs->raw_strings = _data;
2326
2327         return 0;
2328
2329 error_free:
2330         kfree(stringtabs);
2331 error:
2332         kfree(_data);
2333         return -EINVAL;
2334 }
2335
2336
2337 /* Events handling and management *******************************************/
2338
2339 static void __ffs_event_add(struct ffs_data *ffs,
2340                             enum usb_functionfs_event_type type)
2341 {
2342         enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2343         int neg = 0;
2344
2345         /*
2346          * Abort any unhandled setup
2347          *
2348          * We do not need to worry about some cmpxchg() changing value
2349          * of ffs->setup_state without holding the lock because when
2350          * state is FFS_SETUP_PENDING cmpxchg() in several places in
2351          * the source does nothing.
2352          */
2353         if (ffs->setup_state == FFS_SETUP_PENDING)
2354                 ffs->setup_state = FFS_SETUP_CANCELLED;
2355
2356         switch (type) {
2357         case FUNCTIONFS_RESUME:
2358                 rem_type2 = FUNCTIONFS_SUSPEND;
2359                 /* FALL THROUGH */
2360         case FUNCTIONFS_SUSPEND:
2361         case FUNCTIONFS_SETUP:
2362                 rem_type1 = type;
2363                 /* Discard all similar events */
2364                 break;
2365
2366         case FUNCTIONFS_BIND:
2367         case FUNCTIONFS_UNBIND:
2368         case FUNCTIONFS_DISABLE:
2369         case FUNCTIONFS_ENABLE:
2370                 /* Discard everything other then power management. */
2371                 rem_type1 = FUNCTIONFS_SUSPEND;
2372                 rem_type2 = FUNCTIONFS_RESUME;
2373                 neg = 1;
2374                 break;
2375
2376         default:
2377                 WARN(1, "%d: unknown event, this should not happen\n", type);
2378                 return;
2379         }
2380
2381         {
2382                 u8 *ev  = ffs->ev.types, *out = ev;
2383                 unsigned n = ffs->ev.count;
2384                 for (; n; --n, ++ev)
2385                         if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2386                                 *out++ = *ev;
2387                         else
2388                                 pr_vdebug("purging event %d\n", *ev);
2389                 ffs->ev.count = out - ffs->ev.types;
2390         }
2391
2392         pr_vdebug("adding event %d\n", type);
2393         ffs->ev.types[ffs->ev.count++] = type;
2394         wake_up_locked(&ffs->ev.waitq);
2395 }
2396
2397 static void ffs_event_add(struct ffs_data *ffs,
2398                           enum usb_functionfs_event_type type)
2399 {
2400         unsigned long flags;
2401         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2402         __ffs_event_add(ffs, type);
2403         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2404 }
2405
2406 /* Bind/unbind USB function hooks *******************************************/
2407
2408 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2409 {
2410         int i;
2411
2412         for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2413                 if (ffs->eps_addrmap[i] == endpoint_address)
2414                         return i;
2415         return -ENOENT;
2416 }
2417
2418 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2419                                     struct usb_descriptor_header *desc,
2420                                     void *priv)
2421 {
2422         struct usb_endpoint_descriptor *ds = (void *)desc;
2423         struct ffs_function *func = priv;
2424         struct ffs_ep *ffs_ep;
2425         unsigned ep_desc_id;
2426         int idx;
2427         static const char *speed_names[] = { "full", "high", "super" };
2428
2429         if (type != FFS_DESCRIPTOR)
2430                 return 0;
2431
2432         /*
2433          * If ss_descriptors is not NULL, we are reading super speed
2434          * descriptors; if hs_descriptors is not NULL, we are reading high
2435          * speed descriptors; otherwise, we are reading full speed
2436          * descriptors.
2437          */
2438         if (func->function.ss_descriptors) {
2439                 ep_desc_id = 2;
2440                 func->function.ss_descriptors[(long)valuep] = desc;
2441         } else if (func->function.hs_descriptors) {
2442                 ep_desc_id = 1;
2443                 func->function.hs_descriptors[(long)valuep] = desc;
2444         } else {
2445                 ep_desc_id = 0;
2446                 func->function.fs_descriptors[(long)valuep]    = desc;
2447         }
2448
2449         if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2450                 return 0;
2451
2452         idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2453         if (idx < 0)
2454                 return idx;
2455
2456         ffs_ep = func->eps + idx;
2457
2458         if (unlikely(ffs_ep->descs[ep_desc_id])) {
2459                 pr_err("two %sspeed descriptors for EP %d\n",
2460                           speed_names[ep_desc_id],
2461                           ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2462                 return -EINVAL;
2463         }
2464         ffs_ep->descs[ep_desc_id] = ds;
2465
2466         ffs_dump_mem(": Original  ep desc", ds, ds->bLength);
2467         if (ffs_ep->ep) {
2468                 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2469                 if (!ds->wMaxPacketSize)
2470                         ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2471         } else {
2472                 struct usb_request *req;
2473                 struct usb_ep *ep;
2474                 u8 bEndpointAddress;
2475
2476                 /*
2477                  * We back up bEndpointAddress because autoconfig overwrites
2478                  * it with physical endpoint address.
2479                  */
2480                 bEndpointAddress = ds->bEndpointAddress;
2481                 pr_vdebug("autoconfig\n");
2482                 ep = usb_ep_autoconfig(func->gadget, ds);
2483                 if (unlikely(!ep))
2484                         return -ENOTSUPP;
2485                 ep->driver_data = func->eps + idx;
2486
2487                 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2488                 if (unlikely(!req))
2489                         return -ENOMEM;
2490
2491                 ffs_ep->ep  = ep;
2492                 ffs_ep->req = req;
2493                 func->eps_revmap[ds->bEndpointAddress &
2494                                  USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2495                 /*
2496                  * If we use virtual address mapping, we restore
2497                  * original bEndpointAddress value.
2498                  */
2499                 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2500                         ds->bEndpointAddress = bEndpointAddress;
2501         }
2502         ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2503
2504         return 0;
2505 }
2506
2507 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2508                                    struct usb_descriptor_header *desc,
2509                                    void *priv)
2510 {
2511         struct ffs_function *func = priv;
2512         unsigned idx;
2513         u8 newValue;
2514
2515         switch (type) {
2516         default:
2517         case FFS_DESCRIPTOR:
2518                 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2519                 return 0;
2520
2521         case FFS_INTERFACE:
2522                 idx = *valuep;
2523                 if (func->interfaces_nums[idx] < 0) {
2524                         int id = usb_interface_id(func->conf, &func->function);
2525                         if (unlikely(id < 0))
2526                                 return id;
2527                         func->interfaces_nums[idx] = id;
2528                 }
2529                 newValue = func->interfaces_nums[idx];
2530                 break;
2531
2532         case FFS_STRING:
2533                 /* String' IDs are allocated when fsf_data is bound to cdev */
2534                 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2535                 break;
2536
2537         case FFS_ENDPOINT:
2538                 /*
2539                  * USB_DT_ENDPOINT are handled in
2540                  * __ffs_func_bind_do_descs().
2541                  */
2542                 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2543                         return 0;
2544
2545                 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2546                 if (unlikely(!func->eps[idx].ep))
2547                         return -EINVAL;
2548
2549                 {
2550                         struct usb_endpoint_descriptor **descs;
2551                         descs = func->eps[idx].descs;
2552                         newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2553                 }
2554                 break;
2555         }
2556
2557         pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2558         *valuep = newValue;
2559         return 0;
2560 }
2561
2562 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2563                                       struct usb_os_desc_header *h, void *data,
2564                                       unsigned len, void *priv)
2565 {
2566         struct ffs_function *func = priv;
2567         u8 length = 0;
2568
2569         switch (type) {
2570         case FFS_OS_DESC_EXT_COMPAT: {
2571                 struct usb_ext_compat_desc *desc = data;
2572                 struct usb_os_desc_table *t;
2573
2574                 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2575                 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2576                 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2577                        ARRAY_SIZE(desc->CompatibleID) +
2578                        ARRAY_SIZE(desc->SubCompatibleID));
2579                 length = sizeof(*desc);
2580         }
2581                 break;
2582         case FFS_OS_DESC_EXT_PROP: {
2583                 struct usb_ext_prop_desc *desc = data;
2584                 struct usb_os_desc_table *t;
2585                 struct usb_os_desc_ext_prop *ext_prop;
2586                 char *ext_prop_name;
2587                 char *ext_prop_data;
2588
2589                 t = &func->function.os_desc_table[h->interface];
2590                 t->if_id = func->interfaces_nums[h->interface];
2591
2592                 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2593                 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2594
2595                 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2596                 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2597                 ext_prop->data_len = le32_to_cpu(*(u32 *)
2598                         usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2599                 length = ext_prop->name_len + ext_prop->data_len + 14;
2600
2601                 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2602                 func->ffs->ms_os_descs_ext_prop_name_avail +=
2603                         ext_prop->name_len;
2604
2605                 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2606                 func->ffs->ms_os_descs_ext_prop_data_avail +=
2607                         ext_prop->data_len;
2608                 memcpy(ext_prop_data,
2609                        usb_ext_prop_data_ptr(data, ext_prop->name_len),
2610                        ext_prop->data_len);
2611                 /* unicode data reported to the host as "WCHAR"s */
2612                 switch (ext_prop->type) {
2613                 case USB_EXT_PROP_UNICODE:
2614                 case USB_EXT_PROP_UNICODE_ENV:
2615                 case USB_EXT_PROP_UNICODE_LINK:
2616                 case USB_EXT_PROP_UNICODE_MULTI:
2617                         ext_prop->data_len *= 2;
2618                         break;
2619                 }
2620                 ext_prop->data = ext_prop_data;
2621
2622                 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2623                        ext_prop->name_len);
2624                 /* property name reported to the host as "WCHAR"s */
2625                 ext_prop->name_len *= 2;
2626                 ext_prop->name = ext_prop_name;
2627
2628                 t->os_desc->ext_prop_len +=
2629                         ext_prop->name_len + ext_prop->data_len + 14;
2630                 ++t->os_desc->ext_prop_count;
2631                 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2632         }
2633                 break;
2634         default:
2635                 pr_vdebug("unknown descriptor: %d\n", type);
2636         }
2637
2638         return length;
2639 }
2640
2641 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2642                                                 struct usb_configuration *c)
2643 {
2644         struct ffs_function *func = ffs_func_from_usb(f);
2645         struct f_fs_opts *ffs_opts =
2646                 container_of(f->fi, struct f_fs_opts, func_inst);
2647         int ret;
2648
2649         ENTER();
2650
2651         /*
2652          * Legacy gadget triggers binding in functionfs_ready_callback,
2653          * which already uses locking; taking the same lock here would
2654          * cause a deadlock.
2655          *
2656          * Configfs-enabled gadgets however do need ffs_dev_lock.
2657          */
2658         if (!ffs_opts->no_configfs)
2659                 ffs_dev_lock();
2660         ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2661         func->ffs = ffs_opts->dev->ffs_data;
2662         if (!ffs_opts->no_configfs)
2663                 ffs_dev_unlock();
2664         if (ret)
2665                 return ERR_PTR(ret);
2666
2667         func->conf = c;
2668         func->gadget = c->cdev->gadget;
2669
2670         ffs_data_get(func->ffs);
2671
2672         /*
2673          * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2674          * configurations are bound in sequence with list_for_each_entry,
2675          * in each configuration its functions are bound in sequence
2676          * with list_for_each_entry, so we assume no race condition
2677          * with regard to ffs_opts->bound access
2678          */
2679         if (!ffs_opts->refcnt) {
2680                 ret = functionfs_bind(func->ffs, c->cdev);
2681                 if (ret)
2682                         return ERR_PTR(ret);
2683         }
2684         ffs_opts->refcnt++;
2685         func->function.strings = func->ffs->stringtabs;
2686
2687         return ffs_opts;
2688 }
2689
2690 static int _ffs_func_bind(struct usb_configuration *c,
2691                           struct usb_function *f)
2692 {
2693         struct ffs_function *func = ffs_func_from_usb(f);
2694         struct ffs_data *ffs = func->ffs;
2695
2696         const int full = !!func->ffs->fs_descs_count;
2697         const int high = gadget_is_dualspeed(func->gadget) &&
2698                 func->ffs->hs_descs_count;
2699         const int super = gadget_is_superspeed(func->gadget) &&
2700                 func->ffs->ss_descs_count;
2701
2702         int fs_len, hs_len, ss_len, ret, i;
2703
2704         /* Make it a single chunk, less management later on */
2705         vla_group(d);
2706         vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2707         vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2708                 full ? ffs->fs_descs_count + 1 : 0);
2709         vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2710                 high ? ffs->hs_descs_count + 1 : 0);
2711         vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2712                 super ? ffs->ss_descs_count + 1 : 0);
2713         vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2714         vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2715                          c->cdev->use_os_string ? ffs->interfaces_count : 0);
2716         vla_item_with_sz(d, char[16], ext_compat,
2717                          c->cdev->use_os_string ? ffs->interfaces_count : 0);
2718         vla_item_with_sz(d, struct usb_os_desc, os_desc,
2719                          c->cdev->use_os_string ? ffs->interfaces_count : 0);
2720         vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2721                          ffs->ms_os_descs_ext_prop_count);
2722         vla_item_with_sz(d, char, ext_prop_name,
2723                          ffs->ms_os_descs_ext_prop_name_len);
2724         vla_item_with_sz(d, char, ext_prop_data,
2725                          ffs->ms_os_descs_ext_prop_data_len);
2726         vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2727         char *vlabuf;
2728
2729         ENTER();
2730
2731         /* Has descriptors only for speeds gadget does not support */
2732         if (unlikely(!(full | high | super)))
2733                 return -ENOTSUPP;
2734
2735         /* Allocate a single chunk, less management later on */
2736         vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2737         if (unlikely(!vlabuf))
2738                 return -ENOMEM;
2739
2740         ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2741         ffs->ms_os_descs_ext_prop_name_avail =
2742                 vla_ptr(vlabuf, d, ext_prop_name);
2743         ffs->ms_os_descs_ext_prop_data_avail =
2744                 vla_ptr(vlabuf, d, ext_prop_data);
2745
2746         /* Copy descriptors  */
2747         memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2748                ffs->raw_descs_length);
2749
2750         memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2751         for (ret = ffs->eps_count; ret; --ret) {
2752                 struct ffs_ep *ptr;
2753
2754                 ptr = vla_ptr(vlabuf, d, eps);
2755                 ptr[ret].num = -1;
2756         }
2757
2758         /* Save pointers
2759          * d_eps == vlabuf, func->eps used to kfree vlabuf later
2760         */
2761         func->eps             = vla_ptr(vlabuf, d, eps);
2762         func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2763
2764         /*
2765          * Go through all the endpoint descriptors and allocate
2766          * endpoints first, so that later we can rewrite the endpoint
2767          * numbers without worrying that it may be described later on.
2768          */
2769         if (likely(full)) {
2770                 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2771                 fs_len = ffs_do_descs(ffs->fs_descs_count,
2772                                       vla_ptr(vlabuf, d, raw_descs),
2773                                       d_raw_descs__sz,
2774                                       __ffs_func_bind_do_descs, func);
2775                 if (unlikely(fs_len < 0)) {
2776                         ret = fs_len;
2777                         goto error;
2778                 }
2779         } else {
2780                 fs_len = 0;
2781         }
2782
2783         if (likely(high)) {
2784                 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2785                 hs_len = ffs_do_descs(ffs->hs_descs_count,
2786                                       vla_ptr(vlabuf, d, raw_descs) + fs_len,
2787                                       d_raw_descs__sz - fs_len,
2788                                       __ffs_func_bind_do_descs, func);
2789                 if (unlikely(hs_len < 0)) {
2790                         ret = hs_len;
2791                         goto error;
2792                 }
2793         } else {
2794                 hs_len = 0;
2795         }
2796
2797         if (likely(super)) {
2798                 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2799                 ss_len = ffs_do_descs(ffs->ss_descs_count,
2800                                 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2801                                 d_raw_descs__sz - fs_len - hs_len,
2802                                 __ffs_func_bind_do_descs, func);
2803                 if (unlikely(ss_len < 0)) {
2804                         ret = ss_len;
2805                         goto error;
2806                 }
2807         } else {
2808                 ss_len = 0;
2809         }
2810
2811         /*
2812          * Now handle interface numbers allocation and interface and
2813          * endpoint numbers rewriting.  We can do that in one go
2814          * now.
2815          */
2816         ret = ffs_do_descs(ffs->fs_descs_count +
2817                            (high ? ffs->hs_descs_count : 0) +
2818                            (super ? ffs->ss_descs_count : 0),
2819                            vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2820                            __ffs_func_bind_do_nums, func);
2821         if (unlikely(ret < 0))
2822                 goto error;
2823
2824         func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2825         if (c->cdev->use_os_string)
2826                 for (i = 0; i < ffs->interfaces_count; ++i) {
2827                         struct usb_os_desc *desc;
2828
2829                         desc = func->function.os_desc_table[i].os_desc =
2830                                 vla_ptr(vlabuf, d, os_desc) +
2831                                 i * sizeof(struct usb_os_desc);
2832                         desc->ext_compat_id =
2833                                 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2834                         INIT_LIST_HEAD(&desc->ext_prop);
2835                 }
2836         ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2837                               vla_ptr(vlabuf, d, raw_descs) +
2838                               fs_len + hs_len + ss_len,
2839                               d_raw_descs__sz - fs_len - hs_len - ss_len,
2840                               __ffs_func_bind_do_os_desc, func);
2841         if (unlikely(ret < 0))
2842                 goto error;
2843         func->function.os_desc_n =
2844                 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2845
2846         /* And we're done */
2847         ffs_event_add(ffs, FUNCTIONFS_BIND);
2848         return 0;
2849
2850 error:
2851         /* XXX Do we need to release all claimed endpoints here? */
2852         return ret;
2853 }
2854
2855 static int ffs_func_bind(struct usb_configuration *c,
2856                          struct usb_function *f)
2857 {
2858         struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2859
2860         if (IS_ERR(ffs_opts))
2861                 return PTR_ERR(ffs_opts);
2862
2863         return _ffs_func_bind(c, f);
2864 }
2865
2866
2867 /* Other USB function hooks *************************************************/
2868
2869 static int ffs_func_set_alt(struct usb_function *f,
2870                             unsigned interface, unsigned alt)
2871 {
2872         struct ffs_function *func = ffs_func_from_usb(f);
2873         struct ffs_data *ffs = func->ffs;
2874         int ret = 0, intf;
2875
2876         if (alt != (unsigned)-1) {
2877                 intf = ffs_func_revmap_intf(func, interface);
2878                 if (unlikely(intf < 0))
2879                         return intf;
2880         }
2881
2882         if (ffs->func)
2883                 ffs_func_eps_disable(ffs->func);
2884
2885         if (ffs->state != FFS_ACTIVE)
2886                 return -ENODEV;
2887
2888         if (alt == (unsigned)-1) {
2889                 ffs->func = NULL;
2890                 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2891                 return 0;
2892         }
2893
2894         ffs->func = func;
2895         ret = ffs_func_eps_enable(func);
2896         if (likely(ret >= 0))
2897                 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2898         return ret;
2899 }
2900
2901 static void ffs_func_disable(struct usb_function *f)
2902 {
2903         ffs_func_set_alt(f, 0, (unsigned)-1);
2904 }
2905
2906 static int ffs_func_setup(struct usb_function *f,
2907                           const struct usb_ctrlrequest *creq)
2908 {
2909         struct ffs_function *func = ffs_func_from_usb(f);
2910         struct ffs_data *ffs = func->ffs;
2911         unsigned long flags;
2912         int ret;
2913
2914         ENTER();
2915
2916         pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2917         pr_vdebug("creq->bRequest     = %02x\n", creq->bRequest);
2918         pr_vdebug("creq->wValue       = %04x\n", le16_to_cpu(creq->wValue));
2919         pr_vdebug("creq->wIndex       = %04x\n", le16_to_cpu(creq->wIndex));
2920         pr_vdebug("creq->wLength      = %04x\n", le16_to_cpu(creq->wLength));
2921
2922         /*
2923          * Most requests directed to interface go through here
2924          * (notable exceptions are set/get interface) so we need to
2925          * handle them.  All other either handled by composite or
2926          * passed to usb_configuration->setup() (if one is set).  No
2927          * matter, we will handle requests directed to endpoint here
2928          * as well (as it's straightforward) but what to do with any
2929          * other request?
2930          */
2931         if (ffs->state != FFS_ACTIVE)
2932                 return -ENODEV;
2933
2934         switch (creq->bRequestType & USB_RECIP_MASK) {
2935         case USB_RECIP_INTERFACE:
2936                 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2937                 if (unlikely(ret < 0))
2938                         return ret;
2939                 break;
2940
2941         case USB_RECIP_ENDPOINT:
2942                 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2943                 if (unlikely(ret < 0))
2944                         return ret;
2945                 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2946                         ret = func->ffs->eps_addrmap[ret];
2947                 break;
2948
2949         default:
2950                 return -EOPNOTSUPP;
2951         }
2952
2953         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2954         ffs->ev.setup = *creq;
2955         ffs->ev.setup.wIndex = cpu_to_le16(ret);
2956         __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2957         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2958
2959         return 0;
2960 }
2961
2962 static void ffs_func_suspend(struct usb_function *f)
2963 {
2964         ENTER();
2965         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2966 }
2967
2968 static void ffs_func_resume(struct usb_function *f)
2969 {
2970         ENTER();
2971         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2972 }
2973
2974
2975 /* Endpoint and interface numbers reverse mapping ***************************/
2976
2977 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2978 {
2979         num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2980         return num ? num : -EDOM;
2981 }
2982
2983 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2984 {
2985         short *nums = func->interfaces_nums;
2986         unsigned count = func->ffs->interfaces_count;
2987
2988         for (; count; --count, ++nums) {
2989                 if (*nums >= 0 && *nums == intf)
2990                         return nums - func->interfaces_nums;
2991         }
2992
2993         return -EDOM;
2994 }
2995
2996
2997 /* Devices management *******************************************************/
2998
2999 static LIST_HEAD(ffs_devices);
3000
3001 static struct ffs_dev *_ffs_do_find_dev(const char *name)
3002 {
3003         struct ffs_dev *dev;
3004
3005         list_for_each_entry(dev, &ffs_devices, entry) {
3006                 if (!dev->name || !name)
3007                         continue;
3008                 if (strcmp(dev->name, name) == 0)
3009                         return dev;
3010         }
3011
3012         return NULL;
3013 }
3014
3015 /*
3016  * ffs_lock must be taken by the caller of this function
3017  */
3018 static struct ffs_dev *_ffs_get_single_dev(void)
3019 {
3020         struct ffs_dev *dev;
3021
3022         if (list_is_singular(&ffs_devices)) {
3023                 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3024                 if (dev->single)
3025                         return dev;
3026         }
3027
3028         return NULL;
3029 }
3030
3031 /*
3032  * ffs_lock must be taken by the caller of this function
3033  */
3034 static struct ffs_dev *_ffs_find_dev(const char *name)
3035 {
3036         struct ffs_dev *dev;
3037
3038         dev = _ffs_get_single_dev();
3039         if (dev)
3040                 return dev;
3041
3042         return _ffs_do_find_dev(name);
3043 }
3044
3045 /* Configfs support *********************************************************/
3046
3047 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3048 {
3049         return container_of(to_config_group(item), struct f_fs_opts,
3050                             func_inst.group);
3051 }
3052
3053 static void ffs_attr_release(struct config_item *item)
3054 {
3055         struct f_fs_opts *opts = to_ffs_opts(item);
3056
3057         usb_put_function_instance(&opts->func_inst);
3058 }
3059
3060 static struct configfs_item_operations ffs_item_ops = {
3061         .release        = ffs_attr_release,
3062 };
3063
3064 static struct config_item_type ffs_func_type = {
3065         .ct_item_ops    = &ffs_item_ops,
3066         .ct_owner       = THIS_MODULE,
3067 };
3068
3069
3070 /* Function registration interface ******************************************/
3071
3072 static void ffs_free_inst(struct usb_function_instance *f)
3073 {
3074         struct f_fs_opts *opts;
3075
3076         opts = to_f_fs_opts(f);
3077         ffs_dev_lock();
3078         _ffs_free_dev(opts->dev);
3079         ffs_dev_unlock();
3080         kfree(opts);
3081 }
3082
3083 #define MAX_INST_NAME_LEN       40
3084
3085 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3086 {
3087         struct f_fs_opts *opts;
3088         char *ptr;
3089         const char *tmp;
3090         int name_len, ret;
3091
3092         name_len = strlen(name) + 1;
3093         if (name_len > MAX_INST_NAME_LEN)
3094                 return -ENAMETOOLONG;
3095
3096         ptr = kstrndup(name, name_len, GFP_KERNEL);
3097         if (!ptr)
3098                 return -ENOMEM;
3099
3100         opts = to_f_fs_opts(fi);
3101         tmp = NULL;
3102
3103         ffs_dev_lock();
3104
3105         tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3106         ret = _ffs_name_dev(opts->dev, ptr);
3107         if (ret) {
3108                 kfree(ptr);
3109                 ffs_dev_unlock();
3110                 return ret;
3111         }
3112         opts->dev->name_allocated = true;
3113
3114         ffs_dev_unlock();
3115
3116         kfree(tmp);
3117
3118         return 0;
3119 }
3120
3121 static struct usb_function_instance *ffs_alloc_inst(void)
3122 {
3123         struct f_fs_opts *opts;
3124         struct ffs_dev *dev;
3125
3126         opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3127         if (!opts)
3128                 return ERR_PTR(-ENOMEM);
3129
3130         opts->func_inst.set_inst_name = ffs_set_inst_name;
3131         opts->func_inst.free_func_inst = ffs_free_inst;
3132         ffs_dev_lock();
3133         dev = _ffs_alloc_dev();
3134         ffs_dev_unlock();
3135         if (IS_ERR(dev)) {
3136                 kfree(opts);
3137                 return ERR_CAST(dev);
3138         }
3139         opts->dev = dev;
3140         dev->opts = opts;
3141
3142         config_group_init_type_name(&opts->func_inst.group, "",
3143                                     &ffs_func_type);
3144         return &opts->func_inst;
3145 }
3146
3147 static void ffs_free(struct usb_function *f)
3148 {
3149         kfree(ffs_func_from_usb(f));
3150 }
3151
3152 static void ffs_func_unbind(struct usb_configuration *c,
3153                             struct usb_function *f)
3154 {
3155         struct ffs_function *func = ffs_func_from_usb(f);
3156         struct ffs_data *ffs = func->ffs;
3157         struct f_fs_opts *opts =
3158                 container_of(f->fi, struct f_fs_opts, func_inst);
3159         struct ffs_ep *ep = func->eps;
3160         unsigned count = ffs->eps_count;
3161         unsigned long flags;
3162
3163         ENTER();
3164         if (ffs->func == func) {
3165                 ffs_func_eps_disable(func);
3166                 ffs->func = NULL;
3167         }
3168
3169         if (!--opts->refcnt)
3170                 functionfs_unbind(ffs);
3171
3172         /* cleanup after autoconfig */
3173         spin_lock_irqsave(&func->ffs->eps_lock, flags);
3174         do {
3175                 if (ep->ep && ep->req)
3176                         usb_ep_free_request(ep->ep, ep->req);
3177                 ep->req = NULL;
3178                 ++ep;
3179         } while (--count);
3180         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3181         kfree(func->eps);
3182         func->eps = NULL;
3183         /*
3184          * eps, descriptors and interfaces_nums are allocated in the
3185          * same chunk so only one free is required.
3186          */
3187         func->function.fs_descriptors = NULL;
3188         func->function.hs_descriptors = NULL;
3189         func->function.ss_descriptors = NULL;
3190         func->interfaces_nums = NULL;
3191
3192         ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3193 }
3194
3195 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3196 {
3197         struct ffs_function *func;
3198
3199         ENTER();
3200
3201         func = kzalloc(sizeof(*func), GFP_KERNEL);
3202         if (unlikely(!func))
3203                 return ERR_PTR(-ENOMEM);
3204
3205         func->function.name    = "Function FS Gadget";
3206
3207         func->function.bind    = ffs_func_bind;
3208         func->function.unbind  = ffs_func_unbind;
3209         func->function.set_alt = ffs_func_set_alt;
3210         func->function.disable = ffs_func_disable;
3211         func->function.setup   = ffs_func_setup;
3212         func->function.suspend = ffs_func_suspend;
3213         func->function.resume  = ffs_func_resume;
3214         func->function.free_func = ffs_free;
3215
3216         return &func->function;
3217 }
3218
3219 /*
3220  * ffs_lock must be taken by the caller of this function
3221  */
3222 static struct ffs_dev *_ffs_alloc_dev(void)
3223 {
3224         struct ffs_dev *dev;
3225         int ret;
3226
3227         if (_ffs_get_single_dev())
3228                         return ERR_PTR(-EBUSY);
3229
3230         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3231         if (!dev)
3232                 return ERR_PTR(-ENOMEM);
3233
3234         if (list_empty(&ffs_devices)) {
3235                 ret = functionfs_init();
3236                 if (ret) {
3237                         kfree(dev);
3238                         return ERR_PTR(ret);
3239                 }
3240         }
3241
3242         list_add(&dev->entry, &ffs_devices);
3243
3244         return dev;
3245 }
3246
3247 /*
3248  * ffs_lock must be taken by the caller of this function
3249  * The caller is responsible for "name" being available whenever f_fs needs it
3250  */
3251 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3252 {
3253         struct ffs_dev *existing;
3254
3255         existing = _ffs_do_find_dev(name);
3256         if (existing)
3257                 return -EBUSY;
3258
3259         dev->name = name;
3260
3261         return 0;
3262 }
3263
3264 /*
3265  * The caller is responsible for "name" being available whenever f_fs needs it
3266  */
3267 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3268 {
3269         int ret;
3270
3271         ffs_dev_lock();
3272         ret = _ffs_name_dev(dev, name);
3273         ffs_dev_unlock();
3274
3275         return ret;
3276 }
3277 EXPORT_SYMBOL_GPL(ffs_name_dev);
3278
3279 int ffs_single_dev(struct ffs_dev *dev)
3280 {
3281         int ret;
3282
3283         ret = 0;
3284         ffs_dev_lock();
3285
3286         if (!list_is_singular(&ffs_devices))
3287                 ret = -EBUSY;
3288         else
3289                 dev->single = true;
3290
3291         ffs_dev_unlock();
3292         return ret;
3293 }
3294 EXPORT_SYMBOL_GPL(ffs_single_dev);
3295
3296 /*
3297  * ffs_lock must be taken by the caller of this function
3298  */
3299 static void _ffs_free_dev(struct ffs_dev *dev)
3300 {
3301         list_del(&dev->entry);
3302         if (dev->name_allocated)
3303                 kfree(dev->name);
3304         kfree(dev);
3305         if (list_empty(&ffs_devices))
3306                 functionfs_cleanup();
3307 }
3308
3309 static void *ffs_acquire_dev(const char *dev_name)
3310 {
3311         struct ffs_dev *ffs_dev;
3312
3313         ENTER();
3314         ffs_dev_lock();
3315
3316         ffs_dev = _ffs_find_dev(dev_name);
3317         if (!ffs_dev)
3318                 ffs_dev = ERR_PTR(-ENOENT);
3319         else if (ffs_dev->mounted)
3320                 ffs_dev = ERR_PTR(-EBUSY);
3321         else if (ffs_dev->ffs_acquire_dev_callback &&
3322             ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3323                 ffs_dev = ERR_PTR(-ENOENT);
3324         else
3325                 ffs_dev->mounted = true;
3326
3327         ffs_dev_unlock();
3328         return ffs_dev;
3329 }
3330
3331 static void ffs_release_dev(struct ffs_data *ffs_data)
3332 {
3333         struct ffs_dev *ffs_dev;
3334
3335         ENTER();
3336         ffs_dev_lock();
3337
3338         ffs_dev = ffs_data->private_data;
3339         if (ffs_dev) {
3340                 ffs_dev->mounted = false;
3341
3342                 if (ffs_dev->ffs_release_dev_callback)
3343                         ffs_dev->ffs_release_dev_callback(ffs_dev);
3344         }
3345
3346         ffs_dev_unlock();
3347 }
3348
3349 static int ffs_ready(struct ffs_data *ffs)
3350 {
3351         struct ffs_dev *ffs_obj;
3352         int ret = 0;
3353
3354         ENTER();
3355         ffs_dev_lock();
3356
3357         ffs_obj = ffs->private_data;
3358         if (!ffs_obj) {
3359                 ret = -EINVAL;
3360                 goto done;
3361         }
3362         if (WARN_ON(ffs_obj->desc_ready)) {
3363                 ret = -EBUSY;
3364                 goto done;
3365         }
3366
3367         ffs_obj->desc_ready = true;
3368         ffs_obj->ffs_data = ffs;
3369
3370         if (ffs_obj->ffs_ready_callback)
3371                 ret = ffs_obj->ffs_ready_callback(ffs);
3372
3373 done:
3374         ffs_dev_unlock();
3375         return ret;
3376 }
3377
3378 static void ffs_closed(struct ffs_data *ffs)
3379 {
3380         struct ffs_dev *ffs_obj;
3381
3382         ENTER();
3383         ffs_dev_lock();
3384
3385         ffs_obj = ffs->private_data;
3386         if (!ffs_obj)
3387                 goto done;
3388
3389         ffs_obj->desc_ready = false;
3390
3391         if (ffs_obj->ffs_closed_callback)
3392                 ffs_obj->ffs_closed_callback(ffs);
3393
3394         if (!ffs_obj->opts || ffs_obj->opts->no_configfs
3395             || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
3396                 goto done;
3397
3398         unregister_gadget_item(ffs_obj->opts->
3399                                func_inst.group.cg_item.ci_parent->ci_parent);
3400 done:
3401         ffs_dev_unlock();
3402 }
3403
3404 /* Misc helper functions ****************************************************/
3405
3406 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3407 {
3408         return nonblock
3409                 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3410                 : mutex_lock_interruptible(mutex);
3411 }
3412
3413 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3414 {
3415         char *data;
3416
3417         if (unlikely(!len))
3418                 return NULL;
3419
3420         data = kmalloc(len, GFP_KERNEL);
3421         if (unlikely(!data))
3422                 return ERR_PTR(-ENOMEM);
3423
3424         if (unlikely(__copy_from_user(data, buf, len))) {
3425                 kfree(data);
3426                 return ERR_PTR(-EFAULT);
3427         }
3428
3429         pr_vdebug("Buffer from user space:\n");
3430         ffs_dump_mem("", data, len);
3431
3432         return data;
3433 }
3434
3435 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3436 MODULE_LICENSE("GPL");
3437 MODULE_AUTHOR("Michal Nazarewicz");