Btrfs: stop the readahead threads on failed mount
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / drivers / usb / gadget / f_fs.c
blobc161a9aaeb7ecc16cb77b9d8e85eb1dcd4b62e1b
1 /*
2 * f_fs.c -- user mode file system API for USB composite function controllers
4 * Copyright (C) 2010 Samsung Electronics
5 * Author: Michal Nazarewicz <m.nazarewicz@samsung.com>
7 * Based on inode.c (GadgetFS) which was:
8 * Copyright (C) 2003-2004 David Brownell
9 * Copyright (C) 2003 Agilent Technologies
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.
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.
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
27 /* #define DEBUG */
28 /* #define VERBOSE_DEBUG */
30 #include <linux/blkdev.h>
31 #include <linux/pagemap.h>
32 #include <asm/unaligned.h>
34 #include <linux/usb/composite.h>
35 #include <linux/usb/functionfs.h>
38 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
41 /* Debugging ****************************************************************/
43 #ifdef VERBOSE_DEBUG
44 # define pr_vdebug pr_debug
45 # define ffs_dump_mem(prefix, ptr, len) \
46 print_hex_dump_bytes(pr_fmt(prefix ": "), DUMP_PREFIX_NONE, ptr, len)
47 #else
48 # define pr_vdebug(...) do { } while (0)
49 # define ffs_dump_mem(prefix, ptr, len) do { } while (0)
50 #endif /* VERBOSE_DEBUG */
52 #define ENTER() pr_vdebug("%s()\n", __func__)
55 /* The data structure and setup file ****************************************/
57 enum ffs_state {
59 * Waiting for descriptors and strings.
61 * In this state no open(2), read(2) or write(2) on epfiles
62 * may succeed (which should not be the problem as there
63 * should be no such files opened in the first place).
65 FFS_READ_DESCRIPTORS,
66 FFS_READ_STRINGS,
69 * We've got descriptors and strings. We are or have called
70 * functionfs_ready_callback(). functionfs_bind() may have
71 * been called but we don't know.
73 * This is the only state in which operations on epfiles may
74 * succeed.
76 FFS_ACTIVE,
79 * All endpoints have been closed. This state is also set if
80 * we encounter an unrecoverable error. The only
81 * unrecoverable error is situation when after reading strings
82 * from user space we fail to initialise epfiles or
83 * functionfs_ready_callback() returns with error (<0).
85 * In this state no open(2), read(2) or write(2) (both on ep0
86 * as well as epfile) may succeed (at this point epfiles are
87 * unlinked and all closed so this is not a problem; ep0 is
88 * also closed but ep0 file exists and so open(2) on ep0 must
89 * fail).
91 FFS_CLOSING
95 enum ffs_setup_state {
96 /* There is no setup request pending. */
97 FFS_NO_SETUP,
99 * User has read events and there was a setup request event
100 * there. The next read/write on ep0 will handle the
101 * request.
103 FFS_SETUP_PENDING,
105 * There was event pending but before user space handled it
106 * some other event was introduced which canceled existing
107 * setup. If this state is set read/write on ep0 return
108 * -EIDRM. This state is only set when adding event.
110 FFS_SETUP_CANCELED
115 struct ffs_epfile;
116 struct ffs_function;
118 struct ffs_data {
119 struct usb_gadget *gadget;
122 * Protect access read/write operations, only one read/write
123 * at a time. As a consequence protects ep0req and company.
124 * While setup request is being processed (queued) this is
125 * held.
127 struct mutex mutex;
130 * Protect access to endpoint related structures (basically
131 * usb_ep_queue(), usb_ep_dequeue(), etc. calls) except for
132 * endpoint zero.
134 spinlock_t eps_lock;
137 * XXX REVISIT do we need our own request? Since we are not
138 * handling setup requests immediately user space may be so
139 * slow that another setup will be sent to the gadget but this
140 * time not to us but another function and then there could be
141 * a race. Is that the case? Or maybe we can use cdev->req
142 * after all, maybe we just need some spinlock for that?
144 struct usb_request *ep0req; /* P: mutex */
145 struct completion ep0req_completion; /* P: mutex */
146 int ep0req_status; /* P: mutex */
148 /* reference counter */
149 atomic_t ref;
150 /* how many files are opened (EP0 and others) */
151 atomic_t opened;
153 /* EP0 state */
154 enum ffs_state state;
157 * Possible transitions:
158 * + FFS_NO_SETUP -> FFS_SETUP_PENDING -- P: ev.waitq.lock
159 * happens only in ep0 read which is P: mutex
160 * + FFS_SETUP_PENDING -> FFS_NO_SETUP -- P: ev.waitq.lock
161 * happens only in ep0 i/o which is P: mutex
162 * + FFS_SETUP_PENDING -> FFS_SETUP_CANCELED -- P: ev.waitq.lock
163 * + FFS_SETUP_CANCELED -> FFS_NO_SETUP -- cmpxchg
165 enum ffs_setup_state setup_state;
167 #define FFS_SETUP_STATE(ffs) \
168 ((enum ffs_setup_state)cmpxchg(&(ffs)->setup_state, \
169 FFS_SETUP_CANCELED, FFS_NO_SETUP))
171 /* Events & such. */
172 struct {
173 u8 types[4];
174 unsigned short count;
175 /* XXX REVISIT need to update it in some places, or do we? */
176 unsigned short can_stall;
177 struct usb_ctrlrequest setup;
179 wait_queue_head_t waitq;
180 } ev; /* the whole structure, P: ev.waitq.lock */
182 /* Flags */
183 unsigned long flags;
184 #define FFS_FL_CALL_CLOSED_CALLBACK 0
185 #define FFS_FL_BOUND 1
187 /* Active function */
188 struct ffs_function *func;
191 * Device name, write once when file system is mounted.
192 * Intended for user to read if she wants.
194 const char *dev_name;
195 /* Private data for our user (ie. gadget). Managed by user. */
196 void *private_data;
198 /* filled by __ffs_data_got_descs() */
200 * Real descriptors are 16 bytes after raw_descs (so you need
201 * to skip 16 bytes (ie. ffs->raw_descs + 16) to get to the
202 * first full speed descriptor). raw_descs_length and
203 * raw_fs_descs_length do not have those 16 bytes added.
205 const void *raw_descs;
206 unsigned raw_descs_length;
207 unsigned raw_fs_descs_length;
208 unsigned fs_descs_count;
209 unsigned hs_descs_count;
211 unsigned short strings_count;
212 unsigned short interfaces_count;
213 unsigned short eps_count;
214 unsigned short _pad1;
216 /* filled by __ffs_data_got_strings() */
217 /* ids in stringtabs are set in functionfs_bind() */
218 const void *raw_strings;
219 struct usb_gadget_strings **stringtabs;
222 * File system's super block, write once when file system is
223 * mounted.
225 struct super_block *sb;
227 /* File permissions, written once when fs is mounted */
228 struct ffs_file_perms {
229 umode_t mode;
230 uid_t uid;
231 gid_t gid;
232 } file_perms;
235 * The endpoint files, filled by ffs_epfiles_create(),
236 * destroyed by ffs_epfiles_destroy().
238 struct ffs_epfile *epfiles;
241 /* Reference counter handling */
242 static void ffs_data_get(struct ffs_data *ffs);
243 static void ffs_data_put(struct ffs_data *ffs);
244 /* Creates new ffs_data object. */
245 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
247 /* Opened counter handling. */
248 static void ffs_data_opened(struct ffs_data *ffs);
249 static void ffs_data_closed(struct ffs_data *ffs);
251 /* Called with ffs->mutex held; take over ownership of data. */
252 static int __must_check
253 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
254 static int __must_check
255 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
258 /* The function structure ***************************************************/
260 struct ffs_ep;
262 struct ffs_function {
263 struct usb_configuration *conf;
264 struct usb_gadget *gadget;
265 struct ffs_data *ffs;
267 struct ffs_ep *eps;
268 u8 eps_revmap[16];
269 short *interfaces_nums;
271 struct usb_function function;
275 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
277 return container_of(f, struct ffs_function, function);
280 static void ffs_func_free(struct ffs_function *func);
282 static void ffs_func_eps_disable(struct ffs_function *func);
283 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
285 static int ffs_func_bind(struct usb_configuration *,
286 struct usb_function *);
287 static void ffs_func_unbind(struct usb_configuration *,
288 struct usb_function *);
289 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
290 static void ffs_func_disable(struct usb_function *);
291 static int ffs_func_setup(struct usb_function *,
292 const struct usb_ctrlrequest *);
293 static void ffs_func_suspend(struct usb_function *);
294 static void ffs_func_resume(struct usb_function *);
297 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
298 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
301 /* The endpoints structures *************************************************/
303 struct ffs_ep {
304 struct usb_ep *ep; /* P: ffs->eps_lock */
305 struct usb_request *req; /* P: epfile->mutex */
307 /* [0]: full speed, [1]: high speed */
308 struct usb_endpoint_descriptor *descs[2];
310 u8 num;
312 int status; /* P: epfile->mutex */
315 struct ffs_epfile {
316 /* Protects ep->ep and ep->req. */
317 struct mutex mutex;
318 wait_queue_head_t wait;
320 struct ffs_data *ffs;
321 struct ffs_ep *ep; /* P: ffs->eps_lock */
323 struct dentry *dentry;
325 char name[5];
327 unsigned char in; /* P: ffs->eps_lock */
328 unsigned char isoc; /* P: ffs->eps_lock */
330 unsigned char _pad;
333 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
334 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
336 static struct inode *__must_check
337 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
338 const struct file_operations *fops,
339 struct dentry **dentry_p);
342 /* Misc helper functions ****************************************************/
344 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
345 __attribute__((warn_unused_result, nonnull));
346 static char *ffs_prepare_buffer(const char * __user buf, size_t len)
347 __attribute__((warn_unused_result, nonnull));
350 /* Control file aka ep0 *****************************************************/
352 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
354 struct ffs_data *ffs = req->context;
356 complete_all(&ffs->ep0req_completion);
359 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
361 struct usb_request *req = ffs->ep0req;
362 int ret;
364 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
366 spin_unlock_irq(&ffs->ev.waitq.lock);
368 req->buf = data;
369 req->length = len;
372 * UDC layer requires to provide a buffer even for ZLP, but should
373 * not use it at all. Let's provide some poisoned pointer to catch
374 * possible bug in the driver.
376 if (req->buf == NULL)
377 req->buf = (void *)0xDEADBABE;
379 INIT_COMPLETION(ffs->ep0req_completion);
381 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
382 if (unlikely(ret < 0))
383 return ret;
385 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
386 if (unlikely(ret)) {
387 usb_ep_dequeue(ffs->gadget->ep0, req);
388 return -EINTR;
391 ffs->setup_state = FFS_NO_SETUP;
392 return ffs->ep0req_status;
395 static int __ffs_ep0_stall(struct ffs_data *ffs)
397 if (ffs->ev.can_stall) {
398 pr_vdebug("ep0 stall\n");
399 usb_ep_set_halt(ffs->gadget->ep0);
400 ffs->setup_state = FFS_NO_SETUP;
401 return -EL2HLT;
402 } else {
403 pr_debug("bogus ep0 stall!\n");
404 return -ESRCH;
408 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
409 size_t len, loff_t *ptr)
411 struct ffs_data *ffs = file->private_data;
412 ssize_t ret;
413 char *data;
415 ENTER();
417 /* Fast check if setup was canceled */
418 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
419 return -EIDRM;
421 /* Acquire mutex */
422 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
423 if (unlikely(ret < 0))
424 return ret;
426 /* Check state */
427 switch (ffs->state) {
428 case FFS_READ_DESCRIPTORS:
429 case FFS_READ_STRINGS:
430 /* Copy data */
431 if (unlikely(len < 16)) {
432 ret = -EINVAL;
433 break;
436 data = ffs_prepare_buffer(buf, len);
437 if (IS_ERR(data)) {
438 ret = PTR_ERR(data);
439 break;
442 /* Handle data */
443 if (ffs->state == FFS_READ_DESCRIPTORS) {
444 pr_info("read descriptors\n");
445 ret = __ffs_data_got_descs(ffs, data, len);
446 if (unlikely(ret < 0))
447 break;
449 ffs->state = FFS_READ_STRINGS;
450 ret = len;
451 } else {
452 pr_info("read strings\n");
453 ret = __ffs_data_got_strings(ffs, data, len);
454 if (unlikely(ret < 0))
455 break;
457 ret = ffs_epfiles_create(ffs);
458 if (unlikely(ret)) {
459 ffs->state = FFS_CLOSING;
460 break;
463 ffs->state = FFS_ACTIVE;
464 mutex_unlock(&ffs->mutex);
466 ret = functionfs_ready_callback(ffs);
467 if (unlikely(ret < 0)) {
468 ffs->state = FFS_CLOSING;
469 return ret;
472 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
473 return len;
475 break;
477 case FFS_ACTIVE:
478 data = NULL;
480 * We're called from user space, we can use _irq
481 * rather then _irqsave
483 spin_lock_irq(&ffs->ev.waitq.lock);
484 switch (FFS_SETUP_STATE(ffs)) {
485 case FFS_SETUP_CANCELED:
486 ret = -EIDRM;
487 goto done_spin;
489 case FFS_NO_SETUP:
490 ret = -ESRCH;
491 goto done_spin;
493 case FFS_SETUP_PENDING:
494 break;
497 /* FFS_SETUP_PENDING */
498 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
499 spin_unlock_irq(&ffs->ev.waitq.lock);
500 ret = __ffs_ep0_stall(ffs);
501 break;
504 /* FFS_SETUP_PENDING and not stall */
505 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
507 spin_unlock_irq(&ffs->ev.waitq.lock);
509 data = ffs_prepare_buffer(buf, len);
510 if (IS_ERR(data)) {
511 ret = PTR_ERR(data);
512 break;
515 spin_lock_irq(&ffs->ev.waitq.lock);
518 * We are guaranteed to be still in FFS_ACTIVE state
519 * but the state of setup could have changed from
520 * FFS_SETUP_PENDING to FFS_SETUP_CANCELED so we need
521 * to check for that. If that happened we copied data
522 * from user space in vain but it's unlikely.
524 * For sure we are not in FFS_NO_SETUP since this is
525 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
526 * transition can be performed and it's protected by
527 * mutex.
529 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
530 ret = -EIDRM;
531 done_spin:
532 spin_unlock_irq(&ffs->ev.waitq.lock);
533 } else {
534 /* unlocks spinlock */
535 ret = __ffs_ep0_queue_wait(ffs, data, len);
537 kfree(data);
538 break;
540 default:
541 ret = -EBADFD;
542 break;
545 mutex_unlock(&ffs->mutex);
546 return ret;
549 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
550 size_t n)
553 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
554 * to release them.
556 struct usb_functionfs_event events[n];
557 unsigned i = 0;
559 memset(events, 0, sizeof events);
561 do {
562 events[i].type = ffs->ev.types[i];
563 if (events[i].type == FUNCTIONFS_SETUP) {
564 events[i].u.setup = ffs->ev.setup;
565 ffs->setup_state = FFS_SETUP_PENDING;
567 } while (++i < n);
569 if (n < ffs->ev.count) {
570 ffs->ev.count -= n;
571 memmove(ffs->ev.types, ffs->ev.types + n,
572 ffs->ev.count * sizeof *ffs->ev.types);
573 } else {
574 ffs->ev.count = 0;
577 spin_unlock_irq(&ffs->ev.waitq.lock);
578 mutex_unlock(&ffs->mutex);
580 return unlikely(__copy_to_user(buf, events, sizeof events))
581 ? -EFAULT : sizeof events;
584 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
585 size_t len, loff_t *ptr)
587 struct ffs_data *ffs = file->private_data;
588 char *data = NULL;
589 size_t n;
590 int ret;
592 ENTER();
594 /* Fast check if setup was canceled */
595 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
596 return -EIDRM;
598 /* Acquire mutex */
599 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
600 if (unlikely(ret < 0))
601 return ret;
603 /* Check state */
604 if (ffs->state != FFS_ACTIVE) {
605 ret = -EBADFD;
606 goto done_mutex;
610 * We're called from user space, we can use _irq rather then
611 * _irqsave
613 spin_lock_irq(&ffs->ev.waitq.lock);
615 switch (FFS_SETUP_STATE(ffs)) {
616 case FFS_SETUP_CANCELED:
617 ret = -EIDRM;
618 break;
620 case FFS_NO_SETUP:
621 n = len / sizeof(struct usb_functionfs_event);
622 if (unlikely(!n)) {
623 ret = -EINVAL;
624 break;
627 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
628 ret = -EAGAIN;
629 break;
632 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
633 ffs->ev.count)) {
634 ret = -EINTR;
635 break;
638 return __ffs_ep0_read_events(ffs, buf,
639 min(n, (size_t)ffs->ev.count));
641 case FFS_SETUP_PENDING:
642 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
643 spin_unlock_irq(&ffs->ev.waitq.lock);
644 ret = __ffs_ep0_stall(ffs);
645 goto done_mutex;
648 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
650 spin_unlock_irq(&ffs->ev.waitq.lock);
652 if (likely(len)) {
653 data = kmalloc(len, GFP_KERNEL);
654 if (unlikely(!data)) {
655 ret = -ENOMEM;
656 goto done_mutex;
660 spin_lock_irq(&ffs->ev.waitq.lock);
662 /* See ffs_ep0_write() */
663 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
664 ret = -EIDRM;
665 break;
668 /* unlocks spinlock */
669 ret = __ffs_ep0_queue_wait(ffs, data, len);
670 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
671 ret = -EFAULT;
672 goto done_mutex;
674 default:
675 ret = -EBADFD;
676 break;
679 spin_unlock_irq(&ffs->ev.waitq.lock);
680 done_mutex:
681 mutex_unlock(&ffs->mutex);
682 kfree(data);
683 return ret;
686 static int ffs_ep0_open(struct inode *inode, struct file *file)
688 struct ffs_data *ffs = inode->i_private;
690 ENTER();
692 if (unlikely(ffs->state == FFS_CLOSING))
693 return -EBUSY;
695 file->private_data = ffs;
696 ffs_data_opened(ffs);
698 return 0;
701 static int ffs_ep0_release(struct inode *inode, struct file *file)
703 struct ffs_data *ffs = file->private_data;
705 ENTER();
707 ffs_data_closed(ffs);
709 return 0;
712 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
714 struct ffs_data *ffs = file->private_data;
715 struct usb_gadget *gadget = ffs->gadget;
716 long ret;
718 ENTER();
720 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
721 struct ffs_function *func = ffs->func;
722 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
723 } else if (gadget->ops->ioctl) {
724 ret = gadget->ops->ioctl(gadget, code, value);
725 } else {
726 ret = -ENOTTY;
729 return ret;
732 static const struct file_operations ffs_ep0_operations = {
733 .owner = THIS_MODULE,
734 .llseek = no_llseek,
736 .open = ffs_ep0_open,
737 .write = ffs_ep0_write,
738 .read = ffs_ep0_read,
739 .release = ffs_ep0_release,
740 .unlocked_ioctl = ffs_ep0_ioctl,
744 /* "Normal" endpoints operations ********************************************/
746 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
748 ENTER();
749 if (likely(req->context)) {
750 struct ffs_ep *ep = _ep->driver_data;
751 ep->status = req->status ? req->status : req->actual;
752 complete(req->context);
756 static ssize_t ffs_epfile_io(struct file *file,
757 char __user *buf, size_t len, int read)
759 struct ffs_epfile *epfile = file->private_data;
760 struct ffs_ep *ep;
761 char *data = NULL;
762 ssize_t ret;
763 int halt;
765 goto first_try;
766 do {
767 spin_unlock_irq(&epfile->ffs->eps_lock);
768 mutex_unlock(&epfile->mutex);
770 first_try:
771 /* Are we still active? */
772 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
773 ret = -ENODEV;
774 goto error;
777 /* Wait for endpoint to be enabled */
778 ep = epfile->ep;
779 if (!ep) {
780 if (file->f_flags & O_NONBLOCK) {
781 ret = -EAGAIN;
782 goto error;
785 if (wait_event_interruptible(epfile->wait,
786 (ep = epfile->ep))) {
787 ret = -EINTR;
788 goto error;
792 /* Do we halt? */
793 halt = !read == !epfile->in;
794 if (halt && epfile->isoc) {
795 ret = -EINVAL;
796 goto error;
799 /* Allocate & copy */
800 if (!halt && !data) {
801 data = kzalloc(len, GFP_KERNEL);
802 if (unlikely(!data))
803 return -ENOMEM;
805 if (!read &&
806 unlikely(__copy_from_user(data, buf, len))) {
807 ret = -EFAULT;
808 goto error;
812 /* We will be using request */
813 ret = ffs_mutex_lock(&epfile->mutex,
814 file->f_flags & O_NONBLOCK);
815 if (unlikely(ret))
816 goto error;
819 * We're called from user space, we can use _irq rather then
820 * _irqsave
822 spin_lock_irq(&epfile->ffs->eps_lock);
825 * While we were acquiring mutex endpoint got disabled
826 * or changed?
828 } while (unlikely(epfile->ep != ep));
830 /* Halt */
831 if (unlikely(halt)) {
832 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
833 usb_ep_set_halt(ep->ep);
834 spin_unlock_irq(&epfile->ffs->eps_lock);
835 ret = -EBADMSG;
836 } else {
837 /* Fire the request */
838 DECLARE_COMPLETION_ONSTACK(done);
840 struct usb_request *req = ep->req;
841 req->context = &done;
842 req->complete = ffs_epfile_io_complete;
843 req->buf = data;
844 req->length = len;
846 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
848 spin_unlock_irq(&epfile->ffs->eps_lock);
850 if (unlikely(ret < 0)) {
851 /* nop */
852 } else if (unlikely(wait_for_completion_interruptible(&done))) {
853 ret = -EINTR;
854 usb_ep_dequeue(ep->ep, req);
855 } else {
856 ret = ep->status;
857 if (read && ret > 0 &&
858 unlikely(copy_to_user(buf, data, ret)))
859 ret = -EFAULT;
863 mutex_unlock(&epfile->mutex);
864 error:
865 kfree(data);
866 return ret;
869 static ssize_t
870 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
871 loff_t *ptr)
873 ENTER();
875 return ffs_epfile_io(file, (char __user *)buf, len, 0);
878 static ssize_t
879 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
881 ENTER();
883 return ffs_epfile_io(file, buf, len, 1);
886 static int
887 ffs_epfile_open(struct inode *inode, struct file *file)
889 struct ffs_epfile *epfile = inode->i_private;
891 ENTER();
893 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
894 return -ENODEV;
896 file->private_data = epfile;
897 ffs_data_opened(epfile->ffs);
899 return 0;
902 static int
903 ffs_epfile_release(struct inode *inode, struct file *file)
905 struct ffs_epfile *epfile = inode->i_private;
907 ENTER();
909 ffs_data_closed(epfile->ffs);
911 return 0;
914 static long ffs_epfile_ioctl(struct file *file, unsigned code,
915 unsigned long value)
917 struct ffs_epfile *epfile = file->private_data;
918 int ret;
920 ENTER();
922 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
923 return -ENODEV;
925 spin_lock_irq(&epfile->ffs->eps_lock);
926 if (likely(epfile->ep)) {
927 switch (code) {
928 case FUNCTIONFS_FIFO_STATUS:
929 ret = usb_ep_fifo_status(epfile->ep->ep);
930 break;
931 case FUNCTIONFS_FIFO_FLUSH:
932 usb_ep_fifo_flush(epfile->ep->ep);
933 ret = 0;
934 break;
935 case FUNCTIONFS_CLEAR_HALT:
936 ret = usb_ep_clear_halt(epfile->ep->ep);
937 break;
938 case FUNCTIONFS_ENDPOINT_REVMAP:
939 ret = epfile->ep->num;
940 break;
941 default:
942 ret = -ENOTTY;
944 } else {
945 ret = -ENODEV;
947 spin_unlock_irq(&epfile->ffs->eps_lock);
949 return ret;
952 static const struct file_operations ffs_epfile_operations = {
953 .owner = THIS_MODULE,
954 .llseek = no_llseek,
956 .open = ffs_epfile_open,
957 .write = ffs_epfile_write,
958 .read = ffs_epfile_read,
959 .release = ffs_epfile_release,
960 .unlocked_ioctl = ffs_epfile_ioctl,
964 /* File system and super block operations ***********************************/
967 * Mounting the file system creates a controller file, used first for
968 * function configuration then later for event monitoring.
971 static struct inode *__must_check
972 ffs_sb_make_inode(struct super_block *sb, void *data,
973 const struct file_operations *fops,
974 const struct inode_operations *iops,
975 struct ffs_file_perms *perms)
977 struct inode *inode;
979 ENTER();
981 inode = new_inode(sb);
983 if (likely(inode)) {
984 struct timespec current_time = CURRENT_TIME;
986 inode->i_ino = get_next_ino();
987 inode->i_mode = perms->mode;
988 inode->i_uid = perms->uid;
989 inode->i_gid = perms->gid;
990 inode->i_atime = current_time;
991 inode->i_mtime = current_time;
992 inode->i_ctime = current_time;
993 inode->i_private = data;
994 if (fops)
995 inode->i_fop = fops;
996 if (iops)
997 inode->i_op = iops;
1000 return inode;
1003 /* Create "regular" file */
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)
1009 struct ffs_data *ffs = sb->s_fs_info;
1010 struct dentry *dentry;
1011 struct inode *inode;
1013 ENTER();
1015 dentry = d_alloc_name(sb->s_root, name);
1016 if (unlikely(!dentry))
1017 return NULL;
1019 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1020 if (unlikely(!inode)) {
1021 dput(dentry);
1022 return NULL;
1025 d_add(dentry, inode);
1026 if (dentry_p)
1027 *dentry_p = dentry;
1029 return inode;
1032 /* Super block */
1033 static const struct super_operations ffs_sb_operations = {
1034 .statfs = simple_statfs,
1035 .drop_inode = generic_delete_inode,
1038 struct ffs_sb_fill_data {
1039 struct ffs_file_perms perms;
1040 umode_t root_mode;
1041 const char *dev_name;
1044 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1046 struct ffs_sb_fill_data *data = _data;
1047 struct inode *inode;
1048 struct dentry *d;
1049 struct ffs_data *ffs;
1051 ENTER();
1053 /* Initialise data */
1054 ffs = ffs_data_new();
1055 if (unlikely(!ffs))
1056 goto enomem0;
1058 ffs->sb = sb;
1059 ffs->dev_name = data->dev_name;
1060 ffs->file_perms = data->perms;
1062 sb->s_fs_info = ffs;
1063 sb->s_blocksize = PAGE_CACHE_SIZE;
1064 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1065 sb->s_magic = FUNCTIONFS_MAGIC;
1066 sb->s_op = &ffs_sb_operations;
1067 sb->s_time_gran = 1;
1069 /* Root inode */
1070 data->perms.mode = data->root_mode;
1071 inode = ffs_sb_make_inode(sb, NULL,
1072 &simple_dir_operations,
1073 &simple_dir_inode_operations,
1074 &data->perms);
1075 if (unlikely(!inode))
1076 goto enomem1;
1077 d = d_alloc_root(inode);
1078 if (unlikely(!d))
1079 goto enomem2;
1080 sb->s_root = d;
1082 /* EP0 file */
1083 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1084 &ffs_ep0_operations, NULL)))
1085 goto enomem3;
1087 return 0;
1089 enomem3:
1090 dput(d);
1091 enomem2:
1092 iput(inode);
1093 enomem1:
1094 ffs_data_put(ffs);
1095 enomem0:
1096 return -ENOMEM;
1099 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1101 ENTER();
1103 if (!opts || !*opts)
1104 return 0;
1106 for (;;) {
1107 char *end, *eq, *comma;
1108 unsigned long value;
1110 /* Option limit */
1111 comma = strchr(opts, ',');
1112 if (comma)
1113 *comma = 0;
1115 /* Value limit */
1116 eq = strchr(opts, '=');
1117 if (unlikely(!eq)) {
1118 pr_err("'=' missing in %s\n", opts);
1119 return -EINVAL;
1121 *eq = 0;
1123 /* Parse value */
1124 value = simple_strtoul(eq + 1, &end, 0);
1125 if (unlikely(*end != ',' && *end != 0)) {
1126 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1127 return -EINVAL;
1130 /* Interpret option */
1131 switch (eq - opts) {
1132 case 5:
1133 if (!memcmp(opts, "rmode", 5))
1134 data->root_mode = (value & 0555) | S_IFDIR;
1135 else if (!memcmp(opts, "fmode", 5))
1136 data->perms.mode = (value & 0666) | S_IFREG;
1137 else
1138 goto invalid;
1139 break;
1141 case 4:
1142 if (!memcmp(opts, "mode", 4)) {
1143 data->root_mode = (value & 0555) | S_IFDIR;
1144 data->perms.mode = (value & 0666) | S_IFREG;
1145 } else {
1146 goto invalid;
1148 break;
1150 case 3:
1151 if (!memcmp(opts, "uid", 3))
1152 data->perms.uid = value;
1153 else if (!memcmp(opts, "gid", 3))
1154 data->perms.gid = value;
1155 else
1156 goto invalid;
1157 break;
1159 default:
1160 invalid:
1161 pr_err("%s: invalid option\n", opts);
1162 return -EINVAL;
1165 /* Next iteration */
1166 if (!comma)
1167 break;
1168 opts = comma + 1;
1171 return 0;
1174 /* "mount -t functionfs dev_name /dev/function" ends up here */
1176 static struct dentry *
1177 ffs_fs_mount(struct file_system_type *t, int flags,
1178 const char *dev_name, void *opts)
1180 struct ffs_sb_fill_data data = {
1181 .perms = {
1182 .mode = S_IFREG | 0600,
1183 .uid = 0,
1184 .gid = 0
1186 .root_mode = S_IFDIR | 0500,
1188 int ret;
1190 ENTER();
1192 ret = functionfs_check_dev_callback(dev_name);
1193 if (unlikely(ret < 0))
1194 return ERR_PTR(ret);
1196 ret = ffs_fs_parse_opts(&data, opts);
1197 if (unlikely(ret < 0))
1198 return ERR_PTR(ret);
1200 data.dev_name = dev_name;
1201 return mount_single(t, flags, &data, ffs_sb_fill);
1204 static void
1205 ffs_fs_kill_sb(struct super_block *sb)
1207 void *ptr;
1209 ENTER();
1211 kill_litter_super(sb);
1212 ptr = xchg(&sb->s_fs_info, NULL);
1213 if (ptr)
1214 ffs_data_put(ptr);
1217 static struct file_system_type ffs_fs_type = {
1218 .owner = THIS_MODULE,
1219 .name = "functionfs",
1220 .mount = ffs_fs_mount,
1221 .kill_sb = ffs_fs_kill_sb,
1225 /* Driver's main init/cleanup functions *************************************/
1227 static int functionfs_init(void)
1229 int ret;
1231 ENTER();
1233 ret = register_filesystem(&ffs_fs_type);
1234 if (likely(!ret))
1235 pr_info("file system registered\n");
1236 else
1237 pr_err("failed registering file system (%d)\n", ret);
1239 return ret;
1242 static void functionfs_cleanup(void)
1244 ENTER();
1246 pr_info("unloading\n");
1247 unregister_filesystem(&ffs_fs_type);
1251 /* ffs_data and ffs_function construction and destruction code **************/
1253 static void ffs_data_clear(struct ffs_data *ffs);
1254 static void ffs_data_reset(struct ffs_data *ffs);
1256 static void ffs_data_get(struct ffs_data *ffs)
1258 ENTER();
1260 atomic_inc(&ffs->ref);
1263 static void ffs_data_opened(struct ffs_data *ffs)
1265 ENTER();
1267 atomic_inc(&ffs->ref);
1268 atomic_inc(&ffs->opened);
1271 static void ffs_data_put(struct ffs_data *ffs)
1273 ENTER();
1275 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1276 pr_info("%s(): freeing\n", __func__);
1277 ffs_data_clear(ffs);
1278 BUG_ON(mutex_is_locked(&ffs->mutex) ||
1279 spin_is_locked(&ffs->ev.waitq.lock) ||
1280 waitqueue_active(&ffs->ev.waitq) ||
1281 waitqueue_active(&ffs->ep0req_completion.wait));
1282 kfree(ffs);
1286 static void ffs_data_closed(struct ffs_data *ffs)
1288 ENTER();
1290 if (atomic_dec_and_test(&ffs->opened)) {
1291 ffs->state = FFS_CLOSING;
1292 ffs_data_reset(ffs);
1295 ffs_data_put(ffs);
1298 static struct ffs_data *ffs_data_new(void)
1300 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1301 if (unlikely(!ffs))
1302 return 0;
1304 ENTER();
1306 atomic_set(&ffs->ref, 1);
1307 atomic_set(&ffs->opened, 0);
1308 ffs->state = FFS_READ_DESCRIPTORS;
1309 mutex_init(&ffs->mutex);
1310 spin_lock_init(&ffs->eps_lock);
1311 init_waitqueue_head(&ffs->ev.waitq);
1312 init_completion(&ffs->ep0req_completion);
1314 /* XXX REVISIT need to update it in some places, or do we? */
1315 ffs->ev.can_stall = 1;
1317 return ffs;
1320 static void ffs_data_clear(struct ffs_data *ffs)
1322 ENTER();
1324 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1325 functionfs_closed_callback(ffs);
1327 BUG_ON(ffs->gadget);
1329 if (ffs->epfiles)
1330 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1332 kfree(ffs->raw_descs);
1333 kfree(ffs->raw_strings);
1334 kfree(ffs->stringtabs);
1337 static void ffs_data_reset(struct ffs_data *ffs)
1339 ENTER();
1341 ffs_data_clear(ffs);
1343 ffs->epfiles = NULL;
1344 ffs->raw_descs = NULL;
1345 ffs->raw_strings = NULL;
1346 ffs->stringtabs = NULL;
1348 ffs->raw_descs_length = 0;
1349 ffs->raw_fs_descs_length = 0;
1350 ffs->fs_descs_count = 0;
1351 ffs->hs_descs_count = 0;
1353 ffs->strings_count = 0;
1354 ffs->interfaces_count = 0;
1355 ffs->eps_count = 0;
1357 ffs->ev.count = 0;
1359 ffs->state = FFS_READ_DESCRIPTORS;
1360 ffs->setup_state = FFS_NO_SETUP;
1361 ffs->flags = 0;
1365 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1367 struct usb_gadget_strings **lang;
1368 int first_id;
1370 ENTER();
1372 if (WARN_ON(ffs->state != FFS_ACTIVE
1373 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1374 return -EBADFD;
1376 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1377 if (unlikely(first_id < 0))
1378 return first_id;
1380 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1381 if (unlikely(!ffs->ep0req))
1382 return -ENOMEM;
1383 ffs->ep0req->complete = ffs_ep0_complete;
1384 ffs->ep0req->context = ffs;
1386 lang = ffs->stringtabs;
1387 for (lang = ffs->stringtabs; *lang; ++lang) {
1388 struct usb_string *str = (*lang)->strings;
1389 int id = first_id;
1390 for (; str->s; ++id, ++str)
1391 str->id = id;
1394 ffs->gadget = cdev->gadget;
1395 ffs_data_get(ffs);
1396 return 0;
1399 static void functionfs_unbind(struct ffs_data *ffs)
1401 ENTER();
1403 if (!WARN_ON(!ffs->gadget)) {
1404 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1405 ffs->ep0req = NULL;
1406 ffs->gadget = NULL;
1407 ffs_data_put(ffs);
1411 static int ffs_epfiles_create(struct ffs_data *ffs)
1413 struct ffs_epfile *epfile, *epfiles;
1414 unsigned i, count;
1416 ENTER();
1418 count = ffs->eps_count;
1419 epfiles = kzalloc(count * sizeof *epfiles, GFP_KERNEL);
1420 if (!epfiles)
1421 return -ENOMEM;
1423 epfile = epfiles;
1424 for (i = 1; i <= count; ++i, ++epfile) {
1425 epfile->ffs = ffs;
1426 mutex_init(&epfile->mutex);
1427 init_waitqueue_head(&epfile->wait);
1428 sprintf(epfiles->name, "ep%u", i);
1429 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1430 &ffs_epfile_operations,
1431 &epfile->dentry))) {
1432 ffs_epfiles_destroy(epfiles, i - 1);
1433 return -ENOMEM;
1437 ffs->epfiles = epfiles;
1438 return 0;
1441 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1443 struct ffs_epfile *epfile = epfiles;
1445 ENTER();
1447 for (; count; --count, ++epfile) {
1448 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1449 waitqueue_active(&epfile->wait));
1450 if (epfile->dentry) {
1451 d_delete(epfile->dentry);
1452 dput(epfile->dentry);
1453 epfile->dentry = NULL;
1457 kfree(epfiles);
1460 static int functionfs_bind_config(struct usb_composite_dev *cdev,
1461 struct usb_configuration *c,
1462 struct ffs_data *ffs)
1464 struct ffs_function *func;
1465 int ret;
1467 ENTER();
1469 func = kzalloc(sizeof *func, GFP_KERNEL);
1470 if (unlikely(!func))
1471 return -ENOMEM;
1473 func->function.name = "Function FS Gadget";
1474 func->function.strings = ffs->stringtabs;
1476 func->function.bind = ffs_func_bind;
1477 func->function.unbind = ffs_func_unbind;
1478 func->function.set_alt = ffs_func_set_alt;
1479 func->function.disable = ffs_func_disable;
1480 func->function.setup = ffs_func_setup;
1481 func->function.suspend = ffs_func_suspend;
1482 func->function.resume = ffs_func_resume;
1484 func->conf = c;
1485 func->gadget = cdev->gadget;
1486 func->ffs = ffs;
1487 ffs_data_get(ffs);
1489 ret = usb_add_function(c, &func->function);
1490 if (unlikely(ret))
1491 ffs_func_free(func);
1493 return ret;
1496 static void ffs_func_free(struct ffs_function *func)
1498 ENTER();
1500 ffs_data_put(func->ffs);
1502 kfree(func->eps);
1504 * eps and interfaces_nums are allocated in the same chunk so
1505 * only one free is required. Descriptors are also allocated
1506 * in the same chunk.
1509 kfree(func);
1512 static void ffs_func_eps_disable(struct ffs_function *func)
1514 struct ffs_ep *ep = func->eps;
1515 struct ffs_epfile *epfile = func->ffs->epfiles;
1516 unsigned count = func->ffs->eps_count;
1517 unsigned long flags;
1519 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1520 do {
1521 /* pending requests get nuked */
1522 if (likely(ep->ep))
1523 usb_ep_disable(ep->ep);
1524 epfile->ep = NULL;
1526 ++ep;
1527 ++epfile;
1528 } while (--count);
1529 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1532 static int ffs_func_eps_enable(struct ffs_function *func)
1534 struct ffs_data *ffs = func->ffs;
1535 struct ffs_ep *ep = func->eps;
1536 struct ffs_epfile *epfile = ffs->epfiles;
1537 unsigned count = ffs->eps_count;
1538 unsigned long flags;
1539 int ret = 0;
1541 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1542 do {
1543 struct usb_endpoint_descriptor *ds;
1544 ds = ep->descs[ep->descs[1] ? 1 : 0];
1546 ep->ep->driver_data = ep;
1547 ep->ep->desc = ds;
1548 ret = usb_ep_enable(ep->ep);
1549 if (likely(!ret)) {
1550 epfile->ep = ep;
1551 epfile->in = usb_endpoint_dir_in(ds);
1552 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1553 } else {
1554 break;
1557 wake_up(&epfile->wait);
1559 ++ep;
1560 ++epfile;
1561 } while (--count);
1562 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1564 return ret;
1568 /* Parsing and building descriptors and strings *****************************/
1571 * This validates if data pointed by data is a valid USB descriptor as
1572 * well as record how many interfaces, endpoints and strings are
1573 * required by given configuration. Returns address after the
1574 * descriptor or NULL if data is invalid.
1577 enum ffs_entity_type {
1578 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1581 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1582 u8 *valuep,
1583 struct usb_descriptor_header *desc,
1584 void *priv);
1586 static int __must_check ffs_do_desc(char *data, unsigned len,
1587 ffs_entity_callback entity, void *priv)
1589 struct usb_descriptor_header *_ds = (void *)data;
1590 u8 length;
1591 int ret;
1593 ENTER();
1595 /* At least two bytes are required: length and type */
1596 if (len < 2) {
1597 pr_vdebug("descriptor too short\n");
1598 return -EINVAL;
1601 /* If we have at least as many bytes as the descriptor takes? */
1602 length = _ds->bLength;
1603 if (len < length) {
1604 pr_vdebug("descriptor longer then available data\n");
1605 return -EINVAL;
1608 #define __entity_check_INTERFACE(val) 1
1609 #define __entity_check_STRING(val) (val)
1610 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1611 #define __entity(type, val) do { \
1612 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1613 if (unlikely(!__entity_check_ ##type(val))) { \
1614 pr_vdebug("invalid entity's value\n"); \
1615 return -EINVAL; \
1617 ret = entity(FFS_ ##type, &val, _ds, priv); \
1618 if (unlikely(ret < 0)) { \
1619 pr_debug("entity " #type "(%02x); ret = %d\n", \
1620 (val), ret); \
1621 return ret; \
1623 } while (0)
1625 /* Parse descriptor depending on type. */
1626 switch (_ds->bDescriptorType) {
1627 case USB_DT_DEVICE:
1628 case USB_DT_CONFIG:
1629 case USB_DT_STRING:
1630 case USB_DT_DEVICE_QUALIFIER:
1631 /* function can't have any of those */
1632 pr_vdebug("descriptor reserved for gadget: %d\n",
1633 _ds->bDescriptorType);
1634 return -EINVAL;
1636 case USB_DT_INTERFACE: {
1637 struct usb_interface_descriptor *ds = (void *)_ds;
1638 pr_vdebug("interface descriptor\n");
1639 if (length != sizeof *ds)
1640 goto inv_length;
1642 __entity(INTERFACE, ds->bInterfaceNumber);
1643 if (ds->iInterface)
1644 __entity(STRING, ds->iInterface);
1646 break;
1648 case USB_DT_ENDPOINT: {
1649 struct usb_endpoint_descriptor *ds = (void *)_ds;
1650 pr_vdebug("endpoint descriptor\n");
1651 if (length != USB_DT_ENDPOINT_SIZE &&
1652 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1653 goto inv_length;
1654 __entity(ENDPOINT, ds->bEndpointAddress);
1656 break;
1658 case USB_DT_OTG:
1659 if (length != sizeof(struct usb_otg_descriptor))
1660 goto inv_length;
1661 break;
1663 case USB_DT_INTERFACE_ASSOCIATION: {
1664 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1665 pr_vdebug("interface association descriptor\n");
1666 if (length != sizeof *ds)
1667 goto inv_length;
1668 if (ds->iFunction)
1669 __entity(STRING, ds->iFunction);
1671 break;
1673 case USB_DT_OTHER_SPEED_CONFIG:
1674 case USB_DT_INTERFACE_POWER:
1675 case USB_DT_DEBUG:
1676 case USB_DT_SECURITY:
1677 case USB_DT_CS_RADIO_CONTROL:
1678 /* TODO */
1679 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1680 return -EINVAL;
1682 default:
1683 /* We should never be here */
1684 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1685 return -EINVAL;
1687 inv_length:
1688 pr_vdebug("invalid length: %d (descriptor %d)\n",
1689 _ds->bLength, _ds->bDescriptorType);
1690 return -EINVAL;
1693 #undef __entity
1694 #undef __entity_check_DESCRIPTOR
1695 #undef __entity_check_INTERFACE
1696 #undef __entity_check_STRING
1697 #undef __entity_check_ENDPOINT
1699 return length;
1702 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1703 ffs_entity_callback entity, void *priv)
1705 const unsigned _len = len;
1706 unsigned long num = 0;
1708 ENTER();
1710 for (;;) {
1711 int ret;
1713 if (num == count)
1714 data = NULL;
1716 /* Record "descriptor" entity */
1717 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1718 if (unlikely(ret < 0)) {
1719 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1720 num, ret);
1721 return ret;
1724 if (!data)
1725 return _len - len;
1727 ret = ffs_do_desc(data, len, entity, priv);
1728 if (unlikely(ret < 0)) {
1729 pr_debug("%s returns %d\n", __func__, ret);
1730 return ret;
1733 len -= ret;
1734 data += ret;
1735 ++num;
1739 static int __ffs_data_do_entity(enum ffs_entity_type type,
1740 u8 *valuep, struct usb_descriptor_header *desc,
1741 void *priv)
1743 struct ffs_data *ffs = priv;
1745 ENTER();
1747 switch (type) {
1748 case FFS_DESCRIPTOR:
1749 break;
1751 case FFS_INTERFACE:
1753 * Interfaces are indexed from zero so if we
1754 * encountered interface "n" then there are at least
1755 * "n+1" interfaces.
1757 if (*valuep >= ffs->interfaces_count)
1758 ffs->interfaces_count = *valuep + 1;
1759 break;
1761 case FFS_STRING:
1763 * Strings are indexed from 1 (0 is magic ;) reserved
1764 * for languages list or some such)
1766 if (*valuep > ffs->strings_count)
1767 ffs->strings_count = *valuep;
1768 break;
1770 case FFS_ENDPOINT:
1771 /* Endpoints are indexed from 1 as well. */
1772 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1773 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1774 break;
1777 return 0;
1780 static int __ffs_data_got_descs(struct ffs_data *ffs,
1781 char *const _data, size_t len)
1783 unsigned fs_count, hs_count;
1784 int fs_len, ret = -EINVAL;
1785 char *data = _data;
1787 ENTER();
1789 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
1790 get_unaligned_le32(data + 4) != len))
1791 goto error;
1792 fs_count = get_unaligned_le32(data + 8);
1793 hs_count = get_unaligned_le32(data + 12);
1795 if (!fs_count && !hs_count)
1796 goto einval;
1798 data += 16;
1799 len -= 16;
1801 if (likely(fs_count)) {
1802 fs_len = ffs_do_descs(fs_count, data, len,
1803 __ffs_data_do_entity, ffs);
1804 if (unlikely(fs_len < 0)) {
1805 ret = fs_len;
1806 goto error;
1809 data += fs_len;
1810 len -= fs_len;
1811 } else {
1812 fs_len = 0;
1815 if (likely(hs_count)) {
1816 ret = ffs_do_descs(hs_count, data, len,
1817 __ffs_data_do_entity, ffs);
1818 if (unlikely(ret < 0))
1819 goto error;
1820 } else {
1821 ret = 0;
1824 if (unlikely(len != ret))
1825 goto einval;
1827 ffs->raw_fs_descs_length = fs_len;
1828 ffs->raw_descs_length = fs_len + ret;
1829 ffs->raw_descs = _data;
1830 ffs->fs_descs_count = fs_count;
1831 ffs->hs_descs_count = hs_count;
1833 return 0;
1835 einval:
1836 ret = -EINVAL;
1837 error:
1838 kfree(_data);
1839 return ret;
1842 static int __ffs_data_got_strings(struct ffs_data *ffs,
1843 char *const _data, size_t len)
1845 u32 str_count, needed_count, lang_count;
1846 struct usb_gadget_strings **stringtabs, *t;
1847 struct usb_string *strings, *s;
1848 const char *data = _data;
1850 ENTER();
1852 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1853 get_unaligned_le32(data + 4) != len))
1854 goto error;
1855 str_count = get_unaligned_le32(data + 8);
1856 lang_count = get_unaligned_le32(data + 12);
1858 /* if one is zero the other must be zero */
1859 if (unlikely(!str_count != !lang_count))
1860 goto error;
1862 /* Do we have at least as many strings as descriptors need? */
1863 needed_count = ffs->strings_count;
1864 if (unlikely(str_count < needed_count))
1865 goto error;
1868 * If we don't need any strings just return and free all
1869 * memory.
1871 if (!needed_count) {
1872 kfree(_data);
1873 return 0;
1876 /* Allocate everything in one chunk so there's less maintenance. */
1878 struct {
1879 struct usb_gadget_strings *stringtabs[lang_count + 1];
1880 struct usb_gadget_strings stringtab[lang_count];
1881 struct usb_string strings[lang_count*(needed_count+1)];
1882 } *d;
1883 unsigned i = 0;
1885 d = kmalloc(sizeof *d, GFP_KERNEL);
1886 if (unlikely(!d)) {
1887 kfree(_data);
1888 return -ENOMEM;
1891 stringtabs = d->stringtabs;
1892 t = d->stringtab;
1893 i = lang_count;
1894 do {
1895 *stringtabs++ = t++;
1896 } while (--i);
1897 *stringtabs = NULL;
1899 stringtabs = d->stringtabs;
1900 t = d->stringtab;
1901 s = d->strings;
1902 strings = s;
1905 /* For each language */
1906 data += 16;
1907 len -= 16;
1909 do { /* lang_count > 0 so we can use do-while */
1910 unsigned needed = needed_count;
1912 if (unlikely(len < 3))
1913 goto error_free;
1914 t->language = get_unaligned_le16(data);
1915 t->strings = s;
1916 ++t;
1918 data += 2;
1919 len -= 2;
1921 /* For each string */
1922 do { /* str_count > 0 so we can use do-while */
1923 size_t length = strnlen(data, len);
1925 if (unlikely(length == len))
1926 goto error_free;
1929 * User may provide more strings then we need,
1930 * if that's the case we simply ignore the
1931 * rest
1933 if (likely(needed)) {
1935 * s->id will be set while adding
1936 * function to configuration so for
1937 * now just leave garbage here.
1939 s->s = data;
1940 --needed;
1941 ++s;
1944 data += length + 1;
1945 len -= length + 1;
1946 } while (--str_count);
1948 s->id = 0; /* terminator */
1949 s->s = NULL;
1950 ++s;
1952 } while (--lang_count);
1954 /* Some garbage left? */
1955 if (unlikely(len))
1956 goto error_free;
1958 /* Done! */
1959 ffs->stringtabs = stringtabs;
1960 ffs->raw_strings = _data;
1962 return 0;
1964 error_free:
1965 kfree(stringtabs);
1966 error:
1967 kfree(_data);
1968 return -EINVAL;
1972 /* Events handling and management *******************************************/
1974 static void __ffs_event_add(struct ffs_data *ffs,
1975 enum usb_functionfs_event_type type)
1977 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
1978 int neg = 0;
1981 * Abort any unhandled setup
1983 * We do not need to worry about some cmpxchg() changing value
1984 * of ffs->setup_state without holding the lock because when
1985 * state is FFS_SETUP_PENDING cmpxchg() in several places in
1986 * the source does nothing.
1988 if (ffs->setup_state == FFS_SETUP_PENDING)
1989 ffs->setup_state = FFS_SETUP_CANCELED;
1991 switch (type) {
1992 case FUNCTIONFS_RESUME:
1993 rem_type2 = FUNCTIONFS_SUSPEND;
1994 /* FALL THROUGH */
1995 case FUNCTIONFS_SUSPEND:
1996 case FUNCTIONFS_SETUP:
1997 rem_type1 = type;
1998 /* Discard all similar events */
1999 break;
2001 case FUNCTIONFS_BIND:
2002 case FUNCTIONFS_UNBIND:
2003 case FUNCTIONFS_DISABLE:
2004 case FUNCTIONFS_ENABLE:
2005 /* Discard everything other then power management. */
2006 rem_type1 = FUNCTIONFS_SUSPEND;
2007 rem_type2 = FUNCTIONFS_RESUME;
2008 neg = 1;
2009 break;
2011 default:
2012 BUG();
2016 u8 *ev = ffs->ev.types, *out = ev;
2017 unsigned n = ffs->ev.count;
2018 for (; n; --n, ++ev)
2019 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2020 *out++ = *ev;
2021 else
2022 pr_vdebug("purging event %d\n", *ev);
2023 ffs->ev.count = out - ffs->ev.types;
2026 pr_vdebug("adding event %d\n", type);
2027 ffs->ev.types[ffs->ev.count++] = type;
2028 wake_up_locked(&ffs->ev.waitq);
2031 static void ffs_event_add(struct ffs_data *ffs,
2032 enum usb_functionfs_event_type type)
2034 unsigned long flags;
2035 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2036 __ffs_event_add(ffs, type);
2037 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2041 /* Bind/unbind USB function hooks *******************************************/
2043 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2044 struct usb_descriptor_header *desc,
2045 void *priv)
2047 struct usb_endpoint_descriptor *ds = (void *)desc;
2048 struct ffs_function *func = priv;
2049 struct ffs_ep *ffs_ep;
2052 * If hs_descriptors is not NULL then we are reading hs
2053 * descriptors now
2055 const int isHS = func->function.hs_descriptors != NULL;
2056 unsigned idx;
2058 if (type != FFS_DESCRIPTOR)
2059 return 0;
2061 if (isHS)
2062 func->function.hs_descriptors[(long)valuep] = desc;
2063 else
2064 func->function.descriptors[(long)valuep] = desc;
2066 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2067 return 0;
2069 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2070 ffs_ep = func->eps + idx;
2072 if (unlikely(ffs_ep->descs[isHS])) {
2073 pr_vdebug("two %sspeed descriptors for EP %d\n",
2074 isHS ? "high" : "full",
2075 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2076 return -EINVAL;
2078 ffs_ep->descs[isHS] = ds;
2080 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2081 if (ffs_ep->ep) {
2082 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2083 if (!ds->wMaxPacketSize)
2084 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2085 } else {
2086 struct usb_request *req;
2087 struct usb_ep *ep;
2089 pr_vdebug("autoconfig\n");
2090 ep = usb_ep_autoconfig(func->gadget, ds);
2091 if (unlikely(!ep))
2092 return -ENOTSUPP;
2093 ep->driver_data = func->eps + idx;
2095 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2096 if (unlikely(!req))
2097 return -ENOMEM;
2099 ffs_ep->ep = ep;
2100 ffs_ep->req = req;
2101 func->eps_revmap[ds->bEndpointAddress &
2102 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2104 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2106 return 0;
2109 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2110 struct usb_descriptor_header *desc,
2111 void *priv)
2113 struct ffs_function *func = priv;
2114 unsigned idx;
2115 u8 newValue;
2117 switch (type) {
2118 default:
2119 case FFS_DESCRIPTOR:
2120 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2121 return 0;
2123 case FFS_INTERFACE:
2124 idx = *valuep;
2125 if (func->interfaces_nums[idx] < 0) {
2126 int id = usb_interface_id(func->conf, &func->function);
2127 if (unlikely(id < 0))
2128 return id;
2129 func->interfaces_nums[idx] = id;
2131 newValue = func->interfaces_nums[idx];
2132 break;
2134 case FFS_STRING:
2135 /* String' IDs are allocated when fsf_data is bound to cdev */
2136 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2137 break;
2139 case FFS_ENDPOINT:
2141 * USB_DT_ENDPOINT are handled in
2142 * __ffs_func_bind_do_descs().
2144 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2145 return 0;
2147 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2148 if (unlikely(!func->eps[idx].ep))
2149 return -EINVAL;
2152 struct usb_endpoint_descriptor **descs;
2153 descs = func->eps[idx].descs;
2154 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2156 break;
2159 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2160 *valuep = newValue;
2161 return 0;
2164 static int ffs_func_bind(struct usb_configuration *c,
2165 struct usb_function *f)
2167 struct ffs_function *func = ffs_func_from_usb(f);
2168 struct ffs_data *ffs = func->ffs;
2170 const int full = !!func->ffs->fs_descs_count;
2171 const int high = gadget_is_dualspeed(func->gadget) &&
2172 func->ffs->hs_descs_count;
2174 int ret;
2176 /* Make it a single chunk, less management later on */
2177 struct {
2178 struct ffs_ep eps[ffs->eps_count];
2179 struct usb_descriptor_header
2180 *fs_descs[full ? ffs->fs_descs_count + 1 : 0];
2181 struct usb_descriptor_header
2182 *hs_descs[high ? ffs->hs_descs_count + 1 : 0];
2183 short inums[ffs->interfaces_count];
2184 char raw_descs[high ? ffs->raw_descs_length
2185 : ffs->raw_fs_descs_length];
2186 } *data;
2188 ENTER();
2190 /* Only high speed but not supported by gadget? */
2191 if (unlikely(!(full | high)))
2192 return -ENOTSUPP;
2194 /* Allocate */
2195 data = kmalloc(sizeof *data, GFP_KERNEL);
2196 if (unlikely(!data))
2197 return -ENOMEM;
2199 /* Zero */
2200 memset(data->eps, 0, sizeof data->eps);
2201 memcpy(data->raw_descs, ffs->raw_descs + 16, sizeof data->raw_descs);
2202 memset(data->inums, 0xff, sizeof data->inums);
2203 for (ret = ffs->eps_count; ret; --ret)
2204 data->eps[ret].num = -1;
2206 /* Save pointers */
2207 func->eps = data->eps;
2208 func->interfaces_nums = data->inums;
2211 * Go through all the endpoint descriptors and allocate
2212 * endpoints first, so that later we can rewrite the endpoint
2213 * numbers without worrying that it may be described later on.
2215 if (likely(full)) {
2216 func->function.descriptors = data->fs_descs;
2217 ret = ffs_do_descs(ffs->fs_descs_count,
2218 data->raw_descs,
2219 sizeof data->raw_descs,
2220 __ffs_func_bind_do_descs, func);
2221 if (unlikely(ret < 0))
2222 goto error;
2223 } else {
2224 ret = 0;
2227 if (likely(high)) {
2228 func->function.hs_descriptors = data->hs_descs;
2229 ret = ffs_do_descs(ffs->hs_descs_count,
2230 data->raw_descs + ret,
2231 (sizeof data->raw_descs) - ret,
2232 __ffs_func_bind_do_descs, func);
2236 * Now handle interface numbers allocation and interface and
2237 * endpoint numbers rewriting. We can do that in one go
2238 * now.
2240 ret = ffs_do_descs(ffs->fs_descs_count +
2241 (high ? ffs->hs_descs_count : 0),
2242 data->raw_descs, sizeof data->raw_descs,
2243 __ffs_func_bind_do_nums, func);
2244 if (unlikely(ret < 0))
2245 goto error;
2247 /* And we're done */
2248 ffs_event_add(ffs, FUNCTIONFS_BIND);
2249 return 0;
2251 error:
2252 /* XXX Do we need to release all claimed endpoints here? */
2253 return ret;
2257 /* Other USB function hooks *************************************************/
2259 static void ffs_func_unbind(struct usb_configuration *c,
2260 struct usb_function *f)
2262 struct ffs_function *func = ffs_func_from_usb(f);
2263 struct ffs_data *ffs = func->ffs;
2265 ENTER();
2267 if (ffs->func == func) {
2268 ffs_func_eps_disable(func);
2269 ffs->func = NULL;
2272 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2274 ffs_func_free(func);
2277 static int ffs_func_set_alt(struct usb_function *f,
2278 unsigned interface, unsigned alt)
2280 struct ffs_function *func = ffs_func_from_usb(f);
2281 struct ffs_data *ffs = func->ffs;
2282 int ret = 0, intf;
2284 if (alt != (unsigned)-1) {
2285 intf = ffs_func_revmap_intf(func, interface);
2286 if (unlikely(intf < 0))
2287 return intf;
2290 if (ffs->func)
2291 ffs_func_eps_disable(ffs->func);
2293 if (ffs->state != FFS_ACTIVE)
2294 return -ENODEV;
2296 if (alt == (unsigned)-1) {
2297 ffs->func = NULL;
2298 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2299 return 0;
2302 ffs->func = func;
2303 ret = ffs_func_eps_enable(func);
2304 if (likely(ret >= 0))
2305 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2306 return ret;
2309 static void ffs_func_disable(struct usb_function *f)
2311 ffs_func_set_alt(f, 0, (unsigned)-1);
2314 static int ffs_func_setup(struct usb_function *f,
2315 const struct usb_ctrlrequest *creq)
2317 struct ffs_function *func = ffs_func_from_usb(f);
2318 struct ffs_data *ffs = func->ffs;
2319 unsigned long flags;
2320 int ret;
2322 ENTER();
2324 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2325 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2326 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2327 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2328 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2331 * Most requests directed to interface go through here
2332 * (notable exceptions are set/get interface) so we need to
2333 * handle them. All other either handled by composite or
2334 * passed to usb_configuration->setup() (if one is set). No
2335 * matter, we will handle requests directed to endpoint here
2336 * as well (as it's straightforward) but what to do with any
2337 * other request?
2339 if (ffs->state != FFS_ACTIVE)
2340 return -ENODEV;
2342 switch (creq->bRequestType & USB_RECIP_MASK) {
2343 case USB_RECIP_INTERFACE:
2344 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2345 if (unlikely(ret < 0))
2346 return ret;
2347 break;
2349 case USB_RECIP_ENDPOINT:
2350 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2351 if (unlikely(ret < 0))
2352 return ret;
2353 break;
2355 default:
2356 return -EOPNOTSUPP;
2359 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2360 ffs->ev.setup = *creq;
2361 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2362 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2363 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2365 return 0;
2368 static void ffs_func_suspend(struct usb_function *f)
2370 ENTER();
2371 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2374 static void ffs_func_resume(struct usb_function *f)
2376 ENTER();
2377 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2381 /* Endpoint and interface numbers reverse mapping ***************************/
2383 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2385 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2386 return num ? num : -EDOM;
2389 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2391 short *nums = func->interfaces_nums;
2392 unsigned count = func->ffs->interfaces_count;
2394 for (; count; --count, ++nums) {
2395 if (*nums >= 0 && *nums == intf)
2396 return nums - func->interfaces_nums;
2399 return -EDOM;
2403 /* Misc helper functions ****************************************************/
2405 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2407 return nonblock
2408 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2409 : mutex_lock_interruptible(mutex);
2412 static char *ffs_prepare_buffer(const char * __user buf, size_t len)
2414 char *data;
2416 if (unlikely(!len))
2417 return NULL;
2419 data = kmalloc(len, GFP_KERNEL);
2420 if (unlikely(!data))
2421 return ERR_PTR(-ENOMEM);
2423 if (unlikely(__copy_from_user(data, buf, len))) {
2424 kfree(data);
2425 return ERR_PTR(-EFAULT);
2428 pr_vdebug("Buffer from user space:\n");
2429 ffs_dump_mem("", data, len);
2431 return data;