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