memcg: always create memsw files if CONFIG_CGROUP_MEM_RES_CTLR_SWAP
[linux-2.6.git] / drivers / usb / gadget / f_fs.c
blob1cbba70836bcd7c1516c21253b3a54dd24a5849a
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 <mina86@mina86.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.
18 /* #define DEBUG */
19 /* #define VERBOSE_DEBUG */
21 #include <linux/blkdev.h>
22 #include <linux/pagemap.h>
23 #include <linux/export.h>
24 #include <asm/unaligned.h>
26 #include <linux/usb/composite.h>
27 #include <linux/usb/functionfs.h>
30 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
33 /* Debugging ****************************************************************/
35 #ifdef VERBOSE_DEBUG
36 # define pr_vdebug pr_debug
37 # define ffs_dump_mem(prefix, ptr, len) \
38 print_hex_dump_bytes(pr_fmt(prefix ": "), DUMP_PREFIX_NONE, ptr, len)
39 #else
40 # define pr_vdebug(...) do { } while (0)
41 # define ffs_dump_mem(prefix, ptr, len) do { } while (0)
42 #endif /* VERBOSE_DEBUG */
44 #define ENTER() pr_vdebug("%s()\n", __func__)
47 /* The data structure and setup file ****************************************/
49 enum ffs_state {
51 * Waiting for descriptors and strings.
53 * In this state no open(2), read(2) or write(2) on epfiles
54 * may succeed (which should not be the problem as there
55 * should be no such files opened in the first place).
57 FFS_READ_DESCRIPTORS,
58 FFS_READ_STRINGS,
61 * We've got descriptors and strings. We are or have called
62 * functionfs_ready_callback(). functionfs_bind() may have
63 * been called but we don't know.
65 * This is the only state in which operations on epfiles may
66 * succeed.
68 FFS_ACTIVE,
71 * All endpoints have been closed. This state is also set if
72 * we encounter an unrecoverable error. The only
73 * unrecoverable error is situation when after reading strings
74 * from user space we fail to initialise epfiles or
75 * functionfs_ready_callback() returns with error (<0).
77 * In this state no open(2), read(2) or write(2) (both on ep0
78 * as well as epfile) may succeed (at this point epfiles are
79 * unlinked and all closed so this is not a problem; ep0 is
80 * also closed but ep0 file exists and so open(2) on ep0 must
81 * fail).
83 FFS_CLOSING
87 enum ffs_setup_state {
88 /* There is no setup request pending. */
89 FFS_NO_SETUP,
91 * User has read events and there was a setup request event
92 * there. The next read/write on ep0 will handle the
93 * request.
95 FFS_SETUP_PENDING,
97 * There was event pending but before user space handled it
98 * some other event was introduced which canceled existing
99 * setup. If this state is set read/write on ep0 return
100 * -EIDRM. This state is only set when adding event.
102 FFS_SETUP_CANCELED
107 struct ffs_epfile;
108 struct ffs_function;
110 struct ffs_data {
111 struct usb_gadget *gadget;
114 * Protect access read/write operations, only one read/write
115 * at a time. As a consequence protects ep0req and company.
116 * While setup request is being processed (queued) this is
117 * held.
119 struct mutex mutex;
122 * Protect access to endpoint related structures (basically
123 * usb_ep_queue(), usb_ep_dequeue(), etc. calls) except for
124 * endpoint zero.
126 spinlock_t eps_lock;
129 * XXX REVISIT do we need our own request? Since we are not
130 * handling setup requests immediately user space may be so
131 * slow that another setup will be sent to the gadget but this
132 * time not to us but another function and then there could be
133 * a race. Is that the case? Or maybe we can use cdev->req
134 * after all, maybe we just need some spinlock for that?
136 struct usb_request *ep0req; /* P: mutex */
137 struct completion ep0req_completion; /* P: mutex */
138 int ep0req_status; /* P: mutex */
140 /* reference counter */
141 atomic_t ref;
142 /* how many files are opened (EP0 and others) */
143 atomic_t opened;
145 /* EP0 state */
146 enum ffs_state state;
149 * Possible transitions:
150 * + FFS_NO_SETUP -> FFS_SETUP_PENDING -- P: ev.waitq.lock
151 * happens only in ep0 read which is P: mutex
152 * + FFS_SETUP_PENDING -> FFS_NO_SETUP -- P: ev.waitq.lock
153 * happens only in ep0 i/o which is P: mutex
154 * + FFS_SETUP_PENDING -> FFS_SETUP_CANCELED -- P: ev.waitq.lock
155 * + FFS_SETUP_CANCELED -> FFS_NO_SETUP -- cmpxchg
157 enum ffs_setup_state setup_state;
159 #define FFS_SETUP_STATE(ffs) \
160 ((enum ffs_setup_state)cmpxchg(&(ffs)->setup_state, \
161 FFS_SETUP_CANCELED, FFS_NO_SETUP))
163 /* Events & such. */
164 struct {
165 u8 types[4];
166 unsigned short count;
167 /* XXX REVISIT need to update it in some places, or do we? */
168 unsigned short can_stall;
169 struct usb_ctrlrequest setup;
171 wait_queue_head_t waitq;
172 } ev; /* the whole structure, P: ev.waitq.lock */
174 /* Flags */
175 unsigned long flags;
176 #define FFS_FL_CALL_CLOSED_CALLBACK 0
177 #define FFS_FL_BOUND 1
179 /* Active function */
180 struct ffs_function *func;
183 * Device name, write once when file system is mounted.
184 * Intended for user to read if she wants.
186 const char *dev_name;
187 /* Private data for our user (ie. gadget). Managed by user. */
188 void *private_data;
190 /* filled by __ffs_data_got_descs() */
192 * Real descriptors are 16 bytes after raw_descs (so you need
193 * to skip 16 bytes (ie. ffs->raw_descs + 16) to get to the
194 * first full speed descriptor). raw_descs_length and
195 * raw_fs_descs_length do not have those 16 bytes added.
197 const void *raw_descs;
198 unsigned raw_descs_length;
199 unsigned raw_fs_descs_length;
200 unsigned fs_descs_count;
201 unsigned hs_descs_count;
203 unsigned short strings_count;
204 unsigned short interfaces_count;
205 unsigned short eps_count;
206 unsigned short _pad1;
208 /* filled by __ffs_data_got_strings() */
209 /* ids in stringtabs are set in functionfs_bind() */
210 const void *raw_strings;
211 struct usb_gadget_strings **stringtabs;
214 * File system's super block, write once when file system is
215 * mounted.
217 struct super_block *sb;
219 /* File permissions, written once when fs is mounted */
220 struct ffs_file_perms {
221 umode_t mode;
222 uid_t uid;
223 gid_t gid;
224 } file_perms;
227 * The endpoint files, filled by ffs_epfiles_create(),
228 * destroyed by ffs_epfiles_destroy().
230 struct ffs_epfile *epfiles;
233 /* Reference counter handling */
234 static void ffs_data_get(struct ffs_data *ffs);
235 static void ffs_data_put(struct ffs_data *ffs);
236 /* Creates new ffs_data object. */
237 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
239 /* Opened counter handling. */
240 static void ffs_data_opened(struct ffs_data *ffs);
241 static void ffs_data_closed(struct ffs_data *ffs);
243 /* Called with ffs->mutex held; take over ownership of data. */
244 static int __must_check
245 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
246 static int __must_check
247 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
250 /* The function structure ***************************************************/
252 struct ffs_ep;
254 struct ffs_function {
255 struct usb_configuration *conf;
256 struct usb_gadget *gadget;
257 struct ffs_data *ffs;
259 struct ffs_ep *eps;
260 u8 eps_revmap[16];
261 short *interfaces_nums;
263 struct usb_function function;
267 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
269 return container_of(f, struct ffs_function, function);
272 static void ffs_func_free(struct ffs_function *func);
274 static void ffs_func_eps_disable(struct ffs_function *func);
275 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
277 static int ffs_func_bind(struct usb_configuration *,
278 struct usb_function *);
279 static void ffs_func_unbind(struct usb_configuration *,
280 struct usb_function *);
281 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
282 static void ffs_func_disable(struct usb_function *);
283 static int ffs_func_setup(struct usb_function *,
284 const struct usb_ctrlrequest *);
285 static void ffs_func_suspend(struct usb_function *);
286 static void ffs_func_resume(struct usb_function *);
289 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
290 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
293 /* The endpoints structures *************************************************/
295 struct ffs_ep {
296 struct usb_ep *ep; /* P: ffs->eps_lock */
297 struct usb_request *req; /* P: epfile->mutex */
299 /* [0]: full speed, [1]: high speed */
300 struct usb_endpoint_descriptor *descs[2];
302 u8 num;
304 int status; /* P: epfile->mutex */
307 struct ffs_epfile {
308 /* Protects ep->ep and ep->req. */
309 struct mutex mutex;
310 wait_queue_head_t wait;
312 struct ffs_data *ffs;
313 struct ffs_ep *ep; /* P: ffs->eps_lock */
315 struct dentry *dentry;
317 char name[5];
319 unsigned char in; /* P: ffs->eps_lock */
320 unsigned char isoc; /* P: ffs->eps_lock */
322 unsigned char _pad;
325 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
326 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
328 static struct inode *__must_check
329 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
330 const struct file_operations *fops,
331 struct dentry **dentry_p);
334 /* Misc helper functions ****************************************************/
336 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
337 __attribute__((warn_unused_result, nonnull));
338 static char *ffs_prepare_buffer(const char * __user buf, size_t len)
339 __attribute__((warn_unused_result, nonnull));
342 /* Control file aka ep0 *****************************************************/
344 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
346 struct ffs_data *ffs = req->context;
348 complete_all(&ffs->ep0req_completion);
351 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
353 struct usb_request *req = ffs->ep0req;
354 int ret;
356 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
358 spin_unlock_irq(&ffs->ev.waitq.lock);
360 req->buf = data;
361 req->length = len;
364 * UDC layer requires to provide a buffer even for ZLP, but should
365 * not use it at all. Let's provide some poisoned pointer to catch
366 * possible bug in the driver.
368 if (req->buf == NULL)
369 req->buf = (void *)0xDEADBABE;
371 INIT_COMPLETION(ffs->ep0req_completion);
373 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
374 if (unlikely(ret < 0))
375 return ret;
377 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
378 if (unlikely(ret)) {
379 usb_ep_dequeue(ffs->gadget->ep0, req);
380 return -EINTR;
383 ffs->setup_state = FFS_NO_SETUP;
384 return ffs->ep0req_status;
387 static int __ffs_ep0_stall(struct ffs_data *ffs)
389 if (ffs->ev.can_stall) {
390 pr_vdebug("ep0 stall\n");
391 usb_ep_set_halt(ffs->gadget->ep0);
392 ffs->setup_state = FFS_NO_SETUP;
393 return -EL2HLT;
394 } else {
395 pr_debug("bogus ep0 stall!\n");
396 return -ESRCH;
400 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
401 size_t len, loff_t *ptr)
403 struct ffs_data *ffs = file->private_data;
404 ssize_t ret;
405 char *data;
407 ENTER();
409 /* Fast check if setup was canceled */
410 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
411 return -EIDRM;
413 /* Acquire mutex */
414 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
415 if (unlikely(ret < 0))
416 return ret;
418 /* Check state */
419 switch (ffs->state) {
420 case FFS_READ_DESCRIPTORS:
421 case FFS_READ_STRINGS:
422 /* Copy data */
423 if (unlikely(len < 16)) {
424 ret = -EINVAL;
425 break;
428 data = ffs_prepare_buffer(buf, len);
429 if (IS_ERR(data)) {
430 ret = PTR_ERR(data);
431 break;
434 /* Handle data */
435 if (ffs->state == FFS_READ_DESCRIPTORS) {
436 pr_info("read descriptors\n");
437 ret = __ffs_data_got_descs(ffs, data, len);
438 if (unlikely(ret < 0))
439 break;
441 ffs->state = FFS_READ_STRINGS;
442 ret = len;
443 } else {
444 pr_info("read strings\n");
445 ret = __ffs_data_got_strings(ffs, data, len);
446 if (unlikely(ret < 0))
447 break;
449 ret = ffs_epfiles_create(ffs);
450 if (unlikely(ret)) {
451 ffs->state = FFS_CLOSING;
452 break;
455 ffs->state = FFS_ACTIVE;
456 mutex_unlock(&ffs->mutex);
458 ret = functionfs_ready_callback(ffs);
459 if (unlikely(ret < 0)) {
460 ffs->state = FFS_CLOSING;
461 return ret;
464 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
465 return len;
467 break;
469 case FFS_ACTIVE:
470 data = NULL;
472 * We're called from user space, we can use _irq
473 * rather then _irqsave
475 spin_lock_irq(&ffs->ev.waitq.lock);
476 switch (FFS_SETUP_STATE(ffs)) {
477 case FFS_SETUP_CANCELED:
478 ret = -EIDRM;
479 goto done_spin;
481 case FFS_NO_SETUP:
482 ret = -ESRCH;
483 goto done_spin;
485 case FFS_SETUP_PENDING:
486 break;
489 /* FFS_SETUP_PENDING */
490 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
491 spin_unlock_irq(&ffs->ev.waitq.lock);
492 ret = __ffs_ep0_stall(ffs);
493 break;
496 /* FFS_SETUP_PENDING and not stall */
497 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
499 spin_unlock_irq(&ffs->ev.waitq.lock);
501 data = ffs_prepare_buffer(buf, len);
502 if (IS_ERR(data)) {
503 ret = PTR_ERR(data);
504 break;
507 spin_lock_irq(&ffs->ev.waitq.lock);
510 * We are guaranteed to be still in FFS_ACTIVE state
511 * but the state of setup could have changed from
512 * FFS_SETUP_PENDING to FFS_SETUP_CANCELED so we need
513 * to check for that. If that happened we copied data
514 * from user space in vain but it's unlikely.
516 * For sure we are not in FFS_NO_SETUP since this is
517 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
518 * transition can be performed and it's protected by
519 * mutex.
521 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
522 ret = -EIDRM;
523 done_spin:
524 spin_unlock_irq(&ffs->ev.waitq.lock);
525 } else {
526 /* unlocks spinlock */
527 ret = __ffs_ep0_queue_wait(ffs, data, len);
529 kfree(data);
530 break;
532 default:
533 ret = -EBADFD;
534 break;
537 mutex_unlock(&ffs->mutex);
538 return ret;
541 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
542 size_t n)
545 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
546 * to release them.
548 struct usb_functionfs_event events[n];
549 unsigned i = 0;
551 memset(events, 0, sizeof events);
553 do {
554 events[i].type = ffs->ev.types[i];
555 if (events[i].type == FUNCTIONFS_SETUP) {
556 events[i].u.setup = ffs->ev.setup;
557 ffs->setup_state = FFS_SETUP_PENDING;
559 } while (++i < n);
561 if (n < ffs->ev.count) {
562 ffs->ev.count -= n;
563 memmove(ffs->ev.types, ffs->ev.types + n,
564 ffs->ev.count * sizeof *ffs->ev.types);
565 } else {
566 ffs->ev.count = 0;
569 spin_unlock_irq(&ffs->ev.waitq.lock);
570 mutex_unlock(&ffs->mutex);
572 return unlikely(__copy_to_user(buf, events, sizeof events))
573 ? -EFAULT : sizeof events;
576 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
577 size_t len, loff_t *ptr)
579 struct ffs_data *ffs = file->private_data;
580 char *data = NULL;
581 size_t n;
582 int ret;
584 ENTER();
586 /* Fast check if setup was canceled */
587 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
588 return -EIDRM;
590 /* Acquire mutex */
591 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
592 if (unlikely(ret < 0))
593 return ret;
595 /* Check state */
596 if (ffs->state != FFS_ACTIVE) {
597 ret = -EBADFD;
598 goto done_mutex;
602 * We're called from user space, we can use _irq rather then
603 * _irqsave
605 spin_lock_irq(&ffs->ev.waitq.lock);
607 switch (FFS_SETUP_STATE(ffs)) {
608 case FFS_SETUP_CANCELED:
609 ret = -EIDRM;
610 break;
612 case FFS_NO_SETUP:
613 n = len / sizeof(struct usb_functionfs_event);
614 if (unlikely(!n)) {
615 ret = -EINVAL;
616 break;
619 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
620 ret = -EAGAIN;
621 break;
624 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
625 ffs->ev.count)) {
626 ret = -EINTR;
627 break;
630 return __ffs_ep0_read_events(ffs, buf,
631 min(n, (size_t)ffs->ev.count));
633 case FFS_SETUP_PENDING:
634 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
635 spin_unlock_irq(&ffs->ev.waitq.lock);
636 ret = __ffs_ep0_stall(ffs);
637 goto done_mutex;
640 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
642 spin_unlock_irq(&ffs->ev.waitq.lock);
644 if (likely(len)) {
645 data = kmalloc(len, GFP_KERNEL);
646 if (unlikely(!data)) {
647 ret = -ENOMEM;
648 goto done_mutex;
652 spin_lock_irq(&ffs->ev.waitq.lock);
654 /* See ffs_ep0_write() */
655 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
656 ret = -EIDRM;
657 break;
660 /* unlocks spinlock */
661 ret = __ffs_ep0_queue_wait(ffs, data, len);
662 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
663 ret = -EFAULT;
664 goto done_mutex;
666 default:
667 ret = -EBADFD;
668 break;
671 spin_unlock_irq(&ffs->ev.waitq.lock);
672 done_mutex:
673 mutex_unlock(&ffs->mutex);
674 kfree(data);
675 return ret;
678 static int ffs_ep0_open(struct inode *inode, struct file *file)
680 struct ffs_data *ffs = inode->i_private;
682 ENTER();
684 if (unlikely(ffs->state == FFS_CLOSING))
685 return -EBUSY;
687 file->private_data = ffs;
688 ffs_data_opened(ffs);
690 return 0;
693 static int ffs_ep0_release(struct inode *inode, struct file *file)
695 struct ffs_data *ffs = file->private_data;
697 ENTER();
699 ffs_data_closed(ffs);
701 return 0;
704 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
706 struct ffs_data *ffs = file->private_data;
707 struct usb_gadget *gadget = ffs->gadget;
708 long ret;
710 ENTER();
712 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
713 struct ffs_function *func = ffs->func;
714 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
715 } else if (gadget->ops->ioctl) {
716 ret = gadget->ops->ioctl(gadget, code, value);
717 } else {
718 ret = -ENOTTY;
721 return ret;
724 static const struct file_operations ffs_ep0_operations = {
725 .owner = THIS_MODULE,
726 .llseek = no_llseek,
728 .open = ffs_ep0_open,
729 .write = ffs_ep0_write,
730 .read = ffs_ep0_read,
731 .release = ffs_ep0_release,
732 .unlocked_ioctl = ffs_ep0_ioctl,
736 /* "Normal" endpoints operations ********************************************/
738 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
740 ENTER();
741 if (likely(req->context)) {
742 struct ffs_ep *ep = _ep->driver_data;
743 ep->status = req->status ? req->status : req->actual;
744 complete(req->context);
748 static ssize_t ffs_epfile_io(struct file *file,
749 char __user *buf, size_t len, int read)
751 struct ffs_epfile *epfile = file->private_data;
752 struct ffs_ep *ep;
753 char *data = NULL;
754 ssize_t ret;
755 int halt;
757 goto first_try;
758 do {
759 spin_unlock_irq(&epfile->ffs->eps_lock);
760 mutex_unlock(&epfile->mutex);
762 first_try:
763 /* Are we still active? */
764 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
765 ret = -ENODEV;
766 goto error;
769 /* Wait for endpoint to be enabled */
770 ep = epfile->ep;
771 if (!ep) {
772 if (file->f_flags & O_NONBLOCK) {
773 ret = -EAGAIN;
774 goto error;
777 if (wait_event_interruptible(epfile->wait,
778 (ep = epfile->ep))) {
779 ret = -EINTR;
780 goto error;
784 /* Do we halt? */
785 halt = !read == !epfile->in;
786 if (halt && epfile->isoc) {
787 ret = -EINVAL;
788 goto error;
791 /* Allocate & copy */
792 if (!halt && !data) {
793 data = kzalloc(len, GFP_KERNEL);
794 if (unlikely(!data))
795 return -ENOMEM;
797 if (!read &&
798 unlikely(__copy_from_user(data, buf, len))) {
799 ret = -EFAULT;
800 goto error;
804 /* We will be using request */
805 ret = ffs_mutex_lock(&epfile->mutex,
806 file->f_flags & O_NONBLOCK);
807 if (unlikely(ret))
808 goto error;
811 * We're called from user space, we can use _irq rather then
812 * _irqsave
814 spin_lock_irq(&epfile->ffs->eps_lock);
817 * While we were acquiring mutex endpoint got disabled
818 * or changed?
820 } while (unlikely(epfile->ep != ep));
822 /* Halt */
823 if (unlikely(halt)) {
824 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
825 usb_ep_set_halt(ep->ep);
826 spin_unlock_irq(&epfile->ffs->eps_lock);
827 ret = -EBADMSG;
828 } else {
829 /* Fire the request */
830 DECLARE_COMPLETION_ONSTACK(done);
832 struct usb_request *req = ep->req;
833 req->context = &done;
834 req->complete = ffs_epfile_io_complete;
835 req->buf = data;
836 req->length = len;
838 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
840 spin_unlock_irq(&epfile->ffs->eps_lock);
842 if (unlikely(ret < 0)) {
843 /* nop */
844 } else if (unlikely(wait_for_completion_interruptible(&done))) {
845 ret = -EINTR;
846 usb_ep_dequeue(ep->ep, req);
847 } else {
848 ret = ep->status;
849 if (read && ret > 0 &&
850 unlikely(copy_to_user(buf, data, ret)))
851 ret = -EFAULT;
855 mutex_unlock(&epfile->mutex);
856 error:
857 kfree(data);
858 return ret;
861 static ssize_t
862 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
863 loff_t *ptr)
865 ENTER();
867 return ffs_epfile_io(file, (char __user *)buf, len, 0);
870 static ssize_t
871 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
873 ENTER();
875 return ffs_epfile_io(file, buf, len, 1);
878 static int
879 ffs_epfile_open(struct inode *inode, struct file *file)
881 struct ffs_epfile *epfile = inode->i_private;
883 ENTER();
885 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
886 return -ENODEV;
888 file->private_data = epfile;
889 ffs_data_opened(epfile->ffs);
891 return 0;
894 static int
895 ffs_epfile_release(struct inode *inode, struct file *file)
897 struct ffs_epfile *epfile = inode->i_private;
899 ENTER();
901 ffs_data_closed(epfile->ffs);
903 return 0;
906 static long ffs_epfile_ioctl(struct file *file, unsigned code,
907 unsigned long value)
909 struct ffs_epfile *epfile = file->private_data;
910 int ret;
912 ENTER();
914 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
915 return -ENODEV;
917 spin_lock_irq(&epfile->ffs->eps_lock);
918 if (likely(epfile->ep)) {
919 switch (code) {
920 case FUNCTIONFS_FIFO_STATUS:
921 ret = usb_ep_fifo_status(epfile->ep->ep);
922 break;
923 case FUNCTIONFS_FIFO_FLUSH:
924 usb_ep_fifo_flush(epfile->ep->ep);
925 ret = 0;
926 break;
927 case FUNCTIONFS_CLEAR_HALT:
928 ret = usb_ep_clear_halt(epfile->ep->ep);
929 break;
930 case FUNCTIONFS_ENDPOINT_REVMAP:
931 ret = epfile->ep->num;
932 break;
933 default:
934 ret = -ENOTTY;
936 } else {
937 ret = -ENODEV;
939 spin_unlock_irq(&epfile->ffs->eps_lock);
941 return ret;
944 static const struct file_operations ffs_epfile_operations = {
945 .owner = THIS_MODULE,
946 .llseek = no_llseek,
948 .open = ffs_epfile_open,
949 .write = ffs_epfile_write,
950 .read = ffs_epfile_read,
951 .release = ffs_epfile_release,
952 .unlocked_ioctl = ffs_epfile_ioctl,
956 /* File system and super block operations ***********************************/
959 * Mounting the file system creates a controller file, used first for
960 * function configuration then later for event monitoring.
963 static struct inode *__must_check
964 ffs_sb_make_inode(struct super_block *sb, void *data,
965 const struct file_operations *fops,
966 const struct inode_operations *iops,
967 struct ffs_file_perms *perms)
969 struct inode *inode;
971 ENTER();
973 inode = new_inode(sb);
975 if (likely(inode)) {
976 struct timespec current_time = CURRENT_TIME;
978 inode->i_ino = get_next_ino();
979 inode->i_mode = perms->mode;
980 inode->i_uid = perms->uid;
981 inode->i_gid = perms->gid;
982 inode->i_atime = current_time;
983 inode->i_mtime = current_time;
984 inode->i_ctime = current_time;
985 inode->i_private = data;
986 if (fops)
987 inode->i_fop = fops;
988 if (iops)
989 inode->i_op = iops;
992 return inode;
995 /* Create "regular" file */
996 static struct inode *ffs_sb_create_file(struct super_block *sb,
997 const char *name, void *data,
998 const struct file_operations *fops,
999 struct dentry **dentry_p)
1001 struct ffs_data *ffs = sb->s_fs_info;
1002 struct dentry *dentry;
1003 struct inode *inode;
1005 ENTER();
1007 dentry = d_alloc_name(sb->s_root, name);
1008 if (unlikely(!dentry))
1009 return NULL;
1011 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1012 if (unlikely(!inode)) {
1013 dput(dentry);
1014 return NULL;
1017 d_add(dentry, inode);
1018 if (dentry_p)
1019 *dentry_p = dentry;
1021 return inode;
1024 /* Super block */
1025 static const struct super_operations ffs_sb_operations = {
1026 .statfs = simple_statfs,
1027 .drop_inode = generic_delete_inode,
1030 struct ffs_sb_fill_data {
1031 struct ffs_file_perms perms;
1032 umode_t root_mode;
1033 const char *dev_name;
1036 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1038 struct ffs_sb_fill_data *data = _data;
1039 struct inode *inode;
1040 struct ffs_data *ffs;
1042 ENTER();
1044 /* Initialise data */
1045 ffs = ffs_data_new();
1046 if (unlikely(!ffs))
1047 goto Enomem;
1049 ffs->sb = sb;
1050 ffs->dev_name = data->dev_name;
1051 ffs->file_perms = data->perms;
1053 sb->s_fs_info = ffs;
1054 sb->s_blocksize = PAGE_CACHE_SIZE;
1055 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1056 sb->s_magic = FUNCTIONFS_MAGIC;
1057 sb->s_op = &ffs_sb_operations;
1058 sb->s_time_gran = 1;
1060 /* Root inode */
1061 data->perms.mode = data->root_mode;
1062 inode = ffs_sb_make_inode(sb, NULL,
1063 &simple_dir_operations,
1064 &simple_dir_inode_operations,
1065 &data->perms);
1066 sb->s_root = d_make_root(inode);
1067 if (unlikely(!sb->s_root))
1068 goto Enomem;
1070 /* EP0 file */
1071 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1072 &ffs_ep0_operations, NULL)))
1073 goto Enomem;
1075 return 0;
1077 Enomem:
1078 return -ENOMEM;
1081 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1083 ENTER();
1085 if (!opts || !*opts)
1086 return 0;
1088 for (;;) {
1089 char *end, *eq, *comma;
1090 unsigned long value;
1092 /* Option limit */
1093 comma = strchr(opts, ',');
1094 if (comma)
1095 *comma = 0;
1097 /* Value limit */
1098 eq = strchr(opts, '=');
1099 if (unlikely(!eq)) {
1100 pr_err("'=' missing in %s\n", opts);
1101 return -EINVAL;
1103 *eq = 0;
1105 /* Parse value */
1106 value = simple_strtoul(eq + 1, &end, 0);
1107 if (unlikely(*end != ',' && *end != 0)) {
1108 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1109 return -EINVAL;
1112 /* Interpret option */
1113 switch (eq - opts) {
1114 case 5:
1115 if (!memcmp(opts, "rmode", 5))
1116 data->root_mode = (value & 0555) | S_IFDIR;
1117 else if (!memcmp(opts, "fmode", 5))
1118 data->perms.mode = (value & 0666) | S_IFREG;
1119 else
1120 goto invalid;
1121 break;
1123 case 4:
1124 if (!memcmp(opts, "mode", 4)) {
1125 data->root_mode = (value & 0555) | S_IFDIR;
1126 data->perms.mode = (value & 0666) | S_IFREG;
1127 } else {
1128 goto invalid;
1130 break;
1132 case 3:
1133 if (!memcmp(opts, "uid", 3))
1134 data->perms.uid = value;
1135 else if (!memcmp(opts, "gid", 3))
1136 data->perms.gid = value;
1137 else
1138 goto invalid;
1139 break;
1141 default:
1142 invalid:
1143 pr_err("%s: invalid option\n", opts);
1144 return -EINVAL;
1147 /* Next iteration */
1148 if (!comma)
1149 break;
1150 opts = comma + 1;
1153 return 0;
1156 /* "mount -t functionfs dev_name /dev/function" ends up here */
1158 static struct dentry *
1159 ffs_fs_mount(struct file_system_type *t, int flags,
1160 const char *dev_name, void *opts)
1162 struct ffs_sb_fill_data data = {
1163 .perms = {
1164 .mode = S_IFREG | 0600,
1165 .uid = 0,
1166 .gid = 0
1168 .root_mode = S_IFDIR | 0500,
1170 int ret;
1172 ENTER();
1174 ret = functionfs_check_dev_callback(dev_name);
1175 if (unlikely(ret < 0))
1176 return ERR_PTR(ret);
1178 ret = ffs_fs_parse_opts(&data, opts);
1179 if (unlikely(ret < 0))
1180 return ERR_PTR(ret);
1182 data.dev_name = dev_name;
1183 return mount_single(t, flags, &data, ffs_sb_fill);
1186 static void
1187 ffs_fs_kill_sb(struct super_block *sb)
1189 ENTER();
1191 kill_litter_super(sb);
1192 if (sb->s_fs_info)
1193 ffs_data_put(sb->s_fs_info);
1196 static struct file_system_type ffs_fs_type = {
1197 .owner = THIS_MODULE,
1198 .name = "functionfs",
1199 .mount = ffs_fs_mount,
1200 .kill_sb = ffs_fs_kill_sb,
1204 /* Driver's main init/cleanup functions *************************************/
1206 static int functionfs_init(void)
1208 int ret;
1210 ENTER();
1212 ret = register_filesystem(&ffs_fs_type);
1213 if (likely(!ret))
1214 pr_info("file system registered\n");
1215 else
1216 pr_err("failed registering file system (%d)\n", ret);
1218 return ret;
1221 static void functionfs_cleanup(void)
1223 ENTER();
1225 pr_info("unloading\n");
1226 unregister_filesystem(&ffs_fs_type);
1230 /* ffs_data and ffs_function construction and destruction code **************/
1232 static void ffs_data_clear(struct ffs_data *ffs);
1233 static void ffs_data_reset(struct ffs_data *ffs);
1235 static void ffs_data_get(struct ffs_data *ffs)
1237 ENTER();
1239 atomic_inc(&ffs->ref);
1242 static void ffs_data_opened(struct ffs_data *ffs)
1244 ENTER();
1246 atomic_inc(&ffs->ref);
1247 atomic_inc(&ffs->opened);
1250 static void ffs_data_put(struct ffs_data *ffs)
1252 ENTER();
1254 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1255 pr_info("%s(): freeing\n", __func__);
1256 ffs_data_clear(ffs);
1257 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1258 waitqueue_active(&ffs->ep0req_completion.wait));
1259 kfree(ffs);
1263 static void ffs_data_closed(struct ffs_data *ffs)
1265 ENTER();
1267 if (atomic_dec_and_test(&ffs->opened)) {
1268 ffs->state = FFS_CLOSING;
1269 ffs_data_reset(ffs);
1272 ffs_data_put(ffs);
1275 static struct ffs_data *ffs_data_new(void)
1277 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1278 if (unlikely(!ffs))
1279 return 0;
1281 ENTER();
1283 atomic_set(&ffs->ref, 1);
1284 atomic_set(&ffs->opened, 0);
1285 ffs->state = FFS_READ_DESCRIPTORS;
1286 mutex_init(&ffs->mutex);
1287 spin_lock_init(&ffs->eps_lock);
1288 init_waitqueue_head(&ffs->ev.waitq);
1289 init_completion(&ffs->ep0req_completion);
1291 /* XXX REVISIT need to update it in some places, or do we? */
1292 ffs->ev.can_stall = 1;
1294 return ffs;
1297 static void ffs_data_clear(struct ffs_data *ffs)
1299 ENTER();
1301 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1302 functionfs_closed_callback(ffs);
1304 BUG_ON(ffs->gadget);
1306 if (ffs->epfiles)
1307 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1309 kfree(ffs->raw_descs);
1310 kfree(ffs->raw_strings);
1311 kfree(ffs->stringtabs);
1314 static void ffs_data_reset(struct ffs_data *ffs)
1316 ENTER();
1318 ffs_data_clear(ffs);
1320 ffs->epfiles = NULL;
1321 ffs->raw_descs = NULL;
1322 ffs->raw_strings = NULL;
1323 ffs->stringtabs = NULL;
1325 ffs->raw_descs_length = 0;
1326 ffs->raw_fs_descs_length = 0;
1327 ffs->fs_descs_count = 0;
1328 ffs->hs_descs_count = 0;
1330 ffs->strings_count = 0;
1331 ffs->interfaces_count = 0;
1332 ffs->eps_count = 0;
1334 ffs->ev.count = 0;
1336 ffs->state = FFS_READ_DESCRIPTORS;
1337 ffs->setup_state = FFS_NO_SETUP;
1338 ffs->flags = 0;
1342 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1344 struct usb_gadget_strings **lang;
1345 int first_id;
1347 ENTER();
1349 if (WARN_ON(ffs->state != FFS_ACTIVE
1350 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1351 return -EBADFD;
1353 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1354 if (unlikely(first_id < 0))
1355 return first_id;
1357 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1358 if (unlikely(!ffs->ep0req))
1359 return -ENOMEM;
1360 ffs->ep0req->complete = ffs_ep0_complete;
1361 ffs->ep0req->context = ffs;
1363 lang = ffs->stringtabs;
1364 for (lang = ffs->stringtabs; *lang; ++lang) {
1365 struct usb_string *str = (*lang)->strings;
1366 int id = first_id;
1367 for (; str->s; ++id, ++str)
1368 str->id = id;
1371 ffs->gadget = cdev->gadget;
1372 ffs_data_get(ffs);
1373 return 0;
1376 static void functionfs_unbind(struct ffs_data *ffs)
1378 ENTER();
1380 if (!WARN_ON(!ffs->gadget)) {
1381 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1382 ffs->ep0req = NULL;
1383 ffs->gadget = NULL;
1384 ffs_data_put(ffs);
1388 static int ffs_epfiles_create(struct ffs_data *ffs)
1390 struct ffs_epfile *epfile, *epfiles;
1391 unsigned i, count;
1393 ENTER();
1395 count = ffs->eps_count;
1396 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1397 if (!epfiles)
1398 return -ENOMEM;
1400 epfile = epfiles;
1401 for (i = 1; i <= count; ++i, ++epfile) {
1402 epfile->ffs = ffs;
1403 mutex_init(&epfile->mutex);
1404 init_waitqueue_head(&epfile->wait);
1405 sprintf(epfiles->name, "ep%u", i);
1406 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1407 &ffs_epfile_operations,
1408 &epfile->dentry))) {
1409 ffs_epfiles_destroy(epfiles, i - 1);
1410 return -ENOMEM;
1414 ffs->epfiles = epfiles;
1415 return 0;
1418 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1420 struct ffs_epfile *epfile = epfiles;
1422 ENTER();
1424 for (; count; --count, ++epfile) {
1425 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1426 waitqueue_active(&epfile->wait));
1427 if (epfile->dentry) {
1428 d_delete(epfile->dentry);
1429 dput(epfile->dentry);
1430 epfile->dentry = NULL;
1434 kfree(epfiles);
1437 static int functionfs_bind_config(struct usb_composite_dev *cdev,
1438 struct usb_configuration *c,
1439 struct ffs_data *ffs)
1441 struct ffs_function *func;
1442 int ret;
1444 ENTER();
1446 func = kzalloc(sizeof *func, GFP_KERNEL);
1447 if (unlikely(!func))
1448 return -ENOMEM;
1450 func->function.name = "Function FS Gadget";
1451 func->function.strings = ffs->stringtabs;
1453 func->function.bind = ffs_func_bind;
1454 func->function.unbind = ffs_func_unbind;
1455 func->function.set_alt = ffs_func_set_alt;
1456 func->function.disable = ffs_func_disable;
1457 func->function.setup = ffs_func_setup;
1458 func->function.suspend = ffs_func_suspend;
1459 func->function.resume = ffs_func_resume;
1461 func->conf = c;
1462 func->gadget = cdev->gadget;
1463 func->ffs = ffs;
1464 ffs_data_get(ffs);
1466 ret = usb_add_function(c, &func->function);
1467 if (unlikely(ret))
1468 ffs_func_free(func);
1470 return ret;
1473 static void ffs_func_free(struct ffs_function *func)
1475 ENTER();
1477 ffs_data_put(func->ffs);
1479 kfree(func->eps);
1481 * eps and interfaces_nums are allocated in the same chunk so
1482 * only one free is required. Descriptors are also allocated
1483 * in the same chunk.
1486 kfree(func);
1489 static void ffs_func_eps_disable(struct ffs_function *func)
1491 struct ffs_ep *ep = func->eps;
1492 struct ffs_epfile *epfile = func->ffs->epfiles;
1493 unsigned count = func->ffs->eps_count;
1494 unsigned long flags;
1496 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1497 do {
1498 /* pending requests get nuked */
1499 if (likely(ep->ep))
1500 usb_ep_disable(ep->ep);
1501 epfile->ep = NULL;
1503 ++ep;
1504 ++epfile;
1505 } while (--count);
1506 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1509 static int ffs_func_eps_enable(struct ffs_function *func)
1511 struct ffs_data *ffs = func->ffs;
1512 struct ffs_ep *ep = func->eps;
1513 struct ffs_epfile *epfile = ffs->epfiles;
1514 unsigned count = ffs->eps_count;
1515 unsigned long flags;
1516 int ret = 0;
1518 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1519 do {
1520 struct usb_endpoint_descriptor *ds;
1521 ds = ep->descs[ep->descs[1] ? 1 : 0];
1523 ep->ep->driver_data = ep;
1524 ep->ep->desc = ds;
1525 ret = usb_ep_enable(ep->ep);
1526 if (likely(!ret)) {
1527 epfile->ep = ep;
1528 epfile->in = usb_endpoint_dir_in(ds);
1529 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1530 } else {
1531 break;
1534 wake_up(&epfile->wait);
1536 ++ep;
1537 ++epfile;
1538 } while (--count);
1539 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1541 return ret;
1545 /* Parsing and building descriptors and strings *****************************/
1548 * This validates if data pointed by data is a valid USB descriptor as
1549 * well as record how many interfaces, endpoints and strings are
1550 * required by given configuration. Returns address after the
1551 * descriptor or NULL if data is invalid.
1554 enum ffs_entity_type {
1555 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1558 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1559 u8 *valuep,
1560 struct usb_descriptor_header *desc,
1561 void *priv);
1563 static int __must_check ffs_do_desc(char *data, unsigned len,
1564 ffs_entity_callback entity, void *priv)
1566 struct usb_descriptor_header *_ds = (void *)data;
1567 u8 length;
1568 int ret;
1570 ENTER();
1572 /* At least two bytes are required: length and type */
1573 if (len < 2) {
1574 pr_vdebug("descriptor too short\n");
1575 return -EINVAL;
1578 /* If we have at least as many bytes as the descriptor takes? */
1579 length = _ds->bLength;
1580 if (len < length) {
1581 pr_vdebug("descriptor longer then available data\n");
1582 return -EINVAL;
1585 #define __entity_check_INTERFACE(val) 1
1586 #define __entity_check_STRING(val) (val)
1587 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1588 #define __entity(type, val) do { \
1589 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1590 if (unlikely(!__entity_check_ ##type(val))) { \
1591 pr_vdebug("invalid entity's value\n"); \
1592 return -EINVAL; \
1594 ret = entity(FFS_ ##type, &val, _ds, priv); \
1595 if (unlikely(ret < 0)) { \
1596 pr_debug("entity " #type "(%02x); ret = %d\n", \
1597 (val), ret); \
1598 return ret; \
1600 } while (0)
1602 /* Parse descriptor depending on type. */
1603 switch (_ds->bDescriptorType) {
1604 case USB_DT_DEVICE:
1605 case USB_DT_CONFIG:
1606 case USB_DT_STRING:
1607 case USB_DT_DEVICE_QUALIFIER:
1608 /* function can't have any of those */
1609 pr_vdebug("descriptor reserved for gadget: %d\n",
1610 _ds->bDescriptorType);
1611 return -EINVAL;
1613 case USB_DT_INTERFACE: {
1614 struct usb_interface_descriptor *ds = (void *)_ds;
1615 pr_vdebug("interface descriptor\n");
1616 if (length != sizeof *ds)
1617 goto inv_length;
1619 __entity(INTERFACE, ds->bInterfaceNumber);
1620 if (ds->iInterface)
1621 __entity(STRING, ds->iInterface);
1623 break;
1625 case USB_DT_ENDPOINT: {
1626 struct usb_endpoint_descriptor *ds = (void *)_ds;
1627 pr_vdebug("endpoint descriptor\n");
1628 if (length != USB_DT_ENDPOINT_SIZE &&
1629 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1630 goto inv_length;
1631 __entity(ENDPOINT, ds->bEndpointAddress);
1633 break;
1635 case USB_DT_OTG:
1636 if (length != sizeof(struct usb_otg_descriptor))
1637 goto inv_length;
1638 break;
1640 case USB_DT_INTERFACE_ASSOCIATION: {
1641 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1642 pr_vdebug("interface association descriptor\n");
1643 if (length != sizeof *ds)
1644 goto inv_length;
1645 if (ds->iFunction)
1646 __entity(STRING, ds->iFunction);
1648 break;
1650 case USB_DT_OTHER_SPEED_CONFIG:
1651 case USB_DT_INTERFACE_POWER:
1652 case USB_DT_DEBUG:
1653 case USB_DT_SECURITY:
1654 case USB_DT_CS_RADIO_CONTROL:
1655 /* TODO */
1656 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1657 return -EINVAL;
1659 default:
1660 /* We should never be here */
1661 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1662 return -EINVAL;
1664 inv_length:
1665 pr_vdebug("invalid length: %d (descriptor %d)\n",
1666 _ds->bLength, _ds->bDescriptorType);
1667 return -EINVAL;
1670 #undef __entity
1671 #undef __entity_check_DESCRIPTOR
1672 #undef __entity_check_INTERFACE
1673 #undef __entity_check_STRING
1674 #undef __entity_check_ENDPOINT
1676 return length;
1679 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1680 ffs_entity_callback entity, void *priv)
1682 const unsigned _len = len;
1683 unsigned long num = 0;
1685 ENTER();
1687 for (;;) {
1688 int ret;
1690 if (num == count)
1691 data = NULL;
1693 /* Record "descriptor" entity */
1694 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1695 if (unlikely(ret < 0)) {
1696 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1697 num, ret);
1698 return ret;
1701 if (!data)
1702 return _len - len;
1704 ret = ffs_do_desc(data, len, entity, priv);
1705 if (unlikely(ret < 0)) {
1706 pr_debug("%s returns %d\n", __func__, ret);
1707 return ret;
1710 len -= ret;
1711 data += ret;
1712 ++num;
1716 static int __ffs_data_do_entity(enum ffs_entity_type type,
1717 u8 *valuep, struct usb_descriptor_header *desc,
1718 void *priv)
1720 struct ffs_data *ffs = priv;
1722 ENTER();
1724 switch (type) {
1725 case FFS_DESCRIPTOR:
1726 break;
1728 case FFS_INTERFACE:
1730 * Interfaces are indexed from zero so if we
1731 * encountered interface "n" then there are at least
1732 * "n+1" interfaces.
1734 if (*valuep >= ffs->interfaces_count)
1735 ffs->interfaces_count = *valuep + 1;
1736 break;
1738 case FFS_STRING:
1740 * Strings are indexed from 1 (0 is magic ;) reserved
1741 * for languages list or some such)
1743 if (*valuep > ffs->strings_count)
1744 ffs->strings_count = *valuep;
1745 break;
1747 case FFS_ENDPOINT:
1748 /* Endpoints are indexed from 1 as well. */
1749 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1750 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1751 break;
1754 return 0;
1757 static int __ffs_data_got_descs(struct ffs_data *ffs,
1758 char *const _data, size_t len)
1760 unsigned fs_count, hs_count;
1761 int fs_len, ret = -EINVAL;
1762 char *data = _data;
1764 ENTER();
1766 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
1767 get_unaligned_le32(data + 4) != len))
1768 goto error;
1769 fs_count = get_unaligned_le32(data + 8);
1770 hs_count = get_unaligned_le32(data + 12);
1772 if (!fs_count && !hs_count)
1773 goto einval;
1775 data += 16;
1776 len -= 16;
1778 if (likely(fs_count)) {
1779 fs_len = ffs_do_descs(fs_count, data, len,
1780 __ffs_data_do_entity, ffs);
1781 if (unlikely(fs_len < 0)) {
1782 ret = fs_len;
1783 goto error;
1786 data += fs_len;
1787 len -= fs_len;
1788 } else {
1789 fs_len = 0;
1792 if (likely(hs_count)) {
1793 ret = ffs_do_descs(hs_count, data, len,
1794 __ffs_data_do_entity, ffs);
1795 if (unlikely(ret < 0))
1796 goto error;
1797 } else {
1798 ret = 0;
1801 if (unlikely(len != ret))
1802 goto einval;
1804 ffs->raw_fs_descs_length = fs_len;
1805 ffs->raw_descs_length = fs_len + ret;
1806 ffs->raw_descs = _data;
1807 ffs->fs_descs_count = fs_count;
1808 ffs->hs_descs_count = hs_count;
1810 return 0;
1812 einval:
1813 ret = -EINVAL;
1814 error:
1815 kfree(_data);
1816 return ret;
1819 static int __ffs_data_got_strings(struct ffs_data *ffs,
1820 char *const _data, size_t len)
1822 u32 str_count, needed_count, lang_count;
1823 struct usb_gadget_strings **stringtabs, *t;
1824 struct usb_string *strings, *s;
1825 const char *data = _data;
1827 ENTER();
1829 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1830 get_unaligned_le32(data + 4) != len))
1831 goto error;
1832 str_count = get_unaligned_le32(data + 8);
1833 lang_count = get_unaligned_le32(data + 12);
1835 /* if one is zero the other must be zero */
1836 if (unlikely(!str_count != !lang_count))
1837 goto error;
1839 /* Do we have at least as many strings as descriptors need? */
1840 needed_count = ffs->strings_count;
1841 if (unlikely(str_count < needed_count))
1842 goto error;
1845 * If we don't need any strings just return and free all
1846 * memory.
1848 if (!needed_count) {
1849 kfree(_data);
1850 return 0;
1853 /* Allocate everything in one chunk so there's less maintenance. */
1855 struct {
1856 struct usb_gadget_strings *stringtabs[lang_count + 1];
1857 struct usb_gadget_strings stringtab[lang_count];
1858 struct usb_string strings[lang_count*(needed_count+1)];
1859 } *d;
1860 unsigned i = 0;
1862 d = kmalloc(sizeof *d, GFP_KERNEL);
1863 if (unlikely(!d)) {
1864 kfree(_data);
1865 return -ENOMEM;
1868 stringtabs = d->stringtabs;
1869 t = d->stringtab;
1870 i = lang_count;
1871 do {
1872 *stringtabs++ = t++;
1873 } while (--i);
1874 *stringtabs = NULL;
1876 stringtabs = d->stringtabs;
1877 t = d->stringtab;
1878 s = d->strings;
1879 strings = s;
1882 /* For each language */
1883 data += 16;
1884 len -= 16;
1886 do { /* lang_count > 0 so we can use do-while */
1887 unsigned needed = needed_count;
1889 if (unlikely(len < 3))
1890 goto error_free;
1891 t->language = get_unaligned_le16(data);
1892 t->strings = s;
1893 ++t;
1895 data += 2;
1896 len -= 2;
1898 /* For each string */
1899 do { /* str_count > 0 so we can use do-while */
1900 size_t length = strnlen(data, len);
1902 if (unlikely(length == len))
1903 goto error_free;
1906 * User may provide more strings then we need,
1907 * if that's the case we simply ignore the
1908 * rest
1910 if (likely(needed)) {
1912 * s->id will be set while adding
1913 * function to configuration so for
1914 * now just leave garbage here.
1916 s->s = data;
1917 --needed;
1918 ++s;
1921 data += length + 1;
1922 len -= length + 1;
1923 } while (--str_count);
1925 s->id = 0; /* terminator */
1926 s->s = NULL;
1927 ++s;
1929 } while (--lang_count);
1931 /* Some garbage left? */
1932 if (unlikely(len))
1933 goto error_free;
1935 /* Done! */
1936 ffs->stringtabs = stringtabs;
1937 ffs->raw_strings = _data;
1939 return 0;
1941 error_free:
1942 kfree(stringtabs);
1943 error:
1944 kfree(_data);
1945 return -EINVAL;
1949 /* Events handling and management *******************************************/
1951 static void __ffs_event_add(struct ffs_data *ffs,
1952 enum usb_functionfs_event_type type)
1954 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
1955 int neg = 0;
1958 * Abort any unhandled setup
1960 * We do not need to worry about some cmpxchg() changing value
1961 * of ffs->setup_state without holding the lock because when
1962 * state is FFS_SETUP_PENDING cmpxchg() in several places in
1963 * the source does nothing.
1965 if (ffs->setup_state == FFS_SETUP_PENDING)
1966 ffs->setup_state = FFS_SETUP_CANCELED;
1968 switch (type) {
1969 case FUNCTIONFS_RESUME:
1970 rem_type2 = FUNCTIONFS_SUSPEND;
1971 /* FALL THROUGH */
1972 case FUNCTIONFS_SUSPEND:
1973 case FUNCTIONFS_SETUP:
1974 rem_type1 = type;
1975 /* Discard all similar events */
1976 break;
1978 case FUNCTIONFS_BIND:
1979 case FUNCTIONFS_UNBIND:
1980 case FUNCTIONFS_DISABLE:
1981 case FUNCTIONFS_ENABLE:
1982 /* Discard everything other then power management. */
1983 rem_type1 = FUNCTIONFS_SUSPEND;
1984 rem_type2 = FUNCTIONFS_RESUME;
1985 neg = 1;
1986 break;
1988 default:
1989 BUG();
1993 u8 *ev = ffs->ev.types, *out = ev;
1994 unsigned n = ffs->ev.count;
1995 for (; n; --n, ++ev)
1996 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
1997 *out++ = *ev;
1998 else
1999 pr_vdebug("purging event %d\n", *ev);
2000 ffs->ev.count = out - ffs->ev.types;
2003 pr_vdebug("adding event %d\n", type);
2004 ffs->ev.types[ffs->ev.count++] = type;
2005 wake_up_locked(&ffs->ev.waitq);
2008 static void ffs_event_add(struct ffs_data *ffs,
2009 enum usb_functionfs_event_type type)
2011 unsigned long flags;
2012 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2013 __ffs_event_add(ffs, type);
2014 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2018 /* Bind/unbind USB function hooks *******************************************/
2020 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2021 struct usb_descriptor_header *desc,
2022 void *priv)
2024 struct usb_endpoint_descriptor *ds = (void *)desc;
2025 struct ffs_function *func = priv;
2026 struct ffs_ep *ffs_ep;
2029 * If hs_descriptors is not NULL then we are reading hs
2030 * descriptors now
2032 const int isHS = func->function.hs_descriptors != NULL;
2033 unsigned idx;
2035 if (type != FFS_DESCRIPTOR)
2036 return 0;
2038 if (isHS)
2039 func->function.hs_descriptors[(long)valuep] = desc;
2040 else
2041 func->function.descriptors[(long)valuep] = desc;
2043 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2044 return 0;
2046 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2047 ffs_ep = func->eps + idx;
2049 if (unlikely(ffs_ep->descs[isHS])) {
2050 pr_vdebug("two %sspeed descriptors for EP %d\n",
2051 isHS ? "high" : "full",
2052 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2053 return -EINVAL;
2055 ffs_ep->descs[isHS] = ds;
2057 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2058 if (ffs_ep->ep) {
2059 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2060 if (!ds->wMaxPacketSize)
2061 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2062 } else {
2063 struct usb_request *req;
2064 struct usb_ep *ep;
2066 pr_vdebug("autoconfig\n");
2067 ep = usb_ep_autoconfig(func->gadget, ds);
2068 if (unlikely(!ep))
2069 return -ENOTSUPP;
2070 ep->driver_data = func->eps + idx;
2072 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2073 if (unlikely(!req))
2074 return -ENOMEM;
2076 ffs_ep->ep = ep;
2077 ffs_ep->req = req;
2078 func->eps_revmap[ds->bEndpointAddress &
2079 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2081 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2083 return 0;
2086 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2087 struct usb_descriptor_header *desc,
2088 void *priv)
2090 struct ffs_function *func = priv;
2091 unsigned idx;
2092 u8 newValue;
2094 switch (type) {
2095 default:
2096 case FFS_DESCRIPTOR:
2097 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2098 return 0;
2100 case FFS_INTERFACE:
2101 idx = *valuep;
2102 if (func->interfaces_nums[idx] < 0) {
2103 int id = usb_interface_id(func->conf, &func->function);
2104 if (unlikely(id < 0))
2105 return id;
2106 func->interfaces_nums[idx] = id;
2108 newValue = func->interfaces_nums[idx];
2109 break;
2111 case FFS_STRING:
2112 /* String' IDs are allocated when fsf_data is bound to cdev */
2113 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2114 break;
2116 case FFS_ENDPOINT:
2118 * USB_DT_ENDPOINT are handled in
2119 * __ffs_func_bind_do_descs().
2121 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2122 return 0;
2124 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2125 if (unlikely(!func->eps[idx].ep))
2126 return -EINVAL;
2129 struct usb_endpoint_descriptor **descs;
2130 descs = func->eps[idx].descs;
2131 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2133 break;
2136 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2137 *valuep = newValue;
2138 return 0;
2141 static int ffs_func_bind(struct usb_configuration *c,
2142 struct usb_function *f)
2144 struct ffs_function *func = ffs_func_from_usb(f);
2145 struct ffs_data *ffs = func->ffs;
2147 const int full = !!func->ffs->fs_descs_count;
2148 const int high = gadget_is_dualspeed(func->gadget) &&
2149 func->ffs->hs_descs_count;
2151 int ret;
2153 /* Make it a single chunk, less management later on */
2154 struct {
2155 struct ffs_ep eps[ffs->eps_count];
2156 struct usb_descriptor_header
2157 *fs_descs[full ? ffs->fs_descs_count + 1 : 0];
2158 struct usb_descriptor_header
2159 *hs_descs[high ? ffs->hs_descs_count + 1 : 0];
2160 short inums[ffs->interfaces_count];
2161 char raw_descs[high ? ffs->raw_descs_length
2162 : ffs->raw_fs_descs_length];
2163 } *data;
2165 ENTER();
2167 /* Only high speed but not supported by gadget? */
2168 if (unlikely(!(full | high)))
2169 return -ENOTSUPP;
2171 /* Allocate */
2172 data = kmalloc(sizeof *data, GFP_KERNEL);
2173 if (unlikely(!data))
2174 return -ENOMEM;
2176 /* Zero */
2177 memset(data->eps, 0, sizeof data->eps);
2178 memcpy(data->raw_descs, ffs->raw_descs + 16, sizeof data->raw_descs);
2179 memset(data->inums, 0xff, sizeof data->inums);
2180 for (ret = ffs->eps_count; ret; --ret)
2181 data->eps[ret].num = -1;
2183 /* Save pointers */
2184 func->eps = data->eps;
2185 func->interfaces_nums = data->inums;
2188 * Go through all the endpoint descriptors and allocate
2189 * endpoints first, so that later we can rewrite the endpoint
2190 * numbers without worrying that it may be described later on.
2192 if (likely(full)) {
2193 func->function.descriptors = data->fs_descs;
2194 ret = ffs_do_descs(ffs->fs_descs_count,
2195 data->raw_descs,
2196 sizeof data->raw_descs,
2197 __ffs_func_bind_do_descs, func);
2198 if (unlikely(ret < 0))
2199 goto error;
2200 } else {
2201 ret = 0;
2204 if (likely(high)) {
2205 func->function.hs_descriptors = data->hs_descs;
2206 ret = ffs_do_descs(ffs->hs_descs_count,
2207 data->raw_descs + ret,
2208 (sizeof data->raw_descs) - ret,
2209 __ffs_func_bind_do_descs, func);
2213 * Now handle interface numbers allocation and interface and
2214 * endpoint numbers rewriting. We can do that in one go
2215 * now.
2217 ret = ffs_do_descs(ffs->fs_descs_count +
2218 (high ? ffs->hs_descs_count : 0),
2219 data->raw_descs, sizeof data->raw_descs,
2220 __ffs_func_bind_do_nums, func);
2221 if (unlikely(ret < 0))
2222 goto error;
2224 /* And we're done */
2225 ffs_event_add(ffs, FUNCTIONFS_BIND);
2226 return 0;
2228 error:
2229 /* XXX Do we need to release all claimed endpoints here? */
2230 return ret;
2234 /* Other USB function hooks *************************************************/
2236 static void ffs_func_unbind(struct usb_configuration *c,
2237 struct usb_function *f)
2239 struct ffs_function *func = ffs_func_from_usb(f);
2240 struct ffs_data *ffs = func->ffs;
2242 ENTER();
2244 if (ffs->func == func) {
2245 ffs_func_eps_disable(func);
2246 ffs->func = NULL;
2249 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2251 ffs_func_free(func);
2254 static int ffs_func_set_alt(struct usb_function *f,
2255 unsigned interface, unsigned alt)
2257 struct ffs_function *func = ffs_func_from_usb(f);
2258 struct ffs_data *ffs = func->ffs;
2259 int ret = 0, intf;
2261 if (alt != (unsigned)-1) {
2262 intf = ffs_func_revmap_intf(func, interface);
2263 if (unlikely(intf < 0))
2264 return intf;
2267 if (ffs->func)
2268 ffs_func_eps_disable(ffs->func);
2270 if (ffs->state != FFS_ACTIVE)
2271 return -ENODEV;
2273 if (alt == (unsigned)-1) {
2274 ffs->func = NULL;
2275 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2276 return 0;
2279 ffs->func = func;
2280 ret = ffs_func_eps_enable(func);
2281 if (likely(ret >= 0))
2282 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2283 return ret;
2286 static void ffs_func_disable(struct usb_function *f)
2288 ffs_func_set_alt(f, 0, (unsigned)-1);
2291 static int ffs_func_setup(struct usb_function *f,
2292 const struct usb_ctrlrequest *creq)
2294 struct ffs_function *func = ffs_func_from_usb(f);
2295 struct ffs_data *ffs = func->ffs;
2296 unsigned long flags;
2297 int ret;
2299 ENTER();
2301 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2302 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2303 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2304 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2305 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2308 * Most requests directed to interface go through here
2309 * (notable exceptions are set/get interface) so we need to
2310 * handle them. All other either handled by composite or
2311 * passed to usb_configuration->setup() (if one is set). No
2312 * matter, we will handle requests directed to endpoint here
2313 * as well (as it's straightforward) but what to do with any
2314 * other request?
2316 if (ffs->state != FFS_ACTIVE)
2317 return -ENODEV;
2319 switch (creq->bRequestType & USB_RECIP_MASK) {
2320 case USB_RECIP_INTERFACE:
2321 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2322 if (unlikely(ret < 0))
2323 return ret;
2324 break;
2326 case USB_RECIP_ENDPOINT:
2327 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2328 if (unlikely(ret < 0))
2329 return ret;
2330 break;
2332 default:
2333 return -EOPNOTSUPP;
2336 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2337 ffs->ev.setup = *creq;
2338 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2339 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2340 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2342 return 0;
2345 static void ffs_func_suspend(struct usb_function *f)
2347 ENTER();
2348 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2351 static void ffs_func_resume(struct usb_function *f)
2353 ENTER();
2354 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2358 /* Endpoint and interface numbers reverse mapping ***************************/
2360 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2362 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2363 return num ? num : -EDOM;
2366 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2368 short *nums = func->interfaces_nums;
2369 unsigned count = func->ffs->interfaces_count;
2371 for (; count; --count, ++nums) {
2372 if (*nums >= 0 && *nums == intf)
2373 return nums - func->interfaces_nums;
2376 return -EDOM;
2380 /* Misc helper functions ****************************************************/
2382 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2384 return nonblock
2385 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2386 : mutex_lock_interruptible(mutex);
2389 static char *ffs_prepare_buffer(const char * __user buf, size_t len)
2391 char *data;
2393 if (unlikely(!len))
2394 return NULL;
2396 data = kmalloc(len, GFP_KERNEL);
2397 if (unlikely(!data))
2398 return ERR_PTR(-ENOMEM);
2400 if (unlikely(__copy_from_user(data, buf, len))) {
2401 kfree(data);
2402 return ERR_PTR(-EFAULT);
2405 pr_vdebug("Buffer from user space:\n");
2406 ffs_dump_mem("", data, len);
2408 return data;