OSDN Git Service

Merge "diag: Add protection before accessing md_session_map"
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / drivers / usb / gadget / function / f_fs.c
1 /*
2  * f_fs.c -- user mode file system API for USB composite function controllers
3  *
4  * Copyright (C) 2010 Samsung Electronics
5  * Author: Michal Nazarewicz <mina86@mina86.com>
6  *
7  * Based on inode.c (GadgetFS) which was:
8  * Copyright (C) 2003-2004 David Brownell
9  * Copyright (C) 2003 Agilent Technologies
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  */
16
17
18 /* #define DEBUG */
19 /* #define VERBOSE_DEBUG */
20
21 #include <linux/blkdev.h>
22 #include <linux/pagemap.h>
23 #include <linux/export.h>
24 #include <linux/hid.h>
25 #include <linux/module.h>
26 #include <linux/uio.h>
27 #include <linux/ipc_logging.h>
28 #include <asm/unaligned.h>
29
30 #include <linux/usb/composite.h>
31 #include <linux/usb/functionfs.h>
32
33 #include <linux/aio.h>
34 #include <linux/mmu_context.h>
35 #include <linux/poll.h>
36 #include <linux/eventfd.h>
37
38 #include "u_fs.h"
39 #include "u_f.h"
40 #include "u_os_desc.h"
41 #include "configfs.h"
42
43 #define FUNCTIONFS_MAGIC        0xa647361 /* Chosen by a honest dice roll ;) */
44
45 #define NUM_PAGES       10 /* # of pages for ipc logging */
46
47 static void *ffs_ipc_log;
48 #define ffs_log(fmt, ...) do { \
49         if (ffs_ipc_log)        \
50                 ipc_log_string(ffs_ipc_log, "%s: " fmt,  __func__, \
51                         ##__VA_ARGS__); \
52         pr_debug("%s: " fmt, __func__, ##__VA_ARGS__); \
53 } while (0)
54
55 /* Reference counter handling */
56 static void ffs_data_get(struct ffs_data *ffs);
57 static void ffs_data_put(struct ffs_data *ffs);
58 /* Creates new ffs_data object. */
59 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
60
61 /* Opened counter handling. */
62 static void ffs_data_opened(struct ffs_data *ffs);
63 static void ffs_data_closed(struct ffs_data *ffs);
64
65 /* Called with ffs->mutex held; take over ownership of data. */
66 static int __must_check
67 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
68 static int __must_check
69 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
70
71 static LIST_HEAD(inst_list);
72
73 /* ffs instance status */
74 #define INST_NAME_SIZE  16
75
76 struct ffs_inst_status {
77         char inst_name[INST_NAME_SIZE];
78         struct list_head list;
79         struct mutex ffs_lock;
80         bool inst_exist;
81         struct f_fs_opts *opts;
82         struct ffs_data *ffs_data;
83 };
84
85 /* Free instance structures */
86 static void ffs_inst_clean(struct f_fs_opts *opts,
87                 const char *inst_name);
88 static void ffs_inst_clean_delay(const char *inst_name);
89 static int ffs_inst_exist_check(const char *inst_name);
90 static struct ffs_inst_status *name_to_inst_status(
91                 const char *inst_name, bool create_inst);
92
93 /* The function structure ***************************************************/
94
95 struct ffs_ep;
96 static bool first_read_done;
97
98 struct ffs_function {
99         struct usb_configuration        *conf;
100         struct usb_gadget               *gadget;
101         struct ffs_data                 *ffs;
102
103         struct ffs_ep                   *eps;
104         u8                              eps_revmap[16];
105         short                           *interfaces_nums;
106
107         struct usb_function             function;
108 };
109
110
111 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
112 {
113         return container_of(f, struct ffs_function, function);
114 }
115
116
117 static inline enum ffs_setup_state
118 ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
119 {
120         return (enum ffs_setup_state)
121                 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
122 }
123
124
125 static void ffs_func_eps_disable(struct ffs_function *func);
126 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
127
128 static int ffs_func_bind(struct usb_configuration *,
129                          struct usb_function *);
130 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
131 static void ffs_func_disable(struct usb_function *);
132 static int ffs_func_setup(struct usb_function *,
133                           const struct usb_ctrlrequest *);
134 static void ffs_func_suspend(struct usb_function *);
135 static void ffs_func_resume(struct usb_function *);
136
137
138 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
139 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
140
141
142 /* The endpoints structures *************************************************/
143
144 struct ffs_ep {
145         struct usb_ep                   *ep;    /* P: ffs->eps_lock */
146         struct usb_request              *req;   /* P: epfile->mutex */
147
148         /* [0]: full speed, [1]: high speed, [2]: super speed */
149         struct usb_endpoint_descriptor  *descs[3];
150
151         u8                              num;
152
153         int                             status; /* P: epfile->mutex */
154         bool                            is_busy;
155 };
156
157 struct ffs_epfile {
158         /* Protects ep->ep and ep->req. */
159         struct mutex                    mutex;
160         wait_queue_head_t               wait;
161         atomic_t                        error;
162
163         struct ffs_data                 *ffs;
164         struct ffs_ep                   *ep;    /* P: ffs->eps_lock */
165
166         struct dentry                   *dentry;
167
168         char                            name[5];
169
170         unsigned char                   in;     /* P: ffs->eps_lock */
171         unsigned char                   isoc;   /* P: ffs->eps_lock */
172
173         unsigned char                   _pad;
174         atomic_t                        opened;
175 };
176
177 /*  ffs_io_data structure ***************************************************/
178
179 struct ffs_io_data {
180         bool aio;
181         bool read;
182
183         struct kiocb *kiocb;
184         struct iov_iter data;
185         const void *to_free;
186         char *buf;
187
188         struct mm_struct *mm;
189         struct work_struct work;
190
191         struct usb_ep *ep;
192         struct usb_request *req;
193
194         struct ffs_data *ffs;
195 };
196
197 struct ffs_desc_helper {
198         struct ffs_data *ffs;
199         unsigned interfaces_count;
200         unsigned eps_count;
201 };
202
203 static int  __must_check ffs_epfiles_create(struct ffs_data *ffs);
204 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
205
206 static struct dentry *
207 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
208                    const struct file_operations *fops);
209
210 /* Devices management *******************************************************/
211
212 DEFINE_MUTEX(ffs_lock);
213 EXPORT_SYMBOL_GPL(ffs_lock);
214
215 static struct ffs_dev *_ffs_find_dev(const char *name);
216 static struct ffs_dev *_ffs_alloc_dev(void);
217 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
218 static void _ffs_free_dev(struct ffs_dev *dev);
219 static void *ffs_acquire_dev(const char *dev_name);
220 static void ffs_release_dev(struct ffs_data *ffs_data);
221 static int ffs_ready(struct ffs_data *ffs);
222 static void ffs_closed(struct ffs_data *ffs);
223
224 /* Misc helper functions ****************************************************/
225
226 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
227         __attribute__((warn_unused_result, nonnull));
228 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
229         __attribute__((warn_unused_result, nonnull));
230
231
232 /* Control file aka ep0 *****************************************************/
233
234 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
235 {
236         struct ffs_data *ffs = req->context;
237
238         complete_all(&ffs->ep0req_completion);
239 }
240
241 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
242 {
243         struct usb_request *req = ffs->ep0req;
244         int ret;
245
246         req->zero     = len < le16_to_cpu(ffs->ev.setup.wLength);
247
248         spin_unlock_irq(&ffs->ev.waitq.lock);
249
250         ffs_log("enter: state %d setup_state %d flags %lu", ffs->state,
251                 ffs->setup_state, ffs->flags);
252
253         req->buf      = data;
254         req->length   = len;
255
256         /*
257          * UDC layer requires to provide a buffer even for ZLP, but should
258          * not use it at all. Let's provide some poisoned pointer to catch
259          * possible bug in the driver.
260          */
261         if (req->buf == NULL)
262                 req->buf = (void *)0xDEADBABE;
263
264         reinit_completion(&ffs->ep0req_completion);
265
266         ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
267         if (unlikely(ret < 0))
268                 return ret;
269
270         ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
271         if (unlikely(ret)) {
272                 usb_ep_dequeue(ffs->gadget->ep0, req);
273                 return -EINTR;
274         }
275
276         ffs->setup_state = FFS_NO_SETUP;
277
278         ffs_log("exit: state %d setup_state %d flags %lu", ffs->state,
279                 ffs->setup_state, ffs->flags);
280
281         return req->status ? req->status : req->actual;
282 }
283
284 static int __ffs_ep0_stall(struct ffs_data *ffs)
285 {
286         ffs_log("state %d setup_state %d flags %lu can_stall %d", ffs->state,
287                 ffs->setup_state, ffs->flags, ffs->ev.can_stall);
288
289         if (ffs->ev.can_stall) {
290                 pr_vdebug("ep0 stall\n");
291                 usb_ep_set_halt(ffs->gadget->ep0);
292                 ffs->setup_state = FFS_NO_SETUP;
293                 return -EL2HLT;
294         } else {
295                 pr_debug("bogus ep0 stall!\n");
296                 return -ESRCH;
297         }
298 }
299
300 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
301                              size_t len, loff_t *ptr)
302 {
303         struct ffs_data *ffs = file->private_data;
304         ssize_t ret;
305         char *data;
306
307         ENTER();
308
309         ffs_log("enter:len %zu state %d setup_state %d flags %lu", len,
310                 ffs->state, ffs->setup_state, ffs->flags);
311
312         ret = ffs_inst_exist_check(ffs->dev_name);
313         if (ret < 0)
314                 return ret;
315
316         /* Fast check if setup was canceled */
317         if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
318                 return -EIDRM;
319
320         /* Acquire mutex */
321         ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
322         if (unlikely(ret < 0))
323                 return ret;
324
325         /* Check state */
326         switch (ffs->state) {
327         case FFS_READ_DESCRIPTORS:
328         case FFS_READ_STRINGS:
329                 /* Copy data */
330                 if (unlikely(len < 16)) {
331                         ret = -EINVAL;
332                         break;
333                 }
334
335                 data = ffs_prepare_buffer(buf, len);
336                 if (IS_ERR(data)) {
337                         ret = PTR_ERR(data);
338                         break;
339                 }
340
341                 /* Handle data */
342                 if (ffs->state == FFS_READ_DESCRIPTORS) {
343                         pr_info("read descriptors\n");
344                         ret = __ffs_data_got_descs(ffs, data, len);
345                         if (unlikely(ret < 0))
346                                 break;
347
348                         ffs->state = FFS_READ_STRINGS;
349                         ret = len;
350                 } else {
351                         pr_info("read strings\n");
352                         ret = __ffs_data_got_strings(ffs, data, len);
353                         if (unlikely(ret < 0))
354                                 break;
355
356                         ret = ffs_epfiles_create(ffs);
357                         if (unlikely(ret)) {
358                                 ffs->state = FFS_CLOSING;
359                                 break;
360                         }
361
362                         ffs->state = FFS_ACTIVE;
363                         mutex_unlock(&ffs->mutex);
364
365                         ret = ffs_ready(ffs);
366                         if (unlikely(ret < 0)) {
367                                 ffs->state = FFS_CLOSING;
368                                 return ret;
369                         }
370
371                         return len;
372                 }
373                 break;
374
375         case FFS_ACTIVE:
376                 data = NULL;
377                 /*
378                  * We're called from user space, we can use _irq
379                  * rather then _irqsave
380                  */
381                 spin_lock_irq(&ffs->ev.waitq.lock);
382                 switch (ffs_setup_state_clear_cancelled(ffs)) {
383                 case FFS_SETUP_CANCELLED:
384                         ret = -EIDRM;
385                         goto done_spin;
386
387                 case FFS_NO_SETUP:
388                         ret = -ESRCH;
389                         goto done_spin;
390
391                 case FFS_SETUP_PENDING:
392                         break;
393                 }
394
395                 /* FFS_SETUP_PENDING */
396                 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
397                         spin_unlock_irq(&ffs->ev.waitq.lock);
398                         ret = __ffs_ep0_stall(ffs);
399                         break;
400                 }
401
402                 /* FFS_SETUP_PENDING and not stall */
403                 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
404
405                 spin_unlock_irq(&ffs->ev.waitq.lock);
406
407                 data = ffs_prepare_buffer(buf, len);
408                 if (IS_ERR(data)) {
409                         ret = PTR_ERR(data);
410                         break;
411                 }
412
413                 spin_lock_irq(&ffs->ev.waitq.lock);
414
415                 /*
416                  * We are guaranteed to be still in FFS_ACTIVE state
417                  * but the state of setup could have changed from
418                  * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
419                  * to check for that.  If that happened we copied data
420                  * from user space in vain but it's unlikely.
421                  *
422                  * For sure we are not in FFS_NO_SETUP since this is
423                  * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
424                  * transition can be performed and it's protected by
425                  * mutex.
426                  */
427                 if (ffs_setup_state_clear_cancelled(ffs) ==
428                     FFS_SETUP_CANCELLED) {
429                         ret = -EIDRM;
430 done_spin:
431                         spin_unlock_irq(&ffs->ev.waitq.lock);
432                 } else {
433                         /* unlocks spinlock */
434                         ret = __ffs_ep0_queue_wait(ffs, data, len);
435                 }
436                 kfree(data);
437                 break;
438
439         default:
440                 ret = -EBADFD;
441                 break;
442         }
443
444         ffs_log("exit:ret %zu state %d setup_state %d flags %lu", ret,
445                 ffs->state, ffs->setup_state, ffs->flags);
446
447         mutex_unlock(&ffs->mutex);
448         return ret;
449 }
450
451 /* Called with ffs->ev.waitq.lock and ffs->mutex held, both released on exit. */
452 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
453                                      size_t n)
454 {
455         /*
456          * n cannot be bigger than ffs->ev.count, which cannot be bigger than
457          * size of ffs->ev.types array (which is four) so that's how much space
458          * we reserve.
459          */
460         struct usb_functionfs_event events[ARRAY_SIZE(ffs->ev.types)];
461         const size_t size = n * sizeof *events;
462         unsigned i = 0;
463
464         memset(events, 0, size);
465
466         do {
467                 events[i].type = ffs->ev.types[i];
468                 if (events[i].type == FUNCTIONFS_SETUP) {
469                         events[i].u.setup = ffs->ev.setup;
470                         ffs->setup_state = FFS_SETUP_PENDING;
471                 }
472         } while (++i < n);
473
474         ffs->ev.count -= n;
475         if (ffs->ev.count)
476                 memmove(ffs->ev.types, ffs->ev.types + n,
477                         ffs->ev.count * sizeof *ffs->ev.types);
478
479         spin_unlock_irq(&ffs->ev.waitq.lock);
480
481         ffs_log("state %d setup_state %d flags %lu #evt %zu", ffs->state,
482                 ffs->setup_state, ffs->flags, n);
483
484         mutex_unlock(&ffs->mutex);
485
486         return unlikely(copy_to_user(buf, events, size)) ? -EFAULT : size;
487 }
488
489 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
490                             size_t len, loff_t *ptr)
491 {
492         struct ffs_data *ffs = file->private_data;
493         char *data = NULL;
494         size_t n;
495         int ret;
496
497         ENTER();
498
499         ffs_log("enter:len %zu state %d setup_state %d flags %lu", len,
500                 ffs->state, ffs->setup_state, ffs->flags);
501
502         ret = ffs_inst_exist_check(ffs->dev_name);
503         if (ret < 0)
504                 return ret;
505
506         /* Fast check if setup was canceled */
507         if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
508                 return -EIDRM;
509
510         /* Acquire mutex */
511         ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
512         if (unlikely(ret < 0))
513                 return ret;
514
515         /* Check state */
516         if (ffs->state != FFS_ACTIVE) {
517                 ret = -EBADFD;
518                 goto done_mutex;
519         }
520
521         /*
522          * We're called from user space, we can use _irq rather then
523          * _irqsave
524          */
525         spin_lock_irq(&ffs->ev.waitq.lock);
526
527         switch (ffs_setup_state_clear_cancelled(ffs)) {
528         case FFS_SETUP_CANCELLED:
529                 ret = -EIDRM;
530                 break;
531
532         case FFS_NO_SETUP:
533                 n = len / sizeof(struct usb_functionfs_event);
534                 if (unlikely(!n)) {
535                         ret = -EINVAL;
536                         break;
537                 }
538
539                 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
540                         ret = -EAGAIN;
541                         break;
542                 }
543
544                 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
545                                                         ffs->ev.count)) {
546                         ret = -EINTR;
547                         break;
548                 }
549
550                 return __ffs_ep0_read_events(ffs, buf,
551                                              min(n, (size_t)ffs->ev.count));
552
553         case FFS_SETUP_PENDING:
554                 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
555                         spin_unlock_irq(&ffs->ev.waitq.lock);
556                         ret = __ffs_ep0_stall(ffs);
557                         goto done_mutex;
558                 }
559
560                 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
561
562                 spin_unlock_irq(&ffs->ev.waitq.lock);
563
564                 if (likely(len)) {
565                         data = kmalloc(len, GFP_KERNEL);
566                         if (unlikely(!data)) {
567                                 ret = -ENOMEM;
568                                 goto done_mutex;
569                         }
570                 }
571
572                 spin_lock_irq(&ffs->ev.waitq.lock);
573
574                 /* See ffs_ep0_write() */
575                 if (ffs_setup_state_clear_cancelled(ffs) ==
576                     FFS_SETUP_CANCELLED) {
577                         ret = -EIDRM;
578                         break;
579                 }
580
581                 /* unlocks spinlock */
582                 ret = __ffs_ep0_queue_wait(ffs, data, len);
583                 if (likely(ret > 0) && unlikely(copy_to_user(buf, data, len)))
584                         ret = -EFAULT;
585                 goto done_mutex;
586
587         default:
588                 ret = -EBADFD;
589                 break;
590         }
591
592         spin_unlock_irq(&ffs->ev.waitq.lock);
593 done_mutex:
594         ffs_log("exit:ret %d state %d setup_state %d flags %lu", ret,
595                 ffs->state, ffs->setup_state, ffs->flags);
596
597         mutex_unlock(&ffs->mutex);
598         kfree(data);
599
600         return ret;
601 }
602
603 static int ffs_ep0_open(struct inode *inode, struct file *file)
604 {
605         struct ffs_data *ffs = inode->i_private;
606         int ret;
607
608         ENTER();
609
610         ffs_log("state %d setup_state %d flags %lu opened %d", ffs->state,
611                 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
612
613         ret = ffs_inst_exist_check(ffs->dev_name);
614         if (ret < 0)
615                 return ret;
616
617         if (unlikely(ffs->state == FFS_CLOSING))
618                 return -EBUSY;
619
620         smp_mb__before_atomic();
621         if (atomic_read(&ffs->opened))
622                 return -EBUSY;
623
624         file->private_data = ffs;
625         ffs_data_opened(ffs);
626
627         return 0;
628 }
629
630 static int ffs_ep0_release(struct inode *inode, struct file *file)
631 {
632         struct ffs_data *ffs = file->private_data;
633
634         ENTER();
635
636         ffs_log("state %d setup_state %d flags %lu opened %d", ffs->state,
637                 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
638
639         ffs_data_closed(ffs);
640
641         return 0;
642 }
643
644 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
645 {
646         struct ffs_data *ffs = file->private_data;
647         struct usb_gadget *gadget = ffs->gadget;
648         long ret;
649
650         ENTER();
651
652         ffs_log("state %d setup_state %d flags %lu opened %d", ffs->state,
653                 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
654
655         ret = ffs_inst_exist_check(ffs->dev_name);
656         if (ret < 0)
657                 return ret;
658
659         if (code == FUNCTIONFS_INTERFACE_REVMAP) {
660                 struct ffs_function *func = ffs->func;
661                 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
662         } else if (gadget && gadget->ops->ioctl) {
663                 ret = gadget->ops->ioctl(gadget, code, value);
664         } else {
665                 ret = -ENOTTY;
666         }
667
668         return ret;
669 }
670
671 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
672 {
673         struct ffs_data *ffs = file->private_data;
674         unsigned int mask = POLLWRNORM;
675         int ret;
676
677         ffs_log("enter:state %d setup_state %d flags %lu opened %d", ffs->state,
678                 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
679
680         ret = ffs_inst_exist_check(ffs->dev_name);
681         if (ret < 0)
682                 return ret;
683
684         poll_wait(file, &ffs->ev.waitq, wait);
685
686         ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
687         if (unlikely(ret < 0))
688                 return mask;
689
690         switch (ffs->state) {
691         case FFS_READ_DESCRIPTORS:
692         case FFS_READ_STRINGS:
693                 mask |= POLLOUT;
694                 break;
695
696         case FFS_ACTIVE:
697                 switch (ffs->setup_state) {
698                 case FFS_NO_SETUP:
699                         if (ffs->ev.count)
700                                 mask |= POLLIN;
701                         break;
702
703                 case FFS_SETUP_PENDING:
704                 case FFS_SETUP_CANCELLED:
705                         mask |= (POLLIN | POLLOUT);
706                         break;
707                 }
708         case FFS_CLOSING:
709                 break;
710         case FFS_DEACTIVATED:
711                 break;
712         }
713
714         ffs_log("exit: mask %u", mask);
715
716         mutex_unlock(&ffs->mutex);
717
718         return mask;
719 }
720
721 static const struct file_operations ffs_ep0_operations = {
722         .llseek =       no_llseek,
723
724         .open =         ffs_ep0_open,
725         .write =        ffs_ep0_write,
726         .read =         ffs_ep0_read,
727         .release =      ffs_ep0_release,
728         .unlocked_ioctl =       ffs_ep0_ioctl,
729         .poll =         ffs_ep0_poll,
730 };
731
732
733 /* "Normal" endpoints operations ********************************************/
734
735 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
736 {
737         struct ffs_ep *ep = _ep->driver_data;
738         ENTER();
739
740         /* req may be freed during unbind */
741         if (ep && ep->req && likely(req->context)) {
742                 struct ffs_ep *ep = _ep->driver_data;
743                 ep->status = req->status ? req->status : req->actual;
744                 /* Set is_busy false to indicate completion of last request */
745                 ep->is_busy = false;
746                 ffs_log("ep status %d for req %pK", ep->status, req);
747                 complete(req->context);
748         }
749 }
750
751 static void ffs_user_copy_worker(struct work_struct *work)
752 {
753         struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
754                                                    work);
755         int ret = io_data->req->status ? io_data->req->status :
756                                          io_data->req->actual;
757         bool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD;
758
759         ffs_log("enter: ret %d", ret);
760
761         if (io_data->read && ret > 0) {
762                 mm_segment_t oldfs = get_fs();
763
764                 set_fs(USER_DS);
765                 use_mm(io_data->mm);
766                 ret = copy_to_iter(io_data->buf, ret, &io_data->data);
767                 if (ret != io_data->req->actual && iov_iter_count(&io_data->data))
768                         ret = -EFAULT;
769                 unuse_mm(io_data->mm);
770                 set_fs(oldfs);
771         }
772
773         io_data->kiocb->ki_complete(io_data->kiocb, ret, ret);
774
775         if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd)
776                 eventfd_signal(io_data->ffs->ffs_eventfd, 1);
777
778         usb_ep_free_request(io_data->ep, io_data->req);
779
780         if (io_data->read)
781                 kfree(io_data->to_free);
782         kfree(io_data->buf);
783         kfree(io_data);
784
785         ffs_log("exit");
786 }
787
788 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
789                                          struct usb_request *req)
790 {
791         struct ffs_io_data *io_data = req->context;
792
793         ENTER();
794
795         ffs_log("enter");
796
797         INIT_WORK(&io_data->work, ffs_user_copy_worker);
798         schedule_work(&io_data->work);
799
800         ffs_log("exit");
801 }
802
803 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
804 {
805         struct ffs_epfile *epfile = file->private_data;
806         struct ffs_ep *ep;
807         struct ffs_data *ffs = epfile->ffs;
808         char *data = NULL;
809         ssize_t ret, data_len = -EINVAL;
810         int halt;
811
812         ffs_log("enter: epfile name %s epfile err %d (%s)", epfile->name,
813                 atomic_read(&epfile->error), io_data->read ? "READ" : "WRITE");
814
815         ret = ffs_inst_exist_check(epfile->ffs->dev_name);
816         if (ret < 0)
817                 return ret;
818
819         smp_mb__before_atomic();
820 retry:
821         if (atomic_read(&epfile->error))
822                 return -ENODEV;
823
824         /* Are we still active? */
825         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
826                 ret = -ENODEV;
827                 goto error;
828         }
829
830         /* Wait for endpoint to be enabled */
831         ep = epfile->ep;
832         if (!ep) {
833                 if (file->f_flags & O_NONBLOCK) {
834                         ret = -EAGAIN;
835                         goto error;
836                 }
837
838                 /* Don't wait on write if device is offline */
839                 if (!io_data->read) {
840                         ret = -EINTR;
841                         goto error;
842                 }
843
844                 /*
845                  * If ep is disabled, this fails all current IOs
846                  * and wait for next epfile open to happen.
847                  */
848                 smp_mb__before_atomic();
849                 if (!atomic_read(&epfile->error)) {
850                         ret = wait_event_interruptible(epfile->wait,
851                                         (ep = epfile->ep));
852                         if (ret < 0)
853                                 goto error;
854                 }
855
856                 if (!ep) {
857                         ret = -ENODEV;
858                         goto error;
859                 }
860         }
861
862         /* Do we halt? */
863         halt = (!io_data->read == !epfile->in);
864         if (halt && epfile->isoc) {
865                 ret = -EINVAL;
866                 goto error;
867         }
868
869         /* Allocate & copy */
870         if (!halt) {
871                 /*
872                  * if we _do_ wait above, the epfile->ffs->gadget might be NULL
873                  * before the waiting completes, so do not assign to 'gadget' earlier
874                  */
875                 struct usb_gadget *gadget = epfile->ffs->gadget;
876                 size_t copied;
877
878                 spin_lock_irq(&epfile->ffs->eps_lock);
879                 /* In the meantime, endpoint got disabled or changed. */
880                 if (epfile->ep != ep) {
881                         spin_unlock_irq(&epfile->ffs->eps_lock);
882                         return -ESHUTDOWN;
883                 }
884                 data_len = iov_iter_count(&io_data->data);
885                 /*
886                  * Controller may require buffer size to be aligned to
887                  * maxpacketsize of an out endpoint.
888                  */
889                 if (io_data->read)
890                         data_len = usb_ep_align_maybe(gadget, ep->ep, data_len);
891                 spin_unlock_irq(&epfile->ffs->eps_lock);
892
893                 data = kmalloc(data_len, GFP_KERNEL);
894                 if (unlikely(!data))
895                         return -ENOMEM;
896                 if (!io_data->read) {
897                         copied = copy_from_iter(data, data_len, &io_data->data);
898                         if (copied != data_len) {
899                                 ret = -EFAULT;
900                                 goto error;
901                         }
902                 }
903         }
904
905         /* We will be using request */
906         ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
907         if (unlikely(ret))
908                 goto error;
909
910         spin_lock_irq(&epfile->ffs->eps_lock);
911
912         if (epfile->ep != ep) {
913                 /* In the meantime, endpoint got disabled or changed. */
914                 ret = -ESHUTDOWN;
915                 spin_unlock_irq(&epfile->ffs->eps_lock);
916         } else if (halt) {
917                 /* Halt */
918                 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
919                         usb_ep_set_halt(ep->ep);
920                 spin_unlock_irq(&epfile->ffs->eps_lock);
921                 ret = -EBADMSG;
922         } else {
923                 /* Fire the request */
924                 struct usb_request *req;
925
926                 /*
927                  * Sanity Check: even though data_len can't be used
928                  * uninitialized at the time I write this comment, some
929                  * compilers complain about this situation.
930                  * In order to keep the code clean from warnings, data_len is
931                  * being initialized to -EINVAL during its declaration, which
932                  * means we can't rely on compiler anymore to warn no future
933                  * changes won't result in data_len being used uninitialized.
934                  * For such reason, we're adding this redundant sanity check
935                  * here.
936                  */
937                 if (unlikely(data_len == -EINVAL)) {
938                         WARN(1, "%s: data_len == -EINVAL\n", __func__);
939                         ret = -EINVAL;
940                         goto error_lock;
941                 }
942
943                 if (io_data->aio) {
944                         req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC);
945                         if (unlikely(!req))
946                                 goto error_lock;
947
948                         req->buf      = data;
949                         req->length   = data_len;
950
951                         io_data->buf = data;
952                         io_data->ep = ep->ep;
953                         io_data->req = req;
954                         io_data->ffs = epfile->ffs;
955
956                         req->context  = io_data;
957                         req->complete = ffs_epfile_async_io_complete;
958
959                         ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
960                         if (unlikely(ret)) {
961                                 usb_ep_free_request(ep->ep, req);
962                                 goto error_lock;
963                         }
964                         ret = -EIOCBQUEUED;
965
966                         spin_unlock_irq(&epfile->ffs->eps_lock);
967                 } else {
968                         struct completion *done;
969
970                         req = ep->req;
971                         req->buf      = data;
972                         req->length   = data_len;
973                         ret           = 0;
974
975                         req->complete = ffs_epfile_io_complete;
976
977                         if (io_data->read) {
978                                 reinit_completion(&epfile->ffs->epout_completion);
979                                 done = &epfile->ffs->epout_completion;
980                         } else {
981                                 reinit_completion(&epfile->ffs->epin_completion);
982                                 done = &epfile->ffs->epin_completion;
983                         }
984                         req->context = done;
985
986                         /*
987                          * Don't queue another read request if previous is
988                          * still busy.
989                          */
990                         if (!(io_data->read && ep->is_busy)) {
991                                 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
992                                 ep->is_busy = true;
993                         }
994
995                         spin_unlock_irq(&epfile->ffs->eps_lock);
996
997                         if (unlikely(ret < 0)) {
998                                 ret = -EIO;
999                         } else if (unlikely(
1000                                    wait_for_completion_interruptible(done))) {
1001                                 spin_lock_irq(&epfile->ffs->eps_lock);
1002                                 /*
1003                                  * While we were acquiring lock endpoint got
1004                                  * disabled (disconnect) or changed
1005                                  * (composition switch) ?
1006                                  */
1007                                 if (epfile->ep == ep)
1008                                         usb_ep_dequeue(ep->ep, req);
1009                                 spin_unlock_irq(&epfile->ffs->eps_lock);
1010                                 ret = -EINTR;
1011                         } else {
1012                                 /*
1013                                  * XXX We may end up silently droping data
1014                                  * here.  Since data_len (i.e. req->length) may
1015                                  * be bigger than len (after being rounded up
1016                                  * to maxpacketsize), we may end up with more
1017                                  * data then user space has space for.
1018                                  */
1019                                 spin_lock_irq(&epfile->ffs->eps_lock);
1020                                 /*
1021                                  * While we were acquiring lock endpoint got
1022                                  * disabled (disconnect) or changed
1023                                  * (composition switch) ?
1024                                  */
1025                                 if (epfile->ep == ep) {
1026                                         ret = ep->status;
1027                                         if (ret >= 0)
1028                                                 first_read_done = true;
1029                                 } else {
1030                                         ret = -ENODEV;
1031                                 }
1032
1033                                 /* do wait again if func eps are not enabled */
1034                                 if (io_data->read && !first_read_done
1035                                                         && ret < 0) {
1036                                         unsigned short count = ffs->eps_count;
1037
1038                                         pr_debug("%s: waiting for the online state\n",
1039                                                  __func__);
1040                                         ret = 0;
1041                                         kfree(data);
1042                                         data = NULL;
1043                                         data_len = -EINVAL;
1044                                         spin_unlock_irq(&epfile->ffs->eps_lock);
1045                                         mutex_unlock(&epfile->mutex);
1046                                         epfile = ffs->epfiles;
1047                                         do {
1048                                                 atomic_set(&epfile->error, 0);
1049                                                 ++epfile;
1050                                         } while (--count);
1051                                         epfile = file->private_data;
1052                                         goto retry;
1053                                 }
1054
1055                                 spin_unlock_irq(&epfile->ffs->eps_lock);
1056                                 if (io_data->read && ret > 0) {
1057
1058                                         if (ret > data_len) {
1059                                                 ret = -EOVERFLOW;
1060                                                 pr_err("More data(%zd) received than intended length(%zu)\n",
1061                                                                 ret, data_len);
1062
1063                                         } else {
1064                                                 ret = copy_to_iter(data, ret, &io_data->data);
1065                                                 pr_debug("copied (%zd) bytes to user space\n", ret);
1066                                                 if (!ret) {
1067                                                         pr_err("Fail to copy to user\n");
1068                                                         ret = -EFAULT;
1069                                                 }
1070                                         }
1071                                 }
1072                         }
1073                         kfree(data);
1074                 }
1075         }
1076
1077         mutex_unlock(&epfile->mutex);
1078
1079         ffs_log("exit:ret %zu", ret);
1080
1081         return ret;
1082
1083 error_lock:
1084         spin_unlock_irq(&epfile->ffs->eps_lock);
1085         mutex_unlock(&epfile->mutex);
1086 error:
1087         kfree(data);
1088
1089         ffs_log("exit: ret %zu", ret);
1090
1091         return ret;
1092 }
1093
1094 static int
1095 ffs_epfile_open(struct inode *inode, struct file *file)
1096 {
1097         struct ffs_epfile *epfile = inode->i_private;
1098         int ret;
1099
1100         ENTER();
1101
1102         ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1103                 epfile->ffs->setup_state, epfile->ffs->flags);
1104
1105         ret = ffs_inst_exist_check(epfile->ffs->dev_name);
1106         if (ret < 0)
1107                 return ret;
1108
1109         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1110                 return -ENODEV;
1111
1112         smp_mb__before_atomic();
1113         if (atomic_read(&epfile->opened)) {
1114                 pr_err("%s(): ep(%s) is already opened.\n",
1115                                         __func__, epfile->name);
1116                 return -EBUSY;
1117         }
1118
1119         smp_mb__before_atomic();
1120         atomic_set(&epfile->opened, 1);
1121         file->private_data = epfile;
1122         ffs_data_opened(epfile->ffs);
1123
1124         smp_mb__before_atomic();
1125         atomic_set(&epfile->error, 0);
1126         first_read_done = false;
1127
1128         ffs_log("exit:state %d setup_state %d flag %lu", epfile->ffs->state,
1129                 epfile->ffs->setup_state, epfile->ffs->flags);
1130
1131         return 0;
1132 }
1133
1134 static int ffs_aio_cancel(struct kiocb *kiocb)
1135 {
1136         struct ffs_io_data *io_data = kiocb->private;
1137         struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
1138         int value;
1139
1140         ENTER();
1141
1142         ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1143                 epfile->ffs->setup_state, epfile->ffs->flags);
1144
1145         spin_lock_irq(&epfile->ffs->eps_lock);
1146
1147         if (likely(io_data && io_data->ep && io_data->req))
1148                 value = usb_ep_dequeue(io_data->ep, io_data->req);
1149         else
1150                 value = -EINVAL;
1151
1152         spin_unlock_irq(&epfile->ffs->eps_lock);
1153
1154         ffs_log("exit: value %d", value);
1155
1156         return value;
1157 }
1158
1159 static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
1160 {
1161         struct ffs_io_data io_data, *p = &io_data;
1162         ssize_t res;
1163
1164         ENTER();
1165
1166         ffs_log("enter");
1167
1168         if (!is_sync_kiocb(kiocb)) {
1169                 p = kmalloc(sizeof(io_data), GFP_KERNEL);
1170                 if (unlikely(!p))
1171                         return -ENOMEM;
1172                 p->aio = true;
1173         } else {
1174                 p->aio = false;
1175         }
1176
1177         p->read = false;
1178         p->kiocb = kiocb;
1179         p->data = *from;
1180         p->mm = current->mm;
1181
1182         kiocb->private = p;
1183
1184         if (p->aio)
1185                 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1186
1187         res = ffs_epfile_io(kiocb->ki_filp, p);
1188         if (res == -EIOCBQUEUED)
1189                 return res;
1190         if (p->aio)
1191                 kfree(p);
1192         else
1193                 *from = p->data;
1194
1195         ffs_log("exit");
1196
1197         return res;
1198 }
1199
1200 static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
1201 {
1202         struct ffs_io_data io_data, *p = &io_data;
1203         ssize_t res;
1204
1205         ENTER();
1206
1207         ffs_log("enter");
1208
1209         if (!is_sync_kiocb(kiocb)) {
1210                 p = kmalloc(sizeof(io_data), GFP_KERNEL);
1211                 if (unlikely(!p))
1212                         return -ENOMEM;
1213                 p->aio = true;
1214         } else {
1215                 p->aio = false;
1216         }
1217
1218         p->read = true;
1219         p->kiocb = kiocb;
1220         if (p->aio) {
1221                 p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
1222                 if (!p->to_free) {
1223                         kfree(p);
1224                         return -ENOMEM;
1225                 }
1226         } else {
1227                 p->data = *to;
1228                 p->to_free = NULL;
1229         }
1230         p->mm = current->mm;
1231
1232         kiocb->private = p;
1233
1234         if (p->aio)
1235                 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1236
1237         res = ffs_epfile_io(kiocb->ki_filp, p);
1238         if (res == -EIOCBQUEUED)
1239                 return res;
1240
1241         if (p->aio) {
1242                 kfree(p->to_free);
1243                 kfree(p);
1244         } else {
1245                 *to = p->data;
1246         }
1247
1248         ffs_log("exit");
1249
1250         return res;
1251 }
1252
1253 static int
1254 ffs_epfile_release(struct inode *inode, struct file *file)
1255 {
1256         struct ffs_epfile *epfile = inode->i_private;
1257
1258         ENTER();
1259
1260         ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1261                 epfile->ffs->setup_state, epfile->ffs->flags);
1262
1263         smp_mb__before_atomic();
1264         atomic_set(&epfile->opened, 0);
1265         atomic_set(&epfile->error, 1);
1266         ffs_data_closed(epfile->ffs);
1267         file->private_data = NULL;
1268
1269         ffs_log("exit");
1270
1271         return 0;
1272 }
1273
1274 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1275                              unsigned long value)
1276 {
1277         struct ffs_epfile *epfile = file->private_data;
1278         int ret;
1279
1280         ENTER();
1281
1282         ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1283                 epfile->ffs->setup_state, epfile->ffs->flags);
1284
1285         ret = ffs_inst_exist_check(epfile->ffs->dev_name);
1286         if (ret < 0)
1287                 return ret;
1288
1289         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1290                 return -ENODEV;
1291
1292         spin_lock_irq(&epfile->ffs->eps_lock);
1293         if (likely(epfile->ep)) {
1294                 switch (code) {
1295                 case FUNCTIONFS_FIFO_STATUS:
1296                         ret = usb_ep_fifo_status(epfile->ep->ep);
1297                         break;
1298                 case FUNCTIONFS_FIFO_FLUSH:
1299                         usb_ep_fifo_flush(epfile->ep->ep);
1300                         ret = 0;
1301                         break;
1302                 case FUNCTIONFS_CLEAR_HALT:
1303                         ret = usb_ep_clear_halt(epfile->ep->ep);
1304                         break;
1305                 case FUNCTIONFS_ENDPOINT_REVMAP:
1306                         ret = epfile->ep->num;
1307                         break;
1308                 case FUNCTIONFS_ENDPOINT_DESC:
1309                 {
1310                         int desc_idx;
1311                         struct usb_endpoint_descriptor *desc;
1312
1313                         switch (epfile->ffs->gadget->speed) {
1314                         case USB_SPEED_SUPER:
1315                                 desc_idx = 2;
1316                                 break;
1317                         case USB_SPEED_HIGH:
1318                                 desc_idx = 1;
1319                                 break;
1320                         default:
1321                                 desc_idx = 0;
1322                         }
1323                         desc = epfile->ep->descs[desc_idx];
1324
1325                         spin_unlock_irq(&epfile->ffs->eps_lock);
1326                         ret = copy_to_user((void *)value, desc, sizeof(*desc));
1327                         if (ret)
1328                                 ret = -EFAULT;
1329                         return ret;
1330                 }
1331                 default:
1332                         ret = -ENOTTY;
1333                 }
1334         } else {
1335                 ret = -ENODEV;
1336         }
1337         spin_unlock_irq(&epfile->ffs->eps_lock);
1338
1339         ffs_log("exit:ret %d", ret);
1340
1341         return ret;
1342 }
1343
1344 static const struct file_operations ffs_epfile_operations = {
1345         .llseek =       no_llseek,
1346
1347         .open =         ffs_epfile_open,
1348         .write_iter =   ffs_epfile_write_iter,
1349         .read_iter =    ffs_epfile_read_iter,
1350         .release =      ffs_epfile_release,
1351         .unlocked_ioctl =       ffs_epfile_ioctl,
1352 };
1353
1354
1355 /* File system and super block operations ***********************************/
1356
1357 /*
1358  * Mounting the file system creates a controller file, used first for
1359  * function configuration then later for event monitoring.
1360  */
1361
1362 static struct inode *__must_check
1363 ffs_sb_make_inode(struct super_block *sb, void *data,
1364                   const struct file_operations *fops,
1365                   const struct inode_operations *iops,
1366                   struct ffs_file_perms *perms)
1367 {
1368         struct inode *inode;
1369
1370         ENTER();
1371
1372         ffs_log("enter");
1373
1374         inode = new_inode(sb);
1375
1376         if (likely(inode)) {
1377                 struct timespec current_time = CURRENT_TIME;
1378
1379                 inode->i_ino     = get_next_ino();
1380                 inode->i_mode    = perms->mode;
1381                 inode->i_uid     = perms->uid;
1382                 inode->i_gid     = perms->gid;
1383                 inode->i_atime   = current_time;
1384                 inode->i_mtime   = current_time;
1385                 inode->i_ctime   = current_time;
1386                 inode->i_private = data;
1387                 if (fops)
1388                         inode->i_fop = fops;
1389                 if (iops)
1390                         inode->i_op  = iops;
1391         }
1392
1393         ffs_log("exit");
1394
1395         return inode;
1396 }
1397
1398 /* Create "regular" file */
1399 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1400                                         const char *name, void *data,
1401                                         const struct file_operations *fops)
1402 {
1403         struct ffs_data *ffs = sb->s_fs_info;
1404         struct dentry   *dentry;
1405         struct inode    *inode;
1406
1407         ENTER();
1408
1409         ffs_log("enter");
1410
1411         dentry = d_alloc_name(sb->s_root, name);
1412         if (unlikely(!dentry))
1413                 return NULL;
1414
1415         inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1416         if (unlikely(!inode)) {
1417                 dput(dentry);
1418                 return NULL;
1419         }
1420
1421         d_add(dentry, inode);
1422
1423         ffs_log("exit");
1424
1425         return dentry;
1426 }
1427
1428 /* Super block */
1429 static const struct super_operations ffs_sb_operations = {
1430         .statfs =       simple_statfs,
1431         .drop_inode =   generic_delete_inode,
1432 };
1433
1434 struct ffs_sb_fill_data {
1435         struct ffs_file_perms perms;
1436         umode_t root_mode;
1437         const char *dev_name;
1438         bool no_disconnect;
1439         struct ffs_data *ffs_data;
1440 };
1441
1442 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1443 {
1444         struct ffs_sb_fill_data *data = _data;
1445         struct inode    *inode;
1446         struct ffs_data *ffs = data->ffs_data;
1447
1448         ENTER();
1449
1450         ffs_log("enter");
1451
1452         ffs->sb              = sb;
1453         data->ffs_data       = NULL;
1454         sb->s_fs_info        = ffs;
1455         sb->s_blocksize      = PAGE_CACHE_SIZE;
1456         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1457         sb->s_magic          = FUNCTIONFS_MAGIC;
1458         sb->s_op             = &ffs_sb_operations;
1459         sb->s_time_gran      = 1;
1460
1461         /* Root inode */
1462         data->perms.mode = data->root_mode;
1463         inode = ffs_sb_make_inode(sb, NULL,
1464                                   &simple_dir_operations,
1465                                   &simple_dir_inode_operations,
1466                                   &data->perms);
1467         sb->s_root = d_make_root(inode);
1468         if (unlikely(!sb->s_root))
1469                 return -ENOMEM;
1470
1471         /* EP0 file */
1472         if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1473                                          &ffs_ep0_operations)))
1474                 return -ENOMEM;
1475
1476         ffs_log("exit");
1477
1478         return 0;
1479 }
1480
1481 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1482 {
1483         ENTER();
1484
1485         ffs_log("enter");
1486
1487         if (!opts || !*opts)
1488                 return 0;
1489
1490         for (;;) {
1491                 unsigned long value;
1492                 char *eq, *comma;
1493
1494                 /* Option limit */
1495                 comma = strchr(opts, ',');
1496                 if (comma)
1497                         *comma = 0;
1498
1499                 /* Value limit */
1500                 eq = strchr(opts, '=');
1501                 if (unlikely(!eq)) {
1502                         pr_err("'=' missing in %s\n", opts);
1503                         return -EINVAL;
1504                 }
1505                 *eq = 0;
1506
1507                 /* Parse value */
1508                 if (kstrtoul(eq + 1, 0, &value)) {
1509                         pr_err("%s: invalid value: %s\n", opts, eq + 1);
1510                         return -EINVAL;
1511                 }
1512
1513                 /* Interpret option */
1514                 switch (eq - opts) {
1515                 case 13:
1516                         if (!memcmp(opts, "no_disconnect", 13))
1517                                 data->no_disconnect = !!value;
1518                         else
1519                                 goto invalid;
1520                         break;
1521                 case 5:
1522                         if (!memcmp(opts, "rmode", 5))
1523                                 data->root_mode  = (value & 0555) | S_IFDIR;
1524                         else if (!memcmp(opts, "fmode", 5))
1525                                 data->perms.mode = (value & 0666) | S_IFREG;
1526                         else
1527                                 goto invalid;
1528                         break;
1529
1530                 case 4:
1531                         if (!memcmp(opts, "mode", 4)) {
1532                                 data->root_mode  = (value & 0555) | S_IFDIR;
1533                                 data->perms.mode = (value & 0666) | S_IFREG;
1534                         } else {
1535                                 goto invalid;
1536                         }
1537                         break;
1538
1539                 case 3:
1540                         if (!memcmp(opts, "uid", 3)) {
1541                                 data->perms.uid = make_kuid(current_user_ns(), value);
1542                                 if (!uid_valid(data->perms.uid)) {
1543                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1544                                         return -EINVAL;
1545                                 }
1546                         } else if (!memcmp(opts, "gid", 3)) {
1547                                 data->perms.gid = make_kgid(current_user_ns(), value);
1548                                 if (!gid_valid(data->perms.gid)) {
1549                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1550                                         return -EINVAL;
1551                                 }
1552                         } else {
1553                                 goto invalid;
1554                         }
1555                         break;
1556
1557                 default:
1558 invalid:
1559                         pr_err("%s: invalid option\n", opts);
1560                         return -EINVAL;
1561                 }
1562
1563                 /* Next iteration */
1564                 if (!comma)
1565                         break;
1566                 opts = comma + 1;
1567         }
1568
1569         ffs_log("exit");
1570
1571         return 0;
1572 }
1573
1574 /* "mount -t functionfs dev_name /dev/function" ends up here */
1575
1576 static struct dentry *
1577 ffs_fs_mount(struct file_system_type *t, int flags,
1578               const char *dev_name, void *opts)
1579 {
1580         struct ffs_sb_fill_data data = {
1581                 .perms = {
1582                         .mode = S_IFREG | 0600,
1583                         .uid = GLOBAL_ROOT_UID,
1584                         .gid = GLOBAL_ROOT_GID,
1585                 },
1586                 .root_mode = S_IFDIR | 0500,
1587                 .no_disconnect = false,
1588         };
1589         struct dentry *rv;
1590         int ret;
1591         void *ffs_dev;
1592         struct ffs_data *ffs;
1593         struct ffs_inst_status *inst_status;
1594
1595         ENTER();
1596
1597         ffs_log("enter");
1598
1599         ret = ffs_fs_parse_opts(&data, opts);
1600         if (unlikely(ret < 0))
1601                 return ERR_PTR(ret);
1602
1603         ffs = ffs_data_new();
1604         if (unlikely(!ffs))
1605                 return ERR_PTR(-ENOMEM);
1606         ffs->file_perms = data.perms;
1607         ffs->no_disconnect = data.no_disconnect;
1608
1609         ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1610         if (unlikely(!ffs->dev_name)) {
1611                 ffs_data_put(ffs);
1612                 return ERR_PTR(-ENOMEM);
1613         }
1614
1615         ffs_dev = ffs_acquire_dev(dev_name);
1616         if (IS_ERR(ffs_dev)) {
1617                 ffs_data_put(ffs);
1618                 return ERR_CAST(ffs_dev);
1619         }
1620         ffs->private_data = ffs_dev;
1621         data.ffs_data = ffs;
1622
1623         inst_status = name_to_inst_status(ffs->dev_name, false);
1624         if (IS_ERR(inst_status)) {
1625                 ffs_log("failed to find instance (%s)\n",
1626                                 ffs->dev_name);
1627                 return ERR_PTR(-EINVAL);
1628         }
1629
1630         /* Store ffs to global status structure */
1631         ffs_dev_lock();
1632         inst_status->ffs_data = ffs;
1633         ffs_dev_unlock();
1634
1635         rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1636         if (IS_ERR(rv) && data.ffs_data) {
1637                 ffs_release_dev(data.ffs_data);
1638                 ffs_data_put(data.ffs_data);
1639         }
1640
1641         ffs_log("exit");
1642
1643         return rv;
1644 }
1645
1646 static void
1647 ffs_fs_kill_sb(struct super_block *sb)
1648 {
1649         ENTER();
1650
1651         ffs_log("enter");
1652
1653         kill_litter_super(sb);
1654         if (sb->s_fs_info) {
1655                 ffs_release_dev(sb->s_fs_info);
1656                 ffs_data_closed(sb->s_fs_info);
1657         }
1658
1659         ffs_log("exit");
1660 }
1661
1662 static struct file_system_type ffs_fs_type = {
1663         .owner          = THIS_MODULE,
1664         .name           = "functionfs",
1665         .mount          = ffs_fs_mount,
1666         .kill_sb        = ffs_fs_kill_sb,
1667 };
1668 MODULE_ALIAS_FS("functionfs");
1669
1670
1671 /* Driver's main init/cleanup functions *************************************/
1672
1673 static int functionfs_init(void)
1674 {
1675         int ret;
1676
1677         ENTER();
1678
1679         ret = register_filesystem(&ffs_fs_type);
1680         if (likely(!ret))
1681                 pr_info("file system registered\n");
1682         else
1683                 pr_err("failed registering file system (%d)\n", ret);
1684
1685         return ret;
1686 }
1687
1688 static void functionfs_cleanup(void)
1689 {
1690         ENTER();
1691
1692         pr_info("unloading\n");
1693         unregister_filesystem(&ffs_fs_type);
1694 }
1695
1696 /* ffs_data and ffs_function construction and destruction code **************/
1697
1698 static void ffs_data_clear(struct ffs_data *ffs);
1699 static void ffs_data_reset(struct ffs_data *ffs);
1700
1701 static void ffs_data_get(struct ffs_data *ffs)
1702 {
1703         ENTER();
1704
1705         ffs_log("enter");
1706
1707         smp_mb__before_atomic();
1708         atomic_inc(&ffs->ref);
1709
1710         ffs_log("exit");
1711 }
1712
1713 static void ffs_data_opened(struct ffs_data *ffs)
1714 {
1715         ENTER();
1716
1717         ffs_log("enter: state %d setup_state %d flag %lu opened %d", ffs->state,
1718                 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
1719
1720         smp_mb__before_atomic();
1721         atomic_inc(&ffs->ref);
1722         if (atomic_add_return(1, &ffs->opened) == 1 &&
1723                         ffs->state == FFS_DEACTIVATED) {
1724                 ffs->state = FFS_CLOSING;
1725                 ffs_data_reset(ffs);
1726         }
1727
1728         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1729                 ffs->setup_state, ffs->flags);
1730 }
1731
1732 static void ffs_data_put(struct ffs_data *ffs)
1733 {
1734         struct ffs_inst_status *inst_status;
1735         const char *dev_name;
1736
1737         ENTER();
1738
1739         ffs_log("enter");
1740
1741         smp_mb__before_atomic();
1742         if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1743                 pr_info("%s(): freeing\n", __func__);
1744                 /* Clear ffs from global structure */
1745                 inst_status = name_to_inst_status(ffs->dev_name, false);
1746                 if (!IS_ERR(inst_status)) {
1747                         ffs_dev_lock();
1748                         inst_status->ffs_data = NULL;
1749                         ffs_dev_unlock();
1750                 }
1751                 ffs_data_clear(ffs);
1752                 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1753                        waitqueue_active(&ffs->ep0req_completion.wait));
1754                 dev_name = ffs->dev_name;
1755                 kfree(ffs);
1756                 ffs_inst_clean_delay(dev_name);
1757                 kfree(dev_name);
1758         }
1759
1760         ffs_log("exit");
1761 }
1762
1763 static void ffs_data_closed(struct ffs_data *ffs)
1764 {
1765         ENTER();
1766
1767         ffs_log("enter: state %d setup_state %d flag %lu opened %d", ffs->state,
1768                 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
1769
1770         smp_mb__before_atomic();
1771         if (atomic_dec_and_test(&ffs->opened)) {
1772                 if (ffs->no_disconnect) {
1773                         ffs->state = FFS_DEACTIVATED;
1774                         if (ffs->epfiles) {
1775                                 ffs_epfiles_destroy(ffs->epfiles,
1776                                                    ffs->eps_count);
1777                                 ffs->epfiles = NULL;
1778                         }
1779                         if (ffs->setup_state == FFS_SETUP_PENDING)
1780                                 __ffs_ep0_stall(ffs);
1781                 } else {
1782                         ffs->state = FFS_CLOSING;
1783                         ffs_data_reset(ffs);
1784                 }
1785         }
1786
1787         smp_mb__before_atomic();
1788         if (atomic_read(&ffs->opened) < 0) {
1789                 ffs->state = FFS_CLOSING;
1790                 ffs_data_reset(ffs);
1791         }
1792
1793         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1794                 ffs->setup_state, ffs->flags);
1795
1796         ffs_data_put(ffs);
1797 }
1798
1799 static struct ffs_data *ffs_data_new(void)
1800 {
1801         struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1802         if (unlikely(!ffs))
1803                 return NULL;
1804
1805         ENTER();
1806
1807         ffs_log("enter");
1808
1809         atomic_set(&ffs->ref, 1);
1810         atomic_set(&ffs->opened, 0);
1811         ffs->state = FFS_READ_DESCRIPTORS;
1812         mutex_init(&ffs->mutex);
1813         spin_lock_init(&ffs->eps_lock);
1814         init_waitqueue_head(&ffs->ev.waitq);
1815         init_completion(&ffs->ep0req_completion);
1816         init_completion(&ffs->epout_completion);
1817         init_completion(&ffs->epin_completion);
1818
1819         /* XXX REVISIT need to update it in some places, or do we? */
1820         ffs->ev.can_stall = 1;
1821
1822         ffs_log("exit");
1823
1824         return ffs;
1825 }
1826
1827 static void ffs_data_clear(struct ffs_data *ffs)
1828 {
1829         ENTER();
1830
1831         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1832                 ffs->setup_state, ffs->flags);
1833
1834         pr_debug("%s: ffs->gadget= %pK, ffs->flags= %lu\n",
1835                                 __func__, ffs->gadget, ffs->flags);
1836         ffs_closed(ffs);
1837
1838         if (ffs->gadget)
1839                 pr_err("%s: ffs:%pK ffs->gadget= %pK, ffs->flags= %lu\n",
1840                                 __func__, ffs, ffs->gadget, ffs->flags);
1841         BUG_ON(ffs->gadget);
1842
1843         if (ffs->epfiles)
1844                 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1845
1846         if (ffs->ffs_eventfd)
1847                 eventfd_ctx_put(ffs->ffs_eventfd);
1848
1849         kfree(ffs->raw_descs_data);
1850         kfree(ffs->raw_strings);
1851         kfree(ffs->stringtabs);
1852
1853         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1854                 ffs->setup_state, ffs->flags);
1855 }
1856
1857 static void ffs_data_reset(struct ffs_data *ffs)
1858 {
1859         ENTER();
1860
1861         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1862                 ffs->setup_state, ffs->flags);
1863
1864         ffs_data_clear(ffs);
1865
1866         ffs->epfiles = NULL;
1867         ffs->raw_descs_data = NULL;
1868         ffs->raw_descs = NULL;
1869         ffs->raw_strings = NULL;
1870         ffs->stringtabs = NULL;
1871
1872         ffs->raw_descs_length = 0;
1873         ffs->fs_descs_count = 0;
1874         ffs->hs_descs_count = 0;
1875         ffs->ss_descs_count = 0;
1876
1877         ffs->strings_count = 0;
1878         ffs->interfaces_count = 0;
1879         ffs->eps_count = 0;
1880
1881         ffs->ev.count = 0;
1882
1883         ffs->state = FFS_READ_DESCRIPTORS;
1884         ffs->setup_state = FFS_NO_SETUP;
1885         ffs->flags = 0;
1886
1887         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1888                 ffs->setup_state, ffs->flags);
1889 }
1890
1891
1892 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1893 {
1894         struct usb_gadget_strings **lang;
1895         int first_id;
1896
1897         ENTER();
1898
1899         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1900                 ffs->setup_state, ffs->flags);
1901
1902         if (WARN_ON(ffs->state != FFS_ACTIVE
1903                  || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1904                 return -EBADFD;
1905
1906         first_id = usb_string_ids_n(cdev, ffs->strings_count);
1907         if (unlikely(first_id < 0))
1908                 return first_id;
1909
1910         ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1911         if (unlikely(!ffs->ep0req))
1912                 return -ENOMEM;
1913         ffs->ep0req->complete = ffs_ep0_complete;
1914         ffs->ep0req->context = ffs;
1915
1916         lang = ffs->stringtabs;
1917         if (lang) {
1918                 for (; *lang; ++lang) {
1919                         struct usb_string *str = (*lang)->strings;
1920                         int id = first_id;
1921                         for (; str->s; ++id, ++str)
1922                                 str->id = id;
1923                 }
1924         }
1925
1926         ffs->gadget = cdev->gadget;
1927
1928         ffs_log("exit: state %d setup_state %d flag %lu gadget %pK\n",
1929                         ffs->state, ffs->setup_state, ffs->flags, ffs->gadget);
1930
1931         ffs_data_get(ffs);
1932         return 0;
1933 }
1934
1935 static void functionfs_unbind(struct ffs_data *ffs)
1936 {
1937         ENTER();
1938
1939         if (!WARN_ON(!ffs->gadget)) {
1940                 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1941                 ffs->ep0req = NULL;
1942                 ffs->gadget = NULL;
1943                 clear_bit(FFS_FL_BOUND, &ffs->flags);
1944                 ffs_log("state %d setup_state %d flag %lu gadget %pK\n",
1945                         ffs->state, ffs->setup_state, ffs->flags, ffs->gadget);
1946                 ffs_data_put(ffs);
1947         }
1948 }
1949
1950 static int ffs_epfiles_create(struct ffs_data *ffs)
1951 {
1952         struct ffs_epfile *epfile, *epfiles;
1953         unsigned i, count;
1954
1955         ENTER();
1956
1957         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1958                 ffs->setup_state, ffs->flags);
1959
1960         count = ffs->eps_count;
1961         epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1962         if (!epfiles)
1963                 return -ENOMEM;
1964
1965         epfile = epfiles;
1966         for (i = 1; i <= count; ++i, ++epfile) {
1967                 epfile->ffs = ffs;
1968                 mutex_init(&epfile->mutex);
1969                 init_waitqueue_head(&epfile->wait);
1970                 atomic_set(&epfile->opened, 0);
1971                 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1972                         sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
1973                 else
1974                         sprintf(epfile->name, "ep%u", i);
1975                 epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
1976                                                  epfile,
1977                                                  &ffs_epfile_operations);
1978                 if (unlikely(!epfile->dentry)) {
1979                         ffs_epfiles_destroy(epfiles, i - 1);
1980                         return -ENOMEM;
1981                 }
1982         }
1983
1984         ffs->epfiles = epfiles;
1985
1986         ffs_log("exit: eps_count %u state %d setup_state %d flag %lu",
1987                 count, ffs->state, ffs->setup_state, ffs->flags);
1988
1989         return 0;
1990 }
1991
1992 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1993 {
1994         struct ffs_epfile *epfile = epfiles;
1995
1996         ENTER();
1997
1998         ffs_log("enter: count %u", count);
1999
2000         for (; count; --count, ++epfile) {
2001                 BUG_ON(mutex_is_locked(&epfile->mutex) ||
2002                        waitqueue_active(&epfile->wait));
2003                 if (epfile->dentry) {
2004                         d_delete(epfile->dentry);
2005                         dput(epfile->dentry);
2006                         epfile->dentry = NULL;
2007                 }
2008         }
2009
2010         kfree(epfiles);
2011
2012         ffs_log("exit");
2013 }
2014
2015 static void ffs_func_eps_disable(struct ffs_function *func)
2016 {
2017         struct ffs_ep *ep         = func->eps;
2018         struct ffs_epfile *epfile = func->ffs->epfiles;
2019         unsigned count            = func->ffs->eps_count;
2020         unsigned long flags;
2021
2022         ffs_log("enter: state %d setup_state %d flag %lu", func->ffs->state,
2023                 func->ffs->setup_state, func->ffs->flags);
2024
2025         spin_lock_irqsave(&func->ffs->eps_lock, flags);
2026         do {
2027
2028                 smp_mb__before_atomic();
2029                 if (epfile)
2030                         atomic_set(&epfile->error, 1);
2031
2032                 /* pending requests get nuked */
2033                 if (likely(ep->ep))
2034                         usb_ep_disable(ep->ep);
2035                 ++ep;
2036
2037                 if (epfile) {
2038                         atomic_set(&epfile->error, 1);
2039                         epfile->ep = NULL;
2040                         ++epfile;
2041                 }
2042         } while (--count);
2043         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2044
2045         ffs_log("exit");
2046 }
2047
2048 static int ffs_func_eps_enable(struct ffs_function *func)
2049 {
2050         struct ffs_data *ffs      = func->ffs;
2051         struct ffs_ep *ep         = func->eps;
2052         struct ffs_epfile *epfile = ffs->epfiles;
2053         unsigned count            = ffs->eps_count;
2054         unsigned long flags;
2055         int ret = 0;
2056
2057         ffs_log("enter: state %d setup_state %d flag %lu", func->ffs->state,
2058                 func->ffs->setup_state, func->ffs->flags);
2059
2060         spin_lock_irqsave(&func->ffs->eps_lock, flags);
2061         do {
2062                 struct usb_endpoint_descriptor *ds;
2063                 int desc_idx;
2064
2065                 if (ffs->gadget->speed == USB_SPEED_SUPER)
2066                         desc_idx = 2;
2067                 else if (ffs->gadget->speed == USB_SPEED_HIGH)
2068                         desc_idx = 1;
2069                 else
2070                         desc_idx = 0;
2071
2072                 /* fall-back to lower speed if desc missing for current speed */
2073                 do {
2074                         ds = ep->descs[desc_idx];
2075                 } while (!ds && --desc_idx >= 0);
2076
2077                 if (!ds) {
2078                         ret = -EINVAL;
2079                         break;
2080                 }
2081
2082                 ep->ep->driver_data = ep;
2083                 ep->ep->desc = ds;
2084
2085                 ret = config_ep_by_speed(func->gadget, &func->function, ep->ep);
2086                 if (ret) {
2087                         pr_err("%s(): config_ep_by_speed(%d) err for %s\n",
2088                                         __func__, ret, ep->ep->name);
2089                         break;
2090                 }
2091
2092                 /*
2093                  * userspace setting maxburst > 1 results more fifo
2094                  * allocation than without maxburst. Change maxburst to 1
2095                  * only to allocate fifo size of max packet size.
2096                  */
2097                 ep->ep->maxburst = 1;
2098                 ret = usb_ep_enable(ep->ep);
2099                 if (likely(!ret)) {
2100                         epfile->ep = ep;
2101                         epfile->in = usb_endpoint_dir_in(ds);
2102                         epfile->isoc = usb_endpoint_xfer_isoc(ds);
2103                         ffs_log("usb_ep_enable %s", ep->ep->name);
2104                 } else {
2105                         break;
2106                 }
2107
2108                 wake_up(&epfile->wait);
2109
2110                 ++ep;
2111                 ++epfile;
2112         } while (--count);
2113         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2114
2115         ffs_log("exit: ret %d", ret);
2116
2117         return ret;
2118 }
2119
2120
2121 /* Parsing and building descriptors and strings *****************************/
2122
2123 /*
2124  * This validates if data pointed by data is a valid USB descriptor as
2125  * well as record how many interfaces, endpoints and strings are
2126  * required by given configuration.  Returns address after the
2127  * descriptor or NULL if data is invalid.
2128  */
2129
2130 enum ffs_entity_type {
2131         FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
2132 };
2133
2134 enum ffs_os_desc_type {
2135         FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
2136 };
2137
2138 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
2139                                    u8 *valuep,
2140                                    struct usb_descriptor_header *desc,
2141                                    void *priv);
2142
2143 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
2144                                     struct usb_os_desc_header *h, void *data,
2145                                     unsigned len, void *priv);
2146
2147 static int __must_check ffs_do_single_desc(char *data, unsigned len,
2148                                            ffs_entity_callback entity,
2149                                            void *priv)
2150 {
2151         struct usb_descriptor_header *_ds = (void *)data;
2152         u8 length;
2153         int ret;
2154
2155         ENTER();
2156
2157         ffs_log("enter: len %u", len);
2158
2159         /* At least two bytes are required: length and type */
2160         if (len < 2) {
2161                 pr_vdebug("descriptor too short\n");
2162                 return -EINVAL;
2163         }
2164
2165         /* If we have at least as many bytes as the descriptor takes? */
2166         length = _ds->bLength;
2167         if (len < length) {
2168                 pr_vdebug("descriptor longer then available data\n");
2169                 return -EINVAL;
2170         }
2171
2172 #define __entity_check_INTERFACE(val)  1
2173 #define __entity_check_STRING(val)     (val)
2174 #define __entity_check_ENDPOINT(val)   ((val) & USB_ENDPOINT_NUMBER_MASK)
2175 #define __entity(type, val) do {                                        \
2176                 pr_vdebug("entity " #type "(%02x)\n", (val));           \
2177                 if (unlikely(!__entity_check_ ##type(val))) {           \
2178                         pr_vdebug("invalid entity's value\n");          \
2179                         return -EINVAL;                                 \
2180                 }                                                       \
2181                 ret = entity(FFS_ ##type, &val, _ds, priv);             \
2182                 if (unlikely(ret < 0)) {                                \
2183                         pr_debug("entity " #type "(%02x); ret = %d\n",  \
2184                                  (val), ret);                           \
2185                         return ret;                                     \
2186                 }                                                       \
2187         } while (0)
2188
2189         /* Parse descriptor depending on type. */
2190         switch (_ds->bDescriptorType) {
2191         case USB_DT_DEVICE:
2192         case USB_DT_CONFIG:
2193         case USB_DT_STRING:
2194         case USB_DT_DEVICE_QUALIFIER:
2195                 /* function can't have any of those */
2196                 pr_vdebug("descriptor reserved for gadget: %d\n",
2197                       _ds->bDescriptorType);
2198                 return -EINVAL;
2199
2200         case USB_DT_INTERFACE: {
2201                 struct usb_interface_descriptor *ds = (void *)_ds;
2202                 pr_vdebug("interface descriptor\n");
2203                 if (length != sizeof *ds)
2204                         goto inv_length;
2205
2206                 __entity(INTERFACE, ds->bInterfaceNumber);
2207                 if (ds->iInterface)
2208                         __entity(STRING, ds->iInterface);
2209         }
2210                 break;
2211
2212         case USB_DT_ENDPOINT: {
2213                 struct usb_endpoint_descriptor *ds = (void *)_ds;
2214                 pr_vdebug("endpoint descriptor\n");
2215                 if (length != USB_DT_ENDPOINT_SIZE &&
2216                     length != USB_DT_ENDPOINT_AUDIO_SIZE)
2217                         goto inv_length;
2218                 __entity(ENDPOINT, ds->bEndpointAddress);
2219         }
2220                 break;
2221
2222         case HID_DT_HID:
2223                 pr_vdebug("hid descriptor\n");
2224                 if (length != sizeof(struct hid_descriptor))
2225                         goto inv_length;
2226                 break;
2227
2228         case USB_DT_OTG:
2229                 if (length != sizeof(struct usb_otg_descriptor))
2230                         goto inv_length;
2231                 break;
2232
2233         case USB_DT_INTERFACE_ASSOCIATION: {
2234                 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
2235                 pr_vdebug("interface association descriptor\n");
2236                 if (length != sizeof *ds)
2237                         goto inv_length;
2238                 if (ds->iFunction)
2239                         __entity(STRING, ds->iFunction);
2240         }
2241                 break;
2242
2243         case USB_DT_SS_ENDPOINT_COMP:
2244                 pr_vdebug("EP SS companion descriptor\n");
2245                 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
2246                         goto inv_length;
2247                 break;
2248
2249         case USB_DT_OTHER_SPEED_CONFIG:
2250         case USB_DT_INTERFACE_POWER:
2251         case USB_DT_DEBUG:
2252         case USB_DT_SECURITY:
2253         case USB_DT_CS_RADIO_CONTROL:
2254                 /* TODO */
2255                 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
2256                 return -EINVAL;
2257
2258         default:
2259                 /* We should never be here */
2260                 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
2261                 return -EINVAL;
2262
2263 inv_length:
2264                 pr_vdebug("invalid length: %d (descriptor %d)\n",
2265                           _ds->bLength, _ds->bDescriptorType);
2266                 return -EINVAL;
2267         }
2268
2269 #undef __entity
2270 #undef __entity_check_DESCRIPTOR
2271 #undef __entity_check_INTERFACE
2272 #undef __entity_check_STRING
2273 #undef __entity_check_ENDPOINT
2274
2275         ffs_log("exit: desc type %d length %d", _ds->bDescriptorType, length);
2276
2277         return length;
2278 }
2279
2280 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
2281                                      ffs_entity_callback entity, void *priv)
2282 {
2283         const unsigned _len = len;
2284         unsigned long num = 0;
2285
2286         ENTER();
2287
2288         ffs_log("enter: len %u", len);
2289
2290         for (;;) {
2291                 int ret;
2292
2293                 if (num == count)
2294                         data = NULL;
2295
2296                 /* Record "descriptor" entity */
2297                 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
2298                 if (unlikely(ret < 0)) {
2299                         pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
2300                                  num, ret);
2301                         return ret;
2302                 }
2303
2304                 if (!data)
2305                         return _len - len;
2306
2307                 ret = ffs_do_single_desc(data, len, entity, priv);
2308                 if (unlikely(ret < 0)) {
2309                         pr_debug("%s returns %d\n", __func__, ret);
2310                         return ret;
2311                 }
2312
2313                 len -= ret;
2314                 data += ret;
2315                 ++num;
2316         }
2317
2318         ffs_log("exit: len %u", len);
2319 }
2320
2321 static int __ffs_data_do_entity(enum ffs_entity_type type,
2322                                 u8 *valuep, struct usb_descriptor_header *desc,
2323                                 void *priv)
2324 {
2325         struct ffs_desc_helper *helper = priv;
2326         struct usb_endpoint_descriptor *d;
2327
2328         ENTER();
2329
2330         ffs_log("enter: type %u", type);
2331
2332         switch (type) {
2333         case FFS_DESCRIPTOR:
2334                 break;
2335
2336         case FFS_INTERFACE:
2337                 /*
2338                  * Interfaces are indexed from zero so if we
2339                  * encountered interface "n" then there are at least
2340                  * "n+1" interfaces.
2341                  */
2342                 if (*valuep >= helper->interfaces_count)
2343                         helper->interfaces_count = *valuep + 1;
2344                 break;
2345
2346         case FFS_STRING:
2347                 /*
2348                  * Strings are indexed from 1 (0 is magic ;) reserved
2349                  * for languages list or some such)
2350                  */
2351                 if (*valuep > helper->ffs->strings_count)
2352                         helper->ffs->strings_count = *valuep;
2353                 break;
2354
2355         case FFS_ENDPOINT:
2356                 d = (void *)desc;
2357                 helper->eps_count++;
2358                 if (helper->eps_count >= 15)
2359                         return -EINVAL;
2360                 /* Check if descriptors for any speed were already parsed */
2361                 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
2362                         helper->ffs->eps_addrmap[helper->eps_count] =
2363                                 d->bEndpointAddress;
2364                 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
2365                                 d->bEndpointAddress)
2366                         return -EINVAL;
2367                 break;
2368         }
2369
2370         ffs_log("exit");
2371
2372         return 0;
2373 }
2374
2375 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
2376                                    struct usb_os_desc_header *desc)
2377 {
2378         u16 bcd_version = le16_to_cpu(desc->bcdVersion);
2379         u16 w_index = le16_to_cpu(desc->wIndex);
2380
2381         ffs_log("enter");
2382
2383         if (bcd_version != 1) {
2384                 pr_vdebug("unsupported os descriptors version: %d",
2385                           bcd_version);
2386                 return -EINVAL;
2387         }
2388         switch (w_index) {
2389         case 0x4:
2390                 *next_type = FFS_OS_DESC_EXT_COMPAT;
2391                 break;
2392         case 0x5:
2393                 *next_type = FFS_OS_DESC_EXT_PROP;
2394                 break;
2395         default:
2396                 pr_vdebug("unsupported os descriptor type: %d", w_index);
2397                 return -EINVAL;
2398         }
2399
2400         ffs_log("exit: size of desc %zu", sizeof(*desc));
2401
2402         return sizeof(*desc);
2403 }
2404
2405 /*
2406  * Process all extended compatibility/extended property descriptors
2407  * of a feature descriptor
2408  */
2409 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
2410                                               enum ffs_os_desc_type type,
2411                                               u16 feature_count,
2412                                               ffs_os_desc_callback entity,
2413                                               void *priv,
2414                                               struct usb_os_desc_header *h)
2415 {
2416         int ret;
2417         const unsigned _len = len;
2418
2419         ENTER();
2420
2421         ffs_log("enter: len %u os desc type %d", len, type);
2422
2423         /* loop over all ext compat/ext prop descriptors */
2424         while (feature_count--) {
2425                 ret = entity(type, h, data, len, priv);
2426                 if (unlikely(ret < 0)) {
2427                         pr_debug("bad OS descriptor, type: %d\n", type);
2428                         return ret;
2429                 }
2430                 data += ret;
2431                 len -= ret;
2432         }
2433
2434         ffs_log("exit");
2435
2436         return _len - len;
2437 }
2438
2439 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
2440 static int __must_check ffs_do_os_descs(unsigned count,
2441                                         char *data, unsigned len,
2442                                         ffs_os_desc_callback entity, void *priv)
2443 {
2444         const unsigned _len = len;
2445         unsigned long num = 0;
2446
2447         ENTER();
2448
2449         ffs_log("enter: len %u", len);
2450
2451         for (num = 0; num < count; ++num) {
2452                 int ret;
2453                 enum ffs_os_desc_type type;
2454                 u16 feature_count;
2455                 struct usb_os_desc_header *desc = (void *)data;
2456
2457                 if (len < sizeof(*desc))
2458                         return -EINVAL;
2459
2460                 /*
2461                  * Record "descriptor" entity.
2462                  * Process dwLength, bcdVersion, wIndex, get b/wCount.
2463                  * Move the data pointer to the beginning of extended
2464                  * compatibilities proper or extended properties proper
2465                  * portions of the data
2466                  */
2467                 if (le32_to_cpu(desc->dwLength) > len)
2468                         return -EINVAL;
2469
2470                 ret = __ffs_do_os_desc_header(&type, desc);
2471                 if (unlikely(ret < 0)) {
2472                         pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
2473                                  num, ret);
2474                         return ret;
2475                 }
2476                 /*
2477                  * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2478                  */
2479                 feature_count = le16_to_cpu(desc->wCount);
2480                 if (type == FFS_OS_DESC_EXT_COMPAT &&
2481                     (feature_count > 255 || desc->Reserved))
2482                                 return -EINVAL;
2483                 len -= ret;
2484                 data += ret;
2485
2486                 /*
2487                  * Process all function/property descriptors
2488                  * of this Feature Descriptor
2489                  */
2490                 ret = ffs_do_single_os_desc(data, len, type,
2491                                             feature_count, entity, priv, desc);
2492                 if (unlikely(ret < 0)) {
2493                         pr_debug("%s returns %d\n", __func__, ret);
2494                         return ret;
2495                 }
2496
2497                 len -= ret;
2498                 data += ret;
2499         }
2500
2501         ffs_log("exit");
2502
2503         return _len - len;
2504 }
2505
2506 /**
2507  * Validate contents of the buffer from userspace related to OS descriptors.
2508  */
2509 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2510                                  struct usb_os_desc_header *h, void *data,
2511                                  unsigned len, void *priv)
2512 {
2513         struct ffs_data *ffs = priv;
2514         u8 length;
2515
2516         ENTER();
2517
2518         ffs_log("enter: len %u", len);
2519
2520         switch (type) {
2521         case FFS_OS_DESC_EXT_COMPAT: {
2522                 struct usb_ext_compat_desc *d = data;
2523                 int i;
2524
2525                 if (len < sizeof(*d) ||
2526                     d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2527                     d->Reserved1 != 1) {
2528                         pr_err("%s(): Invalid os_desct_ext_compat\n",
2529                                                         __func__);
2530                         return -EINVAL;
2531                 }
2532                 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2533                         if (d->Reserved2[i]) {
2534                                 pr_err("%s(): Invalid Reserved2 of ext_compat\n",
2535                                                         __func__);
2536                                 return -EINVAL;
2537                         }
2538
2539                 length = sizeof(struct usb_ext_compat_desc);
2540         }
2541                 break;
2542         case FFS_OS_DESC_EXT_PROP: {
2543                 struct usb_ext_prop_desc *d = data;
2544                 u32 type, pdl;
2545                 u16 pnl;
2546
2547                 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2548                         return -EINVAL;
2549                 length = le32_to_cpu(d->dwSize);
2550                 if (len < length)
2551                         return -EINVAL;
2552                 type = le32_to_cpu(d->dwPropertyDataType);
2553                 if (type < USB_EXT_PROP_UNICODE ||
2554                     type > USB_EXT_PROP_UNICODE_MULTI) {
2555                         pr_vdebug("unsupported os descriptor property type: %d",
2556                                   type);
2557                         return -EINVAL;
2558                 }
2559                 pnl = le16_to_cpu(d->wPropertyNameLength);
2560                 if (length < 14 + pnl) {
2561                         pr_vdebug("invalid os descriptor length: %d pnl:%d (descriptor %d)\n",
2562                                   length, pnl, type);
2563                         return -EINVAL;
2564                 }
2565                 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2566                 if (length != 14 + pnl + pdl) {
2567                         pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2568                                   length, pnl, pdl, type);
2569                         return -EINVAL;
2570                 }
2571                 ++ffs->ms_os_descs_ext_prop_count;
2572                 /* property name reported to the host as "WCHAR"s */
2573                 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2574                 ffs->ms_os_descs_ext_prop_data_len += pdl;
2575         }
2576                 break;
2577         default:
2578                 pr_vdebug("unknown descriptor: %d\n", type);
2579                 return -EINVAL;
2580         }
2581
2582         ffs_log("exit");
2583
2584         return length;
2585 }
2586
2587 static int __ffs_data_got_descs(struct ffs_data *ffs,
2588                                 char *const _data, size_t len)
2589 {
2590         char *data = _data, *raw_descs;
2591         unsigned os_descs_count = 0, counts[3], flags;
2592         int ret = -EINVAL, i;
2593         struct ffs_desc_helper helper;
2594
2595         ENTER();
2596
2597         ffs_log("enter: len %zu", len);
2598
2599         if (get_unaligned_le32(data + 4) != len)
2600                 goto error;
2601
2602         switch (get_unaligned_le32(data)) {
2603         case FUNCTIONFS_DESCRIPTORS_MAGIC:
2604                 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2605                 data += 8;
2606                 len  -= 8;
2607                 break;
2608         case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2609                 flags = get_unaligned_le32(data + 8);
2610                 ffs->user_flags = flags;
2611                 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2612                               FUNCTIONFS_HAS_HS_DESC |
2613                               FUNCTIONFS_HAS_SS_DESC |
2614                               FUNCTIONFS_HAS_MS_OS_DESC |
2615                               FUNCTIONFS_VIRTUAL_ADDR |
2616                               FUNCTIONFS_EVENTFD)) {
2617                         ret = -ENOSYS;
2618                         goto error;
2619                 }
2620                 data += 12;
2621                 len  -= 12;
2622                 break;
2623         default:
2624                 goto error;
2625         }
2626
2627         if (flags & FUNCTIONFS_EVENTFD) {
2628                 if (len < 4)
2629                         goto error;
2630                 ffs->ffs_eventfd =
2631                         eventfd_ctx_fdget((int)get_unaligned_le32(data));
2632                 if (IS_ERR(ffs->ffs_eventfd)) {
2633                         ret = PTR_ERR(ffs->ffs_eventfd);
2634                         ffs->ffs_eventfd = NULL;
2635                         goto error;
2636                 }
2637                 data += 4;
2638                 len  -= 4;
2639         }
2640
2641         /* Read fs_count, hs_count and ss_count (if present) */
2642         for (i = 0; i < 3; ++i) {
2643                 if (!(flags & (1 << i))) {
2644                         counts[i] = 0;
2645                 } else if (len < 4) {
2646                         goto error;
2647                 } else {
2648                         counts[i] = get_unaligned_le32(data);
2649                         data += 4;
2650                         len  -= 4;
2651                 }
2652         }
2653         if (flags & (1 << i)) {
2654                 if (len < 4) {
2655                         goto error;
2656                 }
2657                 os_descs_count = get_unaligned_le32(data);
2658                 data += 4;
2659                 len -= 4;
2660         };
2661
2662         /* Read descriptors */
2663         raw_descs = data;
2664         helper.ffs = ffs;
2665         for (i = 0; i < 3; ++i) {
2666                 if (!counts[i])
2667                         continue;
2668                 helper.interfaces_count = 0;
2669                 helper.eps_count = 0;
2670                 ret = ffs_do_descs(counts[i], data, len,
2671                                    __ffs_data_do_entity, &helper);
2672                 if (ret < 0)
2673                         goto error;
2674                 if (!ffs->eps_count && !ffs->interfaces_count) {
2675                         ffs->eps_count = helper.eps_count;
2676                         ffs->interfaces_count = helper.interfaces_count;
2677                 } else {
2678                         if (ffs->eps_count != helper.eps_count) {
2679                                 ret = -EINVAL;
2680                                 goto error;
2681                         }
2682                         if (ffs->interfaces_count != helper.interfaces_count) {
2683                                 ret = -EINVAL;
2684                                 goto error;
2685                         }
2686                 }
2687                 data += ret;
2688                 len  -= ret;
2689         }
2690         if (os_descs_count) {
2691                 ret = ffs_do_os_descs(os_descs_count, data, len,
2692                                       __ffs_data_do_os_desc, ffs);
2693                 if (ret < 0)
2694                         goto error;
2695                 data += ret;
2696                 len -= ret;
2697         }
2698
2699         if (raw_descs == data || len) {
2700                 ret = -EINVAL;
2701                 goto error;
2702         }
2703
2704         ffs->raw_descs_data     = _data;
2705         ffs->raw_descs          = raw_descs;
2706         ffs->raw_descs_length   = data - raw_descs;
2707         ffs->fs_descs_count     = counts[0];
2708         ffs->hs_descs_count     = counts[1];
2709         ffs->ss_descs_count     = counts[2];
2710         ffs->ms_os_descs_count  = os_descs_count;
2711
2712         ffs_log("exit");
2713
2714         return 0;
2715
2716 error:
2717         kfree(_data);
2718         ffs_log("exit: ret %d", ret);
2719         return ret;
2720 }
2721
2722 static int __ffs_data_got_strings(struct ffs_data *ffs,
2723                                   char *const _data, size_t len)
2724 {
2725         u32 str_count, needed_count, lang_count;
2726         struct usb_gadget_strings **stringtabs, *t;
2727         struct usb_string *strings, *s;
2728         const char *data = _data;
2729
2730         ENTER();
2731
2732         ffs_log("enter: len %zu", len);
2733
2734         if (unlikely(len < 16 ||
2735                      get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2736                      get_unaligned_le32(data + 4) != len))
2737                 goto error;
2738         str_count  = get_unaligned_le32(data + 8);
2739         lang_count = get_unaligned_le32(data + 12);
2740
2741         /* if one is zero the other must be zero */
2742         if (unlikely(!str_count != !lang_count))
2743                 goto error;
2744
2745         /* Do we have at least as many strings as descriptors need? */
2746         needed_count = ffs->strings_count;
2747         if (unlikely(str_count < needed_count))
2748                 goto error;
2749
2750         /*
2751          * If we don't need any strings just return and free all
2752          * memory.
2753          */
2754         if (!needed_count) {
2755                 kfree(_data);
2756                 return 0;
2757         }
2758
2759         /* Allocate everything in one chunk so there's less maintenance. */
2760         {
2761                 unsigned i = 0;
2762                 vla_group(d);
2763                 vla_item(d, struct usb_gadget_strings *, stringtabs,
2764                         lang_count + 1);
2765                 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2766                 vla_item(d, struct usb_string, strings,
2767                         lang_count*(needed_count+1));
2768
2769                 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2770
2771                 if (unlikely(!vlabuf)) {
2772                         kfree(_data);
2773                         return -ENOMEM;
2774                 }
2775
2776                 /* Initialize the VLA pointers */
2777                 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2778                 t = vla_ptr(vlabuf, d, stringtab);
2779                 i = lang_count;
2780                 do {
2781                         *stringtabs++ = t++;
2782                 } while (--i);
2783                 *stringtabs = NULL;
2784
2785                 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2786                 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2787                 t = vla_ptr(vlabuf, d, stringtab);
2788                 s = vla_ptr(vlabuf, d, strings);
2789                 strings = s;
2790         }
2791
2792         /* For each language */
2793         data += 16;
2794         len -= 16;
2795
2796         do { /* lang_count > 0 so we can use do-while */
2797                 unsigned needed = needed_count;
2798
2799                 if (unlikely(len < 3))
2800                         goto error_free;
2801                 t->language = get_unaligned_le16(data);
2802                 t->strings  = s;
2803                 ++t;
2804
2805                 data += 2;
2806                 len -= 2;
2807
2808                 /* For each string */
2809                 do { /* str_count > 0 so we can use do-while */
2810                         size_t length = strnlen(data, len);
2811
2812                         if (unlikely(length == len))
2813                                 goto error_free;
2814
2815                         /*
2816                          * User may provide more strings then we need,
2817                          * if that's the case we simply ignore the
2818                          * rest
2819                          */
2820                         if (likely(needed)) {
2821                                 /*
2822                                  * s->id will be set while adding
2823                                  * function to configuration so for
2824                                  * now just leave garbage here.
2825                                  */
2826                                 s->s = data;
2827                                 --needed;
2828                                 ++s;
2829                         }
2830
2831                         data += length + 1;
2832                         len -= length + 1;
2833                 } while (--str_count);
2834
2835                 s->id = 0;   /* terminator */
2836                 s->s = NULL;
2837                 ++s;
2838
2839         } while (--lang_count);
2840
2841         /* Some garbage left? */
2842         if (unlikely(len))
2843                 goto error_free;
2844
2845         /* Done! */
2846         ffs->stringtabs = stringtabs;
2847         ffs->raw_strings = _data;
2848
2849         ffs_log("exit");
2850         return 0;
2851
2852 error_free:
2853         kfree(stringtabs);
2854 error:
2855         kfree(_data);
2856         ffs_log("exit: -EINVAL");
2857         return -EINVAL;
2858 }
2859
2860
2861 /* Events handling and management *******************************************/
2862
2863 static void __ffs_event_add(struct ffs_data *ffs,
2864                             enum usb_functionfs_event_type type)
2865 {
2866         enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2867         int neg = 0;
2868
2869         ffs_log("enter: type %d state %d setup_state %d flag %lu", type,
2870                 ffs->state, ffs->setup_state, ffs->flags);
2871
2872         /*
2873          * Abort any unhandled setup
2874          *
2875          * We do not need to worry about some cmpxchg() changing value
2876          * of ffs->setup_state without holding the lock because when
2877          * state is FFS_SETUP_PENDING cmpxchg() in several places in
2878          * the source does nothing.
2879          */
2880         if (ffs->setup_state == FFS_SETUP_PENDING)
2881                 ffs->setup_state = FFS_SETUP_CANCELLED;
2882
2883         /*
2884          * Logic of this function guarantees that there are at most four pending
2885          * evens on ffs->ev.types queue.  This is important because the queue
2886          * has space for four elements only and __ffs_ep0_read_events function
2887          * depends on that limit as well.  If more event types are added, those
2888          * limits have to be revisited or guaranteed to still hold.
2889          */
2890         switch (type) {
2891         case FUNCTIONFS_RESUME:
2892                 rem_type2 = FUNCTIONFS_SUSPEND;
2893                 /* FALL THROUGH */
2894         case FUNCTIONFS_SUSPEND:
2895         case FUNCTIONFS_SETUP:
2896                 rem_type1 = type;
2897                 /* Discard all similar events */
2898                 break;
2899
2900         case FUNCTIONFS_BIND:
2901         case FUNCTIONFS_UNBIND:
2902         case FUNCTIONFS_DISABLE:
2903         case FUNCTIONFS_ENABLE:
2904                 /* Discard everything other then power management. */
2905                 rem_type1 = FUNCTIONFS_SUSPEND;
2906                 rem_type2 = FUNCTIONFS_RESUME;
2907                 neg = 1;
2908                 break;
2909
2910         default:
2911                 WARN(1, "%d: unknown event, this should not happen\n", type);
2912                 return;
2913         }
2914
2915         {
2916                 u8 *ev  = ffs->ev.types, *out = ev;
2917                 unsigned n = ffs->ev.count;
2918                 for (; n; --n, ++ev)
2919                         if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2920                                 *out++ = *ev;
2921                         else
2922                                 pr_vdebug("purging event %d\n", *ev);
2923                 ffs->ev.count = out - ffs->ev.types;
2924         }
2925
2926         pr_vdebug("adding event %d\n", type);
2927         ffs->ev.types[ffs->ev.count++] = type;
2928         wake_up_locked(&ffs->ev.waitq);
2929         if (ffs->ffs_eventfd)
2930                 eventfd_signal(ffs->ffs_eventfd, 1);
2931
2932         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
2933                 ffs->setup_state, ffs->flags);
2934 }
2935
2936 static void ffs_event_add(struct ffs_data *ffs,
2937                           enum usb_functionfs_event_type type)
2938 {
2939         unsigned long flags;
2940         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2941         __ffs_event_add(ffs, type);
2942         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2943 }
2944
2945 /* Bind/unbind USB function hooks *******************************************/
2946
2947 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2948 {
2949         int i;
2950
2951         for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2952                 if (ffs->eps_addrmap[i] == endpoint_address)
2953                         return i;
2954         return -ENOENT;
2955 }
2956
2957 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2958                                     struct usb_descriptor_header *desc,
2959                                     void *priv)
2960 {
2961         struct usb_endpoint_descriptor *ds = (void *)desc;
2962         struct ffs_function *func = priv;
2963         struct ffs_ep *ffs_ep;
2964         unsigned ep_desc_id;
2965         int idx;
2966         static const char *speed_names[] = { "full", "high", "super" };
2967
2968         ffs_log("enter");
2969
2970         if (type != FFS_DESCRIPTOR)
2971                 return 0;
2972
2973         /*
2974          * If ss_descriptors is not NULL, we are reading super speed
2975          * descriptors; if hs_descriptors is not NULL, we are reading high
2976          * speed descriptors; otherwise, we are reading full speed
2977          * descriptors.
2978          */
2979         if (func->function.ss_descriptors) {
2980                 ep_desc_id = 2;
2981                 func->function.ss_descriptors[(long)valuep] = desc;
2982         } else if (func->function.hs_descriptors) {
2983                 ep_desc_id = 1;
2984                 func->function.hs_descriptors[(long)valuep] = desc;
2985         } else {
2986                 ep_desc_id = 0;
2987                 func->function.fs_descriptors[(long)valuep]    = desc;
2988         }
2989
2990         if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2991                 return 0;
2992
2993         idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2994         if (idx < 0)
2995                 return idx;
2996
2997         ffs_ep = func->eps + idx;
2998
2999         if (unlikely(ffs_ep->descs[ep_desc_id])) {
3000                 pr_err("two %sspeed descriptors for EP %d\n",
3001                           speed_names[ep_desc_id],
3002                           ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
3003                 return -EINVAL;
3004         }
3005         ffs_ep->descs[ep_desc_id] = ds;
3006
3007         ffs_dump_mem(": Original  ep desc", ds, ds->bLength);
3008         if (ffs_ep->ep) {
3009                 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
3010                 if (!ds->wMaxPacketSize)
3011                         ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
3012         } else {
3013                 struct usb_request *req;
3014                 struct usb_ep *ep;
3015                 u8 bEndpointAddress;
3016
3017                 /*
3018                  * We back up bEndpointAddress because autoconfig overwrites
3019                  * it with physical endpoint address.
3020                  */
3021                 bEndpointAddress = ds->bEndpointAddress;
3022                 pr_vdebug("autoconfig\n");
3023                 ep = usb_ep_autoconfig(func->gadget, ds);
3024                 if (unlikely(!ep))
3025                         return -ENOTSUPP;
3026                 ep->driver_data = func->eps + idx;
3027
3028                 req = usb_ep_alloc_request(ep, GFP_KERNEL);
3029                 if (unlikely(!req))
3030                         return -ENOMEM;
3031
3032                 ffs_ep->ep  = ep;
3033                 ffs_ep->req = req;
3034                 func->eps_revmap[ds->bEndpointAddress &
3035                                  USB_ENDPOINT_NUMBER_MASK] = idx + 1;
3036                 /*
3037                  * If we use virtual address mapping, we restore
3038                  * original bEndpointAddress value.
3039                  */
3040                 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3041                         ds->bEndpointAddress = bEndpointAddress;
3042         }
3043         ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
3044
3045         ffs_log("exit");
3046
3047         return 0;
3048 }
3049
3050 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
3051                                    struct usb_descriptor_header *desc,
3052                                    void *priv)
3053 {
3054         struct ffs_function *func = priv;
3055         unsigned idx;
3056         u8 newValue;
3057
3058         ffs_log("enter: type %d", type);
3059
3060         switch (type) {
3061         default:
3062         case FFS_DESCRIPTOR:
3063                 /* Handled in previous pass by __ffs_func_bind_do_descs() */
3064                 return 0;
3065
3066         case FFS_INTERFACE:
3067                 idx = *valuep;
3068                 if (func->interfaces_nums[idx] < 0) {
3069                         int id = usb_interface_id(func->conf, &func->function);
3070                         if (unlikely(id < 0))
3071                                 return id;
3072                         func->interfaces_nums[idx] = id;
3073                 }
3074                 newValue = func->interfaces_nums[idx];
3075                 break;
3076
3077         case FFS_STRING:
3078                 /* String' IDs are allocated when fsf_data is bound to cdev */
3079                 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
3080                 break;
3081
3082         case FFS_ENDPOINT:
3083                 /*
3084                  * USB_DT_ENDPOINT are handled in
3085                  * __ffs_func_bind_do_descs().
3086                  */
3087                 if (desc->bDescriptorType == USB_DT_ENDPOINT)
3088                         return 0;
3089
3090                 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
3091                 if (unlikely(!func->eps[idx].ep))
3092                         return -EINVAL;
3093
3094                 {
3095                         struct usb_endpoint_descriptor **descs;
3096                         descs = func->eps[idx].descs;
3097                         newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
3098                 }
3099                 break;
3100         }
3101
3102         pr_vdebug("%02x -> %02x\n", *valuep, newValue);
3103         *valuep = newValue;
3104
3105         ffs_log("exit: newValue %d", newValue);
3106
3107         return 0;
3108 }
3109
3110 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
3111                                       struct usb_os_desc_header *h, void *data,
3112                                       unsigned len, void *priv)
3113 {
3114         struct ffs_function *func = priv;
3115         u8 length = 0;
3116
3117         ffs_log("enter: type %d", type);
3118
3119         switch (type) {
3120         case FFS_OS_DESC_EXT_COMPAT: {
3121                 struct usb_ext_compat_desc *desc = data;
3122                 struct usb_os_desc_table *t;
3123
3124                 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
3125                 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
3126                 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
3127                        ARRAY_SIZE(desc->CompatibleID) +
3128                        ARRAY_SIZE(desc->SubCompatibleID));
3129                 length = sizeof(*desc);
3130         }
3131                 break;
3132         case FFS_OS_DESC_EXT_PROP: {
3133                 struct usb_ext_prop_desc *desc = data;
3134                 struct usb_os_desc_table *t;
3135                 struct usb_os_desc_ext_prop *ext_prop;
3136                 char *ext_prop_name;
3137                 char *ext_prop_data;
3138
3139                 t = &func->function.os_desc_table[h->interface];
3140                 t->if_id = func->interfaces_nums[h->interface];
3141
3142                 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
3143                 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
3144
3145                 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
3146                 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
3147                 ext_prop->data_len = le32_to_cpu(*(u32 *)
3148                         usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
3149                 length = ext_prop->name_len + ext_prop->data_len + 14;
3150
3151                 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
3152                 func->ffs->ms_os_descs_ext_prop_name_avail +=
3153                         ext_prop->name_len;
3154
3155                 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
3156                 func->ffs->ms_os_descs_ext_prop_data_avail +=
3157                         ext_prop->data_len;
3158                 memcpy(ext_prop_data,
3159                        usb_ext_prop_data_ptr(data, ext_prop->name_len),
3160                        ext_prop->data_len);
3161                 /* unicode data reported to the host as "WCHAR"s */
3162                 switch (ext_prop->type) {
3163                 case USB_EXT_PROP_UNICODE:
3164                 case USB_EXT_PROP_UNICODE_ENV:
3165                 case USB_EXT_PROP_UNICODE_LINK:
3166                 case USB_EXT_PROP_UNICODE_MULTI:
3167                         ext_prop->data_len *= 2;
3168                         break;
3169                 }
3170                 ext_prop->data = ext_prop_data;
3171
3172                 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
3173                        ext_prop->name_len);
3174                 /* property name reported to the host as "WCHAR"s */
3175                 ext_prop->name_len *= 2;
3176                 ext_prop->name = ext_prop_name;
3177
3178                 t->os_desc->ext_prop_len +=
3179                         ext_prop->name_len + ext_prop->data_len + 14;
3180                 ++t->os_desc->ext_prop_count;
3181                 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
3182         }
3183                 break;
3184         default:
3185                 pr_vdebug("unknown descriptor: %d\n", type);
3186         }
3187
3188         ffs_log("exit");
3189
3190         return length;
3191 }
3192
3193 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
3194                                                 struct usb_configuration *c)
3195 {
3196         struct ffs_function *func = ffs_func_from_usb(f);
3197         struct f_fs_opts *ffs_opts =
3198                 container_of(f->fi, struct f_fs_opts, func_inst);
3199         int ret;
3200
3201         ENTER();
3202
3203         ffs_log("enter");
3204
3205         /*
3206          * Legacy gadget triggers binding in functionfs_ready_callback,
3207          * which already uses locking; taking the same lock here would
3208          * cause a deadlock.
3209          *
3210          * Configfs-enabled gadgets however do need ffs_dev_lock.
3211          */
3212         if (!ffs_opts->no_configfs)
3213                 ffs_dev_lock();
3214         ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
3215         func->ffs = ffs_opts->dev->ffs_data;
3216         if (!ffs_opts->no_configfs)
3217                 ffs_dev_unlock();
3218         if (ret)
3219                 return ERR_PTR(ret);
3220
3221         func->conf = c;
3222         func->gadget = c->cdev->gadget;
3223
3224         /*
3225          * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
3226          * configurations are bound in sequence with list_for_each_entry,
3227          * in each configuration its functions are bound in sequence
3228          * with list_for_each_entry, so we assume no race condition
3229          * with regard to ffs_opts->bound access
3230          */
3231         if (!ffs_opts->refcnt) {
3232                 ret = functionfs_bind(func->ffs, c->cdev);
3233                 if (ret)
3234                         return ERR_PTR(ret);
3235         }
3236         ffs_opts->refcnt++;
3237         func->function.strings = func->ffs->stringtabs;
3238
3239         ffs_log("exit");
3240
3241         return ffs_opts;
3242 }
3243
3244 static int _ffs_func_bind(struct usb_configuration *c,
3245                           struct usb_function *f)
3246 {
3247         struct ffs_function *func = ffs_func_from_usb(f);
3248         struct ffs_data *ffs = func->ffs;
3249
3250         const int full = !!func->ffs->fs_descs_count;
3251         const int high = !!func->ffs->hs_descs_count;
3252         const int super = !!func->ffs->ss_descs_count;
3253
3254         int fs_len, hs_len, ss_len, ret, i;
3255         struct ffs_ep *eps_ptr;
3256
3257         /* Make it a single chunk, less management later on */
3258         vla_group(d);
3259         vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
3260         vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
3261                 full ? ffs->fs_descs_count + 1 : 0);
3262         vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
3263                 high ? ffs->hs_descs_count + 1 : 0);
3264         vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
3265                 super ? ffs->ss_descs_count + 1 : 0);
3266         vla_item_with_sz(d, short, inums, ffs->interfaces_count);
3267         vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
3268                          c->cdev->use_os_string ? ffs->interfaces_count : 0);
3269         vla_item_with_sz(d, char[16], ext_compat,
3270                          c->cdev->use_os_string ? ffs->interfaces_count : 0);
3271         vla_item_with_sz(d, struct usb_os_desc, os_desc,
3272                          c->cdev->use_os_string ? ffs->interfaces_count : 0);
3273         vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
3274                          ffs->ms_os_descs_ext_prop_count);
3275         vla_item_with_sz(d, char, ext_prop_name,
3276                          ffs->ms_os_descs_ext_prop_name_len);
3277         vla_item_with_sz(d, char, ext_prop_data,
3278                          ffs->ms_os_descs_ext_prop_data_len);
3279         vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
3280         char *vlabuf;
3281
3282         ENTER();
3283
3284         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
3285                 ffs->setup_state, ffs->flags);
3286
3287         /* Has descriptors only for speeds gadget does not support */
3288         if (unlikely(!(full | high | super)))
3289                 return -ENOTSUPP;
3290
3291         /* Allocate a single chunk, less management later on */
3292         vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
3293         if (unlikely(!vlabuf))
3294                 return -ENOMEM;
3295
3296         ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
3297         ffs->ms_os_descs_ext_prop_name_avail =
3298                 vla_ptr(vlabuf, d, ext_prop_name);
3299         ffs->ms_os_descs_ext_prop_data_avail =
3300                 vla_ptr(vlabuf, d, ext_prop_data);
3301
3302         /* Copy descriptors  */
3303         memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
3304                ffs->raw_descs_length);
3305
3306         memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
3307         eps_ptr = vla_ptr(vlabuf, d, eps);
3308         for (i = 0; i < ffs->eps_count; i++)
3309                 eps_ptr[i].num = -1;
3310
3311         /* Save pointers
3312          * d_eps == vlabuf, func->eps used to kfree vlabuf later
3313         */
3314         func->eps             = vla_ptr(vlabuf, d, eps);
3315         func->interfaces_nums = vla_ptr(vlabuf, d, inums);
3316
3317         /*
3318          * Go through all the endpoint descriptors and allocate
3319          * endpoints first, so that later we can rewrite the endpoint
3320          * numbers without worrying that it may be described later on.
3321          */
3322         if (likely(full)) {
3323                 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
3324                 fs_len = ffs_do_descs(ffs->fs_descs_count,
3325                                       vla_ptr(vlabuf, d, raw_descs),
3326                                       d_raw_descs__sz,
3327                                       __ffs_func_bind_do_descs, func);
3328                 if (unlikely(fs_len < 0)) {
3329                         ret = fs_len;
3330                         goto error;
3331                 }
3332         } else {
3333                 fs_len = 0;
3334         }
3335
3336         if (likely(high)) {
3337                 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
3338                 hs_len = ffs_do_descs(ffs->hs_descs_count,
3339                                       vla_ptr(vlabuf, d, raw_descs) + fs_len,
3340                                       d_raw_descs__sz - fs_len,
3341                                       __ffs_func_bind_do_descs, func);
3342                 if (unlikely(hs_len < 0)) {
3343                         ret = hs_len;
3344                         goto error;
3345                 }
3346         } else {
3347                 hs_len = 0;
3348         }
3349
3350         if (likely(super)) {
3351                 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
3352                 ss_len = ffs_do_descs(ffs->ss_descs_count,
3353                                 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
3354                                 d_raw_descs__sz - fs_len - hs_len,
3355                                 __ffs_func_bind_do_descs, func);
3356                 if (unlikely(ss_len < 0)) {
3357                         ret = ss_len;
3358                         goto error;
3359                 }
3360         } else {
3361                 ss_len = 0;
3362         }
3363
3364         /*
3365          * Now handle interface numbers allocation and interface and
3366          * endpoint numbers rewriting.  We can do that in one go
3367          * now.
3368          */
3369         ret = ffs_do_descs(ffs->fs_descs_count +
3370                            (high ? ffs->hs_descs_count : 0) +
3371                            (super ? ffs->ss_descs_count : 0),
3372                            vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
3373                            __ffs_func_bind_do_nums, func);
3374         if (unlikely(ret < 0))
3375                 goto error;
3376
3377         func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
3378         if (c->cdev->use_os_string) {
3379                 for (i = 0; i < ffs->interfaces_count; ++i) {
3380                         struct usb_os_desc *desc;
3381
3382                         desc = func->function.os_desc_table[i].os_desc =
3383                                 vla_ptr(vlabuf, d, os_desc) +
3384                                 i * sizeof(struct usb_os_desc);
3385                         desc->ext_compat_id =
3386                                 vla_ptr(vlabuf, d, ext_compat) + i * 16;
3387                         INIT_LIST_HEAD(&desc->ext_prop);
3388                 }
3389                 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
3390                                       vla_ptr(vlabuf, d, raw_descs) +
3391                                       fs_len + hs_len + ss_len,
3392                                       d_raw_descs__sz - fs_len - hs_len -
3393                                       ss_len,
3394                                       __ffs_func_bind_do_os_desc, func);
3395                 if (unlikely(ret < 0))
3396                         goto error;
3397         }
3398         func->function.os_desc_n =
3399                 c->cdev->use_os_string ? ffs->interfaces_count : 0;
3400
3401         /* And we're done */
3402         ffs_event_add(ffs, FUNCTIONFS_BIND);
3403
3404         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
3405                 ffs->setup_state, ffs->flags);
3406
3407         return 0;
3408
3409 error:
3410         /* XXX Do we need to release all claimed endpoints here? */
3411         ffs_log("exit: ret %d", ret);
3412         return ret;
3413 }
3414
3415 static int ffs_func_bind(struct usb_configuration *c,
3416                          struct usb_function *f)
3417 {
3418         struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
3419         struct ffs_function *func = ffs_func_from_usb(f);
3420         int ret;
3421
3422         ffs_log("enter");
3423
3424         if (IS_ERR(ffs_opts))
3425                 return PTR_ERR(ffs_opts);
3426
3427         ret = _ffs_func_bind(c, f);
3428         if (ret && !--ffs_opts->refcnt)
3429                 functionfs_unbind(func->ffs);
3430
3431         ffs_log("exit: ret %d", ret);
3432
3433         return ret;
3434 }
3435
3436
3437 /* Other USB function hooks *************************************************/
3438
3439 static void ffs_reset_work(struct work_struct *work)
3440 {
3441         struct ffs_data *ffs = container_of(work,
3442                 struct ffs_data, reset_work);
3443
3444         ffs_log("enter");
3445
3446         ffs_data_reset(ffs);
3447
3448         ffs_log("exit");
3449 }
3450
3451 static int ffs_func_set_alt(struct usb_function *f,
3452                             unsigned interface, unsigned alt)
3453 {
3454         struct ffs_function *func = ffs_func_from_usb(f);
3455         struct ffs_data *ffs = func->ffs;
3456         int ret = 0, intf;
3457
3458         ffs_log("enter");
3459
3460         if (alt != (unsigned)-1) {
3461                 intf = ffs_func_revmap_intf(func, interface);
3462                 if (unlikely(intf < 0))
3463                         return intf;
3464         }
3465
3466         if (ffs->func) {
3467                 ffs_func_eps_disable(ffs->func);
3468                 ffs->func = NULL;
3469                 /* matching put to allow LPM on disconnect */
3470                 usb_gadget_autopm_put_async(ffs->gadget);
3471         }
3472
3473         if (ffs->state == FFS_DEACTIVATED) {
3474                 ffs->state = FFS_CLOSING;
3475                 INIT_WORK(&ffs->reset_work, ffs_reset_work);
3476                 schedule_work(&ffs->reset_work);
3477                 return -ENODEV;
3478         }
3479
3480         if (ffs->state != FFS_ACTIVE)
3481                 return -ENODEV;
3482
3483         if (alt == (unsigned)-1) {
3484                 ffs->func = NULL;
3485                 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
3486                 return 0;
3487         }
3488
3489         ffs->func = func;
3490         ret = ffs_func_eps_enable(func);
3491         if (likely(ret >= 0)) {
3492                 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
3493                 /* Disable USB LPM later on bus_suspend */
3494                 usb_gadget_autopm_get_async(ffs->gadget);
3495         }
3496
3497         ffs_log("exit: ret %d", ret);
3498
3499         return ret;
3500 }
3501
3502 static void ffs_func_disable(struct usb_function *f)
3503 {
3504         ffs_log("enter");
3505
3506         ffs_func_set_alt(f, 0, (unsigned)-1);
3507
3508         ffs_log("exit");
3509 }
3510
3511 static int ffs_func_setup(struct usb_function *f,
3512                           const struct usb_ctrlrequest *creq)
3513 {
3514         struct ffs_function *func = ffs_func_from_usb(f);
3515         struct ffs_data *ffs = func->ffs;
3516         unsigned long flags;
3517         int ret;
3518
3519         ENTER();
3520
3521         ffs_log("enter");
3522
3523         pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
3524         pr_vdebug("creq->bRequest     = %02x\n", creq->bRequest);
3525         pr_vdebug("creq->wValue       = %04x\n", le16_to_cpu(creq->wValue));
3526         pr_vdebug("creq->wIndex       = %04x\n", le16_to_cpu(creq->wIndex));
3527         pr_vdebug("creq->wLength      = %04x\n", le16_to_cpu(creq->wLength));
3528
3529         /*
3530          * Most requests directed to interface go through here
3531          * (notable exceptions are set/get interface) so we need to
3532          * handle them.  All other either handled by composite or
3533          * passed to usb_configuration->setup() (if one is set).  No
3534          * matter, we will handle requests directed to endpoint here
3535          * as well (as it's straightforward) but what to do with any
3536          * other request?
3537          */
3538         if (ffs->state != FFS_ACTIVE)
3539                 return -ENODEV;
3540
3541         switch (creq->bRequestType & USB_RECIP_MASK) {
3542         case USB_RECIP_INTERFACE:
3543                 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
3544                 if (unlikely(ret < 0))
3545                         return ret;
3546                 break;
3547
3548         case USB_RECIP_ENDPOINT:
3549                 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
3550                 if (unlikely(ret < 0))
3551                         return ret;
3552                 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3553                         ret = func->ffs->eps_addrmap[ret];
3554                 break;
3555
3556         default:
3557                 return -EOPNOTSUPP;
3558         }
3559
3560         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
3561         ffs->ev.setup = *creq;
3562         ffs->ev.setup.wIndex = cpu_to_le16(ret);
3563         __ffs_event_add(ffs, FUNCTIONFS_SETUP);
3564         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
3565
3566         ffs_log("exit");
3567
3568         return creq->wLength == 0 ? USB_GADGET_DELAYED_STATUS : 0;
3569 }
3570
3571 static void ffs_func_suspend(struct usb_function *f)
3572 {
3573         ENTER();
3574
3575         ffs_log("enter");
3576
3577         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
3578
3579         ffs_log("exit");
3580 }
3581
3582 static void ffs_func_resume(struct usb_function *f)
3583 {
3584         ENTER();
3585
3586         ffs_log("enter");
3587
3588         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
3589
3590         ffs_log("exit");
3591 }
3592
3593
3594 /* Endpoint and interface numbers reverse mapping ***************************/
3595
3596 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
3597 {
3598         num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
3599         return num ? num : -EDOM;
3600 }
3601
3602 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
3603 {
3604         short *nums = func->interfaces_nums;
3605         unsigned count = func->ffs->interfaces_count;
3606
3607         ffs_log("enter");
3608
3609         for (; count; --count, ++nums) {
3610                 if (*nums >= 0 && *nums == intf)
3611                         return nums - func->interfaces_nums;
3612         }
3613
3614         ffs_log("exit");
3615
3616         return -EDOM;
3617 }
3618
3619
3620 /* Devices management *******************************************************/
3621
3622 static LIST_HEAD(ffs_devices);
3623
3624 static struct ffs_dev *_ffs_do_find_dev(const char *name)
3625 {
3626         struct ffs_dev *dev;
3627
3628         ffs_log("enter");
3629
3630         list_for_each_entry(dev, &ffs_devices, entry) {
3631                 if (!dev->name || !name)
3632                         continue;
3633                 if (strcmp(dev->name, name) == 0)
3634                         return dev;
3635         }
3636
3637         ffs_log("exit");
3638
3639         return NULL;
3640 }
3641
3642 /*
3643  * ffs_lock must be taken by the caller of this function
3644  */
3645 static struct ffs_dev *_ffs_get_single_dev(void)
3646 {
3647         struct ffs_dev *dev;
3648
3649         ffs_log("enter");
3650
3651         if (list_is_singular(&ffs_devices)) {
3652                 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3653                 if (dev->single)
3654                         return dev;
3655         }
3656
3657         ffs_log("exit");
3658
3659         return NULL;
3660 }
3661
3662 /*
3663  * ffs_lock must be taken by the caller of this function
3664  */
3665 static struct ffs_dev *_ffs_find_dev(const char *name)
3666 {
3667         struct ffs_dev *dev;
3668
3669         ffs_log("enter");
3670
3671         dev = _ffs_get_single_dev();
3672         if (dev)
3673                 return dev;
3674
3675         dev = _ffs_do_find_dev(name);
3676
3677         ffs_log("exit");
3678
3679         return dev;
3680 }
3681
3682 /* Configfs support *********************************************************/
3683
3684 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3685 {
3686         return container_of(to_config_group(item), struct f_fs_opts,
3687                             func_inst.group);
3688 }
3689
3690 static void ffs_attr_release(struct config_item *item)
3691 {
3692         struct f_fs_opts *opts = to_ffs_opts(item);
3693
3694         usb_put_function_instance(&opts->func_inst);
3695 }
3696
3697 static struct configfs_item_operations ffs_item_ops = {
3698         .release        = ffs_attr_release,
3699 };
3700
3701 static struct config_item_type ffs_func_type = {
3702         .ct_item_ops    = &ffs_item_ops,
3703         .ct_owner       = THIS_MODULE,
3704 };
3705
3706
3707 /* Function registration interface ******************************************/
3708
3709 static struct ffs_inst_status *name_to_inst_status(
3710                 const char *inst_name, bool create_inst)
3711 {
3712         struct ffs_inst_status *inst_status;
3713
3714         list_for_each_entry(inst_status, &inst_list, list) {
3715                 if (!strncasecmp(inst_status->inst_name,
3716                                         inst_name, strlen(inst_name)))
3717                         return inst_status;
3718         }
3719
3720         if (!create_inst)
3721                 return ERR_PTR(-ENODEV);
3722
3723         inst_status = kzalloc(sizeof(struct ffs_inst_status),
3724                                         GFP_KERNEL);
3725         if (!inst_status)
3726                 return ERR_PTR(-ENOMEM);
3727
3728         mutex_init(&inst_status->ffs_lock);
3729         snprintf(inst_status->inst_name, INST_NAME_SIZE, inst_name);
3730         list_add_tail(&inst_status->list, &inst_list);
3731
3732         return inst_status;
3733 }
3734
3735 static int ffs_inst_exist_check(const char *inst_name)
3736 {
3737         struct ffs_inst_status *inst_status;
3738
3739         inst_status = name_to_inst_status(inst_name, false);
3740         if (IS_ERR(inst_status)) {
3741                 pr_err_ratelimited(
3742                                 "%s: failed to find instance (%s)\n",
3743                                 __func__, inst_name);
3744                 return -ENODEV;
3745         }
3746
3747         mutex_lock(&inst_status->ffs_lock);
3748
3749         if (unlikely(inst_status->inst_exist == false)) {
3750                 mutex_unlock(&inst_status->ffs_lock);
3751                 pr_err_ratelimited(
3752                                 "%s: f_fs instance (%s) has been freed already.\n",
3753                                 __func__, inst_name);
3754                 return -ENODEV;
3755         }
3756
3757         mutex_unlock(&inst_status->ffs_lock);
3758
3759         return 0;
3760 }
3761
3762 static void ffs_inst_clean(struct f_fs_opts *opts,
3763                 const char *inst_name)
3764 {
3765         struct ffs_inst_status *inst_status;
3766
3767         inst_status = name_to_inst_status(inst_name, false);
3768         if (IS_ERR(inst_status)) {
3769                 pr_err_ratelimited(
3770                                 "%s: failed to find instance (%s)\n",
3771                                 __func__, inst_name);
3772                 return;
3773         }
3774
3775         inst_status->opts = NULL;
3776
3777         ffs_dev_lock();
3778         _ffs_free_dev(opts->dev);
3779         ffs_dev_unlock();
3780         kfree(opts);
3781 }
3782
3783 static void ffs_inst_clean_delay(const char *inst_name)
3784 {
3785         struct ffs_inst_status *inst_status;
3786
3787         inst_status = name_to_inst_status(inst_name, false);
3788         if (IS_ERR(inst_status)) {
3789                 pr_err_ratelimited(
3790                                 "%s: failed to find (%s) instance\n",
3791                                 __func__, inst_name);
3792                 return;
3793         }
3794
3795         mutex_lock(&inst_status->ffs_lock);
3796
3797         if (unlikely(inst_status->inst_exist == false)) {
3798                 if (inst_status->opts) {
3799                         ffs_inst_clean(inst_status->opts, inst_name);
3800                         pr_err_ratelimited("%s: Delayed free memory\n",
3801                                         __func__);
3802                 }
3803                 mutex_unlock(&inst_status->ffs_lock);
3804                 return;
3805         }
3806
3807         mutex_unlock(&inst_status->ffs_lock);
3808 }
3809
3810 static void ffs_free_inst(struct usb_function_instance *f)
3811 {
3812         struct f_fs_opts *opts;
3813         struct ffs_inst_status *inst_status;
3814
3815         opts = to_f_fs_opts(f);
3816
3817         inst_status = name_to_inst_status(opts->dev->name, false);
3818         if (IS_ERR(inst_status)) {
3819                 ffs_log("failed to find (%s) instance\n",
3820                                 opts->dev->name);
3821                 return;
3822         }
3823
3824         mutex_lock(&inst_status->ffs_lock);
3825         if (opts->dev->ffs_data
3826                         && atomic_read(&opts->dev->ffs_data->opened)) {
3827                 inst_status->inst_exist = false;
3828                 mutex_unlock(&inst_status->ffs_lock);
3829                 ffs_log("Dev is open, free mem when dev (%s) close\n",
3830                                 opts->dev->name);
3831                 return;
3832         }
3833
3834         ffs_inst_clean(opts, opts->dev->name);
3835         inst_status->inst_exist = false;
3836         mutex_unlock(&inst_status->ffs_lock);
3837 }
3838
3839 #define MAX_INST_NAME_LEN       40
3840
3841 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3842 {
3843         struct f_fs_opts *opts, *opts_prev;
3844         struct ffs_data *ffs_data_tmp;
3845         char *ptr;
3846         const char *tmp;
3847         int name_len, ret;
3848         struct ffs_inst_status *inst_status;
3849
3850         name_len = strlen(name) + 1;
3851         if (name_len > MAX_INST_NAME_LEN)
3852                 return -ENAMETOOLONG;
3853
3854         ptr = kstrndup(name, name_len, GFP_KERNEL);
3855         if (!ptr)
3856                 return -ENOMEM;
3857
3858         inst_status = name_to_inst_status(ptr, true);
3859         if (IS_ERR(inst_status)) {
3860                 ffs_log("failed to create status struct for (%s) instance\n",
3861                                 ptr);
3862                 return -EINVAL;
3863         }
3864
3865         mutex_lock(&inst_status->ffs_lock);
3866         opts_prev = inst_status->opts;
3867         if (opts_prev) {
3868                 mutex_unlock(&inst_status->ffs_lock);
3869                 ffs_log("instance (%s): prev inst do not freed yet\n",
3870                                 inst_status->inst_name);
3871                 return -EBUSY;
3872         }
3873         mutex_unlock(&inst_status->ffs_lock);
3874
3875         opts = to_f_fs_opts(fi);
3876         tmp = NULL;
3877
3878         ffs_dev_lock();
3879
3880         tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3881         ret = _ffs_name_dev(opts->dev, ptr);
3882         if (ret) {
3883                 kfree(ptr);
3884                 ffs_dev_unlock();
3885                 return ret;
3886         }
3887         opts->dev->name_allocated = true;
3888
3889         /*
3890          * If ffs instance is freed and created once, new allocated
3891          * opts->dev need to initialize opts->dev->ffs_data, and
3892          * ffs_private_data also need to update new allocated opts->dev
3893          * address.
3894          */
3895         ffs_data_tmp = inst_status->ffs_data;
3896         if (ffs_data_tmp)
3897                 opts->dev->ffs_data = ffs_data_tmp;
3898
3899         if (opts->dev->ffs_data)
3900                 opts->dev->ffs_data->private_data = opts->dev;
3901
3902         ffs_dev_unlock();
3903
3904         kfree(tmp);
3905
3906         mutex_lock(&inst_status->ffs_lock);
3907         inst_status->inst_exist = true;
3908         inst_status->opts = opts;
3909         mutex_unlock(&inst_status->ffs_lock);
3910
3911         return 0;
3912 }
3913
3914 static struct usb_function_instance *ffs_alloc_inst(void)
3915 {
3916         struct f_fs_opts *opts;
3917         struct ffs_dev *dev;
3918
3919         opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3920         if (!opts)
3921                 return ERR_PTR(-ENOMEM);
3922
3923         opts->func_inst.set_inst_name = ffs_set_inst_name;
3924         opts->func_inst.free_func_inst = ffs_free_inst;
3925         ffs_dev_lock();
3926         dev = _ffs_alloc_dev();
3927         ffs_dev_unlock();
3928         if (IS_ERR(dev)) {
3929                 kfree(opts);
3930                 return ERR_CAST(dev);
3931         }
3932         opts->dev = dev;
3933         dev->opts = opts;
3934
3935         config_group_init_type_name(&opts->func_inst.group, "",
3936                                     &ffs_func_type);
3937         return &opts->func_inst;
3938 }
3939
3940 static void ffs_free(struct usb_function *f)
3941 {
3942         kfree(ffs_func_from_usb(f));
3943 }
3944
3945 static void ffs_func_unbind(struct usb_configuration *c,
3946                             struct usb_function *f)
3947 {
3948         struct ffs_function *func = ffs_func_from_usb(f);
3949         struct ffs_data *ffs = func->ffs;
3950         struct f_fs_opts *opts =
3951                 container_of(f->fi, struct f_fs_opts, func_inst);
3952         struct ffs_ep *ep = func->eps;
3953         unsigned count = ffs->eps_count;
3954         unsigned long flags;
3955
3956         ENTER();
3957
3958         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
3959                 ffs->setup_state, ffs->flags);
3960
3961         if (ffs->func == func) {
3962                 ffs_func_eps_disable(func);
3963                 ffs->func = NULL;
3964         }
3965
3966         if (!--opts->refcnt)
3967                 functionfs_unbind(ffs);
3968
3969         /* cleanup after autoconfig */
3970         spin_lock_irqsave(&func->ffs->eps_lock, flags);
3971         do {
3972                 if (ep->ep && ep->req)
3973                         usb_ep_free_request(ep->ep, ep->req);
3974                 ep->req = NULL;
3975                 ep->ep = NULL;
3976                 ++ep;
3977         } while (--count);
3978         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3979         kfree(func->eps);
3980         func->eps = NULL;
3981         /*
3982          * eps, descriptors and interfaces_nums are allocated in the
3983          * same chunk so only one free is required.
3984          */
3985         func->function.fs_descriptors = NULL;
3986         func->function.hs_descriptors = NULL;
3987         func->function.ss_descriptors = NULL;
3988         func->interfaces_nums = NULL;
3989
3990         ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3991
3992         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
3993         ffs->setup_state, ffs->flags);
3994 }
3995
3996 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3997 {
3998         struct ffs_function *func;
3999
4000         ENTER();
4001
4002         func = kzalloc(sizeof(*func), GFP_KERNEL);
4003         if (unlikely(!func))
4004                 return ERR_PTR(-ENOMEM);
4005
4006         func->function.name    = "Function FS Gadget";
4007
4008         func->function.bind    = ffs_func_bind;
4009         func->function.unbind  = ffs_func_unbind;
4010         func->function.set_alt = ffs_func_set_alt;
4011         func->function.disable = ffs_func_disable;
4012         func->function.setup   = ffs_func_setup;
4013         func->function.suspend = ffs_func_suspend;
4014         func->function.resume  = ffs_func_resume;
4015         func->function.free_func = ffs_free;
4016
4017         return &func->function;
4018 }
4019
4020 /*
4021  * ffs_lock must be taken by the caller of this function
4022  */
4023 static struct ffs_dev *_ffs_alloc_dev(void)
4024 {
4025         struct ffs_dev *dev;
4026         int ret;
4027
4028         if (_ffs_get_single_dev())
4029                         return ERR_PTR(-EBUSY);
4030
4031         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
4032         if (!dev)
4033                 return ERR_PTR(-ENOMEM);
4034
4035         if (list_empty(&ffs_devices)) {
4036                 ret = functionfs_init();
4037                 if (ret) {
4038                         kfree(dev);
4039                         return ERR_PTR(ret);
4040                 }
4041         }
4042
4043         list_add(&dev->entry, &ffs_devices);
4044
4045         return dev;
4046 }
4047
4048 /*
4049  * ffs_lock must be taken by the caller of this function
4050  * The caller is responsible for "name" being available whenever f_fs needs it
4051  */
4052 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
4053 {
4054         struct ffs_dev *existing;
4055
4056         ffs_log("enter");
4057
4058         existing = _ffs_do_find_dev(name);
4059         if (existing)
4060                 return -EBUSY;
4061
4062         dev->name = name;
4063
4064         ffs_log("exit");
4065
4066         return 0;
4067 }
4068
4069 /*
4070  * The caller is responsible for "name" being available whenever f_fs needs it
4071  */
4072 int ffs_name_dev(struct ffs_dev *dev, const char *name)
4073 {
4074         int ret;
4075
4076         ffs_log("enter");
4077
4078         ffs_dev_lock();
4079         ret = _ffs_name_dev(dev, name);
4080         ffs_dev_unlock();
4081
4082         ffs_log("exit");
4083
4084         return ret;
4085 }
4086 EXPORT_SYMBOL_GPL(ffs_name_dev);
4087
4088 int ffs_single_dev(struct ffs_dev *dev)
4089 {
4090         int ret;
4091
4092         ffs_log("enter");
4093
4094         ret = 0;
4095         ffs_dev_lock();
4096
4097         if (!list_is_singular(&ffs_devices))
4098                 ret = -EBUSY;
4099         else
4100                 dev->single = true;
4101
4102         ffs_dev_unlock();
4103
4104         ffs_log("exit");
4105
4106         return ret;
4107 }
4108 EXPORT_SYMBOL_GPL(ffs_single_dev);
4109
4110 /*
4111  * ffs_lock must be taken by the caller of this function
4112  */
4113 static void _ffs_free_dev(struct ffs_dev *dev)
4114 {
4115
4116         ffs_log("enter");
4117
4118         list_del(&dev->entry);
4119         if (dev->name_allocated)
4120                 kfree(dev->name);
4121         kfree(dev);
4122         if (list_empty(&ffs_devices))
4123                 functionfs_cleanup();
4124
4125         ffs_log("exit");
4126 }
4127
4128 static void *ffs_acquire_dev(const char *dev_name)
4129 {
4130         struct ffs_dev *ffs_dev;
4131
4132         ENTER();
4133
4134         ffs_log("enter");
4135
4136         ffs_dev_lock();
4137
4138         ffs_dev = _ffs_find_dev(dev_name);
4139         if (!ffs_dev)
4140                 ffs_dev = ERR_PTR(-ENOENT);
4141         else if (ffs_dev->mounted)
4142                 ffs_dev = ERR_PTR(-EBUSY);
4143         else if (ffs_dev->ffs_acquire_dev_callback &&
4144             ffs_dev->ffs_acquire_dev_callback(ffs_dev))
4145                 ffs_dev = ERR_PTR(-ENOENT);
4146         else
4147                 ffs_dev->mounted = true;
4148
4149         ffs_dev_unlock();
4150
4151         ffs_log("exit");
4152
4153         return ffs_dev;
4154 }
4155
4156 static void ffs_release_dev(struct ffs_data *ffs_data)
4157 {
4158         struct ffs_dev *ffs_dev;
4159
4160         ENTER();
4161
4162         ffs_log("enter");
4163
4164         ffs_dev_lock();
4165
4166         ffs_dev = ffs_data->private_data;
4167         if (ffs_dev) {
4168                 ffs_dev->mounted = false;
4169
4170                 if (ffs_dev->ffs_release_dev_callback)
4171                         ffs_dev->ffs_release_dev_callback(ffs_dev);
4172         }
4173
4174         ffs_dev_unlock();
4175
4176         ffs_log("exit");
4177 }
4178
4179 static int ffs_ready(struct ffs_data *ffs)
4180 {
4181         struct ffs_dev *ffs_obj;
4182         int ret = 0;
4183
4184         ENTER();
4185
4186         ffs_log("enter");
4187
4188         ffs_dev_lock();
4189
4190         ffs_obj = ffs->private_data;
4191         if (!ffs_obj) {
4192                 ret = -EINVAL;
4193                 goto done;
4194         }
4195         if (WARN_ON(ffs_obj->desc_ready)) {
4196                 ret = -EBUSY;
4197                 goto done;
4198         }
4199
4200         ffs_obj->desc_ready = true;
4201         ffs_obj->ffs_data = ffs;
4202
4203         if (ffs_obj->ffs_ready_callback) {
4204                 ret = ffs_obj->ffs_ready_callback(ffs);
4205                 if (ret)
4206                         goto done;
4207         }
4208
4209         set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
4210 done:
4211         ffs_dev_unlock();
4212
4213         ffs_log("exit");
4214
4215         return ret;
4216 }
4217
4218 static void ffs_closed(struct ffs_data *ffs)
4219 {
4220         struct ffs_dev *ffs_obj;
4221         struct f_fs_opts *opts;
4222
4223         ENTER();
4224
4225         ffs_log("enter");
4226
4227         ffs_dev_lock();
4228
4229         ffs_obj = ffs->private_data;
4230         if (!ffs_obj) {
4231                 ffs_dev_unlock();
4232                 goto done;
4233         }
4234
4235         ffs_obj->desc_ready = false;
4236
4237         if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags) &&
4238             ffs_obj->ffs_closed_callback)
4239                 ffs_obj->ffs_closed_callback(ffs);
4240
4241         if (ffs_obj->opts) {
4242                 opts = ffs_obj->opts;
4243         } else {
4244                 ffs_dev_unlock();
4245                 goto done;
4246         }
4247
4248         smp_mb__before_atomic();
4249         if (opts->no_configfs || !opts->func_inst.group.cg_item.ci_parent
4250             || !atomic_read(&opts->func_inst.group.cg_item.ci_kref.refcount)) {
4251                 ffs_dev_unlock();
4252                 goto done;
4253         }
4254
4255         ffs_dev_unlock();
4256
4257         if (test_bit(FFS_FL_BOUND, &ffs->flags)) {
4258                 unregister_gadget_item(opts->
4259                                func_inst.group.cg_item.ci_parent->ci_parent);
4260                 ffs_log("unreg gadget done");
4261         }
4262 done:
4263         ffs_log("exit");
4264 }
4265
4266 /* Misc helper functions ****************************************************/
4267
4268 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
4269 {
4270         return nonblock
4271                 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
4272                 : mutex_lock_interruptible(mutex);
4273 }
4274
4275 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
4276 {
4277         char *data;
4278
4279         if (unlikely(!len))
4280                 return NULL;
4281
4282         data = kmalloc(len, GFP_KERNEL);
4283         if (unlikely(!data))
4284                 return ERR_PTR(-ENOMEM);
4285
4286         if (unlikely(copy_from_user(data, buf, len))) {
4287                 kfree(data);
4288                 return ERR_PTR(-EFAULT);
4289         }
4290
4291         pr_vdebug("Buffer from user space:\n");
4292         ffs_dump_mem("", data, len);
4293
4294         return data;
4295 }
4296
4297 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
4298
4299 static int ffs_init(void)
4300 {
4301         ffs_ipc_log = ipc_log_context_create(NUM_PAGES, "f_fs", 0);
4302         if (IS_ERR_OR_NULL(ffs_ipc_log))
4303                 ffs_ipc_log =  NULL;
4304
4305         return 0;
4306 }
4307 module_init(ffs_init);
4308
4309 static void __exit ffs_exit(void)
4310 {
4311         struct ffs_inst_status *inst_status, *inst_status_tmp = NULL;
4312
4313         list_for_each_entry(inst_status, &inst_list, list) {
4314                 if (inst_status_tmp) {
4315                         list_del(&inst_status_tmp->list);
4316                         kfree(inst_status_tmp);
4317                 }
4318                 inst_status_tmp = inst_status;
4319         }
4320         if (inst_status_tmp) {
4321                 list_del(&inst_status_tmp->list);
4322                 kfree(inst_status_tmp);
4323         }
4324
4325         if (ffs_ipc_log) {
4326                 ipc_log_context_destroy(ffs_ipc_log);
4327                 ffs_ipc_log = NULL;
4328         }
4329 }
4330 module_exit(ffs_exit);
4331
4332 MODULE_LICENSE("GPL");
4333 MODULE_AUTHOR("Michal Nazarewicz");