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