include: replace linux/module.h with "struct module" wherever possible
[linux-2.6/next.git] / drivers / usb / gadget / f_fs.c
blobdac59ae80390980cf664915e68a6c67a824830e9
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 <linux/export.h>
33 #include <asm/unaligned.h>
35 #include <linux/usb/composite.h>
36 #include <linux/usb/functionfs.h>
39 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
42 /* Debugging ****************************************************************/
44 #ifdef VERBOSE_DEBUG
45 # define pr_vdebug pr_debug
46 # define ffs_dump_mem(prefix, ptr, len) \
47 print_hex_dump_bytes(pr_fmt(prefix ": "), DUMP_PREFIX_NONE, ptr, len)
48 #else
49 # define pr_vdebug(...) do { } while (0)
50 # define ffs_dump_mem(prefix, ptr, len) do { } while (0)
51 #endif /* VERBOSE_DEBUG */
53 #define ENTER() pr_vdebug("%s()\n", __func__)
56 /* The data structure and setup file ****************************************/
58 enum ffs_state {
60 * Waiting for descriptors and strings.
62 * In this state no open(2), read(2) or write(2) on epfiles
63 * may succeed (which should not be the problem as there
64 * should be no such files opened in the first place).
66 FFS_READ_DESCRIPTORS,
67 FFS_READ_STRINGS,
70 * We've got descriptors and strings. We are or have called
71 * functionfs_ready_callback(). functionfs_bind() may have
72 * been called but we don't know.
74 * This is the only state in which operations on epfiles may
75 * succeed.
77 FFS_ACTIVE,
80 * All endpoints have been closed. This state is also set if
81 * we encounter an unrecoverable error. The only
82 * unrecoverable error is situation when after reading strings
83 * from user space we fail to initialise epfiles or
84 * functionfs_ready_callback() returns with error (<0).
86 * In this state no open(2), read(2) or write(2) (both on ep0
87 * as well as epfile) may succeed (at this point epfiles are
88 * unlinked and all closed so this is not a problem; ep0 is
89 * also closed but ep0 file exists and so open(2) on ep0 must
90 * fail).
92 FFS_CLOSING
96 enum ffs_setup_state {
97 /* There is no setup request pending. */
98 FFS_NO_SETUP,
100 * User has read events and there was a setup request event
101 * there. The next read/write on ep0 will handle the
102 * request.
104 FFS_SETUP_PENDING,
106 * There was event pending but before user space handled it
107 * some other event was introduced which canceled existing
108 * setup. If this state is set read/write on ep0 return
109 * -EIDRM. This state is only set when adding event.
111 FFS_SETUP_CANCELED
116 struct ffs_epfile;
117 struct ffs_function;
119 struct ffs_data {
120 struct usb_gadget *gadget;
123 * Protect access read/write operations, only one read/write
124 * at a time. As a consequence protects ep0req and company.
125 * While setup request is being processed (queued) this is
126 * held.
128 struct mutex mutex;
131 * Protect access to endpoint related structures (basically
132 * usb_ep_queue(), usb_ep_dequeue(), etc. calls) except for
133 * endpoint zero.
135 spinlock_t eps_lock;
138 * XXX REVISIT do we need our own request? Since we are not
139 * handling setup requests immediately user space may be so
140 * slow that another setup will be sent to the gadget but this
141 * time not to us but another function and then there could be
142 * a race. Is that the case? Or maybe we can use cdev->req
143 * after all, maybe we just need some spinlock for that?
145 struct usb_request *ep0req; /* P: mutex */
146 struct completion ep0req_completion; /* P: mutex */
147 int ep0req_status; /* P: mutex */
149 /* reference counter */
150 atomic_t ref;
151 /* how many files are opened (EP0 and others) */
152 atomic_t opened;
154 /* EP0 state */
155 enum ffs_state state;
158 * Possible transitions:
159 * + FFS_NO_SETUP -> FFS_SETUP_PENDING -- P: ev.waitq.lock
160 * happens only in ep0 read which is P: mutex
161 * + FFS_SETUP_PENDING -> FFS_NO_SETUP -- P: ev.waitq.lock
162 * happens only in ep0 i/o which is P: mutex
163 * + FFS_SETUP_PENDING -> FFS_SETUP_CANCELED -- P: ev.waitq.lock
164 * + FFS_SETUP_CANCELED -> FFS_NO_SETUP -- cmpxchg
166 enum ffs_setup_state setup_state;
168 #define FFS_SETUP_STATE(ffs) \
169 ((enum ffs_setup_state)cmpxchg(&(ffs)->setup_state, \
170 FFS_SETUP_CANCELED, FFS_NO_SETUP))
172 /* Events & such. */
173 struct {
174 u8 types[4];
175 unsigned short count;
176 /* XXX REVISIT need to update it in some places, or do we? */
177 unsigned short can_stall;
178 struct usb_ctrlrequest setup;
180 wait_queue_head_t waitq;
181 } ev; /* the whole structure, P: ev.waitq.lock */
183 /* Flags */
184 unsigned long flags;
185 #define FFS_FL_CALL_CLOSED_CALLBACK 0
186 #define FFS_FL_BOUND 1
188 /* Active function */
189 struct ffs_function *func;
192 * Device name, write once when file system is mounted.
193 * Intended for user to read if she wants.
195 const char *dev_name;
196 /* Private data for our user (ie. gadget). Managed by user. */
197 void *private_data;
199 /* filled by __ffs_data_got_descs() */
201 * Real descriptors are 16 bytes after raw_descs (so you need
202 * to skip 16 bytes (ie. ffs->raw_descs + 16) to get to the
203 * first full speed descriptor). raw_descs_length and
204 * raw_fs_descs_length do not have those 16 bytes added.
206 const void *raw_descs;
207 unsigned raw_descs_length;
208 unsigned raw_fs_descs_length;
209 unsigned fs_descs_count;
210 unsigned hs_descs_count;
212 unsigned short strings_count;
213 unsigned short interfaces_count;
214 unsigned short eps_count;
215 unsigned short _pad1;
217 /* filled by __ffs_data_got_strings() */
218 /* ids in stringtabs are set in functionfs_bind() */
219 const void *raw_strings;
220 struct usb_gadget_strings **stringtabs;
223 * File system's super block, write once when file system is
224 * mounted.
226 struct super_block *sb;
228 /* File permissions, written once when fs is mounted */
229 struct ffs_file_perms {
230 umode_t mode;
231 uid_t uid;
232 gid_t gid;
233 } file_perms;
236 * The endpoint files, filled by ffs_epfiles_create(),
237 * destroyed by ffs_epfiles_destroy().
239 struct ffs_epfile *epfiles;
242 /* Reference counter handling */
243 static void ffs_data_get(struct ffs_data *ffs);
244 static void ffs_data_put(struct ffs_data *ffs);
245 /* Creates new ffs_data object. */
246 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
248 /* Opened counter handling. */
249 static void ffs_data_opened(struct ffs_data *ffs);
250 static void ffs_data_closed(struct ffs_data *ffs);
252 /* Called with ffs->mutex held; take over ownership of data. */
253 static int __must_check
254 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
255 static int __must_check
256 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
259 /* The function structure ***************************************************/
261 struct ffs_ep;
263 struct ffs_function {
264 struct usb_configuration *conf;
265 struct usb_gadget *gadget;
266 struct ffs_data *ffs;
268 struct ffs_ep *eps;
269 u8 eps_revmap[16];
270 short *interfaces_nums;
272 struct usb_function function;
276 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
278 return container_of(f, struct ffs_function, function);
281 static void ffs_func_free(struct ffs_function *func);
283 static void ffs_func_eps_disable(struct ffs_function *func);
284 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
286 static int ffs_func_bind(struct usb_configuration *,
287 struct usb_function *);
288 static void ffs_func_unbind(struct usb_configuration *,
289 struct usb_function *);
290 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
291 static void ffs_func_disable(struct usb_function *);
292 static int ffs_func_setup(struct usb_function *,
293 const struct usb_ctrlrequest *);
294 static void ffs_func_suspend(struct usb_function *);
295 static void ffs_func_resume(struct usb_function *);
298 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
299 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
302 /* The endpoints structures *************************************************/
304 struct ffs_ep {
305 struct usb_ep *ep; /* P: ffs->eps_lock */
306 struct usb_request *req; /* P: epfile->mutex */
308 /* [0]: full speed, [1]: high speed */
309 struct usb_endpoint_descriptor *descs[2];
311 u8 num;
313 int status; /* P: epfile->mutex */
316 struct ffs_epfile {
317 /* Protects ep->ep and ep->req. */
318 struct mutex mutex;
319 wait_queue_head_t wait;
321 struct ffs_data *ffs;
322 struct ffs_ep *ep; /* P: ffs->eps_lock */
324 struct dentry *dentry;
326 char name[5];
328 unsigned char in; /* P: ffs->eps_lock */
329 unsigned char isoc; /* P: ffs->eps_lock */
331 unsigned char _pad;
334 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
335 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
337 static struct inode *__must_check
338 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
339 const struct file_operations *fops,
340 struct dentry **dentry_p);
343 /* Misc helper functions ****************************************************/
345 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
346 __attribute__((warn_unused_result, nonnull));
347 static char *ffs_prepare_buffer(const char * __user buf, size_t len)
348 __attribute__((warn_unused_result, nonnull));
351 /* Control file aka ep0 *****************************************************/
353 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
355 struct ffs_data *ffs = req->context;
357 complete_all(&ffs->ep0req_completion);
360 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
362 struct usb_request *req = ffs->ep0req;
363 int ret;
365 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
367 spin_unlock_irq(&ffs->ev.waitq.lock);
369 req->buf = data;
370 req->length = len;
373 * UDC layer requires to provide a buffer even for ZLP, but should
374 * not use it at all. Let's provide some poisoned pointer to catch
375 * possible bug in the driver.
377 if (req->buf == NULL)
378 req->buf = (void *)0xDEADBABE;
380 INIT_COMPLETION(ffs->ep0req_completion);
382 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
383 if (unlikely(ret < 0))
384 return ret;
386 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
387 if (unlikely(ret)) {
388 usb_ep_dequeue(ffs->gadget->ep0, req);
389 return -EINTR;
392 ffs->setup_state = FFS_NO_SETUP;
393 return ffs->ep0req_status;
396 static int __ffs_ep0_stall(struct ffs_data *ffs)
398 if (ffs->ev.can_stall) {
399 pr_vdebug("ep0 stall\n");
400 usb_ep_set_halt(ffs->gadget->ep0);
401 ffs->setup_state = FFS_NO_SETUP;
402 return -EL2HLT;
403 } else {
404 pr_debug("bogus ep0 stall!\n");
405 return -ESRCH;
409 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
410 size_t len, loff_t *ptr)
412 struct ffs_data *ffs = file->private_data;
413 ssize_t ret;
414 char *data;
416 ENTER();
418 /* Fast check if setup was canceled */
419 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
420 return -EIDRM;
422 /* Acquire mutex */
423 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
424 if (unlikely(ret < 0))
425 return ret;
427 /* Check state */
428 switch (ffs->state) {
429 case FFS_READ_DESCRIPTORS:
430 case FFS_READ_STRINGS:
431 /* Copy data */
432 if (unlikely(len < 16)) {
433 ret = -EINVAL;
434 break;
437 data = ffs_prepare_buffer(buf, len);
438 if (IS_ERR(data)) {
439 ret = PTR_ERR(data);
440 break;
443 /* Handle data */
444 if (ffs->state == FFS_READ_DESCRIPTORS) {
445 pr_info("read descriptors\n");
446 ret = __ffs_data_got_descs(ffs, data, len);
447 if (unlikely(ret < 0))
448 break;
450 ffs->state = FFS_READ_STRINGS;
451 ret = len;
452 } else {
453 pr_info("read strings\n");
454 ret = __ffs_data_got_strings(ffs, data, len);
455 if (unlikely(ret < 0))
456 break;
458 ret = ffs_epfiles_create(ffs);
459 if (unlikely(ret)) {
460 ffs->state = FFS_CLOSING;
461 break;
464 ffs->state = FFS_ACTIVE;
465 mutex_unlock(&ffs->mutex);
467 ret = functionfs_ready_callback(ffs);
468 if (unlikely(ret < 0)) {
469 ffs->state = FFS_CLOSING;
470 return ret;
473 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
474 return len;
476 break;
478 case FFS_ACTIVE:
479 data = NULL;
481 * We're called from user space, we can use _irq
482 * rather then _irqsave
484 spin_lock_irq(&ffs->ev.waitq.lock);
485 switch (FFS_SETUP_STATE(ffs)) {
486 case FFS_SETUP_CANCELED:
487 ret = -EIDRM;
488 goto done_spin;
490 case FFS_NO_SETUP:
491 ret = -ESRCH;
492 goto done_spin;
494 case FFS_SETUP_PENDING:
495 break;
498 /* FFS_SETUP_PENDING */
499 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
500 spin_unlock_irq(&ffs->ev.waitq.lock);
501 ret = __ffs_ep0_stall(ffs);
502 break;
505 /* FFS_SETUP_PENDING and not stall */
506 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
508 spin_unlock_irq(&ffs->ev.waitq.lock);
510 data = ffs_prepare_buffer(buf, len);
511 if (IS_ERR(data)) {
512 ret = PTR_ERR(data);
513 break;
516 spin_lock_irq(&ffs->ev.waitq.lock);
519 * We are guaranteed to be still in FFS_ACTIVE state
520 * but the state of setup could have changed from
521 * FFS_SETUP_PENDING to FFS_SETUP_CANCELED so we need
522 * to check for that. If that happened we copied data
523 * from user space in vain but it's unlikely.
525 * For sure we are not in FFS_NO_SETUP since this is
526 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
527 * transition can be performed and it's protected by
528 * mutex.
530 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
531 ret = -EIDRM;
532 done_spin:
533 spin_unlock_irq(&ffs->ev.waitq.lock);
534 } else {
535 /* unlocks spinlock */
536 ret = __ffs_ep0_queue_wait(ffs, data, len);
538 kfree(data);
539 break;
541 default:
542 ret = -EBADFD;
543 break;
546 mutex_unlock(&ffs->mutex);
547 return ret;
550 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
551 size_t n)
554 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
555 * to release them.
557 struct usb_functionfs_event events[n];
558 unsigned i = 0;
560 memset(events, 0, sizeof events);
562 do {
563 events[i].type = ffs->ev.types[i];
564 if (events[i].type == FUNCTIONFS_SETUP) {
565 events[i].u.setup = ffs->ev.setup;
566 ffs->setup_state = FFS_SETUP_PENDING;
568 } while (++i < n);
570 if (n < ffs->ev.count) {
571 ffs->ev.count -= n;
572 memmove(ffs->ev.types, ffs->ev.types + n,
573 ffs->ev.count * sizeof *ffs->ev.types);
574 } else {
575 ffs->ev.count = 0;
578 spin_unlock_irq(&ffs->ev.waitq.lock);
579 mutex_unlock(&ffs->mutex);
581 return unlikely(__copy_to_user(buf, events, sizeof events))
582 ? -EFAULT : sizeof events;
585 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
586 size_t len, loff_t *ptr)
588 struct ffs_data *ffs = file->private_data;
589 char *data = NULL;
590 size_t n;
591 int ret;
593 ENTER();
595 /* Fast check if setup was canceled */
596 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
597 return -EIDRM;
599 /* Acquire mutex */
600 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
601 if (unlikely(ret < 0))
602 return ret;
604 /* Check state */
605 if (ffs->state != FFS_ACTIVE) {
606 ret = -EBADFD;
607 goto done_mutex;
611 * We're called from user space, we can use _irq rather then
612 * _irqsave
614 spin_lock_irq(&ffs->ev.waitq.lock);
616 switch (FFS_SETUP_STATE(ffs)) {
617 case FFS_SETUP_CANCELED:
618 ret = -EIDRM;
619 break;
621 case FFS_NO_SETUP:
622 n = len / sizeof(struct usb_functionfs_event);
623 if (unlikely(!n)) {
624 ret = -EINVAL;
625 break;
628 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
629 ret = -EAGAIN;
630 break;
633 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
634 ffs->ev.count)) {
635 ret = -EINTR;
636 break;
639 return __ffs_ep0_read_events(ffs, buf,
640 min(n, (size_t)ffs->ev.count));
642 case FFS_SETUP_PENDING:
643 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
644 spin_unlock_irq(&ffs->ev.waitq.lock);
645 ret = __ffs_ep0_stall(ffs);
646 goto done_mutex;
649 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
651 spin_unlock_irq(&ffs->ev.waitq.lock);
653 if (likely(len)) {
654 data = kmalloc(len, GFP_KERNEL);
655 if (unlikely(!data)) {
656 ret = -ENOMEM;
657 goto done_mutex;
661 spin_lock_irq(&ffs->ev.waitq.lock);
663 /* See ffs_ep0_write() */
664 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
665 ret = -EIDRM;
666 break;
669 /* unlocks spinlock */
670 ret = __ffs_ep0_queue_wait(ffs, data, len);
671 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
672 ret = -EFAULT;
673 goto done_mutex;
675 default:
676 ret = -EBADFD;
677 break;
680 spin_unlock_irq(&ffs->ev.waitq.lock);
681 done_mutex:
682 mutex_unlock(&ffs->mutex);
683 kfree(data);
684 return ret;
687 static int ffs_ep0_open(struct inode *inode, struct file *file)
689 struct ffs_data *ffs = inode->i_private;
691 ENTER();
693 if (unlikely(ffs->state == FFS_CLOSING))
694 return -EBUSY;
696 file->private_data = ffs;
697 ffs_data_opened(ffs);
699 return 0;
702 static int ffs_ep0_release(struct inode *inode, struct file *file)
704 struct ffs_data *ffs = file->private_data;
706 ENTER();
708 ffs_data_closed(ffs);
710 return 0;
713 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
715 struct ffs_data *ffs = file->private_data;
716 struct usb_gadget *gadget = ffs->gadget;
717 long ret;
719 ENTER();
721 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
722 struct ffs_function *func = ffs->func;
723 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
724 } else if (gadget->ops->ioctl) {
725 ret = gadget->ops->ioctl(gadget, code, value);
726 } else {
727 ret = -ENOTTY;
730 return ret;
733 static const struct file_operations ffs_ep0_operations = {
734 .owner = THIS_MODULE,
735 .llseek = no_llseek,
737 .open = ffs_ep0_open,
738 .write = ffs_ep0_write,
739 .read = ffs_ep0_read,
740 .release = ffs_ep0_release,
741 .unlocked_ioctl = ffs_ep0_ioctl,
745 /* "Normal" endpoints operations ********************************************/
747 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
749 ENTER();
750 if (likely(req->context)) {
751 struct ffs_ep *ep = _ep->driver_data;
752 ep->status = req->status ? req->status : req->actual;
753 complete(req->context);
757 static ssize_t ffs_epfile_io(struct file *file,
758 char __user *buf, size_t len, int read)
760 struct ffs_epfile *epfile = file->private_data;
761 struct ffs_ep *ep;
762 char *data = NULL;
763 ssize_t ret;
764 int halt;
766 goto first_try;
767 do {
768 spin_unlock_irq(&epfile->ffs->eps_lock);
769 mutex_unlock(&epfile->mutex);
771 first_try:
772 /* Are we still active? */
773 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
774 ret = -ENODEV;
775 goto error;
778 /* Wait for endpoint to be enabled */
779 ep = epfile->ep;
780 if (!ep) {
781 if (file->f_flags & O_NONBLOCK) {
782 ret = -EAGAIN;
783 goto error;
786 if (wait_event_interruptible(epfile->wait,
787 (ep = epfile->ep))) {
788 ret = -EINTR;
789 goto error;
793 /* Do we halt? */
794 halt = !read == !epfile->in;
795 if (halt && epfile->isoc) {
796 ret = -EINVAL;
797 goto error;
800 /* Allocate & copy */
801 if (!halt && !data) {
802 data = kzalloc(len, GFP_KERNEL);
803 if (unlikely(!data))
804 return -ENOMEM;
806 if (!read &&
807 unlikely(__copy_from_user(data, buf, len))) {
808 ret = -EFAULT;
809 goto error;
813 /* We will be using request */
814 ret = ffs_mutex_lock(&epfile->mutex,
815 file->f_flags & O_NONBLOCK);
816 if (unlikely(ret))
817 goto error;
820 * We're called from user space, we can use _irq rather then
821 * _irqsave
823 spin_lock_irq(&epfile->ffs->eps_lock);
826 * While we were acquiring mutex endpoint got disabled
827 * or changed?
829 } while (unlikely(epfile->ep != ep));
831 /* Halt */
832 if (unlikely(halt)) {
833 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
834 usb_ep_set_halt(ep->ep);
835 spin_unlock_irq(&epfile->ffs->eps_lock);
836 ret = -EBADMSG;
837 } else {
838 /* Fire the request */
839 DECLARE_COMPLETION_ONSTACK(done);
841 struct usb_request *req = ep->req;
842 req->context = &done;
843 req->complete = ffs_epfile_io_complete;
844 req->buf = data;
845 req->length = len;
847 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
849 spin_unlock_irq(&epfile->ffs->eps_lock);
851 if (unlikely(ret < 0)) {
852 /* nop */
853 } else if (unlikely(wait_for_completion_interruptible(&done))) {
854 ret = -EINTR;
855 usb_ep_dequeue(ep->ep, req);
856 } else {
857 ret = ep->status;
858 if (read && ret > 0 &&
859 unlikely(copy_to_user(buf, data, ret)))
860 ret = -EFAULT;
864 mutex_unlock(&epfile->mutex);
865 error:
866 kfree(data);
867 return ret;
870 static ssize_t
871 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
872 loff_t *ptr)
874 ENTER();
876 return ffs_epfile_io(file, (char __user *)buf, len, 0);
879 static ssize_t
880 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
882 ENTER();
884 return ffs_epfile_io(file, buf, len, 1);
887 static int
888 ffs_epfile_open(struct inode *inode, struct file *file)
890 struct ffs_epfile *epfile = inode->i_private;
892 ENTER();
894 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
895 return -ENODEV;
897 file->private_data = epfile;
898 ffs_data_opened(epfile->ffs);
900 return 0;
903 static int
904 ffs_epfile_release(struct inode *inode, struct file *file)
906 struct ffs_epfile *epfile = inode->i_private;
908 ENTER();
910 ffs_data_closed(epfile->ffs);
912 return 0;
915 static long ffs_epfile_ioctl(struct file *file, unsigned code,
916 unsigned long value)
918 struct ffs_epfile *epfile = file->private_data;
919 int ret;
921 ENTER();
923 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
924 return -ENODEV;
926 spin_lock_irq(&epfile->ffs->eps_lock);
927 if (likely(epfile->ep)) {
928 switch (code) {
929 case FUNCTIONFS_FIFO_STATUS:
930 ret = usb_ep_fifo_status(epfile->ep->ep);
931 break;
932 case FUNCTIONFS_FIFO_FLUSH:
933 usb_ep_fifo_flush(epfile->ep->ep);
934 ret = 0;
935 break;
936 case FUNCTIONFS_CLEAR_HALT:
937 ret = usb_ep_clear_halt(epfile->ep->ep);
938 break;
939 case FUNCTIONFS_ENDPOINT_REVMAP:
940 ret = epfile->ep->num;
941 break;
942 default:
943 ret = -ENOTTY;
945 } else {
946 ret = -ENODEV;
948 spin_unlock_irq(&epfile->ffs->eps_lock);
950 return ret;
953 static const struct file_operations ffs_epfile_operations = {
954 .owner = THIS_MODULE,
955 .llseek = no_llseek,
957 .open = ffs_epfile_open,
958 .write = ffs_epfile_write,
959 .read = ffs_epfile_read,
960 .release = ffs_epfile_release,
961 .unlocked_ioctl = ffs_epfile_ioctl,
965 /* File system and super block operations ***********************************/
968 * Mounting the file system creates a controller file, used first for
969 * function configuration then later for event monitoring.
972 static struct inode *__must_check
973 ffs_sb_make_inode(struct super_block *sb, void *data,
974 const struct file_operations *fops,
975 const struct inode_operations *iops,
976 struct ffs_file_perms *perms)
978 struct inode *inode;
980 ENTER();
982 inode = new_inode(sb);
984 if (likely(inode)) {
985 struct timespec current_time = CURRENT_TIME;
987 inode->i_ino = get_next_ino();
988 inode->i_mode = perms->mode;
989 inode->i_uid = perms->uid;
990 inode->i_gid = perms->gid;
991 inode->i_atime = current_time;
992 inode->i_mtime = current_time;
993 inode->i_ctime = current_time;
994 inode->i_private = data;
995 if (fops)
996 inode->i_fop = fops;
997 if (iops)
998 inode->i_op = iops;
1001 return inode;
1004 /* Create "regular" file */
1005 static struct inode *ffs_sb_create_file(struct super_block *sb,
1006 const char *name, void *data,
1007 const struct file_operations *fops,
1008 struct dentry **dentry_p)
1010 struct ffs_data *ffs = sb->s_fs_info;
1011 struct dentry *dentry;
1012 struct inode *inode;
1014 ENTER();
1016 dentry = d_alloc_name(sb->s_root, name);
1017 if (unlikely(!dentry))
1018 return NULL;
1020 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1021 if (unlikely(!inode)) {
1022 dput(dentry);
1023 return NULL;
1026 d_add(dentry, inode);
1027 if (dentry_p)
1028 *dentry_p = dentry;
1030 return inode;
1033 /* Super block */
1034 static const struct super_operations ffs_sb_operations = {
1035 .statfs = simple_statfs,
1036 .drop_inode = generic_delete_inode,
1039 struct ffs_sb_fill_data {
1040 struct ffs_file_perms perms;
1041 umode_t root_mode;
1042 const char *dev_name;
1045 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1047 struct ffs_sb_fill_data *data = _data;
1048 struct inode *inode;
1049 struct dentry *d;
1050 struct ffs_data *ffs;
1052 ENTER();
1054 /* Initialise data */
1055 ffs = ffs_data_new();
1056 if (unlikely(!ffs))
1057 goto enomem0;
1059 ffs->sb = sb;
1060 ffs->dev_name = data->dev_name;
1061 ffs->file_perms = data->perms;
1063 sb->s_fs_info = ffs;
1064 sb->s_blocksize = PAGE_CACHE_SIZE;
1065 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1066 sb->s_magic = FUNCTIONFS_MAGIC;
1067 sb->s_op = &ffs_sb_operations;
1068 sb->s_time_gran = 1;
1070 /* Root inode */
1071 data->perms.mode = data->root_mode;
1072 inode = ffs_sb_make_inode(sb, NULL,
1073 &simple_dir_operations,
1074 &simple_dir_inode_operations,
1075 &data->perms);
1076 if (unlikely(!inode))
1077 goto enomem1;
1078 d = d_alloc_root(inode);
1079 if (unlikely(!d))
1080 goto enomem2;
1081 sb->s_root = d;
1083 /* EP0 file */
1084 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1085 &ffs_ep0_operations, NULL)))
1086 goto enomem3;
1088 return 0;
1090 enomem3:
1091 dput(d);
1092 enomem2:
1093 iput(inode);
1094 enomem1:
1095 ffs_data_put(ffs);
1096 enomem0:
1097 return -ENOMEM;
1100 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1102 ENTER();
1104 if (!opts || !*opts)
1105 return 0;
1107 for (;;) {
1108 char *end, *eq, *comma;
1109 unsigned long value;
1111 /* Option limit */
1112 comma = strchr(opts, ',');
1113 if (comma)
1114 *comma = 0;
1116 /* Value limit */
1117 eq = strchr(opts, '=');
1118 if (unlikely(!eq)) {
1119 pr_err("'=' missing in %s\n", opts);
1120 return -EINVAL;
1122 *eq = 0;
1124 /* Parse value */
1125 value = simple_strtoul(eq + 1, &end, 0);
1126 if (unlikely(*end != ',' && *end != 0)) {
1127 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1128 return -EINVAL;
1131 /* Interpret option */
1132 switch (eq - opts) {
1133 case 5:
1134 if (!memcmp(opts, "rmode", 5))
1135 data->root_mode = (value & 0555) | S_IFDIR;
1136 else if (!memcmp(opts, "fmode", 5))
1137 data->perms.mode = (value & 0666) | S_IFREG;
1138 else
1139 goto invalid;
1140 break;
1142 case 4:
1143 if (!memcmp(opts, "mode", 4)) {
1144 data->root_mode = (value & 0555) | S_IFDIR;
1145 data->perms.mode = (value & 0666) | S_IFREG;
1146 } else {
1147 goto invalid;
1149 break;
1151 case 3:
1152 if (!memcmp(opts, "uid", 3))
1153 data->perms.uid = value;
1154 else if (!memcmp(opts, "gid", 3))
1155 data->perms.gid = value;
1156 else
1157 goto invalid;
1158 break;
1160 default:
1161 invalid:
1162 pr_err("%s: invalid option\n", opts);
1163 return -EINVAL;
1166 /* Next iteration */
1167 if (!comma)
1168 break;
1169 opts = comma + 1;
1172 return 0;
1175 /* "mount -t functionfs dev_name /dev/function" ends up here */
1177 static struct dentry *
1178 ffs_fs_mount(struct file_system_type *t, int flags,
1179 const char *dev_name, void *opts)
1181 struct ffs_sb_fill_data data = {
1182 .perms = {
1183 .mode = S_IFREG | 0600,
1184 .uid = 0,
1185 .gid = 0
1187 .root_mode = S_IFDIR | 0500,
1189 int ret;
1191 ENTER();
1193 ret = functionfs_check_dev_callback(dev_name);
1194 if (unlikely(ret < 0))
1195 return ERR_PTR(ret);
1197 ret = ffs_fs_parse_opts(&data, opts);
1198 if (unlikely(ret < 0))
1199 return ERR_PTR(ret);
1201 data.dev_name = dev_name;
1202 return mount_single(t, flags, &data, ffs_sb_fill);
1205 static void
1206 ffs_fs_kill_sb(struct super_block *sb)
1208 void *ptr;
1210 ENTER();
1212 kill_litter_super(sb);
1213 ptr = xchg(&sb->s_fs_info, NULL);
1214 if (ptr)
1215 ffs_data_put(ptr);
1218 static struct file_system_type ffs_fs_type = {
1219 .owner = THIS_MODULE,
1220 .name = "functionfs",
1221 .mount = ffs_fs_mount,
1222 .kill_sb = ffs_fs_kill_sb,
1226 /* Driver's main init/cleanup functions *************************************/
1228 static int functionfs_init(void)
1230 int ret;
1232 ENTER();
1234 ret = register_filesystem(&ffs_fs_type);
1235 if (likely(!ret))
1236 pr_info("file system registered\n");
1237 else
1238 pr_err("failed registering file system (%d)\n", ret);
1240 return ret;
1243 static void functionfs_cleanup(void)
1245 ENTER();
1247 pr_info("unloading\n");
1248 unregister_filesystem(&ffs_fs_type);
1252 /* ffs_data and ffs_function construction and destruction code **************/
1254 static void ffs_data_clear(struct ffs_data *ffs);
1255 static void ffs_data_reset(struct ffs_data *ffs);
1257 static void ffs_data_get(struct ffs_data *ffs)
1259 ENTER();
1261 atomic_inc(&ffs->ref);
1264 static void ffs_data_opened(struct ffs_data *ffs)
1266 ENTER();
1268 atomic_inc(&ffs->ref);
1269 atomic_inc(&ffs->opened);
1272 static void ffs_data_put(struct ffs_data *ffs)
1274 ENTER();
1276 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1277 pr_info("%s(): freeing\n", __func__);
1278 ffs_data_clear(ffs);
1279 BUG_ON(mutex_is_locked(&ffs->mutex) ||
1280 spin_is_locked(&ffs->ev.waitq.lock) ||
1281 waitqueue_active(&ffs->ev.waitq) ||
1282 waitqueue_active(&ffs->ep0req_completion.wait));
1283 kfree(ffs);
1287 static void ffs_data_closed(struct ffs_data *ffs)
1289 ENTER();
1291 if (atomic_dec_and_test(&ffs->opened)) {
1292 ffs->state = FFS_CLOSING;
1293 ffs_data_reset(ffs);
1296 ffs_data_put(ffs);
1299 static struct ffs_data *ffs_data_new(void)
1301 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1302 if (unlikely(!ffs))
1303 return 0;
1305 ENTER();
1307 atomic_set(&ffs->ref, 1);
1308 atomic_set(&ffs->opened, 0);
1309 ffs->state = FFS_READ_DESCRIPTORS;
1310 mutex_init(&ffs->mutex);
1311 spin_lock_init(&ffs->eps_lock);
1312 init_waitqueue_head(&ffs->ev.waitq);
1313 init_completion(&ffs->ep0req_completion);
1315 /* XXX REVISIT need to update it in some places, or do we? */
1316 ffs->ev.can_stall = 1;
1318 return ffs;
1321 static void ffs_data_clear(struct ffs_data *ffs)
1323 ENTER();
1325 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1326 functionfs_closed_callback(ffs);
1328 BUG_ON(ffs->gadget);
1330 if (ffs->epfiles)
1331 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1333 kfree(ffs->raw_descs);
1334 kfree(ffs->raw_strings);
1335 kfree(ffs->stringtabs);
1338 static void ffs_data_reset(struct ffs_data *ffs)
1340 ENTER();
1342 ffs_data_clear(ffs);
1344 ffs->epfiles = NULL;
1345 ffs->raw_descs = NULL;
1346 ffs->raw_strings = NULL;
1347 ffs->stringtabs = NULL;
1349 ffs->raw_descs_length = 0;
1350 ffs->raw_fs_descs_length = 0;
1351 ffs->fs_descs_count = 0;
1352 ffs->hs_descs_count = 0;
1354 ffs->strings_count = 0;
1355 ffs->interfaces_count = 0;
1356 ffs->eps_count = 0;
1358 ffs->ev.count = 0;
1360 ffs->state = FFS_READ_DESCRIPTORS;
1361 ffs->setup_state = FFS_NO_SETUP;
1362 ffs->flags = 0;
1366 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1368 struct usb_gadget_strings **lang;
1369 int first_id;
1371 ENTER();
1373 if (WARN_ON(ffs->state != FFS_ACTIVE
1374 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1375 return -EBADFD;
1377 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1378 if (unlikely(first_id < 0))
1379 return first_id;
1381 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1382 if (unlikely(!ffs->ep0req))
1383 return -ENOMEM;
1384 ffs->ep0req->complete = ffs_ep0_complete;
1385 ffs->ep0req->context = ffs;
1387 lang = ffs->stringtabs;
1388 for (lang = ffs->stringtabs; *lang; ++lang) {
1389 struct usb_string *str = (*lang)->strings;
1390 int id = first_id;
1391 for (; str->s; ++id, ++str)
1392 str->id = id;
1395 ffs->gadget = cdev->gadget;
1396 ffs_data_get(ffs);
1397 return 0;
1400 static void functionfs_unbind(struct ffs_data *ffs)
1402 ENTER();
1404 if (!WARN_ON(!ffs->gadget)) {
1405 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1406 ffs->ep0req = NULL;
1407 ffs->gadget = NULL;
1408 ffs_data_put(ffs);
1412 static int ffs_epfiles_create(struct ffs_data *ffs)
1414 struct ffs_epfile *epfile, *epfiles;
1415 unsigned i, count;
1417 ENTER();
1419 count = ffs->eps_count;
1420 epfiles = kzalloc(count * sizeof *epfiles, GFP_KERNEL);
1421 if (!epfiles)
1422 return -ENOMEM;
1424 epfile = epfiles;
1425 for (i = 1; i <= count; ++i, ++epfile) {
1426 epfile->ffs = ffs;
1427 mutex_init(&epfile->mutex);
1428 init_waitqueue_head(&epfile->wait);
1429 sprintf(epfiles->name, "ep%u", i);
1430 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1431 &ffs_epfile_operations,
1432 &epfile->dentry))) {
1433 ffs_epfiles_destroy(epfiles, i - 1);
1434 return -ENOMEM;
1438 ffs->epfiles = epfiles;
1439 return 0;
1442 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1444 struct ffs_epfile *epfile = epfiles;
1446 ENTER();
1448 for (; count; --count, ++epfile) {
1449 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1450 waitqueue_active(&epfile->wait));
1451 if (epfile->dentry) {
1452 d_delete(epfile->dentry);
1453 dput(epfile->dentry);
1454 epfile->dentry = NULL;
1458 kfree(epfiles);
1461 static int functionfs_bind_config(struct usb_composite_dev *cdev,
1462 struct usb_configuration *c,
1463 struct ffs_data *ffs)
1465 struct ffs_function *func;
1466 int ret;
1468 ENTER();
1470 func = kzalloc(sizeof *func, GFP_KERNEL);
1471 if (unlikely(!func))
1472 return -ENOMEM;
1474 func->function.name = "Function FS Gadget";
1475 func->function.strings = ffs->stringtabs;
1477 func->function.bind = ffs_func_bind;
1478 func->function.unbind = ffs_func_unbind;
1479 func->function.set_alt = ffs_func_set_alt;
1480 func->function.disable = ffs_func_disable;
1481 func->function.setup = ffs_func_setup;
1482 func->function.suspend = ffs_func_suspend;
1483 func->function.resume = ffs_func_resume;
1485 func->conf = c;
1486 func->gadget = cdev->gadget;
1487 func->ffs = ffs;
1488 ffs_data_get(ffs);
1490 ret = usb_add_function(c, &func->function);
1491 if (unlikely(ret))
1492 ffs_func_free(func);
1494 return ret;
1497 static void ffs_func_free(struct ffs_function *func)
1499 ENTER();
1501 ffs_data_put(func->ffs);
1503 kfree(func->eps);
1505 * eps and interfaces_nums are allocated in the same chunk so
1506 * only one free is required. Descriptors are also allocated
1507 * in the same chunk.
1510 kfree(func);
1513 static void ffs_func_eps_disable(struct ffs_function *func)
1515 struct ffs_ep *ep = func->eps;
1516 struct ffs_epfile *epfile = func->ffs->epfiles;
1517 unsigned count = func->ffs->eps_count;
1518 unsigned long flags;
1520 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1521 do {
1522 /* pending requests get nuked */
1523 if (likely(ep->ep))
1524 usb_ep_disable(ep->ep);
1525 epfile->ep = NULL;
1527 ++ep;
1528 ++epfile;
1529 } while (--count);
1530 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1533 static int ffs_func_eps_enable(struct ffs_function *func)
1535 struct ffs_data *ffs = func->ffs;
1536 struct ffs_ep *ep = func->eps;
1537 struct ffs_epfile *epfile = ffs->epfiles;
1538 unsigned count = ffs->eps_count;
1539 unsigned long flags;
1540 int ret = 0;
1542 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1543 do {
1544 struct usb_endpoint_descriptor *ds;
1545 ds = ep->descs[ep->descs[1] ? 1 : 0];
1547 ep->ep->driver_data = ep;
1548 ep->ep->desc = ds;
1549 ret = usb_ep_enable(ep->ep);
1550 if (likely(!ret)) {
1551 epfile->ep = ep;
1552 epfile->in = usb_endpoint_dir_in(ds);
1553 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1554 } else {
1555 break;
1558 wake_up(&epfile->wait);
1560 ++ep;
1561 ++epfile;
1562 } while (--count);
1563 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1565 return ret;
1569 /* Parsing and building descriptors and strings *****************************/
1572 * This validates if data pointed by data is a valid USB descriptor as
1573 * well as record how many interfaces, endpoints and strings are
1574 * required by given configuration. Returns address after the
1575 * descriptor or NULL if data is invalid.
1578 enum ffs_entity_type {
1579 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1582 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1583 u8 *valuep,
1584 struct usb_descriptor_header *desc,
1585 void *priv);
1587 static int __must_check ffs_do_desc(char *data, unsigned len,
1588 ffs_entity_callback entity, void *priv)
1590 struct usb_descriptor_header *_ds = (void *)data;
1591 u8 length;
1592 int ret;
1594 ENTER();
1596 /* At least two bytes are required: length and type */
1597 if (len < 2) {
1598 pr_vdebug("descriptor too short\n");
1599 return -EINVAL;
1602 /* If we have at least as many bytes as the descriptor takes? */
1603 length = _ds->bLength;
1604 if (len < length) {
1605 pr_vdebug("descriptor longer then available data\n");
1606 return -EINVAL;
1609 #define __entity_check_INTERFACE(val) 1
1610 #define __entity_check_STRING(val) (val)
1611 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1612 #define __entity(type, val) do { \
1613 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1614 if (unlikely(!__entity_check_ ##type(val))) { \
1615 pr_vdebug("invalid entity's value\n"); \
1616 return -EINVAL; \
1618 ret = entity(FFS_ ##type, &val, _ds, priv); \
1619 if (unlikely(ret < 0)) { \
1620 pr_debug("entity " #type "(%02x); ret = %d\n", \
1621 (val), ret); \
1622 return ret; \
1624 } while (0)
1626 /* Parse descriptor depending on type. */
1627 switch (_ds->bDescriptorType) {
1628 case USB_DT_DEVICE:
1629 case USB_DT_CONFIG:
1630 case USB_DT_STRING:
1631 case USB_DT_DEVICE_QUALIFIER:
1632 /* function can't have any of those */
1633 pr_vdebug("descriptor reserved for gadget: %d\n",
1634 _ds->bDescriptorType);
1635 return -EINVAL;
1637 case USB_DT_INTERFACE: {
1638 struct usb_interface_descriptor *ds = (void *)_ds;
1639 pr_vdebug("interface descriptor\n");
1640 if (length != sizeof *ds)
1641 goto inv_length;
1643 __entity(INTERFACE, ds->bInterfaceNumber);
1644 if (ds->iInterface)
1645 __entity(STRING, ds->iInterface);
1647 break;
1649 case USB_DT_ENDPOINT: {
1650 struct usb_endpoint_descriptor *ds = (void *)_ds;
1651 pr_vdebug("endpoint descriptor\n");
1652 if (length != USB_DT_ENDPOINT_SIZE &&
1653 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1654 goto inv_length;
1655 __entity(ENDPOINT, ds->bEndpointAddress);
1657 break;
1659 case USB_DT_OTG:
1660 if (length != sizeof(struct usb_otg_descriptor))
1661 goto inv_length;
1662 break;
1664 case USB_DT_INTERFACE_ASSOCIATION: {
1665 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1666 pr_vdebug("interface association descriptor\n");
1667 if (length != sizeof *ds)
1668 goto inv_length;
1669 if (ds->iFunction)
1670 __entity(STRING, ds->iFunction);
1672 break;
1674 case USB_DT_OTHER_SPEED_CONFIG:
1675 case USB_DT_INTERFACE_POWER:
1676 case USB_DT_DEBUG:
1677 case USB_DT_SECURITY:
1678 case USB_DT_CS_RADIO_CONTROL:
1679 /* TODO */
1680 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1681 return -EINVAL;
1683 default:
1684 /* We should never be here */
1685 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1686 return -EINVAL;
1688 inv_length:
1689 pr_vdebug("invalid length: %d (descriptor %d)\n",
1690 _ds->bLength, _ds->bDescriptorType);
1691 return -EINVAL;
1694 #undef __entity
1695 #undef __entity_check_DESCRIPTOR
1696 #undef __entity_check_INTERFACE
1697 #undef __entity_check_STRING
1698 #undef __entity_check_ENDPOINT
1700 return length;
1703 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1704 ffs_entity_callback entity, void *priv)
1706 const unsigned _len = len;
1707 unsigned long num = 0;
1709 ENTER();
1711 for (;;) {
1712 int ret;
1714 if (num == count)
1715 data = NULL;
1717 /* Record "descriptor" entity */
1718 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1719 if (unlikely(ret < 0)) {
1720 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1721 num, ret);
1722 return ret;
1725 if (!data)
1726 return _len - len;
1728 ret = ffs_do_desc(data, len, entity, priv);
1729 if (unlikely(ret < 0)) {
1730 pr_debug("%s returns %d\n", __func__, ret);
1731 return ret;
1734 len -= ret;
1735 data += ret;
1736 ++num;
1740 static int __ffs_data_do_entity(enum ffs_entity_type type,
1741 u8 *valuep, struct usb_descriptor_header *desc,
1742 void *priv)
1744 struct ffs_data *ffs = priv;
1746 ENTER();
1748 switch (type) {
1749 case FFS_DESCRIPTOR:
1750 break;
1752 case FFS_INTERFACE:
1754 * Interfaces are indexed from zero so if we
1755 * encountered interface "n" then there are at least
1756 * "n+1" interfaces.
1758 if (*valuep >= ffs->interfaces_count)
1759 ffs->interfaces_count = *valuep + 1;
1760 break;
1762 case FFS_STRING:
1764 * Strings are indexed from 1 (0 is magic ;) reserved
1765 * for languages list or some such)
1767 if (*valuep > ffs->strings_count)
1768 ffs->strings_count = *valuep;
1769 break;
1771 case FFS_ENDPOINT:
1772 /* Endpoints are indexed from 1 as well. */
1773 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1774 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1775 break;
1778 return 0;
1781 static int __ffs_data_got_descs(struct ffs_data *ffs,
1782 char *const _data, size_t len)
1784 unsigned fs_count, hs_count;
1785 int fs_len, ret = -EINVAL;
1786 char *data = _data;
1788 ENTER();
1790 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
1791 get_unaligned_le32(data + 4) != len))
1792 goto error;
1793 fs_count = get_unaligned_le32(data + 8);
1794 hs_count = get_unaligned_le32(data + 12);
1796 if (!fs_count && !hs_count)
1797 goto einval;
1799 data += 16;
1800 len -= 16;
1802 if (likely(fs_count)) {
1803 fs_len = ffs_do_descs(fs_count, data, len,
1804 __ffs_data_do_entity, ffs);
1805 if (unlikely(fs_len < 0)) {
1806 ret = fs_len;
1807 goto error;
1810 data += fs_len;
1811 len -= fs_len;
1812 } else {
1813 fs_len = 0;
1816 if (likely(hs_count)) {
1817 ret = ffs_do_descs(hs_count, data, len,
1818 __ffs_data_do_entity, ffs);
1819 if (unlikely(ret < 0))
1820 goto error;
1821 } else {
1822 ret = 0;
1825 if (unlikely(len != ret))
1826 goto einval;
1828 ffs->raw_fs_descs_length = fs_len;
1829 ffs->raw_descs_length = fs_len + ret;
1830 ffs->raw_descs = _data;
1831 ffs->fs_descs_count = fs_count;
1832 ffs->hs_descs_count = hs_count;
1834 return 0;
1836 einval:
1837 ret = -EINVAL;
1838 error:
1839 kfree(_data);
1840 return ret;
1843 static int __ffs_data_got_strings(struct ffs_data *ffs,
1844 char *const _data, size_t len)
1846 u32 str_count, needed_count, lang_count;
1847 struct usb_gadget_strings **stringtabs, *t;
1848 struct usb_string *strings, *s;
1849 const char *data = _data;
1851 ENTER();
1853 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1854 get_unaligned_le32(data + 4) != len))
1855 goto error;
1856 str_count = get_unaligned_le32(data + 8);
1857 lang_count = get_unaligned_le32(data + 12);
1859 /* if one is zero the other must be zero */
1860 if (unlikely(!str_count != !lang_count))
1861 goto error;
1863 /* Do we have at least as many strings as descriptors need? */
1864 needed_count = ffs->strings_count;
1865 if (unlikely(str_count < needed_count))
1866 goto error;
1869 * If we don't need any strings just return and free all
1870 * memory.
1872 if (!needed_count) {
1873 kfree(_data);
1874 return 0;
1877 /* Allocate everything in one chunk so there's less maintenance. */
1879 struct {
1880 struct usb_gadget_strings *stringtabs[lang_count + 1];
1881 struct usb_gadget_strings stringtab[lang_count];
1882 struct usb_string strings[lang_count*(needed_count+1)];
1883 } *d;
1884 unsigned i = 0;
1886 d = kmalloc(sizeof *d, GFP_KERNEL);
1887 if (unlikely(!d)) {
1888 kfree(_data);
1889 return -ENOMEM;
1892 stringtabs = d->stringtabs;
1893 t = d->stringtab;
1894 i = lang_count;
1895 do {
1896 *stringtabs++ = t++;
1897 } while (--i);
1898 *stringtabs = NULL;
1900 stringtabs = d->stringtabs;
1901 t = d->stringtab;
1902 s = d->strings;
1903 strings = s;
1906 /* For each language */
1907 data += 16;
1908 len -= 16;
1910 do { /* lang_count > 0 so we can use do-while */
1911 unsigned needed = needed_count;
1913 if (unlikely(len < 3))
1914 goto error_free;
1915 t->language = get_unaligned_le16(data);
1916 t->strings = s;
1917 ++t;
1919 data += 2;
1920 len -= 2;
1922 /* For each string */
1923 do { /* str_count > 0 so we can use do-while */
1924 size_t length = strnlen(data, len);
1926 if (unlikely(length == len))
1927 goto error_free;
1930 * User may provide more strings then we need,
1931 * if that's the case we simply ignore the
1932 * rest
1934 if (likely(needed)) {
1936 * s->id will be set while adding
1937 * function to configuration so for
1938 * now just leave garbage here.
1940 s->s = data;
1941 --needed;
1942 ++s;
1945 data += length + 1;
1946 len -= length + 1;
1947 } while (--str_count);
1949 s->id = 0; /* terminator */
1950 s->s = NULL;
1951 ++s;
1953 } while (--lang_count);
1955 /* Some garbage left? */
1956 if (unlikely(len))
1957 goto error_free;
1959 /* Done! */
1960 ffs->stringtabs = stringtabs;
1961 ffs->raw_strings = _data;
1963 return 0;
1965 error_free:
1966 kfree(stringtabs);
1967 error:
1968 kfree(_data);
1969 return -EINVAL;
1973 /* Events handling and management *******************************************/
1975 static void __ffs_event_add(struct ffs_data *ffs,
1976 enum usb_functionfs_event_type type)
1978 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
1979 int neg = 0;
1982 * Abort any unhandled setup
1984 * We do not need to worry about some cmpxchg() changing value
1985 * of ffs->setup_state without holding the lock because when
1986 * state is FFS_SETUP_PENDING cmpxchg() in several places in
1987 * the source does nothing.
1989 if (ffs->setup_state == FFS_SETUP_PENDING)
1990 ffs->setup_state = FFS_SETUP_CANCELED;
1992 switch (type) {
1993 case FUNCTIONFS_RESUME:
1994 rem_type2 = FUNCTIONFS_SUSPEND;
1995 /* FALL THROUGH */
1996 case FUNCTIONFS_SUSPEND:
1997 case FUNCTIONFS_SETUP:
1998 rem_type1 = type;
1999 /* Discard all similar events */
2000 break;
2002 case FUNCTIONFS_BIND:
2003 case FUNCTIONFS_UNBIND:
2004 case FUNCTIONFS_DISABLE:
2005 case FUNCTIONFS_ENABLE:
2006 /* Discard everything other then power management. */
2007 rem_type1 = FUNCTIONFS_SUSPEND;
2008 rem_type2 = FUNCTIONFS_RESUME;
2009 neg = 1;
2010 break;
2012 default:
2013 BUG();
2017 u8 *ev = ffs->ev.types, *out = ev;
2018 unsigned n = ffs->ev.count;
2019 for (; n; --n, ++ev)
2020 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2021 *out++ = *ev;
2022 else
2023 pr_vdebug("purging event %d\n", *ev);
2024 ffs->ev.count = out - ffs->ev.types;
2027 pr_vdebug("adding event %d\n", type);
2028 ffs->ev.types[ffs->ev.count++] = type;
2029 wake_up_locked(&ffs->ev.waitq);
2032 static void ffs_event_add(struct ffs_data *ffs,
2033 enum usb_functionfs_event_type type)
2035 unsigned long flags;
2036 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2037 __ffs_event_add(ffs, type);
2038 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2042 /* Bind/unbind USB function hooks *******************************************/
2044 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2045 struct usb_descriptor_header *desc,
2046 void *priv)
2048 struct usb_endpoint_descriptor *ds = (void *)desc;
2049 struct ffs_function *func = priv;
2050 struct ffs_ep *ffs_ep;
2053 * If hs_descriptors is not NULL then we are reading hs
2054 * descriptors now
2056 const int isHS = func->function.hs_descriptors != NULL;
2057 unsigned idx;
2059 if (type != FFS_DESCRIPTOR)
2060 return 0;
2062 if (isHS)
2063 func->function.hs_descriptors[(long)valuep] = desc;
2064 else
2065 func->function.descriptors[(long)valuep] = desc;
2067 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2068 return 0;
2070 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2071 ffs_ep = func->eps + idx;
2073 if (unlikely(ffs_ep->descs[isHS])) {
2074 pr_vdebug("two %sspeed descriptors for EP %d\n",
2075 isHS ? "high" : "full",
2076 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2077 return -EINVAL;
2079 ffs_ep->descs[isHS] = ds;
2081 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2082 if (ffs_ep->ep) {
2083 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2084 if (!ds->wMaxPacketSize)
2085 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2086 } else {
2087 struct usb_request *req;
2088 struct usb_ep *ep;
2090 pr_vdebug("autoconfig\n");
2091 ep = usb_ep_autoconfig(func->gadget, ds);
2092 if (unlikely(!ep))
2093 return -ENOTSUPP;
2094 ep->driver_data = func->eps + idx;
2096 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2097 if (unlikely(!req))
2098 return -ENOMEM;
2100 ffs_ep->ep = ep;
2101 ffs_ep->req = req;
2102 func->eps_revmap[ds->bEndpointAddress &
2103 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2105 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2107 return 0;
2110 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2111 struct usb_descriptor_header *desc,
2112 void *priv)
2114 struct ffs_function *func = priv;
2115 unsigned idx;
2116 u8 newValue;
2118 switch (type) {
2119 default:
2120 case FFS_DESCRIPTOR:
2121 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2122 return 0;
2124 case FFS_INTERFACE:
2125 idx = *valuep;
2126 if (func->interfaces_nums[idx] < 0) {
2127 int id = usb_interface_id(func->conf, &func->function);
2128 if (unlikely(id < 0))
2129 return id;
2130 func->interfaces_nums[idx] = id;
2132 newValue = func->interfaces_nums[idx];
2133 break;
2135 case FFS_STRING:
2136 /* String' IDs are allocated when fsf_data is bound to cdev */
2137 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2138 break;
2140 case FFS_ENDPOINT:
2142 * USB_DT_ENDPOINT are handled in
2143 * __ffs_func_bind_do_descs().
2145 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2146 return 0;
2148 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2149 if (unlikely(!func->eps[idx].ep))
2150 return -EINVAL;
2153 struct usb_endpoint_descriptor **descs;
2154 descs = func->eps[idx].descs;
2155 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2157 break;
2160 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2161 *valuep = newValue;
2162 return 0;
2165 static int ffs_func_bind(struct usb_configuration *c,
2166 struct usb_function *f)
2168 struct ffs_function *func = ffs_func_from_usb(f);
2169 struct ffs_data *ffs = func->ffs;
2171 const int full = !!func->ffs->fs_descs_count;
2172 const int high = gadget_is_dualspeed(func->gadget) &&
2173 func->ffs->hs_descs_count;
2175 int ret;
2177 /* Make it a single chunk, less management later on */
2178 struct {
2179 struct ffs_ep eps[ffs->eps_count];
2180 struct usb_descriptor_header
2181 *fs_descs[full ? ffs->fs_descs_count + 1 : 0];
2182 struct usb_descriptor_header
2183 *hs_descs[high ? ffs->hs_descs_count + 1 : 0];
2184 short inums[ffs->interfaces_count];
2185 char raw_descs[high ? ffs->raw_descs_length
2186 : ffs->raw_fs_descs_length];
2187 } *data;
2189 ENTER();
2191 /* Only high speed but not supported by gadget? */
2192 if (unlikely(!(full | high)))
2193 return -ENOTSUPP;
2195 /* Allocate */
2196 data = kmalloc(sizeof *data, GFP_KERNEL);
2197 if (unlikely(!data))
2198 return -ENOMEM;
2200 /* Zero */
2201 memset(data->eps, 0, sizeof data->eps);
2202 memcpy(data->raw_descs, ffs->raw_descs + 16, sizeof data->raw_descs);
2203 memset(data->inums, 0xff, sizeof data->inums);
2204 for (ret = ffs->eps_count; ret; --ret)
2205 data->eps[ret].num = -1;
2207 /* Save pointers */
2208 func->eps = data->eps;
2209 func->interfaces_nums = data->inums;
2212 * Go through all the endpoint descriptors and allocate
2213 * endpoints first, so that later we can rewrite the endpoint
2214 * numbers without worrying that it may be described later on.
2216 if (likely(full)) {
2217 func->function.descriptors = data->fs_descs;
2218 ret = ffs_do_descs(ffs->fs_descs_count,
2219 data->raw_descs,
2220 sizeof data->raw_descs,
2221 __ffs_func_bind_do_descs, func);
2222 if (unlikely(ret < 0))
2223 goto error;
2224 } else {
2225 ret = 0;
2228 if (likely(high)) {
2229 func->function.hs_descriptors = data->hs_descs;
2230 ret = ffs_do_descs(ffs->hs_descs_count,
2231 data->raw_descs + ret,
2232 (sizeof data->raw_descs) - ret,
2233 __ffs_func_bind_do_descs, func);
2237 * Now handle interface numbers allocation and interface and
2238 * endpoint numbers rewriting. We can do that in one go
2239 * now.
2241 ret = ffs_do_descs(ffs->fs_descs_count +
2242 (high ? ffs->hs_descs_count : 0),
2243 data->raw_descs, sizeof data->raw_descs,
2244 __ffs_func_bind_do_nums, func);
2245 if (unlikely(ret < 0))
2246 goto error;
2248 /* And we're done */
2249 ffs_event_add(ffs, FUNCTIONFS_BIND);
2250 return 0;
2252 error:
2253 /* XXX Do we need to release all claimed endpoints here? */
2254 return ret;
2258 /* Other USB function hooks *************************************************/
2260 static void ffs_func_unbind(struct usb_configuration *c,
2261 struct usb_function *f)
2263 struct ffs_function *func = ffs_func_from_usb(f);
2264 struct ffs_data *ffs = func->ffs;
2266 ENTER();
2268 if (ffs->func == func) {
2269 ffs_func_eps_disable(func);
2270 ffs->func = NULL;
2273 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2275 ffs_func_free(func);
2278 static int ffs_func_set_alt(struct usb_function *f,
2279 unsigned interface, unsigned alt)
2281 struct ffs_function *func = ffs_func_from_usb(f);
2282 struct ffs_data *ffs = func->ffs;
2283 int ret = 0, intf;
2285 if (alt != (unsigned)-1) {
2286 intf = ffs_func_revmap_intf(func, interface);
2287 if (unlikely(intf < 0))
2288 return intf;
2291 if (ffs->func)
2292 ffs_func_eps_disable(ffs->func);
2294 if (ffs->state != FFS_ACTIVE)
2295 return -ENODEV;
2297 if (alt == (unsigned)-1) {
2298 ffs->func = NULL;
2299 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2300 return 0;
2303 ffs->func = func;
2304 ret = ffs_func_eps_enable(func);
2305 if (likely(ret >= 0))
2306 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2307 return ret;
2310 static void ffs_func_disable(struct usb_function *f)
2312 ffs_func_set_alt(f, 0, (unsigned)-1);
2315 static int ffs_func_setup(struct usb_function *f,
2316 const struct usb_ctrlrequest *creq)
2318 struct ffs_function *func = ffs_func_from_usb(f);
2319 struct ffs_data *ffs = func->ffs;
2320 unsigned long flags;
2321 int ret;
2323 ENTER();
2325 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2326 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2327 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2328 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2329 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2332 * Most requests directed to interface go through here
2333 * (notable exceptions are set/get interface) so we need to
2334 * handle them. All other either handled by composite or
2335 * passed to usb_configuration->setup() (if one is set). No
2336 * matter, we will handle requests directed to endpoint here
2337 * as well (as it's straightforward) but what to do with any
2338 * other request?
2340 if (ffs->state != FFS_ACTIVE)
2341 return -ENODEV;
2343 switch (creq->bRequestType & USB_RECIP_MASK) {
2344 case USB_RECIP_INTERFACE:
2345 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2346 if (unlikely(ret < 0))
2347 return ret;
2348 break;
2350 case USB_RECIP_ENDPOINT:
2351 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2352 if (unlikely(ret < 0))
2353 return ret;
2354 break;
2356 default:
2357 return -EOPNOTSUPP;
2360 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2361 ffs->ev.setup = *creq;
2362 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2363 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2364 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2366 return 0;
2369 static void ffs_func_suspend(struct usb_function *f)
2371 ENTER();
2372 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2375 static void ffs_func_resume(struct usb_function *f)
2377 ENTER();
2378 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2382 /* Endpoint and interface numbers reverse mapping ***************************/
2384 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2386 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2387 return num ? num : -EDOM;
2390 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2392 short *nums = func->interfaces_nums;
2393 unsigned count = func->ffs->interfaces_count;
2395 for (; count; --count, ++nums) {
2396 if (*nums >= 0 && *nums == intf)
2397 return nums - func->interfaces_nums;
2400 return -EDOM;
2404 /* Misc helper functions ****************************************************/
2406 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2408 return nonblock
2409 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2410 : mutex_lock_interruptible(mutex);
2413 static char *ffs_prepare_buffer(const char * __user buf, size_t len)
2415 char *data;
2417 if (unlikely(!len))
2418 return NULL;
2420 data = kmalloc(len, GFP_KERNEL);
2421 if (unlikely(!data))
2422 return ERR_PTR(-ENOMEM);
2424 if (unlikely(__copy_from_user(data, buf, len))) {
2425 kfree(data);
2426 return ERR_PTR(-EFAULT);
2429 pr_vdebug("Buffer from user space:\n");
2430 ffs_dump_mem("", data, len);
2432 return data;