OSDN Git Service

Merge "fbdev: msm: Call vsync_handler only after ctl start"
[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                                 ep->is_busy = true;
992                                 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
993                         }
994
995                         spin_unlock_irq(&epfile->ffs->eps_lock);
996
997                         if (unlikely(ret < 0)) {
998                                 ep->is_busy = false;
999                                 ret = -EIO;
1000                         } else if (unlikely(
1001                                    wait_for_completion_interruptible(done))) {
1002                                 spin_lock_irq(&epfile->ffs->eps_lock);
1003                                 /*
1004                                  * While we were acquiring lock endpoint got
1005                                  * disabled (disconnect) or changed
1006                                  * (composition switch) ?
1007                                  */
1008                                 if (epfile->ep == ep)
1009                                         usb_ep_dequeue(ep->ep, req);
1010                                 spin_unlock_irq(&epfile->ffs->eps_lock);
1011                                 ret = -EINTR;
1012                         } else {
1013                                 /*
1014                                  * XXX We may end up silently droping data
1015                                  * here.  Since data_len (i.e. req->length) may
1016                                  * be bigger than len (after being rounded up
1017                                  * to maxpacketsize), we may end up with more
1018                                  * data then user space has space for.
1019                                  */
1020                                 spin_lock_irq(&epfile->ffs->eps_lock);
1021                                 /*
1022                                  * While we were acquiring lock endpoint got
1023                                  * disabled (disconnect) or changed
1024                                  * (composition switch) ?
1025                                  */
1026                                 if (epfile->ep == ep) {
1027                                         ret = ep->status;
1028                                         if (ret >= 0)
1029                                                 first_read_done = true;
1030                                 } else {
1031                                         ret = -ENODEV;
1032                                 }
1033
1034                                 /* do wait again if func eps are not enabled */
1035                                 if (io_data->read && !first_read_done
1036                                                         && ret < 0) {
1037                                         unsigned short count = ffs->eps_count;
1038
1039                                         pr_debug("%s: waiting for the online state\n",
1040                                                  __func__);
1041                                         ret = 0;
1042                                         kfree(data);
1043                                         data = NULL;
1044                                         data_len = -EINVAL;
1045                                         spin_unlock_irq(&epfile->ffs->eps_lock);
1046                                         mutex_unlock(&epfile->mutex);
1047                                         epfile = ffs->epfiles;
1048                                         do {
1049                                                 atomic_set(&epfile->error, 0);
1050                                                 ++epfile;
1051                                         } while (--count);
1052                                         epfile = file->private_data;
1053                                         goto retry;
1054                                 }
1055
1056                                 spin_unlock_irq(&epfile->ffs->eps_lock);
1057                                 if (io_data->read && ret > 0) {
1058
1059                                         if (ret > data_len) {
1060                                                 ret = -EOVERFLOW;
1061                                                 pr_err("More data(%zd) received than intended length(%zu)\n",
1062                                                                 ret, data_len);
1063
1064                                         } else {
1065                                                 ret = copy_to_iter(data, ret, &io_data->data);
1066                                                 pr_debug("copied (%zd) bytes to user space\n", ret);
1067                                                 if (!ret) {
1068                                                         pr_err("Fail to copy to user\n");
1069                                                         ret = -EFAULT;
1070                                                 }
1071                                         }
1072                                 }
1073                         }
1074                         kfree(data);
1075                 }
1076         }
1077
1078         mutex_unlock(&epfile->mutex);
1079
1080         ffs_log("exit:ret %zu", ret);
1081
1082         return ret;
1083
1084 error_lock:
1085         spin_unlock_irq(&epfile->ffs->eps_lock);
1086         mutex_unlock(&epfile->mutex);
1087 error:
1088         kfree(data);
1089
1090         ffs_log("exit: ret %zu", ret);
1091
1092         return ret;
1093 }
1094
1095 static int
1096 ffs_epfile_open(struct inode *inode, struct file *file)
1097 {
1098         struct ffs_epfile *epfile = inode->i_private;
1099         int ret;
1100
1101         ENTER();
1102
1103         ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1104                 epfile->ffs->setup_state, epfile->ffs->flags);
1105
1106         ret = ffs_inst_exist_check(epfile->ffs->dev_name);
1107         if (ret < 0)
1108                 return ret;
1109
1110         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1111                 return -ENODEV;
1112
1113         smp_mb__before_atomic();
1114         if (atomic_read(&epfile->opened)) {
1115                 pr_err("%s(): ep(%s) is already opened.\n",
1116                                         __func__, epfile->name);
1117                 return -EBUSY;
1118         }
1119
1120         smp_mb__before_atomic();
1121         atomic_set(&epfile->opened, 1);
1122         file->private_data = epfile;
1123         ffs_data_opened(epfile->ffs);
1124
1125         smp_mb__before_atomic();
1126         atomic_set(&epfile->error, 0);
1127         first_read_done = false;
1128
1129         ffs_log("exit:state %d setup_state %d flag %lu", epfile->ffs->state,
1130                 epfile->ffs->setup_state, epfile->ffs->flags);
1131
1132         return 0;
1133 }
1134
1135 static int ffs_aio_cancel(struct kiocb *kiocb)
1136 {
1137         struct ffs_io_data *io_data = kiocb->private;
1138         struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
1139         int value;
1140
1141         ENTER();
1142
1143         ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1144                 epfile->ffs->setup_state, epfile->ffs->flags);
1145
1146         spin_lock_irq(&epfile->ffs->eps_lock);
1147
1148         if (likely(io_data && io_data->ep && io_data->req))
1149                 value = usb_ep_dequeue(io_data->ep, io_data->req);
1150         else
1151                 value = -EINVAL;
1152
1153         spin_unlock_irq(&epfile->ffs->eps_lock);
1154
1155         ffs_log("exit: value %d", value);
1156
1157         return value;
1158 }
1159
1160 static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
1161 {
1162         struct ffs_io_data io_data, *p = &io_data;
1163         ssize_t res;
1164
1165         ENTER();
1166
1167         ffs_log("enter");
1168
1169         if (!is_sync_kiocb(kiocb)) {
1170                 p = kmalloc(sizeof(io_data), GFP_KERNEL);
1171                 if (unlikely(!p))
1172                         return -ENOMEM;
1173                 p->aio = true;
1174         } else {
1175                 p->aio = false;
1176         }
1177
1178         p->read = false;
1179         p->kiocb = kiocb;
1180         p->data = *from;
1181         p->mm = current->mm;
1182
1183         kiocb->private = p;
1184
1185         if (p->aio)
1186                 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1187
1188         res = ffs_epfile_io(kiocb->ki_filp, p);
1189         if (res == -EIOCBQUEUED)
1190                 return res;
1191         if (p->aio)
1192                 kfree(p);
1193         else
1194                 *from = p->data;
1195
1196         ffs_log("exit");
1197
1198         return res;
1199 }
1200
1201 static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
1202 {
1203         struct ffs_io_data io_data, *p = &io_data;
1204         ssize_t res;
1205
1206         ENTER();
1207
1208         ffs_log("enter");
1209
1210         if (!is_sync_kiocb(kiocb)) {
1211                 p = kmalloc(sizeof(io_data), GFP_KERNEL);
1212                 if (unlikely(!p))
1213                         return -ENOMEM;
1214                 p->aio = true;
1215         } else {
1216                 p->aio = false;
1217         }
1218
1219         p->read = true;
1220         p->kiocb = kiocb;
1221         if (p->aio) {
1222                 p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
1223                 if (!p->to_free) {
1224                         kfree(p);
1225                         return -ENOMEM;
1226                 }
1227         } else {
1228                 p->data = *to;
1229                 p->to_free = NULL;
1230         }
1231         p->mm = current->mm;
1232
1233         kiocb->private = p;
1234
1235         if (p->aio)
1236                 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1237
1238         res = ffs_epfile_io(kiocb->ki_filp, p);
1239         if (res == -EIOCBQUEUED)
1240                 return res;
1241
1242         if (p->aio) {
1243                 kfree(p->to_free);
1244                 kfree(p);
1245         } else {
1246                 *to = p->data;
1247         }
1248
1249         ffs_log("exit");
1250
1251         return res;
1252 }
1253
1254 static int
1255 ffs_epfile_release(struct inode *inode, struct file *file)
1256 {
1257         struct ffs_epfile *epfile = inode->i_private;
1258
1259         ENTER();
1260
1261         ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1262                 epfile->ffs->setup_state, epfile->ffs->flags);
1263
1264         smp_mb__before_atomic();
1265         atomic_set(&epfile->opened, 0);
1266         atomic_set(&epfile->error, 1);
1267         ffs_data_closed(epfile->ffs);
1268         file->private_data = NULL;
1269
1270         ffs_log("exit");
1271
1272         return 0;
1273 }
1274
1275 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1276                              unsigned long value)
1277 {
1278         struct ffs_epfile *epfile = file->private_data;
1279         int ret;
1280
1281         ENTER();
1282
1283         ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1284                 epfile->ffs->setup_state, epfile->ffs->flags);
1285
1286         ret = ffs_inst_exist_check(epfile->ffs->dev_name);
1287         if (ret < 0)
1288                 return ret;
1289
1290         if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1291                 return -ENODEV;
1292
1293         spin_lock_irq(&epfile->ffs->eps_lock);
1294         if (likely(epfile->ep)) {
1295                 switch (code) {
1296                 case FUNCTIONFS_FIFO_STATUS:
1297                         ret = usb_ep_fifo_status(epfile->ep->ep);
1298                         break;
1299                 case FUNCTIONFS_FIFO_FLUSH:
1300                         usb_ep_fifo_flush(epfile->ep->ep);
1301                         ret = 0;
1302                         break;
1303                 case FUNCTIONFS_CLEAR_HALT:
1304                         ret = usb_ep_clear_halt(epfile->ep->ep);
1305                         break;
1306                 case FUNCTIONFS_ENDPOINT_REVMAP:
1307                         ret = epfile->ep->num;
1308                         break;
1309                 case FUNCTIONFS_ENDPOINT_DESC:
1310                 {
1311                         int desc_idx;
1312                         struct usb_endpoint_descriptor *desc;
1313
1314                         switch (epfile->ffs->gadget->speed) {
1315                         case USB_SPEED_SUPER:
1316                                 desc_idx = 2;
1317                                 break;
1318                         case USB_SPEED_HIGH:
1319                                 desc_idx = 1;
1320                                 break;
1321                         default:
1322                                 desc_idx = 0;
1323                         }
1324                         desc = epfile->ep->descs[desc_idx];
1325
1326                         spin_unlock_irq(&epfile->ffs->eps_lock);
1327                         ret = copy_to_user((void *)value, desc, sizeof(*desc));
1328                         if (ret)
1329                                 ret = -EFAULT;
1330                         return ret;
1331                 }
1332                 default:
1333                         ret = -ENOTTY;
1334                 }
1335         } else {
1336                 ret = -ENODEV;
1337         }
1338         spin_unlock_irq(&epfile->ffs->eps_lock);
1339
1340         ffs_log("exit:ret %d", ret);
1341
1342         return ret;
1343 }
1344
1345 static const struct file_operations ffs_epfile_operations = {
1346         .llseek =       no_llseek,
1347
1348         .open =         ffs_epfile_open,
1349         .write_iter =   ffs_epfile_write_iter,
1350         .read_iter =    ffs_epfile_read_iter,
1351         .release =      ffs_epfile_release,
1352         .unlocked_ioctl =       ffs_epfile_ioctl,
1353 };
1354
1355
1356 /* File system and super block operations ***********************************/
1357
1358 /*
1359  * Mounting the file system creates a controller file, used first for
1360  * function configuration then later for event monitoring.
1361  */
1362
1363 static struct inode *__must_check
1364 ffs_sb_make_inode(struct super_block *sb, void *data,
1365                   const struct file_operations *fops,
1366                   const struct inode_operations *iops,
1367                   struct ffs_file_perms *perms)
1368 {
1369         struct inode *inode;
1370
1371         ENTER();
1372
1373         ffs_log("enter");
1374
1375         inode = new_inode(sb);
1376
1377         if (likely(inode)) {
1378                 struct timespec current_time = CURRENT_TIME;
1379
1380                 inode->i_ino     = get_next_ino();
1381                 inode->i_mode    = perms->mode;
1382                 inode->i_uid     = perms->uid;
1383                 inode->i_gid     = perms->gid;
1384                 inode->i_atime   = current_time;
1385                 inode->i_mtime   = current_time;
1386                 inode->i_ctime   = current_time;
1387                 inode->i_private = data;
1388                 if (fops)
1389                         inode->i_fop = fops;
1390                 if (iops)
1391                         inode->i_op  = iops;
1392         }
1393
1394         ffs_log("exit");
1395
1396         return inode;
1397 }
1398
1399 /* Create "regular" file */
1400 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1401                                         const char *name, void *data,
1402                                         const struct file_operations *fops)
1403 {
1404         struct ffs_data *ffs = sb->s_fs_info;
1405         struct dentry   *dentry;
1406         struct inode    *inode;
1407
1408         ENTER();
1409
1410         ffs_log("enter");
1411
1412         dentry = d_alloc_name(sb->s_root, name);
1413         if (unlikely(!dentry))
1414                 return NULL;
1415
1416         inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1417         if (unlikely(!inode)) {
1418                 dput(dentry);
1419                 return NULL;
1420         }
1421
1422         d_add(dentry, inode);
1423
1424         ffs_log("exit");
1425
1426         return dentry;
1427 }
1428
1429 /* Super block */
1430 static const struct super_operations ffs_sb_operations = {
1431         .statfs =       simple_statfs,
1432         .drop_inode =   generic_delete_inode,
1433 };
1434
1435 struct ffs_sb_fill_data {
1436         struct ffs_file_perms perms;
1437         umode_t root_mode;
1438         const char *dev_name;
1439         bool no_disconnect;
1440         struct ffs_data *ffs_data;
1441 };
1442
1443 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1444 {
1445         struct ffs_sb_fill_data *data = _data;
1446         struct inode    *inode;
1447         struct ffs_data *ffs = data->ffs_data;
1448
1449         ENTER();
1450
1451         ffs_log("enter");
1452
1453         ffs->sb              = sb;
1454         data->ffs_data       = NULL;
1455         sb->s_fs_info        = ffs;
1456         sb->s_blocksize      = PAGE_CACHE_SIZE;
1457         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1458         sb->s_magic          = FUNCTIONFS_MAGIC;
1459         sb->s_op             = &ffs_sb_operations;
1460         sb->s_time_gran      = 1;
1461
1462         /* Root inode */
1463         data->perms.mode = data->root_mode;
1464         inode = ffs_sb_make_inode(sb, NULL,
1465                                   &simple_dir_operations,
1466                                   &simple_dir_inode_operations,
1467                                   &data->perms);
1468         sb->s_root = d_make_root(inode);
1469         if (unlikely(!sb->s_root))
1470                 return -ENOMEM;
1471
1472         /* EP0 file */
1473         if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1474                                          &ffs_ep0_operations)))
1475                 return -ENOMEM;
1476
1477         ffs_log("exit");
1478
1479         return 0;
1480 }
1481
1482 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1483 {
1484         ENTER();
1485
1486         ffs_log("enter");
1487
1488         if (!opts || !*opts)
1489                 return 0;
1490
1491         for (;;) {
1492                 unsigned long value;
1493                 char *eq, *comma;
1494
1495                 /* Option limit */
1496                 comma = strchr(opts, ',');
1497                 if (comma)
1498                         *comma = 0;
1499
1500                 /* Value limit */
1501                 eq = strchr(opts, '=');
1502                 if (unlikely(!eq)) {
1503                         pr_err("'=' missing in %s\n", opts);
1504                         return -EINVAL;
1505                 }
1506                 *eq = 0;
1507
1508                 /* Parse value */
1509                 if (kstrtoul(eq + 1, 0, &value)) {
1510                         pr_err("%s: invalid value: %s\n", opts, eq + 1);
1511                         return -EINVAL;
1512                 }
1513
1514                 /* Interpret option */
1515                 switch (eq - opts) {
1516                 case 13:
1517                         if (!memcmp(opts, "no_disconnect", 13))
1518                                 data->no_disconnect = !!value;
1519                         else
1520                                 goto invalid;
1521                         break;
1522                 case 5:
1523                         if (!memcmp(opts, "rmode", 5))
1524                                 data->root_mode  = (value & 0555) | S_IFDIR;
1525                         else if (!memcmp(opts, "fmode", 5))
1526                                 data->perms.mode = (value & 0666) | S_IFREG;
1527                         else
1528                                 goto invalid;
1529                         break;
1530
1531                 case 4:
1532                         if (!memcmp(opts, "mode", 4)) {
1533                                 data->root_mode  = (value & 0555) | S_IFDIR;
1534                                 data->perms.mode = (value & 0666) | S_IFREG;
1535                         } else {
1536                                 goto invalid;
1537                         }
1538                         break;
1539
1540                 case 3:
1541                         if (!memcmp(opts, "uid", 3)) {
1542                                 data->perms.uid = make_kuid(current_user_ns(), value);
1543                                 if (!uid_valid(data->perms.uid)) {
1544                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1545                                         return -EINVAL;
1546                                 }
1547                         } else if (!memcmp(opts, "gid", 3)) {
1548                                 data->perms.gid = make_kgid(current_user_ns(), value);
1549                                 if (!gid_valid(data->perms.gid)) {
1550                                         pr_err("%s: unmapped value: %lu\n", opts, value);
1551                                         return -EINVAL;
1552                                 }
1553                         } else {
1554                                 goto invalid;
1555                         }
1556                         break;
1557
1558                 default:
1559 invalid:
1560                         pr_err("%s: invalid option\n", opts);
1561                         return -EINVAL;
1562                 }
1563
1564                 /* Next iteration */
1565                 if (!comma)
1566                         break;
1567                 opts = comma + 1;
1568         }
1569
1570         ffs_log("exit");
1571
1572         return 0;
1573 }
1574
1575 /* "mount -t functionfs dev_name /dev/function" ends up here */
1576
1577 static struct dentry *
1578 ffs_fs_mount(struct file_system_type *t, int flags,
1579               const char *dev_name, void *opts)
1580 {
1581         struct ffs_sb_fill_data data = {
1582                 .perms = {
1583                         .mode = S_IFREG | 0600,
1584                         .uid = GLOBAL_ROOT_UID,
1585                         .gid = GLOBAL_ROOT_GID,
1586                 },
1587                 .root_mode = S_IFDIR | 0500,
1588                 .no_disconnect = false,
1589         };
1590         struct dentry *rv;
1591         int ret;
1592         void *ffs_dev;
1593         struct ffs_data *ffs;
1594         struct ffs_inst_status *inst_status;
1595
1596         ENTER();
1597
1598         ffs_log("enter");
1599
1600         ret = ffs_fs_parse_opts(&data, opts);
1601         if (unlikely(ret < 0))
1602                 return ERR_PTR(ret);
1603
1604         ffs = ffs_data_new();
1605         if (unlikely(!ffs))
1606                 return ERR_PTR(-ENOMEM);
1607         ffs->file_perms = data.perms;
1608         ffs->no_disconnect = data.no_disconnect;
1609
1610         ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1611         if (unlikely(!ffs->dev_name)) {
1612                 ffs_data_put(ffs);
1613                 return ERR_PTR(-ENOMEM);
1614         }
1615
1616         ffs_dev = ffs_acquire_dev(dev_name);
1617         if (IS_ERR(ffs_dev)) {
1618                 ffs_data_put(ffs);
1619                 return ERR_CAST(ffs_dev);
1620         }
1621         ffs->private_data = ffs_dev;
1622         data.ffs_data = ffs;
1623
1624         inst_status = name_to_inst_status(ffs->dev_name, false);
1625         if (IS_ERR(inst_status)) {
1626                 ffs_log("failed to find instance (%s)\n",
1627                                 ffs->dev_name);
1628                 return ERR_PTR(-EINVAL);
1629         }
1630
1631         /* Store ffs to global status structure */
1632         ffs_dev_lock();
1633         inst_status->ffs_data = ffs;
1634         ffs_dev_unlock();
1635
1636         rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1637         if (IS_ERR(rv) && data.ffs_data) {
1638                 ffs_release_dev(data.ffs_data);
1639                 ffs_data_put(data.ffs_data);
1640         }
1641
1642         ffs_log("exit");
1643
1644         return rv;
1645 }
1646
1647 static void
1648 ffs_fs_kill_sb(struct super_block *sb)
1649 {
1650         ENTER();
1651
1652         ffs_log("enter");
1653
1654         kill_litter_super(sb);
1655         if (sb->s_fs_info) {
1656                 ffs_release_dev(sb->s_fs_info);
1657                 ffs_data_closed(sb->s_fs_info);
1658         }
1659
1660         ffs_log("exit");
1661 }
1662
1663 static struct file_system_type ffs_fs_type = {
1664         .owner          = THIS_MODULE,
1665         .name           = "functionfs",
1666         .mount          = ffs_fs_mount,
1667         .kill_sb        = ffs_fs_kill_sb,
1668 };
1669 MODULE_ALIAS_FS("functionfs");
1670
1671
1672 /* Driver's main init/cleanup functions *************************************/
1673
1674 static int functionfs_init(void)
1675 {
1676         int ret;
1677
1678         ENTER();
1679
1680         ret = register_filesystem(&ffs_fs_type);
1681         if (likely(!ret))
1682                 pr_info("file system registered\n");
1683         else
1684                 pr_err("failed registering file system (%d)\n", ret);
1685
1686         return ret;
1687 }
1688
1689 static void functionfs_cleanup(void)
1690 {
1691         ENTER();
1692
1693         pr_info("unloading\n");
1694         unregister_filesystem(&ffs_fs_type);
1695 }
1696
1697 /* ffs_data and ffs_function construction and destruction code **************/
1698
1699 static void ffs_data_clear(struct ffs_data *ffs);
1700 static void ffs_data_reset(struct ffs_data *ffs);
1701
1702 static void ffs_data_get(struct ffs_data *ffs)
1703 {
1704         ENTER();
1705
1706         ffs_log("enter");
1707
1708         smp_mb__before_atomic();
1709         atomic_inc(&ffs->ref);
1710
1711         ffs_log("exit");
1712 }
1713
1714 static void ffs_data_opened(struct ffs_data *ffs)
1715 {
1716         ENTER();
1717
1718         ffs_log("enter: state %d setup_state %d flag %lu opened %d", ffs->state,
1719                 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
1720
1721         smp_mb__before_atomic();
1722         atomic_inc(&ffs->ref);
1723         if (atomic_add_return(1, &ffs->opened) == 1 &&
1724                         ffs->state == FFS_DEACTIVATED) {
1725                 ffs->state = FFS_CLOSING;
1726                 ffs_data_reset(ffs);
1727         }
1728
1729         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1730                 ffs->setup_state, ffs->flags);
1731 }
1732
1733 static void ffs_data_put(struct ffs_data *ffs)
1734 {
1735         struct ffs_inst_status *inst_status;
1736         const char *dev_name;
1737
1738         ENTER();
1739
1740         ffs_log("enter");
1741
1742         smp_mb__before_atomic();
1743         if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1744                 pr_info("%s(): freeing\n", __func__);
1745                 /* Clear ffs from global structure */
1746                 inst_status = name_to_inst_status(ffs->dev_name, false);
1747                 if (!IS_ERR(inst_status)) {
1748                         ffs_dev_lock();
1749                         inst_status->ffs_data = NULL;
1750                         ffs_dev_unlock();
1751                 }
1752                 ffs_data_clear(ffs);
1753                 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1754                        waitqueue_active(&ffs->ep0req_completion.wait));
1755                 dev_name = ffs->dev_name;
1756                 kfree(ffs);
1757                 ffs_inst_clean_delay(dev_name);
1758                 kfree(dev_name);
1759         }
1760
1761         ffs_log("exit");
1762 }
1763
1764 static void ffs_data_closed(struct ffs_data *ffs)
1765 {
1766         ENTER();
1767
1768         ffs_log("enter: state %d setup_state %d flag %lu opened %d", ffs->state,
1769                 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
1770
1771         smp_mb__before_atomic();
1772         if (atomic_dec_and_test(&ffs->opened)) {
1773                 if (ffs->no_disconnect) {
1774                         ffs->state = FFS_DEACTIVATED;
1775                         if (ffs->epfiles) {
1776                                 ffs_epfiles_destroy(ffs->epfiles,
1777                                                    ffs->eps_count);
1778                                 ffs->epfiles = NULL;
1779                         }
1780                         if (ffs->setup_state == FFS_SETUP_PENDING)
1781                                 __ffs_ep0_stall(ffs);
1782                 } else {
1783                         ffs->state = FFS_CLOSING;
1784                         ffs_data_reset(ffs);
1785                 }
1786         }
1787
1788         smp_mb__before_atomic();
1789         if (atomic_read(&ffs->opened) < 0) {
1790                 ffs->state = FFS_CLOSING;
1791                 ffs_data_reset(ffs);
1792         }
1793
1794         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1795                 ffs->setup_state, ffs->flags);
1796
1797         ffs_data_put(ffs);
1798 }
1799
1800 static struct ffs_data *ffs_data_new(void)
1801 {
1802         struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1803         if (unlikely(!ffs))
1804                 return NULL;
1805
1806         ENTER();
1807
1808         ffs_log("enter");
1809
1810         atomic_set(&ffs->ref, 1);
1811         atomic_set(&ffs->opened, 0);
1812         ffs->state = FFS_READ_DESCRIPTORS;
1813         mutex_init(&ffs->mutex);
1814         spin_lock_init(&ffs->eps_lock);
1815         init_waitqueue_head(&ffs->ev.waitq);
1816         init_completion(&ffs->ep0req_completion);
1817         init_completion(&ffs->epout_completion);
1818         init_completion(&ffs->epin_completion);
1819
1820         /* XXX REVISIT need to update it in some places, or do we? */
1821         ffs->ev.can_stall = 1;
1822
1823         ffs_log("exit");
1824
1825         return ffs;
1826 }
1827
1828 static void ffs_data_clear(struct ffs_data *ffs)
1829 {
1830         ENTER();
1831
1832         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1833                 ffs->setup_state, ffs->flags);
1834
1835         pr_debug("%s: ffs->gadget= %pK, ffs->flags= %lu\n",
1836                                 __func__, ffs->gadget, ffs->flags);
1837         ffs_closed(ffs);
1838
1839         if (ffs->gadget)
1840                 pr_err("%s: ffs:%pK ffs->gadget= %pK, ffs->flags= %lu\n",
1841                                 __func__, ffs, ffs->gadget, ffs->flags);
1842         BUG_ON(ffs->gadget);
1843
1844         if (ffs->epfiles)
1845                 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1846
1847         if (ffs->ffs_eventfd)
1848                 eventfd_ctx_put(ffs->ffs_eventfd);
1849
1850         kfree(ffs->raw_descs_data);
1851         kfree(ffs->raw_strings);
1852         kfree(ffs->stringtabs);
1853
1854         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1855                 ffs->setup_state, ffs->flags);
1856 }
1857
1858 static void ffs_data_reset(struct ffs_data *ffs)
1859 {
1860         ENTER();
1861
1862         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1863                 ffs->setup_state, ffs->flags);
1864
1865         ffs_data_clear(ffs);
1866
1867         ffs->epfiles = NULL;
1868         ffs->raw_descs_data = NULL;
1869         ffs->raw_descs = NULL;
1870         ffs->raw_strings = NULL;
1871         ffs->stringtabs = NULL;
1872
1873         ffs->raw_descs_length = 0;
1874         ffs->fs_descs_count = 0;
1875         ffs->hs_descs_count = 0;
1876         ffs->ss_descs_count = 0;
1877
1878         ffs->strings_count = 0;
1879         ffs->interfaces_count = 0;
1880         ffs->eps_count = 0;
1881
1882         ffs->ev.count = 0;
1883
1884         ffs->state = FFS_READ_DESCRIPTORS;
1885         ffs->setup_state = FFS_NO_SETUP;
1886         ffs->flags = 0;
1887
1888         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1889                 ffs->setup_state, ffs->flags);
1890 }
1891
1892
1893 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1894 {
1895         struct usb_gadget_strings **lang;
1896         int first_id;
1897
1898         ENTER();
1899
1900         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1901                 ffs->setup_state, ffs->flags);
1902
1903         if (WARN_ON(ffs->state != FFS_ACTIVE
1904                  || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1905                 return -EBADFD;
1906
1907         first_id = usb_string_ids_n(cdev, ffs->strings_count);
1908         if (unlikely(first_id < 0))
1909                 return first_id;
1910
1911         ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1912         if (unlikely(!ffs->ep0req))
1913                 return -ENOMEM;
1914         ffs->ep0req->complete = ffs_ep0_complete;
1915         ffs->ep0req->context = ffs;
1916
1917         lang = ffs->stringtabs;
1918         if (lang) {
1919                 for (; *lang; ++lang) {
1920                         struct usb_string *str = (*lang)->strings;
1921                         int id = first_id;
1922                         for (; str->s; ++id, ++str)
1923                                 str->id = id;
1924                 }
1925         }
1926
1927         ffs->gadget = cdev->gadget;
1928
1929         ffs_log("exit: state %d setup_state %d flag %lu gadget %pK\n",
1930                         ffs->state, ffs->setup_state, ffs->flags, ffs->gadget);
1931
1932         ffs_data_get(ffs);
1933         return 0;
1934 }
1935
1936 static void functionfs_unbind(struct ffs_data *ffs)
1937 {
1938         ENTER();
1939
1940         if (!WARN_ON(!ffs->gadget)) {
1941                 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1942                 ffs->ep0req = NULL;
1943                 ffs->gadget = NULL;
1944                 clear_bit(FFS_FL_BOUND, &ffs->flags);
1945                 ffs_log("state %d setup_state %d flag %lu gadget %pK\n",
1946                         ffs->state, ffs->setup_state, ffs->flags, ffs->gadget);
1947                 ffs_data_put(ffs);
1948         }
1949 }
1950
1951 static int ffs_epfiles_create(struct ffs_data *ffs)
1952 {
1953         struct ffs_epfile *epfile, *epfiles;
1954         unsigned i, count;
1955
1956         ENTER();
1957
1958         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1959                 ffs->setup_state, ffs->flags);
1960
1961         count = ffs->eps_count;
1962         epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1963         if (!epfiles)
1964                 return -ENOMEM;
1965
1966         epfile = epfiles;
1967         for (i = 1; i <= count; ++i, ++epfile) {
1968                 epfile->ffs = ffs;
1969                 mutex_init(&epfile->mutex);
1970                 init_waitqueue_head(&epfile->wait);
1971                 atomic_set(&epfile->opened, 0);
1972                 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1973                         sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
1974                 else
1975                         sprintf(epfile->name, "ep%u", i);
1976                 epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
1977                                                  epfile,
1978                                                  &ffs_epfile_operations);
1979                 if (unlikely(!epfile->dentry)) {
1980                         ffs_epfiles_destroy(epfiles, i - 1);
1981                         return -ENOMEM;
1982                 }
1983         }
1984
1985         ffs->epfiles = epfiles;
1986
1987         ffs_log("exit: eps_count %u state %d setup_state %d flag %lu",
1988                 count, ffs->state, ffs->setup_state, ffs->flags);
1989
1990         return 0;
1991 }
1992
1993 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1994 {
1995         struct ffs_epfile *epfile = epfiles;
1996
1997         ENTER();
1998
1999         ffs_log("enter: count %u", count);
2000
2001         for (; count; --count, ++epfile) {
2002                 BUG_ON(mutex_is_locked(&epfile->mutex) ||
2003                        waitqueue_active(&epfile->wait));
2004                 if (epfile->dentry) {
2005                         d_delete(epfile->dentry);
2006                         dput(epfile->dentry);
2007                         epfile->dentry = NULL;
2008                 }
2009         }
2010
2011         kfree(epfiles);
2012
2013         ffs_log("exit");
2014 }
2015
2016 static void ffs_func_eps_disable(struct ffs_function *func)
2017 {
2018         struct ffs_ep *ep         = func->eps;
2019         struct ffs_epfile *epfile = func->ffs->epfiles;
2020         unsigned count            = func->ffs->eps_count;
2021         unsigned long flags;
2022
2023         ffs_log("enter: state %d setup_state %d flag %lu", func->ffs->state,
2024                 func->ffs->setup_state, func->ffs->flags);
2025
2026         spin_lock_irqsave(&func->ffs->eps_lock, flags);
2027         do {
2028
2029                 smp_mb__before_atomic();
2030                 if (epfile)
2031                         atomic_set(&epfile->error, 1);
2032
2033                 /* pending requests get nuked */
2034                 if (likely(ep->ep))
2035                         usb_ep_disable(ep->ep);
2036                 ++ep;
2037
2038                 if (epfile) {
2039                         atomic_set(&epfile->error, 1);
2040                         epfile->ep = NULL;
2041                         ++epfile;
2042                 }
2043         } while (--count);
2044         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2045
2046         ffs_log("exit");
2047 }
2048
2049 static int ffs_func_eps_enable(struct ffs_function *func)
2050 {
2051         struct ffs_data *ffs      = func->ffs;
2052         struct ffs_ep *ep         = func->eps;
2053         struct ffs_epfile *epfile = ffs->epfiles;
2054         unsigned count            = ffs->eps_count;
2055         unsigned long flags;
2056         int ret = 0;
2057
2058         ffs_log("enter: state %d setup_state %d flag %lu", func->ffs->state,
2059                 func->ffs->setup_state, func->ffs->flags);
2060
2061         spin_lock_irqsave(&func->ffs->eps_lock, flags);
2062         do {
2063                 struct usb_endpoint_descriptor *ds;
2064                 int desc_idx;
2065
2066                 if (ffs->gadget->speed == USB_SPEED_SUPER)
2067                         desc_idx = 2;
2068                 else if (ffs->gadget->speed == USB_SPEED_HIGH)
2069                         desc_idx = 1;
2070                 else
2071                         desc_idx = 0;
2072
2073                 /* fall-back to lower speed if desc missing for current speed */
2074                 do {
2075                         ds = ep->descs[desc_idx];
2076                 } while (!ds && --desc_idx >= 0);
2077
2078                 if (!ds) {
2079                         ret = -EINVAL;
2080                         break;
2081                 }
2082
2083                 ep->ep->driver_data = ep;
2084                 ep->ep->desc = ds;
2085
2086                 ret = config_ep_by_speed(func->gadget, &func->function, ep->ep);
2087                 if (ret) {
2088                         pr_err("%s(): config_ep_by_speed(%d) err for %s\n",
2089                                         __func__, ret, ep->ep->name);
2090                         break;
2091                 }
2092
2093                 /*
2094                  * userspace setting maxburst > 1 results more fifo
2095                  * allocation than without maxburst. Change maxburst to 1
2096                  * only to allocate fifo size of max packet size.
2097                  */
2098                 ep->ep->maxburst = 1;
2099                 ret = usb_ep_enable(ep->ep);
2100                 if (likely(!ret)) {
2101                         epfile->ep = ep;
2102                         epfile->in = usb_endpoint_dir_in(ds);
2103                         epfile->isoc = usb_endpoint_xfer_isoc(ds);
2104                         ffs_log("usb_ep_enable %s", ep->ep->name);
2105                 } else {
2106                         break;
2107                 }
2108
2109                 wake_up(&epfile->wait);
2110
2111                 ++ep;
2112                 ++epfile;
2113         } while (--count);
2114         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2115
2116         ffs_log("exit: ret %d", ret);
2117
2118         return ret;
2119 }
2120
2121
2122 /* Parsing and building descriptors and strings *****************************/
2123
2124 /*
2125  * This validates if data pointed by data is a valid USB descriptor as
2126  * well as record how many interfaces, endpoints and strings are
2127  * required by given configuration.  Returns address after the
2128  * descriptor or NULL if data is invalid.
2129  */
2130
2131 enum ffs_entity_type {
2132         FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
2133 };
2134
2135 enum ffs_os_desc_type {
2136         FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
2137 };
2138
2139 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
2140                                    u8 *valuep,
2141                                    struct usb_descriptor_header *desc,
2142                                    void *priv);
2143
2144 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
2145                                     struct usb_os_desc_header *h, void *data,
2146                                     unsigned len, void *priv);
2147
2148 static int __must_check ffs_do_single_desc(char *data, unsigned len,
2149                                            ffs_entity_callback entity,
2150                                            void *priv)
2151 {
2152         struct usb_descriptor_header *_ds = (void *)data;
2153         u8 length;
2154         int ret;
2155
2156         ENTER();
2157
2158         ffs_log("enter: len %u", len);
2159
2160         /* At least two bytes are required: length and type */
2161         if (len < 2) {
2162                 pr_vdebug("descriptor too short\n");
2163                 return -EINVAL;
2164         }
2165
2166         /* If we have at least as many bytes as the descriptor takes? */
2167         length = _ds->bLength;
2168         if (len < length) {
2169                 pr_vdebug("descriptor longer then available data\n");
2170                 return -EINVAL;
2171         }
2172
2173 #define __entity_check_INTERFACE(val)  1
2174 #define __entity_check_STRING(val)     (val)
2175 #define __entity_check_ENDPOINT(val)   ((val) & USB_ENDPOINT_NUMBER_MASK)
2176 #define __entity(type, val) do {                                        \
2177                 pr_vdebug("entity " #type "(%02x)\n", (val));           \
2178                 if (unlikely(!__entity_check_ ##type(val))) {           \
2179                         pr_vdebug("invalid entity's value\n");          \
2180                         return -EINVAL;                                 \
2181                 }                                                       \
2182                 ret = entity(FFS_ ##type, &val, _ds, priv);             \
2183                 if (unlikely(ret < 0)) {                                \
2184                         pr_debug("entity " #type "(%02x); ret = %d\n",  \
2185                                  (val), ret);                           \
2186                         return ret;                                     \
2187                 }                                                       \
2188         } while (0)
2189
2190         /* Parse descriptor depending on type. */
2191         switch (_ds->bDescriptorType) {
2192         case USB_DT_DEVICE:
2193         case USB_DT_CONFIG:
2194         case USB_DT_STRING:
2195         case USB_DT_DEVICE_QUALIFIER:
2196                 /* function can't have any of those */
2197                 pr_vdebug("descriptor reserved for gadget: %d\n",
2198                       _ds->bDescriptorType);
2199                 return -EINVAL;
2200
2201         case USB_DT_INTERFACE: {
2202                 struct usb_interface_descriptor *ds = (void *)_ds;
2203                 pr_vdebug("interface descriptor\n");
2204                 if (length != sizeof *ds)
2205                         goto inv_length;
2206
2207                 __entity(INTERFACE, ds->bInterfaceNumber);
2208                 if (ds->iInterface)
2209                         __entity(STRING, ds->iInterface);
2210         }
2211                 break;
2212
2213         case USB_DT_ENDPOINT: {
2214                 struct usb_endpoint_descriptor *ds = (void *)_ds;
2215                 pr_vdebug("endpoint descriptor\n");
2216                 if (length != USB_DT_ENDPOINT_SIZE &&
2217                     length != USB_DT_ENDPOINT_AUDIO_SIZE)
2218                         goto inv_length;
2219                 __entity(ENDPOINT, ds->bEndpointAddress);
2220         }
2221                 break;
2222
2223         case HID_DT_HID:
2224                 pr_vdebug("hid descriptor\n");
2225                 if (length != sizeof(struct hid_descriptor))
2226                         goto inv_length;
2227                 break;
2228
2229         case USB_DT_OTG:
2230                 if (length != sizeof(struct usb_otg_descriptor))
2231                         goto inv_length;
2232                 break;
2233
2234         case USB_DT_INTERFACE_ASSOCIATION: {
2235                 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
2236                 pr_vdebug("interface association descriptor\n");
2237                 if (length != sizeof *ds)
2238                         goto inv_length;
2239                 if (ds->iFunction)
2240                         __entity(STRING, ds->iFunction);
2241         }
2242                 break;
2243
2244         case USB_DT_SS_ENDPOINT_COMP:
2245                 pr_vdebug("EP SS companion descriptor\n");
2246                 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
2247                         goto inv_length;
2248                 break;
2249
2250         case USB_DT_OTHER_SPEED_CONFIG:
2251         case USB_DT_INTERFACE_POWER:
2252         case USB_DT_DEBUG:
2253         case USB_DT_SECURITY:
2254         case USB_DT_CS_RADIO_CONTROL:
2255                 /* TODO */
2256                 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
2257                 return -EINVAL;
2258
2259         default:
2260                 /* We should never be here */
2261                 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
2262                 return -EINVAL;
2263
2264 inv_length:
2265                 pr_vdebug("invalid length: %d (descriptor %d)\n",
2266                           _ds->bLength, _ds->bDescriptorType);
2267                 return -EINVAL;
2268         }
2269
2270 #undef __entity
2271 #undef __entity_check_DESCRIPTOR
2272 #undef __entity_check_INTERFACE
2273 #undef __entity_check_STRING
2274 #undef __entity_check_ENDPOINT
2275
2276         ffs_log("exit: desc type %d length %d", _ds->bDescriptorType, length);
2277
2278         return length;
2279 }
2280
2281 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
2282                                      ffs_entity_callback entity, void *priv)
2283 {
2284         const unsigned _len = len;
2285         unsigned long num = 0;
2286
2287         ENTER();
2288
2289         ffs_log("enter: len %u", len);
2290
2291         for (;;) {
2292                 int ret;
2293
2294                 if (num == count)
2295                         data = NULL;
2296
2297                 /* Record "descriptor" entity */
2298                 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
2299                 if (unlikely(ret < 0)) {
2300                         pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
2301                                  num, ret);
2302                         return ret;
2303                 }
2304
2305                 if (!data)
2306                         return _len - len;
2307
2308                 ret = ffs_do_single_desc(data, len, entity, priv);
2309                 if (unlikely(ret < 0)) {
2310                         pr_debug("%s returns %d\n", __func__, ret);
2311                         return ret;
2312                 }
2313
2314                 len -= ret;
2315                 data += ret;
2316                 ++num;
2317         }
2318
2319         ffs_log("exit: len %u", len);
2320 }
2321
2322 static int __ffs_data_do_entity(enum ffs_entity_type type,
2323                                 u8 *valuep, struct usb_descriptor_header *desc,
2324                                 void *priv)
2325 {
2326         struct ffs_desc_helper *helper = priv;
2327         struct usb_endpoint_descriptor *d;
2328
2329         ENTER();
2330
2331         ffs_log("enter: type %u", type);
2332
2333         switch (type) {
2334         case FFS_DESCRIPTOR:
2335                 break;
2336
2337         case FFS_INTERFACE:
2338                 /*
2339                  * Interfaces are indexed from zero so if we
2340                  * encountered interface "n" then there are at least
2341                  * "n+1" interfaces.
2342                  */
2343                 if (*valuep >= helper->interfaces_count)
2344                         helper->interfaces_count = *valuep + 1;
2345                 break;
2346
2347         case FFS_STRING:
2348                 /*
2349                  * Strings are indexed from 1 (0 is magic ;) reserved
2350                  * for languages list or some such)
2351                  */
2352                 if (*valuep > helper->ffs->strings_count)
2353                         helper->ffs->strings_count = *valuep;
2354                 break;
2355
2356         case FFS_ENDPOINT:
2357                 d = (void *)desc;
2358                 helper->eps_count++;
2359                 if (helper->eps_count >= 15)
2360                         return -EINVAL;
2361                 /* Check if descriptors for any speed were already parsed */
2362                 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
2363                         helper->ffs->eps_addrmap[helper->eps_count] =
2364                                 d->bEndpointAddress;
2365                 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
2366                                 d->bEndpointAddress)
2367                         return -EINVAL;
2368                 break;
2369         }
2370
2371         ffs_log("exit");
2372
2373         return 0;
2374 }
2375
2376 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
2377                                    struct usb_os_desc_header *desc)
2378 {
2379         u16 bcd_version = le16_to_cpu(desc->bcdVersion);
2380         u16 w_index = le16_to_cpu(desc->wIndex);
2381
2382         ffs_log("enter");
2383
2384         if (bcd_version != 1) {
2385                 pr_vdebug("unsupported os descriptors version: %d",
2386                           bcd_version);
2387                 return -EINVAL;
2388         }
2389         switch (w_index) {
2390         case 0x4:
2391                 *next_type = FFS_OS_DESC_EXT_COMPAT;
2392                 break;
2393         case 0x5:
2394                 *next_type = FFS_OS_DESC_EXT_PROP;
2395                 break;
2396         default:
2397                 pr_vdebug("unsupported os descriptor type: %d", w_index);
2398                 return -EINVAL;
2399         }
2400
2401         ffs_log("exit: size of desc %zu", sizeof(*desc));
2402
2403         return sizeof(*desc);
2404 }
2405
2406 /*
2407  * Process all extended compatibility/extended property descriptors
2408  * of a feature descriptor
2409  */
2410 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
2411                                               enum ffs_os_desc_type type,
2412                                               u16 feature_count,
2413                                               ffs_os_desc_callback entity,
2414                                               void *priv,
2415                                               struct usb_os_desc_header *h)
2416 {
2417         int ret;
2418         const unsigned _len = len;
2419
2420         ENTER();
2421
2422         ffs_log("enter: len %u os desc type %d", len, type);
2423
2424         /* loop over all ext compat/ext prop descriptors */
2425         while (feature_count--) {
2426                 ret = entity(type, h, data, len, priv);
2427                 if (unlikely(ret < 0)) {
2428                         pr_debug("bad OS descriptor, type: %d\n", type);
2429                         return ret;
2430                 }
2431                 data += ret;
2432                 len -= ret;
2433         }
2434
2435         ffs_log("exit");
2436
2437         return _len - len;
2438 }
2439
2440 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
2441 static int __must_check ffs_do_os_descs(unsigned count,
2442                                         char *data, unsigned len,
2443                                         ffs_os_desc_callback entity, void *priv)
2444 {
2445         const unsigned _len = len;
2446         unsigned long num = 0;
2447
2448         ENTER();
2449
2450         ffs_log("enter: len %u", len);
2451
2452         for (num = 0; num < count; ++num) {
2453                 int ret;
2454                 enum ffs_os_desc_type type;
2455                 u16 feature_count;
2456                 struct usb_os_desc_header *desc = (void *)data;
2457
2458                 if (len < sizeof(*desc))
2459                         return -EINVAL;
2460
2461                 /*
2462                  * Record "descriptor" entity.
2463                  * Process dwLength, bcdVersion, wIndex, get b/wCount.
2464                  * Move the data pointer to the beginning of extended
2465                  * compatibilities proper or extended properties proper
2466                  * portions of the data
2467                  */
2468                 if (le32_to_cpu(desc->dwLength) > len)
2469                         return -EINVAL;
2470
2471                 ret = __ffs_do_os_desc_header(&type, desc);
2472                 if (unlikely(ret < 0)) {
2473                         pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
2474                                  num, ret);
2475                         return ret;
2476                 }
2477                 /*
2478                  * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2479                  */
2480                 feature_count = le16_to_cpu(desc->wCount);
2481                 if (type == FFS_OS_DESC_EXT_COMPAT &&
2482                     (feature_count > 255 || desc->Reserved))
2483                                 return -EINVAL;
2484                 len -= ret;
2485                 data += ret;
2486
2487                 /*
2488                  * Process all function/property descriptors
2489                  * of this Feature Descriptor
2490                  */
2491                 ret = ffs_do_single_os_desc(data, len, type,
2492                                             feature_count, entity, priv, desc);
2493                 if (unlikely(ret < 0)) {
2494                         pr_debug("%s returns %d\n", __func__, ret);
2495                         return ret;
2496                 }
2497
2498                 len -= ret;
2499                 data += ret;
2500         }
2501
2502         ffs_log("exit");
2503
2504         return _len - len;
2505 }
2506
2507 /**
2508  * Validate contents of the buffer from userspace related to OS descriptors.
2509  */
2510 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2511                                  struct usb_os_desc_header *h, void *data,
2512                                  unsigned len, void *priv)
2513 {
2514         struct ffs_data *ffs = priv;
2515         u8 length;
2516
2517         ENTER();
2518
2519         ffs_log("enter: len %u", len);
2520
2521         switch (type) {
2522         case FFS_OS_DESC_EXT_COMPAT: {
2523                 struct usb_ext_compat_desc *d = data;
2524                 int i;
2525
2526                 if (len < sizeof(*d) ||
2527                     d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2528                     d->Reserved1 != 1) {
2529                         pr_err("%s(): Invalid os_desct_ext_compat\n",
2530                                                         __func__);
2531                         return -EINVAL;
2532                 }
2533                 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2534                         if (d->Reserved2[i]) {
2535                                 pr_err("%s(): Invalid Reserved2 of ext_compat\n",
2536                                                         __func__);
2537                                 return -EINVAL;
2538                         }
2539
2540                 length = sizeof(struct usb_ext_compat_desc);
2541         }
2542                 break;
2543         case FFS_OS_DESC_EXT_PROP: {
2544                 struct usb_ext_prop_desc *d = data;
2545                 u32 type, pdl;
2546                 u16 pnl;
2547
2548                 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2549                         return -EINVAL;
2550                 length = le32_to_cpu(d->dwSize);
2551                 if (len < length)
2552                         return -EINVAL;
2553                 type = le32_to_cpu(d->dwPropertyDataType);
2554                 if (type < USB_EXT_PROP_UNICODE ||
2555                     type > USB_EXT_PROP_UNICODE_MULTI) {
2556                         pr_vdebug("unsupported os descriptor property type: %d",
2557                                   type);
2558                         return -EINVAL;
2559                 }
2560                 pnl = le16_to_cpu(d->wPropertyNameLength);
2561                 if (length < 14 + pnl) {
2562                         pr_vdebug("invalid os descriptor length: %d pnl:%d (descriptor %d)\n",
2563                                   length, pnl, type);
2564                         return -EINVAL;
2565                 }
2566                 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2567                 if (length != 14 + pnl + pdl) {
2568                         pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2569                                   length, pnl, pdl, type);
2570                         return -EINVAL;
2571                 }
2572                 ++ffs->ms_os_descs_ext_prop_count;
2573                 /* property name reported to the host as "WCHAR"s */
2574                 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2575                 ffs->ms_os_descs_ext_prop_data_len += pdl;
2576         }
2577                 break;
2578         default:
2579                 pr_vdebug("unknown descriptor: %d\n", type);
2580                 return -EINVAL;
2581         }
2582
2583         ffs_log("exit");
2584
2585         return length;
2586 }
2587
2588 static int __ffs_data_got_descs(struct ffs_data *ffs,
2589                                 char *const _data, size_t len)
2590 {
2591         char *data = _data, *raw_descs;
2592         unsigned os_descs_count = 0, counts[3], flags;
2593         int ret = -EINVAL, i;
2594         struct ffs_desc_helper helper;
2595
2596         ENTER();
2597
2598         ffs_log("enter: len %zu", len);
2599
2600         if (get_unaligned_le32(data + 4) != len)
2601                 goto error;
2602
2603         switch (get_unaligned_le32(data)) {
2604         case FUNCTIONFS_DESCRIPTORS_MAGIC:
2605                 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2606                 data += 8;
2607                 len  -= 8;
2608                 break;
2609         case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2610                 flags = get_unaligned_le32(data + 8);
2611                 ffs->user_flags = flags;
2612                 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2613                               FUNCTIONFS_HAS_HS_DESC |
2614                               FUNCTIONFS_HAS_SS_DESC |
2615                               FUNCTIONFS_HAS_MS_OS_DESC |
2616                               FUNCTIONFS_VIRTUAL_ADDR |
2617                               FUNCTIONFS_EVENTFD)) {
2618                         ret = -ENOSYS;
2619                         goto error;
2620                 }
2621                 data += 12;
2622                 len  -= 12;
2623                 break;
2624         default:
2625                 goto error;
2626         }
2627
2628         if (flags & FUNCTIONFS_EVENTFD) {
2629                 if (len < 4)
2630                         goto error;
2631                 ffs->ffs_eventfd =
2632                         eventfd_ctx_fdget((int)get_unaligned_le32(data));
2633                 if (IS_ERR(ffs->ffs_eventfd)) {
2634                         ret = PTR_ERR(ffs->ffs_eventfd);
2635                         ffs->ffs_eventfd = NULL;
2636                         goto error;
2637                 }
2638                 data += 4;
2639                 len  -= 4;
2640         }
2641
2642         /* Read fs_count, hs_count and ss_count (if present) */
2643         for (i = 0; i < 3; ++i) {
2644                 if (!(flags & (1 << i))) {
2645                         counts[i] = 0;
2646                 } else if (len < 4) {
2647                         goto error;
2648                 } else {
2649                         counts[i] = get_unaligned_le32(data);
2650                         data += 4;
2651                         len  -= 4;
2652                 }
2653         }
2654         if (flags & (1 << i)) {
2655                 if (len < 4) {
2656                         goto error;
2657                 }
2658                 os_descs_count = get_unaligned_le32(data);
2659                 data += 4;
2660                 len -= 4;
2661         };
2662
2663         /* Read descriptors */
2664         raw_descs = data;
2665         helper.ffs = ffs;
2666         for (i = 0; i < 3; ++i) {
2667                 if (!counts[i])
2668                         continue;
2669                 helper.interfaces_count = 0;
2670                 helper.eps_count = 0;
2671                 ret = ffs_do_descs(counts[i], data, len,
2672                                    __ffs_data_do_entity, &helper);
2673                 if (ret < 0)
2674                         goto error;
2675                 if (!ffs->eps_count && !ffs->interfaces_count) {
2676                         ffs->eps_count = helper.eps_count;
2677                         ffs->interfaces_count = helper.interfaces_count;
2678                 } else {
2679                         if (ffs->eps_count != helper.eps_count) {
2680                                 ret = -EINVAL;
2681                                 goto error;
2682                         }
2683                         if (ffs->interfaces_count != helper.interfaces_count) {
2684                                 ret = -EINVAL;
2685                                 goto error;
2686                         }
2687                 }
2688                 data += ret;
2689                 len  -= ret;
2690         }
2691         if (os_descs_count) {
2692                 ret = ffs_do_os_descs(os_descs_count, data, len,
2693                                       __ffs_data_do_os_desc, ffs);
2694                 if (ret < 0)
2695                         goto error;
2696                 data += ret;
2697                 len -= ret;
2698         }
2699
2700         if (raw_descs == data || len) {
2701                 ret = -EINVAL;
2702                 goto error;
2703         }
2704
2705         ffs->raw_descs_data     = _data;
2706         ffs->raw_descs          = raw_descs;
2707         ffs->raw_descs_length   = data - raw_descs;
2708         ffs->fs_descs_count     = counts[0];
2709         ffs->hs_descs_count     = counts[1];
2710         ffs->ss_descs_count     = counts[2];
2711         ffs->ms_os_descs_count  = os_descs_count;
2712
2713         ffs_log("exit");
2714
2715         return 0;
2716
2717 error:
2718         kfree(_data);
2719         ffs_log("exit: ret %d", ret);
2720         return ret;
2721 }
2722
2723 static int __ffs_data_got_strings(struct ffs_data *ffs,
2724                                   char *const _data, size_t len)
2725 {
2726         u32 str_count, needed_count, lang_count;
2727         struct usb_gadget_strings **stringtabs, *t;
2728         struct usb_string *strings, *s;
2729         const char *data = _data;
2730
2731         ENTER();
2732
2733         ffs_log("enter: len %zu", len);
2734
2735         if (unlikely(len < 16 ||
2736                      get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2737                      get_unaligned_le32(data + 4) != len))
2738                 goto error;
2739         str_count  = get_unaligned_le32(data + 8);
2740         lang_count = get_unaligned_le32(data + 12);
2741
2742         /* if one is zero the other must be zero */
2743         if (unlikely(!str_count != !lang_count))
2744                 goto error;
2745
2746         /* Do we have at least as many strings as descriptors need? */
2747         needed_count = ffs->strings_count;
2748         if (unlikely(str_count < needed_count))
2749                 goto error;
2750
2751         /*
2752          * If we don't need any strings just return and free all
2753          * memory.
2754          */
2755         if (!needed_count) {
2756                 kfree(_data);
2757                 return 0;
2758         }
2759
2760         /* Allocate everything in one chunk so there's less maintenance. */
2761         {
2762                 unsigned i = 0;
2763                 vla_group(d);
2764                 vla_item(d, struct usb_gadget_strings *, stringtabs,
2765                         lang_count + 1);
2766                 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2767                 vla_item(d, struct usb_string, strings,
2768                         lang_count*(needed_count+1));
2769
2770                 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2771
2772                 if (unlikely(!vlabuf)) {
2773                         kfree(_data);
2774                         return -ENOMEM;
2775                 }
2776
2777                 /* Initialize the VLA pointers */
2778                 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2779                 t = vla_ptr(vlabuf, d, stringtab);
2780                 i = lang_count;
2781                 do {
2782                         *stringtabs++ = t++;
2783                 } while (--i);
2784                 *stringtabs = NULL;
2785
2786                 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2787                 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2788                 t = vla_ptr(vlabuf, d, stringtab);
2789                 s = vla_ptr(vlabuf, d, strings);
2790                 strings = s;
2791         }
2792
2793         /* For each language */
2794         data += 16;
2795         len -= 16;
2796
2797         do { /* lang_count > 0 so we can use do-while */
2798                 unsigned needed = needed_count;
2799
2800                 if (unlikely(len < 3))
2801                         goto error_free;
2802                 t->language = get_unaligned_le16(data);
2803                 t->strings  = s;
2804                 ++t;
2805
2806                 data += 2;
2807                 len -= 2;
2808
2809                 /* For each string */
2810                 do { /* str_count > 0 so we can use do-while */
2811                         size_t length = strnlen(data, len);
2812
2813                         if (unlikely(length == len))
2814                                 goto error_free;
2815
2816                         /*
2817                          * User may provide more strings then we need,
2818                          * if that's the case we simply ignore the
2819                          * rest
2820                          */
2821                         if (likely(needed)) {
2822                                 /*
2823                                  * s->id will be set while adding
2824                                  * function to configuration so for
2825                                  * now just leave garbage here.
2826                                  */
2827                                 s->s = data;
2828                                 --needed;
2829                                 ++s;
2830                         }
2831
2832                         data += length + 1;
2833                         len -= length + 1;
2834                 } while (--str_count);
2835
2836                 s->id = 0;   /* terminator */
2837                 s->s = NULL;
2838                 ++s;
2839
2840         } while (--lang_count);
2841
2842         /* Some garbage left? */
2843         if (unlikely(len))
2844                 goto error_free;
2845
2846         /* Done! */
2847         ffs->stringtabs = stringtabs;
2848         ffs->raw_strings = _data;
2849
2850         ffs_log("exit");
2851         return 0;
2852
2853 error_free:
2854         kfree(stringtabs);
2855 error:
2856         kfree(_data);
2857         ffs_log("exit: -EINVAL");
2858         return -EINVAL;
2859 }
2860
2861
2862 /* Events handling and management *******************************************/
2863
2864 static void __ffs_event_add(struct ffs_data *ffs,
2865                             enum usb_functionfs_event_type type)
2866 {
2867         enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2868         int neg = 0;
2869
2870         ffs_log("enter: type %d state %d setup_state %d flag %lu", type,
2871                 ffs->state, ffs->setup_state, ffs->flags);
2872
2873         /*
2874          * Abort any unhandled setup
2875          *
2876          * We do not need to worry about some cmpxchg() changing value
2877          * of ffs->setup_state without holding the lock because when
2878          * state is FFS_SETUP_PENDING cmpxchg() in several places in
2879          * the source does nothing.
2880          */
2881         if (ffs->setup_state == FFS_SETUP_PENDING)
2882                 ffs->setup_state = FFS_SETUP_CANCELLED;
2883
2884         /*
2885          * Logic of this function guarantees that there are at most four pending
2886          * evens on ffs->ev.types queue.  This is important because the queue
2887          * has space for four elements only and __ffs_ep0_read_events function
2888          * depends on that limit as well.  If more event types are added, those
2889          * limits have to be revisited or guaranteed to still hold.
2890          */
2891         switch (type) {
2892         case FUNCTIONFS_RESUME:
2893                 rem_type2 = FUNCTIONFS_SUSPEND;
2894                 /* FALL THROUGH */
2895         case FUNCTIONFS_SUSPEND:
2896         case FUNCTIONFS_SETUP:
2897                 rem_type1 = type;
2898                 /* Discard all similar events */
2899                 break;
2900
2901         case FUNCTIONFS_BIND:
2902         case FUNCTIONFS_UNBIND:
2903         case FUNCTIONFS_DISABLE:
2904         case FUNCTIONFS_ENABLE:
2905                 /* Discard everything other then power management. */
2906                 rem_type1 = FUNCTIONFS_SUSPEND;
2907                 rem_type2 = FUNCTIONFS_RESUME;
2908                 neg = 1;
2909                 break;
2910
2911         default:
2912                 WARN(1, "%d: unknown event, this should not happen\n", type);
2913                 return;
2914         }
2915
2916         {
2917                 u8 *ev  = ffs->ev.types, *out = ev;
2918                 unsigned n = ffs->ev.count;
2919                 for (; n; --n, ++ev)
2920                         if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2921                                 *out++ = *ev;
2922                         else
2923                                 pr_vdebug("purging event %d\n", *ev);
2924                 ffs->ev.count = out - ffs->ev.types;
2925         }
2926
2927         pr_vdebug("adding event %d\n", type);
2928         ffs->ev.types[ffs->ev.count++] = type;
2929         wake_up_locked(&ffs->ev.waitq);
2930         if (ffs->ffs_eventfd)
2931                 eventfd_signal(ffs->ffs_eventfd, 1);
2932
2933         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
2934                 ffs->setup_state, ffs->flags);
2935 }
2936
2937 static void ffs_event_add(struct ffs_data *ffs,
2938                           enum usb_functionfs_event_type type)
2939 {
2940         unsigned long flags;
2941         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2942         __ffs_event_add(ffs, type);
2943         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2944 }
2945
2946 /* Bind/unbind USB function hooks *******************************************/
2947
2948 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2949 {
2950         int i;
2951
2952         for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2953                 if (ffs->eps_addrmap[i] == endpoint_address)
2954                         return i;
2955         return -ENOENT;
2956 }
2957
2958 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2959                                     struct usb_descriptor_header *desc,
2960                                     void *priv)
2961 {
2962         struct usb_endpoint_descriptor *ds = (void *)desc;
2963         struct ffs_function *func = priv;
2964         struct ffs_ep *ffs_ep;
2965         unsigned ep_desc_id;
2966         int idx;
2967         static const char *speed_names[] = { "full", "high", "super" };
2968
2969         ffs_log("enter");
2970
2971         if (type != FFS_DESCRIPTOR)
2972                 return 0;
2973
2974         /*
2975          * If ss_descriptors is not NULL, we are reading super speed
2976          * descriptors; if hs_descriptors is not NULL, we are reading high
2977          * speed descriptors; otherwise, we are reading full speed
2978          * descriptors.
2979          */
2980         if (func->function.ss_descriptors) {
2981                 ep_desc_id = 2;
2982                 func->function.ss_descriptors[(long)valuep] = desc;
2983         } else if (func->function.hs_descriptors) {
2984                 ep_desc_id = 1;
2985                 func->function.hs_descriptors[(long)valuep] = desc;
2986         } else {
2987                 ep_desc_id = 0;
2988                 func->function.fs_descriptors[(long)valuep]    = desc;
2989         }
2990
2991         if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2992                 return 0;
2993
2994         idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2995         if (idx < 0)
2996                 return idx;
2997
2998         ffs_ep = func->eps + idx;
2999
3000         if (unlikely(ffs_ep->descs[ep_desc_id])) {
3001                 pr_err("two %sspeed descriptors for EP %d\n",
3002                           speed_names[ep_desc_id],
3003                           ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
3004                 return -EINVAL;
3005         }
3006         ffs_ep->descs[ep_desc_id] = ds;
3007
3008         ffs_dump_mem(": Original  ep desc", ds, ds->bLength);
3009         if (ffs_ep->ep) {
3010                 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
3011                 if (!ds->wMaxPacketSize)
3012                         ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
3013         } else {
3014                 struct usb_request *req;
3015                 struct usb_ep *ep;
3016                 u8 bEndpointAddress;
3017
3018                 /*
3019                  * We back up bEndpointAddress because autoconfig overwrites
3020                  * it with physical endpoint address.
3021                  */
3022                 bEndpointAddress = ds->bEndpointAddress;
3023                 pr_vdebug("autoconfig\n");
3024                 ep = usb_ep_autoconfig(func->gadget, ds);
3025                 if (unlikely(!ep))
3026                         return -ENOTSUPP;
3027                 ep->driver_data = func->eps + idx;
3028
3029                 req = usb_ep_alloc_request(ep, GFP_KERNEL);
3030                 if (unlikely(!req))
3031                         return -ENOMEM;
3032
3033                 ffs_ep->ep  = ep;
3034                 ffs_ep->req = req;
3035                 func->eps_revmap[ds->bEndpointAddress &
3036                                  USB_ENDPOINT_NUMBER_MASK] = idx + 1;
3037                 /*
3038                  * If we use virtual address mapping, we restore
3039                  * original bEndpointAddress value.
3040                  */
3041                 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3042                         ds->bEndpointAddress = bEndpointAddress;
3043         }
3044         ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
3045
3046         ffs_log("exit");
3047
3048         return 0;
3049 }
3050
3051 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
3052                                    struct usb_descriptor_header *desc,
3053                                    void *priv)
3054 {
3055         struct ffs_function *func = priv;
3056         unsigned idx;
3057         u8 newValue;
3058
3059         ffs_log("enter: type %d", type);
3060
3061         switch (type) {
3062         default:
3063         case FFS_DESCRIPTOR:
3064                 /* Handled in previous pass by __ffs_func_bind_do_descs() */
3065                 return 0;
3066
3067         case FFS_INTERFACE:
3068                 idx = *valuep;
3069                 if (func->interfaces_nums[idx] < 0) {
3070                         int id = usb_interface_id(func->conf, &func->function);
3071                         if (unlikely(id < 0))
3072                                 return id;
3073                         func->interfaces_nums[idx] = id;
3074                 }
3075                 newValue = func->interfaces_nums[idx];
3076                 break;
3077
3078         case FFS_STRING:
3079                 /* String' IDs are allocated when fsf_data is bound to cdev */
3080                 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
3081                 break;
3082
3083         case FFS_ENDPOINT:
3084                 /*
3085                  * USB_DT_ENDPOINT are handled in
3086                  * __ffs_func_bind_do_descs().
3087                  */
3088                 if (desc->bDescriptorType == USB_DT_ENDPOINT)
3089                         return 0;
3090
3091                 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
3092                 if (unlikely(!func->eps[idx].ep))
3093                         return -EINVAL;
3094
3095                 {
3096                         struct usb_endpoint_descriptor **descs;
3097                         descs = func->eps[idx].descs;
3098                         newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
3099                 }
3100                 break;
3101         }
3102
3103         pr_vdebug("%02x -> %02x\n", *valuep, newValue);
3104         *valuep = newValue;
3105
3106         ffs_log("exit: newValue %d", newValue);
3107
3108         return 0;
3109 }
3110
3111 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
3112                                       struct usb_os_desc_header *h, void *data,
3113                                       unsigned len, void *priv)
3114 {
3115         struct ffs_function *func = priv;
3116         u8 length = 0;
3117
3118         ffs_log("enter: type %d", type);
3119
3120         switch (type) {
3121         case FFS_OS_DESC_EXT_COMPAT: {
3122                 struct usb_ext_compat_desc *desc = data;
3123                 struct usb_os_desc_table *t;
3124
3125                 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
3126                 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
3127                 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
3128                        ARRAY_SIZE(desc->CompatibleID) +
3129                        ARRAY_SIZE(desc->SubCompatibleID));
3130                 length = sizeof(*desc);
3131         }
3132                 break;
3133         case FFS_OS_DESC_EXT_PROP: {
3134                 struct usb_ext_prop_desc *desc = data;
3135                 struct usb_os_desc_table *t;
3136                 struct usb_os_desc_ext_prop *ext_prop;
3137                 char *ext_prop_name;
3138                 char *ext_prop_data;
3139
3140                 t = &func->function.os_desc_table[h->interface];
3141                 t->if_id = func->interfaces_nums[h->interface];
3142
3143                 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
3144                 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
3145
3146                 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
3147                 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
3148                 ext_prop->data_len = le32_to_cpu(*(u32 *)
3149                         usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
3150                 length = ext_prop->name_len + ext_prop->data_len + 14;
3151
3152                 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
3153                 func->ffs->ms_os_descs_ext_prop_name_avail +=
3154                         ext_prop->name_len;
3155
3156                 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
3157                 func->ffs->ms_os_descs_ext_prop_data_avail +=
3158                         ext_prop->data_len;
3159                 memcpy(ext_prop_data,
3160                        usb_ext_prop_data_ptr(data, ext_prop->name_len),
3161                        ext_prop->data_len);
3162                 /* unicode data reported to the host as "WCHAR"s */
3163                 switch (ext_prop->type) {
3164                 case USB_EXT_PROP_UNICODE:
3165                 case USB_EXT_PROP_UNICODE_ENV:
3166                 case USB_EXT_PROP_UNICODE_LINK:
3167                 case USB_EXT_PROP_UNICODE_MULTI:
3168                         ext_prop->data_len *= 2;
3169                         break;
3170                 }
3171                 ext_prop->data = ext_prop_data;
3172
3173                 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
3174                        ext_prop->name_len);
3175                 /* property name reported to the host as "WCHAR"s */
3176                 ext_prop->name_len *= 2;
3177                 ext_prop->name = ext_prop_name;
3178
3179                 t->os_desc->ext_prop_len +=
3180                         ext_prop->name_len + ext_prop->data_len + 14;
3181                 ++t->os_desc->ext_prop_count;
3182                 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
3183         }
3184                 break;
3185         default:
3186                 pr_vdebug("unknown descriptor: %d\n", type);
3187         }
3188
3189         ffs_log("exit");
3190
3191         return length;
3192 }
3193
3194 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
3195                                                 struct usb_configuration *c)
3196 {
3197         struct ffs_function *func = ffs_func_from_usb(f);
3198         struct f_fs_opts *ffs_opts =
3199                 container_of(f->fi, struct f_fs_opts, func_inst);
3200         int ret;
3201
3202         ENTER();
3203
3204         ffs_log("enter");
3205
3206         /*
3207          * Legacy gadget triggers binding in functionfs_ready_callback,
3208          * which already uses locking; taking the same lock here would
3209          * cause a deadlock.
3210          *
3211          * Configfs-enabled gadgets however do need ffs_dev_lock.
3212          */
3213         if (!ffs_opts->no_configfs)
3214                 ffs_dev_lock();
3215         ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
3216         func->ffs = ffs_opts->dev->ffs_data;
3217         if (!ffs_opts->no_configfs)
3218                 ffs_dev_unlock();
3219         if (ret)
3220                 return ERR_PTR(ret);
3221
3222         func->conf = c;
3223         func->gadget = c->cdev->gadget;
3224
3225         /*
3226          * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
3227          * configurations are bound in sequence with list_for_each_entry,
3228          * in each configuration its functions are bound in sequence
3229          * with list_for_each_entry, so we assume no race condition
3230          * with regard to ffs_opts->bound access
3231          */
3232         if (!ffs_opts->refcnt) {
3233                 ret = functionfs_bind(func->ffs, c->cdev);
3234                 if (ret)
3235                         return ERR_PTR(ret);
3236         }
3237         ffs_opts->refcnt++;
3238         func->function.strings = func->ffs->stringtabs;
3239
3240         ffs_log("exit");
3241
3242         return ffs_opts;
3243 }
3244
3245 static int _ffs_func_bind(struct usb_configuration *c,
3246                           struct usb_function *f)
3247 {
3248         struct ffs_function *func = ffs_func_from_usb(f);
3249         struct ffs_data *ffs = func->ffs;
3250
3251         const int full = !!func->ffs->fs_descs_count;
3252         const int high = !!func->ffs->hs_descs_count;
3253         const int super = !!func->ffs->ss_descs_count;
3254
3255         int fs_len, hs_len, ss_len, ret, i;
3256         struct ffs_ep *eps_ptr;
3257
3258         /* Make it a single chunk, less management later on */
3259         vla_group(d);
3260         vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
3261         vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
3262                 full ? ffs->fs_descs_count + 1 : 0);
3263         vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
3264                 high ? ffs->hs_descs_count + 1 : 0);
3265         vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
3266                 super ? ffs->ss_descs_count + 1 : 0);
3267         vla_item_with_sz(d, short, inums, ffs->interfaces_count);
3268         vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
3269                          c->cdev->use_os_string ? ffs->interfaces_count : 0);
3270         vla_item_with_sz(d, char[16], ext_compat,
3271                          c->cdev->use_os_string ? ffs->interfaces_count : 0);
3272         vla_item_with_sz(d, struct usb_os_desc, os_desc,
3273                          c->cdev->use_os_string ? ffs->interfaces_count : 0);
3274         vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
3275                          ffs->ms_os_descs_ext_prop_count);
3276         vla_item_with_sz(d, char, ext_prop_name,
3277                          ffs->ms_os_descs_ext_prop_name_len);
3278         vla_item_with_sz(d, char, ext_prop_data,
3279                          ffs->ms_os_descs_ext_prop_data_len);
3280         vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
3281         char *vlabuf;
3282
3283         ENTER();
3284
3285         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
3286                 ffs->setup_state, ffs->flags);
3287
3288         /* Has descriptors only for speeds gadget does not support */
3289         if (unlikely(!(full | high | super)))
3290                 return -ENOTSUPP;
3291
3292         /* Allocate a single chunk, less management later on */
3293         vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
3294         if (unlikely(!vlabuf))
3295                 return -ENOMEM;
3296
3297         ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
3298         ffs->ms_os_descs_ext_prop_name_avail =
3299                 vla_ptr(vlabuf, d, ext_prop_name);
3300         ffs->ms_os_descs_ext_prop_data_avail =
3301                 vla_ptr(vlabuf, d, ext_prop_data);
3302
3303         /* Copy descriptors  */
3304         memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
3305                ffs->raw_descs_length);
3306
3307         memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
3308         eps_ptr = vla_ptr(vlabuf, d, eps);
3309         for (i = 0; i < ffs->eps_count; i++)
3310                 eps_ptr[i].num = -1;
3311
3312         /* Save pointers
3313          * d_eps == vlabuf, func->eps used to kfree vlabuf later
3314         */
3315         func->eps             = vla_ptr(vlabuf, d, eps);
3316         func->interfaces_nums = vla_ptr(vlabuf, d, inums);
3317
3318         /*
3319          * Go through all the endpoint descriptors and allocate
3320          * endpoints first, so that later we can rewrite the endpoint
3321          * numbers without worrying that it may be described later on.
3322          */
3323         if (likely(full)) {
3324                 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
3325                 fs_len = ffs_do_descs(ffs->fs_descs_count,
3326                                       vla_ptr(vlabuf, d, raw_descs),
3327                                       d_raw_descs__sz,
3328                                       __ffs_func_bind_do_descs, func);
3329                 if (unlikely(fs_len < 0)) {
3330                         ret = fs_len;
3331                         goto error;
3332                 }
3333         } else {
3334                 fs_len = 0;
3335         }
3336
3337         if (likely(high)) {
3338                 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
3339                 hs_len = ffs_do_descs(ffs->hs_descs_count,
3340                                       vla_ptr(vlabuf, d, raw_descs) + fs_len,
3341                                       d_raw_descs__sz - fs_len,
3342                                       __ffs_func_bind_do_descs, func);
3343                 if (unlikely(hs_len < 0)) {
3344                         ret = hs_len;
3345                         goto error;
3346                 }
3347         } else {
3348                 hs_len = 0;
3349         }
3350
3351         if (likely(super)) {
3352                 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
3353                 ss_len = ffs_do_descs(ffs->ss_descs_count,
3354                                 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
3355                                 d_raw_descs__sz - fs_len - hs_len,
3356                                 __ffs_func_bind_do_descs, func);
3357                 if (unlikely(ss_len < 0)) {
3358                         ret = ss_len;
3359                         goto error;
3360                 }
3361         } else {
3362                 ss_len = 0;
3363         }
3364
3365         /*
3366          * Now handle interface numbers allocation and interface and
3367          * endpoint numbers rewriting.  We can do that in one go
3368          * now.
3369          */
3370         ret = ffs_do_descs(ffs->fs_descs_count +
3371                            (high ? ffs->hs_descs_count : 0) +
3372                            (super ? ffs->ss_descs_count : 0),
3373                            vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
3374                            __ffs_func_bind_do_nums, func);
3375         if (unlikely(ret < 0))
3376                 goto error;
3377
3378         func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
3379         if (c->cdev->use_os_string) {
3380                 for (i = 0; i < ffs->interfaces_count; ++i) {
3381                         struct usb_os_desc *desc;
3382
3383                         desc = func->function.os_desc_table[i].os_desc =
3384                                 vla_ptr(vlabuf, d, os_desc) +
3385                                 i * sizeof(struct usb_os_desc);
3386                         desc->ext_compat_id =
3387                                 vla_ptr(vlabuf, d, ext_compat) + i * 16;
3388                         INIT_LIST_HEAD(&desc->ext_prop);
3389                 }
3390                 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
3391                                       vla_ptr(vlabuf, d, raw_descs) +
3392                                       fs_len + hs_len + ss_len,
3393                                       d_raw_descs__sz - fs_len - hs_len -
3394                                       ss_len,
3395                                       __ffs_func_bind_do_os_desc, func);
3396                 if (unlikely(ret < 0))
3397                         goto error;
3398         }
3399         func->function.os_desc_n =
3400                 c->cdev->use_os_string ? ffs->interfaces_count : 0;
3401
3402         /* And we're done */
3403         ffs_event_add(ffs, FUNCTIONFS_BIND);
3404
3405         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
3406                 ffs->setup_state, ffs->flags);
3407
3408         return 0;
3409
3410 error:
3411         /* XXX Do we need to release all claimed endpoints here? */
3412         ffs_log("exit: ret %d", ret);
3413         return ret;
3414 }
3415
3416 static int ffs_func_bind(struct usb_configuration *c,
3417                          struct usb_function *f)
3418 {
3419         struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
3420         struct ffs_function *func = ffs_func_from_usb(f);
3421         int ret;
3422
3423         ffs_log("enter");
3424
3425         if (IS_ERR(ffs_opts))
3426                 return PTR_ERR(ffs_opts);
3427
3428         ret = _ffs_func_bind(c, f);
3429         if (ret && !--ffs_opts->refcnt)
3430                 functionfs_unbind(func->ffs);
3431
3432         ffs_log("exit: ret %d", ret);
3433
3434         return ret;
3435 }
3436
3437
3438 /* Other USB function hooks *************************************************/
3439
3440 static void ffs_reset_work(struct work_struct *work)
3441 {
3442         struct ffs_data *ffs = container_of(work,
3443                 struct ffs_data, reset_work);
3444
3445         ffs_log("enter");
3446
3447         ffs_data_reset(ffs);
3448
3449         ffs_log("exit");
3450 }
3451
3452 static int ffs_func_set_alt(struct usb_function *f,
3453                             unsigned interface, unsigned alt)
3454 {
3455         struct ffs_function *func = ffs_func_from_usb(f);
3456         struct ffs_data *ffs = func->ffs;
3457         int ret = 0, intf;
3458
3459         ffs_log("enter");
3460
3461         if (alt != (unsigned)-1) {
3462                 intf = ffs_func_revmap_intf(func, interface);
3463                 if (unlikely(intf < 0))
3464                         return intf;
3465         }
3466
3467         if (ffs->func) {
3468                 ffs_func_eps_disable(ffs->func);
3469                 ffs->func = NULL;
3470                 /* matching put to allow LPM on disconnect */
3471                 usb_gadget_autopm_put_async(ffs->gadget);
3472         }
3473
3474         if (ffs->state == FFS_DEACTIVATED) {
3475                 ffs->state = FFS_CLOSING;
3476                 INIT_WORK(&ffs->reset_work, ffs_reset_work);
3477                 schedule_work(&ffs->reset_work);
3478                 return -ENODEV;
3479         }
3480
3481         if (ffs->state != FFS_ACTIVE)
3482                 return -ENODEV;
3483
3484         if (alt == (unsigned)-1) {
3485                 ffs->func = NULL;
3486                 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
3487                 return 0;
3488         }
3489
3490         ffs->func = func;
3491         ret = ffs_func_eps_enable(func);
3492         if (likely(ret >= 0)) {
3493                 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
3494                 /* Disable USB LPM later on bus_suspend */
3495                 usb_gadget_autopm_get_async(ffs->gadget);
3496         }
3497
3498         ffs_log("exit: ret %d", ret);
3499
3500         return ret;
3501 }
3502
3503 static void ffs_func_disable(struct usb_function *f)
3504 {
3505         ffs_log("enter");
3506
3507         ffs_func_set_alt(f, 0, (unsigned)-1);
3508
3509         ffs_log("exit");
3510 }
3511
3512 static int ffs_func_setup(struct usb_function *f,
3513                           const struct usb_ctrlrequest *creq)
3514 {
3515         struct ffs_function *func = ffs_func_from_usb(f);
3516         struct ffs_data *ffs = func->ffs;
3517         unsigned long flags;
3518         int ret;
3519
3520         ENTER();
3521
3522         ffs_log("enter");
3523
3524         pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
3525         pr_vdebug("creq->bRequest     = %02x\n", creq->bRequest);
3526         pr_vdebug("creq->wValue       = %04x\n", le16_to_cpu(creq->wValue));
3527         pr_vdebug("creq->wIndex       = %04x\n", le16_to_cpu(creq->wIndex));
3528         pr_vdebug("creq->wLength      = %04x\n", le16_to_cpu(creq->wLength));
3529
3530         /*
3531          * Most requests directed to interface go through here
3532          * (notable exceptions are set/get interface) so we need to
3533          * handle them.  All other either handled by composite or
3534          * passed to usb_configuration->setup() (if one is set).  No
3535          * matter, we will handle requests directed to endpoint here
3536          * as well (as it's straightforward) but what to do with any
3537          * other request?
3538          */
3539         if (ffs->state != FFS_ACTIVE)
3540                 return -ENODEV;
3541
3542         switch (creq->bRequestType & USB_RECIP_MASK) {
3543         case USB_RECIP_INTERFACE:
3544                 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
3545                 if (unlikely(ret < 0))
3546                         return ret;
3547                 break;
3548
3549         case USB_RECIP_ENDPOINT:
3550                 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
3551                 if (unlikely(ret < 0))
3552                         return ret;
3553                 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3554                         ret = func->ffs->eps_addrmap[ret];
3555                 break;
3556
3557         default:
3558                 return -EOPNOTSUPP;
3559         }
3560
3561         spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
3562         ffs->ev.setup = *creq;
3563         ffs->ev.setup.wIndex = cpu_to_le16(ret);
3564         __ffs_event_add(ffs, FUNCTIONFS_SETUP);
3565         spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
3566
3567         ffs_log("exit");
3568
3569         return creq->wLength == 0 ? USB_GADGET_DELAYED_STATUS : 0;
3570 }
3571
3572 static void ffs_func_suspend(struct usb_function *f)
3573 {
3574         ENTER();
3575
3576         ffs_log("enter");
3577
3578         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
3579
3580         ffs_log("exit");
3581 }
3582
3583 static void ffs_func_resume(struct usb_function *f)
3584 {
3585         ENTER();
3586
3587         ffs_log("enter");
3588
3589         ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
3590
3591         ffs_log("exit");
3592 }
3593
3594
3595 /* Endpoint and interface numbers reverse mapping ***************************/
3596
3597 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
3598 {
3599         num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
3600         return num ? num : -EDOM;
3601 }
3602
3603 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
3604 {
3605         short *nums = func->interfaces_nums;
3606         unsigned count = func->ffs->interfaces_count;
3607
3608         ffs_log("enter");
3609
3610         for (; count; --count, ++nums) {
3611                 if (*nums >= 0 && *nums == intf)
3612                         return nums - func->interfaces_nums;
3613         }
3614
3615         ffs_log("exit");
3616
3617         return -EDOM;
3618 }
3619
3620
3621 /* Devices management *******************************************************/
3622
3623 static LIST_HEAD(ffs_devices);
3624
3625 static struct ffs_dev *_ffs_do_find_dev(const char *name)
3626 {
3627         struct ffs_dev *dev;
3628
3629         ffs_log("enter");
3630
3631         list_for_each_entry(dev, &ffs_devices, entry) {
3632                 if (!dev->name || !name)
3633                         continue;
3634                 if (strcmp(dev->name, name) == 0)
3635                         return dev;
3636         }
3637
3638         ffs_log("exit");
3639
3640         return NULL;
3641 }
3642
3643 /*
3644  * ffs_lock must be taken by the caller of this function
3645  */
3646 static struct ffs_dev *_ffs_get_single_dev(void)
3647 {
3648         struct ffs_dev *dev;
3649
3650         ffs_log("enter");
3651
3652         if (list_is_singular(&ffs_devices)) {
3653                 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3654                 if (dev->single)
3655                         return dev;
3656         }
3657
3658         ffs_log("exit");
3659
3660         return NULL;
3661 }
3662
3663 /*
3664  * ffs_lock must be taken by the caller of this function
3665  */
3666 static struct ffs_dev *_ffs_find_dev(const char *name)
3667 {
3668         struct ffs_dev *dev;
3669
3670         ffs_log("enter");
3671
3672         dev = _ffs_get_single_dev();
3673         if (dev)
3674                 return dev;
3675
3676         dev = _ffs_do_find_dev(name);
3677
3678         ffs_log("exit");
3679
3680         return dev;
3681 }
3682
3683 /* Configfs support *********************************************************/
3684
3685 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3686 {
3687         return container_of(to_config_group(item), struct f_fs_opts,
3688                             func_inst.group);
3689 }
3690
3691 static void ffs_attr_release(struct config_item *item)
3692 {
3693         struct f_fs_opts *opts = to_ffs_opts(item);
3694
3695         usb_put_function_instance(&opts->func_inst);
3696 }
3697
3698 static struct configfs_item_operations ffs_item_ops = {
3699         .release        = ffs_attr_release,
3700 };
3701
3702 static struct config_item_type ffs_func_type = {
3703         .ct_item_ops    = &ffs_item_ops,
3704         .ct_owner       = THIS_MODULE,
3705 };
3706
3707
3708 /* Function registration interface ******************************************/
3709
3710 static struct ffs_inst_status *name_to_inst_status(
3711                 const char *inst_name, bool create_inst)
3712 {
3713         struct ffs_inst_status *inst_status;
3714
3715         list_for_each_entry(inst_status, &inst_list, list) {
3716                 if (!strncasecmp(inst_status->inst_name,
3717                                         inst_name, strlen(inst_name)))
3718                         return inst_status;
3719         }
3720
3721         if (!create_inst)
3722                 return ERR_PTR(-ENODEV);
3723
3724         inst_status = kzalloc(sizeof(struct ffs_inst_status),
3725                                         GFP_KERNEL);
3726         if (!inst_status)
3727                 return ERR_PTR(-ENOMEM);
3728
3729         mutex_init(&inst_status->ffs_lock);
3730         snprintf(inst_status->inst_name, INST_NAME_SIZE, inst_name);
3731         list_add_tail(&inst_status->list, &inst_list);
3732
3733         return inst_status;
3734 }
3735
3736 static int ffs_inst_exist_check(const char *inst_name)
3737 {
3738         struct ffs_inst_status *inst_status;
3739
3740         inst_status = name_to_inst_status(inst_name, false);
3741         if (IS_ERR(inst_status)) {
3742                 pr_err_ratelimited(
3743                                 "%s: failed to find instance (%s)\n",
3744                                 __func__, inst_name);
3745                 return -ENODEV;
3746         }
3747
3748         mutex_lock(&inst_status->ffs_lock);
3749
3750         if (unlikely(inst_status->inst_exist == false)) {
3751                 mutex_unlock(&inst_status->ffs_lock);
3752                 pr_err_ratelimited(
3753                                 "%s: f_fs instance (%s) has been freed already.\n",
3754                                 __func__, inst_name);
3755                 return -ENODEV;
3756         }
3757
3758         mutex_unlock(&inst_status->ffs_lock);
3759
3760         return 0;
3761 }
3762
3763 static void ffs_inst_clean(struct f_fs_opts *opts,
3764                 const char *inst_name)
3765 {
3766         struct ffs_inst_status *inst_status;
3767
3768         inst_status = name_to_inst_status(inst_name, false);
3769         if (IS_ERR(inst_status)) {
3770                 pr_err_ratelimited(
3771                                 "%s: failed to find instance (%s)\n",
3772                                 __func__, inst_name);
3773                 return;
3774         }
3775
3776         inst_status->opts = NULL;
3777
3778         ffs_dev_lock();
3779         _ffs_free_dev(opts->dev);
3780         ffs_dev_unlock();
3781         kfree(opts);
3782 }
3783
3784 static void ffs_inst_clean_delay(const char *inst_name)
3785 {
3786         struct ffs_inst_status *inst_status;
3787
3788         inst_status = name_to_inst_status(inst_name, false);
3789         if (IS_ERR(inst_status)) {
3790                 pr_err_ratelimited(
3791                                 "%s: failed to find (%s) instance\n",
3792                                 __func__, inst_name);
3793                 return;
3794         }
3795
3796         mutex_lock(&inst_status->ffs_lock);
3797
3798         if (unlikely(inst_status->inst_exist == false)) {
3799                 if (inst_status->opts) {
3800                         ffs_inst_clean(inst_status->opts, inst_name);
3801                         pr_err_ratelimited("%s: Delayed free memory\n",
3802                                         __func__);
3803                 }
3804                 mutex_unlock(&inst_status->ffs_lock);
3805                 return;
3806         }
3807
3808         mutex_unlock(&inst_status->ffs_lock);
3809 }
3810
3811 static void ffs_free_inst(struct usb_function_instance *f)
3812 {
3813         struct f_fs_opts *opts;
3814         struct ffs_inst_status *inst_status;
3815
3816         opts = to_f_fs_opts(f);
3817
3818         inst_status = name_to_inst_status(opts->dev->name, false);
3819         if (IS_ERR(inst_status)) {
3820                 ffs_log("failed to find (%s) instance\n",
3821                                 opts->dev->name);
3822                 return;
3823         }
3824
3825         mutex_lock(&inst_status->ffs_lock);
3826         if (opts->dev->ffs_data
3827                         && atomic_read(&opts->dev->ffs_data->opened)) {
3828                 inst_status->inst_exist = false;
3829                 mutex_unlock(&inst_status->ffs_lock);
3830                 ffs_log("Dev is open, free mem when dev (%s) close\n",
3831                                 opts->dev->name);
3832                 return;
3833         }
3834
3835         ffs_inst_clean(opts, opts->dev->name);
3836         inst_status->inst_exist = false;
3837         mutex_unlock(&inst_status->ffs_lock);
3838 }
3839
3840 #define MAX_INST_NAME_LEN       40
3841
3842 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3843 {
3844         struct f_fs_opts *opts, *opts_prev;
3845         struct ffs_data *ffs_data_tmp;
3846         char *ptr;
3847         const char *tmp;
3848         int name_len, ret;
3849         struct ffs_inst_status *inst_status;
3850
3851         name_len = strlen(name) + 1;
3852         if (name_len > MAX_INST_NAME_LEN)
3853                 return -ENAMETOOLONG;
3854
3855         ptr = kstrndup(name, name_len, GFP_KERNEL);
3856         if (!ptr)
3857                 return -ENOMEM;
3858
3859         inst_status = name_to_inst_status(ptr, true);
3860         if (IS_ERR(inst_status)) {
3861                 ffs_log("failed to create status struct for (%s) instance\n",
3862                                 ptr);
3863                 return -EINVAL;
3864         }
3865
3866         mutex_lock(&inst_status->ffs_lock);
3867         opts_prev = inst_status->opts;
3868         if (opts_prev) {
3869                 mutex_unlock(&inst_status->ffs_lock);
3870                 ffs_log("instance (%s): prev inst do not freed yet\n",
3871                                 inst_status->inst_name);
3872                 return -EBUSY;
3873         }
3874         mutex_unlock(&inst_status->ffs_lock);
3875
3876         opts = to_f_fs_opts(fi);
3877         tmp = NULL;
3878
3879         ffs_dev_lock();
3880
3881         tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3882         ret = _ffs_name_dev(opts->dev, ptr);
3883         if (ret) {
3884                 kfree(ptr);
3885                 ffs_dev_unlock();
3886                 return ret;
3887         }
3888         opts->dev->name_allocated = true;
3889
3890         /*
3891          * If ffs instance is freed and created once, new allocated
3892          * opts->dev need to initialize opts->dev->ffs_data, and
3893          * ffs_private_data also need to update new allocated opts->dev
3894          * address.
3895          */
3896         ffs_data_tmp = inst_status->ffs_data;
3897         if (ffs_data_tmp)
3898                 opts->dev->ffs_data = ffs_data_tmp;
3899
3900         if (opts->dev->ffs_data)
3901                 opts->dev->ffs_data->private_data = opts->dev;
3902
3903         ffs_dev_unlock();
3904
3905         kfree(tmp);
3906
3907         mutex_lock(&inst_status->ffs_lock);
3908         inst_status->inst_exist = true;
3909         inst_status->opts = opts;
3910         mutex_unlock(&inst_status->ffs_lock);
3911
3912         return 0;
3913 }
3914
3915 static struct usb_function_instance *ffs_alloc_inst(void)
3916 {
3917         struct f_fs_opts *opts;
3918         struct ffs_dev *dev;
3919
3920         opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3921         if (!opts)
3922                 return ERR_PTR(-ENOMEM);
3923
3924         opts->func_inst.set_inst_name = ffs_set_inst_name;
3925         opts->func_inst.free_func_inst = ffs_free_inst;
3926         ffs_dev_lock();
3927         dev = _ffs_alloc_dev();
3928         ffs_dev_unlock();
3929         if (IS_ERR(dev)) {
3930                 kfree(opts);
3931                 return ERR_CAST(dev);
3932         }
3933         opts->dev = dev;
3934         dev->opts = opts;
3935
3936         config_group_init_type_name(&opts->func_inst.group, "",
3937                                     &ffs_func_type);
3938         return &opts->func_inst;
3939 }
3940
3941 static void ffs_free(struct usb_function *f)
3942 {
3943         kfree(ffs_func_from_usb(f));
3944 }
3945
3946 static void ffs_func_unbind(struct usb_configuration *c,
3947                             struct usb_function *f)
3948 {
3949         struct ffs_function *func = ffs_func_from_usb(f);
3950         struct ffs_data *ffs = func->ffs;
3951         struct f_fs_opts *opts =
3952                 container_of(f->fi, struct f_fs_opts, func_inst);
3953         struct ffs_ep *ep = func->eps;
3954         unsigned count = ffs->eps_count;
3955         unsigned long flags;
3956
3957         ENTER();
3958
3959         ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
3960                 ffs->setup_state, ffs->flags);
3961
3962         if (ffs->func == func) {
3963                 ffs_func_eps_disable(func);
3964                 ffs->func = NULL;
3965         }
3966
3967         if (!--opts->refcnt)
3968                 functionfs_unbind(ffs);
3969
3970         /* cleanup after autoconfig */
3971         spin_lock_irqsave(&func->ffs->eps_lock, flags);
3972         do {
3973                 if (ep->ep && ep->req)
3974                         usb_ep_free_request(ep->ep, ep->req);
3975                 ep->req = NULL;
3976                 ep->ep = NULL;
3977                 ++ep;
3978         } while (--count);
3979         spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3980         kfree(func->eps);
3981         func->eps = NULL;
3982         /*
3983          * eps, descriptors and interfaces_nums are allocated in the
3984          * same chunk so only one free is required.
3985          */
3986         func->function.fs_descriptors = NULL;
3987         func->function.hs_descriptors = NULL;
3988         func->function.ss_descriptors = NULL;
3989         func->interfaces_nums = NULL;
3990
3991         ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3992
3993         ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
3994         ffs->setup_state, ffs->flags);
3995 }
3996
3997 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3998 {
3999         struct ffs_function *func;
4000
4001         ENTER();
4002
4003         func = kzalloc(sizeof(*func), GFP_KERNEL);
4004         if (unlikely(!func))
4005                 return ERR_PTR(-ENOMEM);
4006
4007         func->function.name    = "Function FS Gadget";
4008
4009         func->function.bind    = ffs_func_bind;
4010         func->function.unbind  = ffs_func_unbind;
4011         func->function.set_alt = ffs_func_set_alt;
4012         func->function.disable = ffs_func_disable;
4013         func->function.setup   = ffs_func_setup;
4014         func->function.suspend = ffs_func_suspend;
4015         func->function.resume  = ffs_func_resume;
4016         func->function.free_func = ffs_free;
4017
4018         return &func->function;
4019 }
4020
4021 /*
4022  * ffs_lock must be taken by the caller of this function
4023  */
4024 static struct ffs_dev *_ffs_alloc_dev(void)
4025 {
4026         struct ffs_dev *dev;
4027         int ret;
4028
4029         if (_ffs_get_single_dev())
4030                         return ERR_PTR(-EBUSY);
4031
4032         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
4033         if (!dev)
4034                 return ERR_PTR(-ENOMEM);
4035
4036         if (list_empty(&ffs_devices)) {
4037                 ret = functionfs_init();
4038                 if (ret) {
4039                         kfree(dev);
4040                         return ERR_PTR(ret);
4041                 }
4042         }
4043
4044         list_add(&dev->entry, &ffs_devices);
4045
4046         return dev;
4047 }
4048
4049 /*
4050  * ffs_lock must be taken by the caller of this function
4051  * The caller is responsible for "name" being available whenever f_fs needs it
4052  */
4053 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
4054 {
4055         struct ffs_dev *existing;
4056
4057         ffs_log("enter");
4058
4059         existing = _ffs_do_find_dev(name);
4060         if (existing)
4061                 return -EBUSY;
4062
4063         dev->name = name;
4064
4065         ffs_log("exit");
4066
4067         return 0;
4068 }
4069
4070 /*
4071  * The caller is responsible for "name" being available whenever f_fs needs it
4072  */
4073 int ffs_name_dev(struct ffs_dev *dev, const char *name)
4074 {
4075         int ret;
4076
4077         ffs_log("enter");
4078
4079         ffs_dev_lock();
4080         ret = _ffs_name_dev(dev, name);
4081         ffs_dev_unlock();
4082
4083         ffs_log("exit");
4084
4085         return ret;
4086 }
4087 EXPORT_SYMBOL_GPL(ffs_name_dev);
4088
4089 int ffs_single_dev(struct ffs_dev *dev)
4090 {
4091         int ret;
4092
4093         ffs_log("enter");
4094
4095         ret = 0;
4096         ffs_dev_lock();
4097
4098         if (!list_is_singular(&ffs_devices))
4099                 ret = -EBUSY;
4100         else
4101                 dev->single = true;
4102
4103         ffs_dev_unlock();
4104
4105         ffs_log("exit");
4106
4107         return ret;
4108 }
4109 EXPORT_SYMBOL_GPL(ffs_single_dev);
4110
4111 /*
4112  * ffs_lock must be taken by the caller of this function
4113  */
4114 static void _ffs_free_dev(struct ffs_dev *dev)
4115 {
4116
4117         ffs_log("enter");
4118
4119         list_del(&dev->entry);
4120         if (dev->name_allocated)
4121                 kfree(dev->name);
4122         kfree(dev);
4123         if (list_empty(&ffs_devices))
4124                 functionfs_cleanup();
4125
4126         ffs_log("exit");
4127 }
4128
4129 static void *ffs_acquire_dev(const char *dev_name)
4130 {
4131         struct ffs_dev *ffs_dev;
4132
4133         ENTER();
4134
4135         ffs_log("enter");
4136
4137         ffs_dev_lock();
4138
4139         ffs_dev = _ffs_find_dev(dev_name);
4140         if (!ffs_dev)
4141                 ffs_dev = ERR_PTR(-ENOENT);
4142         else if (ffs_dev->mounted)
4143                 ffs_dev = ERR_PTR(-EBUSY);
4144         else if (ffs_dev->ffs_acquire_dev_callback &&
4145             ffs_dev->ffs_acquire_dev_callback(ffs_dev))
4146                 ffs_dev = ERR_PTR(-ENOENT);
4147         else
4148                 ffs_dev->mounted = true;
4149
4150         ffs_dev_unlock();
4151
4152         ffs_log("exit");
4153
4154         return ffs_dev;
4155 }
4156
4157 static void ffs_release_dev(struct ffs_data *ffs_data)
4158 {
4159         struct ffs_dev *ffs_dev;
4160
4161         ENTER();
4162
4163         ffs_log("enter");
4164
4165         ffs_dev_lock();
4166
4167         ffs_dev = ffs_data->private_data;
4168         if (ffs_dev) {
4169                 ffs_dev->mounted = false;
4170
4171                 if (ffs_dev->ffs_release_dev_callback)
4172                         ffs_dev->ffs_release_dev_callback(ffs_dev);
4173         }
4174
4175         ffs_dev_unlock();
4176
4177         ffs_log("exit");
4178 }
4179
4180 static int ffs_ready(struct ffs_data *ffs)
4181 {
4182         struct ffs_dev *ffs_obj;
4183         int ret = 0;
4184
4185         ENTER();
4186
4187         ffs_log("enter");
4188
4189         ffs_dev_lock();
4190
4191         ffs_obj = ffs->private_data;
4192         if (!ffs_obj) {
4193                 ret = -EINVAL;
4194                 goto done;
4195         }
4196         if (WARN_ON(ffs_obj->desc_ready)) {
4197                 ret = -EBUSY;
4198                 goto done;
4199         }
4200
4201         ffs_obj->desc_ready = true;
4202         ffs_obj->ffs_data = ffs;
4203
4204         if (ffs_obj->ffs_ready_callback) {
4205                 ret = ffs_obj->ffs_ready_callback(ffs);
4206                 if (ret)
4207                         goto done;
4208         }
4209
4210         set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
4211 done:
4212         ffs_dev_unlock();
4213
4214         ffs_log("exit");
4215
4216         return ret;
4217 }
4218
4219 static void ffs_closed(struct ffs_data *ffs)
4220 {
4221         struct ffs_dev *ffs_obj;
4222         struct f_fs_opts *opts;
4223
4224         ENTER();
4225
4226         ffs_log("enter");
4227
4228         ffs_dev_lock();
4229
4230         ffs_obj = ffs->private_data;
4231         if (!ffs_obj) {
4232                 ffs_dev_unlock();
4233                 goto done;
4234         }
4235
4236         ffs_obj->desc_ready = false;
4237
4238         if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags) &&
4239             ffs_obj->ffs_closed_callback)
4240                 ffs_obj->ffs_closed_callback(ffs);
4241
4242         if (ffs_obj->opts) {
4243                 opts = ffs_obj->opts;
4244         } else {
4245                 ffs_dev_unlock();
4246                 goto done;
4247         }
4248
4249         smp_mb__before_atomic();
4250         if (opts->no_configfs || !opts->func_inst.group.cg_item.ci_parent
4251             || !atomic_read(&opts->func_inst.group.cg_item.ci_kref.refcount)) {
4252                 ffs_dev_unlock();
4253                 goto done;
4254         }
4255
4256         ffs_dev_unlock();
4257
4258         if (test_bit(FFS_FL_BOUND, &ffs->flags)) {
4259                 unregister_gadget_item(opts->
4260                                func_inst.group.cg_item.ci_parent->ci_parent);
4261                 ffs_log("unreg gadget done");
4262         }
4263 done:
4264         ffs_log("exit");
4265 }
4266
4267 /* Misc helper functions ****************************************************/
4268
4269 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
4270 {
4271         return nonblock
4272                 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
4273                 : mutex_lock_interruptible(mutex);
4274 }
4275
4276 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
4277 {
4278         char *data;
4279
4280         if (unlikely(!len))
4281                 return NULL;
4282
4283         data = kmalloc(len, GFP_KERNEL);
4284         if (unlikely(!data))
4285                 return ERR_PTR(-ENOMEM);
4286
4287         if (unlikely(copy_from_user(data, buf, len))) {
4288                 kfree(data);
4289                 return ERR_PTR(-EFAULT);
4290         }
4291
4292         pr_vdebug("Buffer from user space:\n");
4293         ffs_dump_mem("", data, len);
4294
4295         return data;
4296 }
4297
4298 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
4299
4300 static int ffs_init(void)
4301 {
4302         ffs_ipc_log = ipc_log_context_create(NUM_PAGES, "f_fs", 0);
4303         if (IS_ERR_OR_NULL(ffs_ipc_log))
4304                 ffs_ipc_log =  NULL;
4305
4306         return 0;
4307 }
4308 module_init(ffs_init);
4309
4310 static void __exit ffs_exit(void)
4311 {
4312         struct ffs_inst_status *inst_status, *inst_status_tmp = NULL;
4313
4314         list_for_each_entry(inst_status, &inst_list, list) {
4315                 if (inst_status_tmp) {
4316                         list_del(&inst_status_tmp->list);
4317                         kfree(inst_status_tmp);
4318                 }
4319                 inst_status_tmp = inst_status;
4320         }
4321         if (inst_status_tmp) {
4322                 list_del(&inst_status_tmp->list);
4323                 kfree(inst_status_tmp);
4324         }
4325
4326         if (ffs_ipc_log) {
4327                 ipc_log_context_destroy(ffs_ipc_log);
4328                 ffs_ipc_log = NULL;
4329         }
4330 }
4331 module_exit(ffs_exit);
4332
4333 MODULE_LICENSE("GPL");
4334 MODULE_AUTHOR("Michal Nazarewicz");