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