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