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.
19 /* #define VERBOSE_DEBUG */
21 #include <linux/blkdev.h>
22 #include <linux/pagemap.h>
23 #include <linux/export.h>
24 #include <linux/hid.h>
25 #include <asm/unaligned.h>
27 #include <linux/usb/composite.h>
28 #include <linux/usb/functionfs.h>
31 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
33 /* Variable Length Array Macros **********************************************/
34 #define vla_group(groupname) size_t groupname##__next = 0
35 #define vla_group_size(groupname) groupname##__next
37 #define vla_item(groupname, type, name, n) \
38 size_t groupname##_##name##__offset = ({ \
39 size_t align_mask = __alignof__(type) - 1; \
40 size_t offset = (groupname##__next + align_mask) & ~align_mask;\
41 size_t size = (n) * sizeof(type); \
42 groupname##__next = offset + size; \
46 #define vla_item_with_sz(groupname, type, name, n) \
47 size_t groupname##_##name##__sz = (n) * sizeof(type); \
48 size_t groupname##_##name##__offset = ({ \
49 size_t align_mask = __alignof__(type) - 1; \
50 size_t offset = (groupname##__next + align_mask) & ~align_mask;\
51 size_t size = groupname##_##name##__sz; \
52 groupname##__next = offset + size; \
56 #define vla_ptr(ptr, groupname, name) \
57 ((void *) ((char *)ptr + groupname##_##name##__offset))
59 /* Debugging ****************************************************************/
63 # define pr_vdebug pr_debug
64 #endif /* pr_vdebug */
65 # define ffs_dump_mem(prefix, ptr, len) \
66 print_hex_dump_bytes(pr_fmt(prefix ": "), DUMP_PREFIX_NONE, ptr, len)
69 # define pr_vdebug(...) do { } while (0)
70 #endif /* pr_vdebug */
71 # define ffs_dump_mem(prefix, ptr, len) do { } while (0)
72 #endif /* VERBOSE_DEBUG */
74 #define ENTER() pr_vdebug("%s()\n", __func__)
77 /* The data structure and setup file ****************************************/
81 * Waiting for descriptors and strings.
83 * In this state no open(2), read(2) or write(2) on epfiles
84 * may succeed (which should not be the problem as there
85 * should be no such files opened in the first place).
91 * We've got descriptors and strings. We are or have called
92 * functionfs_ready_callback(). functionfs_bind() may have
93 * been called but we don't know.
95 * This is the only state in which operations on epfiles may
101 * All endpoints have been closed. This state is also set if
102 * we encounter an unrecoverable error. The only
103 * unrecoverable error is situation when after reading strings
104 * from user space we fail to initialise epfiles or
105 * functionfs_ready_callback() returns with error (<0).
107 * In this state no open(2), read(2) or write(2) (both on ep0
108 * as well as epfile) may succeed (at this point epfiles are
109 * unlinked and all closed so this is not a problem; ep0 is
110 * also closed but ep0 file exists and so open(2) on ep0 must
117 enum ffs_setup_state {
118 /* There is no setup request pending. */
121 * User has read events and there was a setup request event
122 * there. The next read/write on ep0 will handle the
127 * There was event pending but before user space handled it
128 * some other event was introduced which canceled existing
129 * setup. If this state is set read/write on ep0 return
130 * -EIDRM. This state is only set when adding event.
141 struct usb_gadget *gadget;
144 * Protect access read/write operations, only one read/write
145 * at a time. As a consequence protects ep0req and company.
146 * While setup request is being processed (queued) this is
152 * Protect access to endpoint related structures (basically
153 * usb_ep_queue(), usb_ep_dequeue(), etc. calls) except for
159 * XXX REVISIT do we need our own request? Since we are not
160 * handling setup requests immediately user space may be so
161 * slow that another setup will be sent to the gadget but this
162 * time not to us but another function and then there could be
163 * a race. Is that the case? Or maybe we can use cdev->req
164 * after all, maybe we just need some spinlock for that?
166 struct usb_request *ep0req; /* P: mutex */
167 struct completion ep0req_completion; /* P: mutex */
168 int ep0req_status; /* P: mutex */
170 /* reference counter */
172 /* how many files are opened (EP0 and others) */
176 enum ffs_state state;
179 * Possible transitions:
180 * + FFS_NO_SETUP -> FFS_SETUP_PENDING -- P: ev.waitq.lock
181 * happens only in ep0 read which is P: mutex
182 * + FFS_SETUP_PENDING -> FFS_NO_SETUP -- P: ev.waitq.lock
183 * happens only in ep0 i/o which is P: mutex
184 * + FFS_SETUP_PENDING -> FFS_SETUP_CANCELED -- P: ev.waitq.lock
185 * + FFS_SETUP_CANCELED -> FFS_NO_SETUP -- cmpxchg
187 enum ffs_setup_state setup_state;
189 #define FFS_SETUP_STATE(ffs) \
190 ((enum ffs_setup_state)cmpxchg(&(ffs)->setup_state, \
191 FFS_SETUP_CANCELED, FFS_NO_SETUP))
196 unsigned short count;
197 /* XXX REVISIT need to update it in some places, or do we? */
198 unsigned short can_stall;
199 struct usb_ctrlrequest setup;
201 wait_queue_head_t waitq;
202 } ev; /* the whole structure, P: ev.waitq.lock */
206 #define FFS_FL_CALL_CLOSED_CALLBACK 0
207 #define FFS_FL_BOUND 1
209 /* Active function */
210 struct ffs_function *func;
213 * Device name, write once when file system is mounted.
214 * Intended for user to read if she wants.
216 const char *dev_name;
217 /* Private data for our user (ie. gadget). Managed by user. */
220 /* filled by __ffs_data_got_descs() */
222 * Real descriptors are 16 bytes after raw_descs (so you need
223 * to skip 16 bytes (ie. ffs->raw_descs + 16) to get to the
224 * first full speed descriptor). raw_descs_length and
225 * raw_fs_descs_length do not have those 16 bytes added.
227 const void *raw_descs;
228 unsigned raw_descs_length;
229 unsigned raw_fs_descs_length;
230 unsigned fs_descs_count;
231 unsigned hs_descs_count;
233 unsigned short strings_count;
234 unsigned short interfaces_count;
235 unsigned short eps_count;
236 unsigned short _pad1;
238 /* filled by __ffs_data_got_strings() */
239 /* ids in stringtabs are set in functionfs_bind() */
240 const void *raw_strings;
241 struct usb_gadget_strings **stringtabs;
244 * File system's super block, write once when file system is
247 struct super_block *sb;
249 /* File permissions, written once when fs is mounted */
250 struct ffs_file_perms {
257 * The endpoint files, filled by ffs_epfiles_create(),
258 * destroyed by ffs_epfiles_destroy().
260 struct ffs_epfile *epfiles;
263 /* Reference counter handling */
264 static void ffs_data_get(struct ffs_data *ffs);
265 static void ffs_data_put(struct ffs_data *ffs);
266 /* Creates new ffs_data object. */
267 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
269 /* Opened counter handling. */
270 static void ffs_data_opened(struct ffs_data *ffs);
271 static void ffs_data_closed(struct ffs_data *ffs);
273 /* Called with ffs->mutex held; take over ownership of data. */
274 static int __must_check
275 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
276 static int __must_check
277 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
280 /* The function structure ***************************************************/
284 struct ffs_function {
285 struct usb_configuration *conf;
286 struct usb_gadget *gadget;
287 struct ffs_data *ffs;
291 short *interfaces_nums;
293 struct usb_function function;
297 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
299 return container_of(f, struct ffs_function, function);
302 static void ffs_func_free(struct ffs_function *func);
304 static void ffs_func_eps_disable(struct ffs_function *func);
305 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
307 static int ffs_func_bind(struct usb_configuration *,
308 struct usb_function *);
309 static void ffs_func_unbind(struct usb_configuration *,
310 struct usb_function *);
311 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
312 static void ffs_func_disable(struct usb_function *);
313 static int ffs_func_setup(struct usb_function *,
314 const struct usb_ctrlrequest *);
315 static void ffs_func_suspend(struct usb_function *);
316 static void ffs_func_resume(struct usb_function *);
319 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
320 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
323 /* The endpoints structures *************************************************/
326 struct usb_ep *ep; /* P: ffs->eps_lock */
327 struct usb_request *req; /* P: epfile->mutex */
329 /* [0]: full speed, [1]: high speed */
330 struct usb_endpoint_descriptor *descs[2];
334 int status; /* P: epfile->mutex */
338 /* Protects ep->ep and ep->req. */
340 wait_queue_head_t wait;
342 struct ffs_data *ffs;
343 struct ffs_ep *ep; /* P: ffs->eps_lock */
345 struct dentry *dentry;
349 unsigned char in; /* P: ffs->eps_lock */
350 unsigned char isoc; /* P: ffs->eps_lock */
355 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
356 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
358 static struct inode *__must_check
359 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
360 const struct file_operations *fops,
361 struct dentry **dentry_p);
364 /* Misc helper functions ****************************************************/
366 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
367 __attribute__((warn_unused_result, nonnull));
368 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
369 __attribute__((warn_unused_result, nonnull));
372 /* Control file aka ep0 *****************************************************/
374 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
376 struct ffs_data *ffs = req->context;
378 complete_all(&ffs->ep0req_completion);
381 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
383 struct usb_request *req = ffs->ep0req;
386 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
388 spin_unlock_irq(&ffs->ev.waitq.lock);
394 * UDC layer requires to provide a buffer even for ZLP, but should
395 * not use it at all. Let's provide some poisoned pointer to catch
396 * possible bug in the driver.
398 if (req->buf == NULL)
399 req->buf = (void *)0xDEADBABE;
401 reinit_completion(&ffs->ep0req_completion);
403 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
404 if (unlikely(ret < 0))
407 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
409 usb_ep_dequeue(ffs->gadget->ep0, req);
413 ffs->setup_state = FFS_NO_SETUP;
414 return ffs->ep0req_status;
417 static int __ffs_ep0_stall(struct ffs_data *ffs)
419 if (ffs->ev.can_stall) {
420 pr_vdebug("ep0 stall\n");
421 usb_ep_set_halt(ffs->gadget->ep0);
422 ffs->setup_state = FFS_NO_SETUP;
425 pr_debug("bogus ep0 stall!\n");
430 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
431 size_t len, loff_t *ptr)
433 struct ffs_data *ffs = file->private_data;
439 /* Fast check if setup was canceled */
440 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
444 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
445 if (unlikely(ret < 0))
449 switch (ffs->state) {
450 case FFS_READ_DESCRIPTORS:
451 case FFS_READ_STRINGS:
453 if (unlikely(len < 16)) {
458 data = ffs_prepare_buffer(buf, len);
465 if (ffs->state == FFS_READ_DESCRIPTORS) {
466 pr_info("read descriptors\n");
467 ret = __ffs_data_got_descs(ffs, data, len);
468 if (unlikely(ret < 0))
471 ffs->state = FFS_READ_STRINGS;
474 pr_info("read strings\n");
475 ret = __ffs_data_got_strings(ffs, data, len);
476 if (unlikely(ret < 0))
479 ret = ffs_epfiles_create(ffs);
481 ffs->state = FFS_CLOSING;
485 ffs->state = FFS_ACTIVE;
486 mutex_unlock(&ffs->mutex);
488 ret = functionfs_ready_callback(ffs);
489 if (unlikely(ret < 0)) {
490 ffs->state = FFS_CLOSING;
494 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
502 * We're called from user space, we can use _irq
503 * rather then _irqsave
505 spin_lock_irq(&ffs->ev.waitq.lock);
506 switch (FFS_SETUP_STATE(ffs)) {
507 case FFS_SETUP_CANCELED:
515 case FFS_SETUP_PENDING:
519 /* FFS_SETUP_PENDING */
520 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
521 spin_unlock_irq(&ffs->ev.waitq.lock);
522 ret = __ffs_ep0_stall(ffs);
526 /* FFS_SETUP_PENDING and not stall */
527 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
529 spin_unlock_irq(&ffs->ev.waitq.lock);
531 data = ffs_prepare_buffer(buf, len);
537 spin_lock_irq(&ffs->ev.waitq.lock);
540 * We are guaranteed to be still in FFS_ACTIVE state
541 * but the state of setup could have changed from
542 * FFS_SETUP_PENDING to FFS_SETUP_CANCELED so we need
543 * to check for that. If that happened we copied data
544 * from user space in vain but it's unlikely.
546 * For sure we are not in FFS_NO_SETUP since this is
547 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
548 * transition can be performed and it's protected by
551 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
554 spin_unlock_irq(&ffs->ev.waitq.lock);
556 /* unlocks spinlock */
557 ret = __ffs_ep0_queue_wait(ffs, data, len);
567 mutex_unlock(&ffs->mutex);
571 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
575 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
578 struct usb_functionfs_event events[n];
581 memset(events, 0, sizeof events);
584 events[i].type = ffs->ev.types[i];
585 if (events[i].type == FUNCTIONFS_SETUP) {
586 events[i].u.setup = ffs->ev.setup;
587 ffs->setup_state = FFS_SETUP_PENDING;
591 if (n < ffs->ev.count) {
593 memmove(ffs->ev.types, ffs->ev.types + n,
594 ffs->ev.count * sizeof *ffs->ev.types);
599 spin_unlock_irq(&ffs->ev.waitq.lock);
600 mutex_unlock(&ffs->mutex);
602 return unlikely(__copy_to_user(buf, events, sizeof events))
603 ? -EFAULT : sizeof events;
606 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
607 size_t len, loff_t *ptr)
609 struct ffs_data *ffs = file->private_data;
616 /* Fast check if setup was canceled */
617 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
621 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
622 if (unlikely(ret < 0))
626 if (ffs->state != FFS_ACTIVE) {
632 * We're called from user space, we can use _irq rather then
635 spin_lock_irq(&ffs->ev.waitq.lock);
637 switch (FFS_SETUP_STATE(ffs)) {
638 case FFS_SETUP_CANCELED:
643 n = len / sizeof(struct usb_functionfs_event);
649 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
654 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
660 return __ffs_ep0_read_events(ffs, buf,
661 min(n, (size_t)ffs->ev.count));
663 case FFS_SETUP_PENDING:
664 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
665 spin_unlock_irq(&ffs->ev.waitq.lock);
666 ret = __ffs_ep0_stall(ffs);
670 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
672 spin_unlock_irq(&ffs->ev.waitq.lock);
675 data = kmalloc(len, GFP_KERNEL);
676 if (unlikely(!data)) {
682 spin_lock_irq(&ffs->ev.waitq.lock);
684 /* See ffs_ep0_write() */
685 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
690 /* unlocks spinlock */
691 ret = __ffs_ep0_queue_wait(ffs, data, len);
692 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
701 spin_unlock_irq(&ffs->ev.waitq.lock);
703 mutex_unlock(&ffs->mutex);
708 static int ffs_ep0_open(struct inode *inode, struct file *file)
710 struct ffs_data *ffs = inode->i_private;
714 if (unlikely(ffs->state == FFS_CLOSING))
717 file->private_data = ffs;
718 ffs_data_opened(ffs);
723 static int ffs_ep0_release(struct inode *inode, struct file *file)
725 struct ffs_data *ffs = file->private_data;
729 ffs_data_closed(ffs);
734 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
736 struct ffs_data *ffs = file->private_data;
737 struct usb_gadget *gadget = ffs->gadget;
742 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
743 struct ffs_function *func = ffs->func;
744 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
745 } else if (gadget && gadget->ops->ioctl) {
746 ret = gadget->ops->ioctl(gadget, code, value);
754 static const struct file_operations ffs_ep0_operations = {
757 .open = ffs_ep0_open,
758 .write = ffs_ep0_write,
759 .read = ffs_ep0_read,
760 .release = ffs_ep0_release,
761 .unlocked_ioctl = ffs_ep0_ioctl,
765 /* "Normal" endpoints operations ********************************************/
767 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
770 if (likely(req->context)) {
771 struct ffs_ep *ep = _ep->driver_data;
772 ep->status = req->status ? req->status : req->actual;
773 complete(req->context);
777 static ssize_t ffs_epfile_io(struct file *file,
778 char __user *buf, size_t len, int read)
780 struct ffs_epfile *epfile = file->private_data;
781 struct usb_gadget *gadget = epfile->ffs->gadget;
784 ssize_t ret, data_len;
787 /* Are we still active? */
788 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
793 /* Wait for endpoint to be enabled */
796 if (file->f_flags & O_NONBLOCK) {
801 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
809 halt = !read == !epfile->in;
810 if (halt && epfile->isoc) {
815 /* Allocate & copy */
818 * Controller may require buffer size to be aligned to
819 * maxpacketsize of an out endpoint.
821 data_len = read ? usb_ep_align_maybe(gadget, ep->ep, len) : len;
823 data = kmalloc(data_len, GFP_KERNEL);
827 if (!read && unlikely(copy_from_user(data, buf, len))) {
833 /* We will be using request */
834 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
838 spin_lock_irq(&epfile->ffs->eps_lock);
840 if (epfile->ep != ep) {
841 /* In the meantime, endpoint got disabled or changed. */
843 spin_unlock_irq(&epfile->ffs->eps_lock);
846 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
847 usb_ep_set_halt(ep->ep);
848 spin_unlock_irq(&epfile->ffs->eps_lock);
851 /* Fire the request */
852 DECLARE_COMPLETION_ONSTACK(done);
854 struct usb_request *req = ep->req;
855 req->context = &done;
856 req->complete = ffs_epfile_io_complete;
858 req->length = data_len;
860 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
862 spin_unlock_irq(&epfile->ffs->eps_lock);
864 if (unlikely(ret < 0)) {
866 } else if (unlikely(wait_for_completion_interruptible(&done))) {
868 usb_ep_dequeue(ep->ep, req);
871 * XXX We may end up silently droping data here.
872 * Since data_len (i.e. req->length) may be bigger
873 * than len (after being rounded up to maxpacketsize),
874 * we may end up with more data then user space has
878 if (read && ret > 0 &&
879 unlikely(copy_to_user(buf, data,
880 min_t(size_t, ret, len))))
885 mutex_unlock(&epfile->mutex);
892 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
897 return ffs_epfile_io(file, (char __user *)buf, len, 0);
901 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
905 return ffs_epfile_io(file, buf, len, 1);
909 ffs_epfile_open(struct inode *inode, struct file *file)
911 struct ffs_epfile *epfile = inode->i_private;
915 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
918 file->private_data = epfile;
919 ffs_data_opened(epfile->ffs);
925 ffs_epfile_release(struct inode *inode, struct file *file)
927 struct ffs_epfile *epfile = inode->i_private;
931 ffs_data_closed(epfile->ffs);
936 static long ffs_epfile_ioctl(struct file *file, unsigned code,
939 struct ffs_epfile *epfile = file->private_data;
944 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
947 spin_lock_irq(&epfile->ffs->eps_lock);
948 if (likely(epfile->ep)) {
950 case FUNCTIONFS_FIFO_STATUS:
951 ret = usb_ep_fifo_status(epfile->ep->ep);
953 case FUNCTIONFS_FIFO_FLUSH:
954 usb_ep_fifo_flush(epfile->ep->ep);
957 case FUNCTIONFS_CLEAR_HALT:
958 ret = usb_ep_clear_halt(epfile->ep->ep);
960 case FUNCTIONFS_ENDPOINT_REVMAP:
961 ret = epfile->ep->num;
969 spin_unlock_irq(&epfile->ffs->eps_lock);
974 static const struct file_operations ffs_epfile_operations = {
977 .open = ffs_epfile_open,
978 .write = ffs_epfile_write,
979 .read = ffs_epfile_read,
980 .release = ffs_epfile_release,
981 .unlocked_ioctl = ffs_epfile_ioctl,
985 /* File system and super block operations ***********************************/
988 * Mounting the file system creates a controller file, used first for
989 * function configuration then later for event monitoring.
992 static struct inode *__must_check
993 ffs_sb_make_inode(struct super_block *sb, void *data,
994 const struct file_operations *fops,
995 const struct inode_operations *iops,
996 struct ffs_file_perms *perms)
1002 inode = new_inode(sb);
1004 if (likely(inode)) {
1005 struct timespec current_time = CURRENT_TIME;
1007 inode->i_ino = get_next_ino();
1008 inode->i_mode = perms->mode;
1009 inode->i_uid = perms->uid;
1010 inode->i_gid = perms->gid;
1011 inode->i_atime = current_time;
1012 inode->i_mtime = current_time;
1013 inode->i_ctime = current_time;
1014 inode->i_private = data;
1016 inode->i_fop = fops;
1024 /* Create "regular" file */
1025 static struct inode *ffs_sb_create_file(struct super_block *sb,
1026 const char *name, void *data,
1027 const struct file_operations *fops,
1028 struct dentry **dentry_p)
1030 struct ffs_data *ffs = sb->s_fs_info;
1031 struct dentry *dentry;
1032 struct inode *inode;
1036 dentry = d_alloc_name(sb->s_root, name);
1037 if (unlikely(!dentry))
1040 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1041 if (unlikely(!inode)) {
1046 d_add(dentry, inode);
1054 static const struct super_operations ffs_sb_operations = {
1055 .statfs = simple_statfs,
1056 .drop_inode = generic_delete_inode,
1059 struct ffs_sb_fill_data {
1060 struct ffs_file_perms perms;
1062 const char *dev_name;
1063 struct ffs_data *ffs_data;
1066 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1068 struct ffs_sb_fill_data *data = _data;
1069 struct inode *inode;
1070 struct ffs_data *ffs = data->ffs_data;
1075 data->ffs_data = NULL;
1076 sb->s_fs_info = ffs;
1077 sb->s_blocksize = PAGE_CACHE_SIZE;
1078 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1079 sb->s_magic = FUNCTIONFS_MAGIC;
1080 sb->s_op = &ffs_sb_operations;
1081 sb->s_time_gran = 1;
1084 data->perms.mode = data->root_mode;
1085 inode = ffs_sb_make_inode(sb, NULL,
1086 &simple_dir_operations,
1087 &simple_dir_inode_operations,
1089 sb->s_root = d_make_root(inode);
1090 if (unlikely(!sb->s_root))
1094 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1095 &ffs_ep0_operations, NULL)))
1101 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1105 if (!opts || !*opts)
1109 unsigned long value;
1113 comma = strchr(opts, ',');
1118 eq = strchr(opts, '=');
1119 if (unlikely(!eq)) {
1120 pr_err("'=' missing in %s\n", opts);
1126 if (kstrtoul(eq + 1, 0, &value)) {
1127 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1131 /* Interpret option */
1132 switch (eq - opts) {
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;
1143 if (!memcmp(opts, "mode", 4)) {
1144 data->root_mode = (value & 0555) | S_IFDIR;
1145 data->perms.mode = (value & 0666) | S_IFREG;
1152 if (!memcmp(opts, "uid", 3)) {
1153 data->perms.uid = make_kuid(current_user_ns(), value);
1154 if (!uid_valid(data->perms.uid)) {
1155 pr_err("%s: unmapped value: %lu\n", opts, value);
1158 } else if (!memcmp(opts, "gid", 3)) {
1159 data->perms.gid = make_kgid(current_user_ns(), value);
1160 if (!gid_valid(data->perms.gid)) {
1161 pr_err("%s: unmapped value: %lu\n", opts, value);
1171 pr_err("%s: invalid option\n", opts);
1175 /* Next iteration */
1184 /* "mount -t functionfs dev_name /dev/function" ends up here */
1186 static struct dentry *
1187 ffs_fs_mount(struct file_system_type *t, int flags,
1188 const char *dev_name, void *opts)
1190 struct ffs_sb_fill_data data = {
1192 .mode = S_IFREG | 0600,
1193 .uid = GLOBAL_ROOT_UID,
1194 .gid = GLOBAL_ROOT_GID,
1196 .root_mode = S_IFDIR | 0500,
1201 struct ffs_data *ffs;
1205 ret = ffs_fs_parse_opts(&data, opts);
1206 if (unlikely(ret < 0))
1207 return ERR_PTR(ret);
1209 ffs = ffs_data_new();
1211 return ERR_PTR(-ENOMEM);
1212 ffs->file_perms = data.perms;
1214 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1215 if (unlikely(!ffs->dev_name)) {
1217 return ERR_PTR(-ENOMEM);
1220 ffs_dev = functionfs_acquire_dev_callback(dev_name);
1221 if (IS_ERR(ffs_dev)) {
1223 return ERR_CAST(ffs_dev);
1225 ffs->private_data = ffs_dev;
1226 data.ffs_data = ffs;
1228 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1229 if (IS_ERR(rv) && data.ffs_data) {
1230 functionfs_release_dev_callback(data.ffs_data);
1231 ffs_data_put(data.ffs_data);
1237 ffs_fs_kill_sb(struct super_block *sb)
1241 kill_litter_super(sb);
1242 if (sb->s_fs_info) {
1243 functionfs_release_dev_callback(sb->s_fs_info);
1244 ffs_data_put(sb->s_fs_info);
1248 static struct file_system_type ffs_fs_type = {
1249 .owner = THIS_MODULE,
1250 .name = "functionfs",
1251 .mount = ffs_fs_mount,
1252 .kill_sb = ffs_fs_kill_sb,
1254 MODULE_ALIAS_FS("functionfs");
1257 /* Driver's main init/cleanup functions *************************************/
1259 static int functionfs_init(void)
1265 ret = register_filesystem(&ffs_fs_type);
1267 pr_info("file system registered\n");
1269 pr_err("failed registering file system (%d)\n", ret);
1274 static void functionfs_cleanup(void)
1278 pr_info("unloading\n");
1279 unregister_filesystem(&ffs_fs_type);
1283 /* ffs_data and ffs_function construction and destruction code **************/
1285 static void ffs_data_clear(struct ffs_data *ffs);
1286 static void ffs_data_reset(struct ffs_data *ffs);
1288 static void ffs_data_get(struct ffs_data *ffs)
1292 atomic_inc(&ffs->ref);
1295 static void ffs_data_opened(struct ffs_data *ffs)
1299 atomic_inc(&ffs->ref);
1300 atomic_inc(&ffs->opened);
1303 static void ffs_data_put(struct ffs_data *ffs)
1307 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1308 pr_info("%s(): freeing\n", __func__);
1309 ffs_data_clear(ffs);
1310 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1311 waitqueue_active(&ffs->ep0req_completion.wait));
1312 kfree(ffs->dev_name);
1317 static void ffs_data_closed(struct ffs_data *ffs)
1321 if (atomic_dec_and_test(&ffs->opened)) {
1322 ffs->state = FFS_CLOSING;
1323 ffs_data_reset(ffs);
1329 static struct ffs_data *ffs_data_new(void)
1331 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1337 atomic_set(&ffs->ref, 1);
1338 atomic_set(&ffs->opened, 0);
1339 ffs->state = FFS_READ_DESCRIPTORS;
1340 mutex_init(&ffs->mutex);
1341 spin_lock_init(&ffs->eps_lock);
1342 init_waitqueue_head(&ffs->ev.waitq);
1343 init_completion(&ffs->ep0req_completion);
1345 /* XXX REVISIT need to update it in some places, or do we? */
1346 ffs->ev.can_stall = 1;
1351 static void ffs_data_clear(struct ffs_data *ffs)
1355 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1356 functionfs_closed_callback(ffs);
1358 BUG_ON(ffs->gadget);
1361 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1363 kfree(ffs->raw_descs);
1364 kfree(ffs->raw_strings);
1365 kfree(ffs->stringtabs);
1368 static void ffs_data_reset(struct ffs_data *ffs)
1372 ffs_data_clear(ffs);
1374 ffs->epfiles = NULL;
1375 ffs->raw_descs = NULL;
1376 ffs->raw_strings = NULL;
1377 ffs->stringtabs = NULL;
1379 ffs->raw_descs_length = 0;
1380 ffs->raw_fs_descs_length = 0;
1381 ffs->fs_descs_count = 0;
1382 ffs->hs_descs_count = 0;
1384 ffs->strings_count = 0;
1385 ffs->interfaces_count = 0;
1390 ffs->state = FFS_READ_DESCRIPTORS;
1391 ffs->setup_state = FFS_NO_SETUP;
1396 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1398 struct usb_gadget_strings **lang;
1403 if (WARN_ON(ffs->state != FFS_ACTIVE
1404 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1407 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1408 if (unlikely(first_id < 0))
1411 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1412 if (unlikely(!ffs->ep0req))
1414 ffs->ep0req->complete = ffs_ep0_complete;
1415 ffs->ep0req->context = ffs;
1417 lang = ffs->stringtabs;
1418 for (lang = ffs->stringtabs; *lang; ++lang) {
1419 struct usb_string *str = (*lang)->strings;
1421 for (; str->s; ++id, ++str)
1425 ffs->gadget = cdev->gadget;
1430 static void functionfs_unbind(struct ffs_data *ffs)
1434 if (!WARN_ON(!ffs->gadget)) {
1435 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1438 clear_bit(FFS_FL_BOUND, &ffs->flags);
1443 static int ffs_epfiles_create(struct ffs_data *ffs)
1445 struct ffs_epfile *epfile, *epfiles;
1450 count = ffs->eps_count;
1451 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1456 for (i = 1; i <= count; ++i, ++epfile) {
1458 mutex_init(&epfile->mutex);
1459 init_waitqueue_head(&epfile->wait);
1460 sprintf(epfiles->name, "ep%u", i);
1461 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1462 &ffs_epfile_operations,
1463 &epfile->dentry))) {
1464 ffs_epfiles_destroy(epfiles, i - 1);
1469 ffs->epfiles = epfiles;
1473 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1475 struct ffs_epfile *epfile = epfiles;
1479 for (; count; --count, ++epfile) {
1480 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1481 waitqueue_active(&epfile->wait));
1482 if (epfile->dentry) {
1483 d_delete(epfile->dentry);
1484 dput(epfile->dentry);
1485 epfile->dentry = NULL;
1492 static int functionfs_bind_config(struct usb_composite_dev *cdev,
1493 struct usb_configuration *c,
1494 struct ffs_data *ffs)
1496 struct ffs_function *func;
1501 func = kzalloc(sizeof *func, GFP_KERNEL);
1502 if (unlikely(!func))
1505 func->function.name = "Function FS Gadget";
1506 func->function.strings = ffs->stringtabs;
1508 func->function.bind = ffs_func_bind;
1509 func->function.unbind = ffs_func_unbind;
1510 func->function.set_alt = ffs_func_set_alt;
1511 func->function.disable = ffs_func_disable;
1512 func->function.setup = ffs_func_setup;
1513 func->function.suspend = ffs_func_suspend;
1514 func->function.resume = ffs_func_resume;
1517 func->gadget = cdev->gadget;
1521 ret = usb_add_function(c, &func->function);
1523 ffs_func_free(func);
1528 static void ffs_func_free(struct ffs_function *func)
1530 struct ffs_ep *ep = func->eps;
1531 unsigned count = func->ffs->eps_count;
1532 unsigned long flags;
1536 /* cleanup after autoconfig */
1537 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1539 if (ep->ep && ep->req)
1540 usb_ep_free_request(ep->ep, ep->req);
1544 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1546 ffs_data_put(func->ffs);
1550 * eps and interfaces_nums are allocated in the same chunk so
1551 * only one free is required. Descriptors are also allocated
1552 * in the same chunk.
1558 static void ffs_func_eps_disable(struct ffs_function *func)
1560 struct ffs_ep *ep = func->eps;
1561 struct ffs_epfile *epfile = func->ffs->epfiles;
1562 unsigned count = func->ffs->eps_count;
1563 unsigned long flags;
1565 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1567 /* pending requests get nuked */
1569 usb_ep_disable(ep->ep);
1575 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1578 static int ffs_func_eps_enable(struct ffs_function *func)
1580 struct ffs_data *ffs = func->ffs;
1581 struct ffs_ep *ep = func->eps;
1582 struct ffs_epfile *epfile = ffs->epfiles;
1583 unsigned count = ffs->eps_count;
1584 unsigned long flags;
1587 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1589 struct usb_endpoint_descriptor *ds;
1590 ds = ep->descs[ep->descs[1] ? 1 : 0];
1592 ep->ep->driver_data = ep;
1594 ret = usb_ep_enable(ep->ep);
1597 epfile->in = usb_endpoint_dir_in(ds);
1598 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1603 wake_up(&epfile->wait);
1608 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1614 /* Parsing and building descriptors and strings *****************************/
1617 * This validates if data pointed by data is a valid USB descriptor as
1618 * well as record how many interfaces, endpoints and strings are
1619 * required by given configuration. Returns address after the
1620 * descriptor or NULL if data is invalid.
1623 enum ffs_entity_type {
1624 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1627 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1629 struct usb_descriptor_header *desc,
1632 static int __must_check ffs_do_desc(char *data, unsigned len,
1633 ffs_entity_callback entity, void *priv)
1635 struct usb_descriptor_header *_ds = (void *)data;
1641 /* At least two bytes are required: length and type */
1643 pr_vdebug("descriptor too short\n");
1647 /* If we have at least as many bytes as the descriptor takes? */
1648 length = _ds->bLength;
1650 pr_vdebug("descriptor longer then available data\n");
1654 #define __entity_check_INTERFACE(val) 1
1655 #define __entity_check_STRING(val) (val)
1656 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1657 #define __entity(type, val) do { \
1658 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1659 if (unlikely(!__entity_check_ ##type(val))) { \
1660 pr_vdebug("invalid entity's value\n"); \
1663 ret = entity(FFS_ ##type, &val, _ds, priv); \
1664 if (unlikely(ret < 0)) { \
1665 pr_debug("entity " #type "(%02x); ret = %d\n", \
1671 /* Parse descriptor depending on type. */
1672 switch (_ds->bDescriptorType) {
1676 case USB_DT_DEVICE_QUALIFIER:
1677 /* function can't have any of those */
1678 pr_vdebug("descriptor reserved for gadget: %d\n",
1679 _ds->bDescriptorType);
1682 case USB_DT_INTERFACE: {
1683 struct usb_interface_descriptor *ds = (void *)_ds;
1684 pr_vdebug("interface descriptor\n");
1685 if (length != sizeof *ds)
1688 __entity(INTERFACE, ds->bInterfaceNumber);
1690 __entity(STRING, ds->iInterface);
1694 case USB_DT_ENDPOINT: {
1695 struct usb_endpoint_descriptor *ds = (void *)_ds;
1696 pr_vdebug("endpoint descriptor\n");
1697 if (length != USB_DT_ENDPOINT_SIZE &&
1698 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1700 __entity(ENDPOINT, ds->bEndpointAddress);
1705 pr_vdebug("hid descriptor\n");
1706 if (length != sizeof(struct hid_descriptor))
1711 if (length != sizeof(struct usb_otg_descriptor))
1715 case USB_DT_INTERFACE_ASSOCIATION: {
1716 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1717 pr_vdebug("interface association descriptor\n");
1718 if (length != sizeof *ds)
1721 __entity(STRING, ds->iFunction);
1725 case USB_DT_OTHER_SPEED_CONFIG:
1726 case USB_DT_INTERFACE_POWER:
1728 case USB_DT_SECURITY:
1729 case USB_DT_CS_RADIO_CONTROL:
1731 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1735 /* We should never be here */
1736 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1740 pr_vdebug("invalid length: %d (descriptor %d)\n",
1741 _ds->bLength, _ds->bDescriptorType);
1746 #undef __entity_check_DESCRIPTOR
1747 #undef __entity_check_INTERFACE
1748 #undef __entity_check_STRING
1749 #undef __entity_check_ENDPOINT
1754 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1755 ffs_entity_callback entity, void *priv)
1757 const unsigned _len = len;
1758 unsigned long num = 0;
1768 /* Record "descriptor" entity */
1769 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1770 if (unlikely(ret < 0)) {
1771 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1779 ret = ffs_do_desc(data, len, entity, priv);
1780 if (unlikely(ret < 0)) {
1781 pr_debug("%s returns %d\n", __func__, ret);
1791 static int __ffs_data_do_entity(enum ffs_entity_type type,
1792 u8 *valuep, struct usb_descriptor_header *desc,
1795 struct ffs_data *ffs = priv;
1800 case FFS_DESCRIPTOR:
1805 * Interfaces are indexed from zero so if we
1806 * encountered interface "n" then there are at least
1809 if (*valuep >= ffs->interfaces_count)
1810 ffs->interfaces_count = *valuep + 1;
1815 * Strings are indexed from 1 (0 is magic ;) reserved
1816 * for languages list or some such)
1818 if (*valuep > ffs->strings_count)
1819 ffs->strings_count = *valuep;
1823 /* Endpoints are indexed from 1 as well. */
1824 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1825 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1832 static int __ffs_data_got_descs(struct ffs_data *ffs,
1833 char *const _data, size_t len)
1835 unsigned fs_count, hs_count;
1836 int fs_len, ret = -EINVAL;
1841 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
1842 get_unaligned_le32(data + 4) != len))
1844 fs_count = get_unaligned_le32(data + 8);
1845 hs_count = get_unaligned_le32(data + 12);
1847 if (!fs_count && !hs_count)
1853 if (likely(fs_count)) {
1854 fs_len = ffs_do_descs(fs_count, data, len,
1855 __ffs_data_do_entity, ffs);
1856 if (unlikely(fs_len < 0)) {
1867 if (likely(hs_count)) {
1868 ret = ffs_do_descs(hs_count, data, len,
1869 __ffs_data_do_entity, ffs);
1870 if (unlikely(ret < 0))
1876 if (unlikely(len != ret))
1879 ffs->raw_fs_descs_length = fs_len;
1880 ffs->raw_descs_length = fs_len + ret;
1881 ffs->raw_descs = _data;
1882 ffs->fs_descs_count = fs_count;
1883 ffs->hs_descs_count = hs_count;
1894 static int __ffs_data_got_strings(struct ffs_data *ffs,
1895 char *const _data, size_t len)
1897 u32 str_count, needed_count, lang_count;
1898 struct usb_gadget_strings **stringtabs, *t;
1899 struct usb_string *strings, *s;
1900 const char *data = _data;
1904 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1905 get_unaligned_le32(data + 4) != len))
1907 str_count = get_unaligned_le32(data + 8);
1908 lang_count = get_unaligned_le32(data + 12);
1910 /* if one is zero the other must be zero */
1911 if (unlikely(!str_count != !lang_count))
1914 /* Do we have at least as many strings as descriptors need? */
1915 needed_count = ffs->strings_count;
1916 if (unlikely(str_count < needed_count))
1920 * If we don't need any strings just return and free all
1923 if (!needed_count) {
1928 /* Allocate everything in one chunk so there's less maintenance. */
1932 vla_item(d, struct usb_gadget_strings *, stringtabs,
1934 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
1935 vla_item(d, struct usb_string, strings,
1936 lang_count*(needed_count+1));
1938 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
1940 if (unlikely(!vlabuf)) {
1945 /* Initialize the VLA pointers */
1946 stringtabs = vla_ptr(vlabuf, d, stringtabs);
1947 t = vla_ptr(vlabuf, d, stringtab);
1950 *stringtabs++ = t++;
1954 /* stringtabs = vlabuf = d_stringtabs for later kfree */
1955 stringtabs = vla_ptr(vlabuf, d, stringtabs);
1956 t = vla_ptr(vlabuf, d, stringtab);
1957 s = vla_ptr(vlabuf, d, strings);
1961 /* For each language */
1965 do { /* lang_count > 0 so we can use do-while */
1966 unsigned needed = needed_count;
1968 if (unlikely(len < 3))
1970 t->language = get_unaligned_le16(data);
1977 /* For each string */
1978 do { /* str_count > 0 so we can use do-while */
1979 size_t length = strnlen(data, len);
1981 if (unlikely(length == len))
1985 * User may provide more strings then we need,
1986 * if that's the case we simply ignore the
1989 if (likely(needed)) {
1991 * s->id will be set while adding
1992 * function to configuration so for
1993 * now just leave garbage here.
2002 } while (--str_count);
2004 s->id = 0; /* terminator */
2008 } while (--lang_count);
2010 /* Some garbage left? */
2015 ffs->stringtabs = stringtabs;
2016 ffs->raw_strings = _data;
2028 /* Events handling and management *******************************************/
2030 static void __ffs_event_add(struct ffs_data *ffs,
2031 enum usb_functionfs_event_type type)
2033 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2037 * Abort any unhandled setup
2039 * We do not need to worry about some cmpxchg() changing value
2040 * of ffs->setup_state without holding the lock because when
2041 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2042 * the source does nothing.
2044 if (ffs->setup_state == FFS_SETUP_PENDING)
2045 ffs->setup_state = FFS_SETUP_CANCELED;
2048 case FUNCTIONFS_RESUME:
2049 rem_type2 = FUNCTIONFS_SUSPEND;
2051 case FUNCTIONFS_SUSPEND:
2052 case FUNCTIONFS_SETUP:
2054 /* Discard all similar events */
2057 case FUNCTIONFS_BIND:
2058 case FUNCTIONFS_UNBIND:
2059 case FUNCTIONFS_DISABLE:
2060 case FUNCTIONFS_ENABLE:
2061 /* Discard everything other then power management. */
2062 rem_type1 = FUNCTIONFS_SUSPEND;
2063 rem_type2 = FUNCTIONFS_RESUME;
2072 u8 *ev = ffs->ev.types, *out = ev;
2073 unsigned n = ffs->ev.count;
2074 for (; n; --n, ++ev)
2075 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2078 pr_vdebug("purging event %d\n", *ev);
2079 ffs->ev.count = out - ffs->ev.types;
2082 pr_vdebug("adding event %d\n", type);
2083 ffs->ev.types[ffs->ev.count++] = type;
2084 wake_up_locked(&ffs->ev.waitq);
2087 static void ffs_event_add(struct ffs_data *ffs,
2088 enum usb_functionfs_event_type type)
2090 unsigned long flags;
2091 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2092 __ffs_event_add(ffs, type);
2093 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2097 /* Bind/unbind USB function hooks *******************************************/
2099 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2100 struct usb_descriptor_header *desc,
2103 struct usb_endpoint_descriptor *ds = (void *)desc;
2104 struct ffs_function *func = priv;
2105 struct ffs_ep *ffs_ep;
2108 * If hs_descriptors is not NULL then we are reading hs
2111 const int isHS = func->function.hs_descriptors != NULL;
2114 if (type != FFS_DESCRIPTOR)
2118 func->function.hs_descriptors[(long)valuep] = desc;
2120 func->function.fs_descriptors[(long)valuep] = desc;
2122 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2125 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2126 ffs_ep = func->eps + idx;
2128 if (unlikely(ffs_ep->descs[isHS])) {
2129 pr_vdebug("two %sspeed descriptors for EP %d\n",
2130 isHS ? "high" : "full",
2131 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2134 ffs_ep->descs[isHS] = ds;
2136 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2138 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2139 if (!ds->wMaxPacketSize)
2140 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2142 struct usb_request *req;
2145 pr_vdebug("autoconfig\n");
2146 ep = usb_ep_autoconfig(func->gadget, ds);
2149 ep->driver_data = func->eps + idx;
2151 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2157 func->eps_revmap[ds->bEndpointAddress &
2158 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2160 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2165 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2166 struct usb_descriptor_header *desc,
2169 struct ffs_function *func = priv;
2175 case FFS_DESCRIPTOR:
2176 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2181 if (func->interfaces_nums[idx] < 0) {
2182 int id = usb_interface_id(func->conf, &func->function);
2183 if (unlikely(id < 0))
2185 func->interfaces_nums[idx] = id;
2187 newValue = func->interfaces_nums[idx];
2191 /* String' IDs are allocated when fsf_data is bound to cdev */
2192 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2197 * USB_DT_ENDPOINT are handled in
2198 * __ffs_func_bind_do_descs().
2200 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2203 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2204 if (unlikely(!func->eps[idx].ep))
2208 struct usb_endpoint_descriptor **descs;
2209 descs = func->eps[idx].descs;
2210 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2215 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2220 static int ffs_func_bind(struct usb_configuration *c,
2221 struct usb_function *f)
2223 struct ffs_function *func = ffs_func_from_usb(f);
2224 struct ffs_data *ffs = func->ffs;
2226 const int full = !!func->ffs->fs_descs_count;
2227 const int high = gadget_is_dualspeed(func->gadget) &&
2228 func->ffs->hs_descs_count;
2232 /* Make it a single chunk, less management later on */
2234 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2235 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2236 full ? ffs->fs_descs_count + 1 : 0);
2237 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2238 high ? ffs->hs_descs_count + 1 : 0);
2239 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2240 vla_item_with_sz(d, char, raw_descs,
2241 high ? ffs->raw_descs_length : ffs->raw_fs_descs_length);
2246 /* Only high speed but not supported by gadget? */
2247 if (unlikely(!(full | high)))
2250 /* Allocate a single chunk, less management later on */
2251 vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2252 if (unlikely(!vlabuf))
2256 memset(vla_ptr(vlabuf, d, eps), 0, d_eps__sz);
2257 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs + 16,
2259 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2260 for (ret = ffs->eps_count; ret; --ret) {
2263 ptr = vla_ptr(vlabuf, d, eps);
2268 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2270 func->eps = vla_ptr(vlabuf, d, eps);
2271 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2274 * Go through all the endpoint descriptors and allocate
2275 * endpoints first, so that later we can rewrite the endpoint
2276 * numbers without worrying that it may be described later on.
2279 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2280 ret = ffs_do_descs(ffs->fs_descs_count,
2281 vla_ptr(vlabuf, d, raw_descs),
2283 __ffs_func_bind_do_descs, func);
2284 if (unlikely(ret < 0))
2291 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2292 ret = ffs_do_descs(ffs->hs_descs_count,
2293 vla_ptr(vlabuf, d, raw_descs) + ret,
2294 d_raw_descs__sz - ret,
2295 __ffs_func_bind_do_descs, func);
2296 if (unlikely(ret < 0))
2301 * Now handle interface numbers allocation and interface and
2302 * endpoint numbers rewriting. We can do that in one go
2305 ret = ffs_do_descs(ffs->fs_descs_count +
2306 (high ? ffs->hs_descs_count : 0),
2307 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2308 __ffs_func_bind_do_nums, func);
2309 if (unlikely(ret < 0))
2312 /* And we're done */
2313 ffs_event_add(ffs, FUNCTIONFS_BIND);
2317 /* XXX Do we need to release all claimed endpoints here? */
2322 /* Other USB function hooks *************************************************/
2324 static void ffs_func_unbind(struct usb_configuration *c,
2325 struct usb_function *f)
2327 struct ffs_function *func = ffs_func_from_usb(f);
2328 struct ffs_data *ffs = func->ffs;
2332 if (ffs->func == func) {
2333 ffs_func_eps_disable(func);
2337 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2339 ffs_func_free(func);
2342 static int ffs_func_set_alt(struct usb_function *f,
2343 unsigned interface, unsigned alt)
2345 struct ffs_function *func = ffs_func_from_usb(f);
2346 struct ffs_data *ffs = func->ffs;
2349 if (alt != (unsigned)-1) {
2350 intf = ffs_func_revmap_intf(func, interface);
2351 if (unlikely(intf < 0))
2356 ffs_func_eps_disable(ffs->func);
2358 if (ffs->state != FFS_ACTIVE)
2361 if (alt == (unsigned)-1) {
2363 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2368 ret = ffs_func_eps_enable(func);
2369 if (likely(ret >= 0))
2370 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2374 static void ffs_func_disable(struct usb_function *f)
2376 ffs_func_set_alt(f, 0, (unsigned)-1);
2379 static int ffs_func_setup(struct usb_function *f,
2380 const struct usb_ctrlrequest *creq)
2382 struct ffs_function *func = ffs_func_from_usb(f);
2383 struct ffs_data *ffs = func->ffs;
2384 unsigned long flags;
2389 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2390 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2391 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2392 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2393 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2396 * Most requests directed to interface go through here
2397 * (notable exceptions are set/get interface) so we need to
2398 * handle them. All other either handled by composite or
2399 * passed to usb_configuration->setup() (if one is set). No
2400 * matter, we will handle requests directed to endpoint here
2401 * as well (as it's straightforward) but what to do with any
2404 if (ffs->state != FFS_ACTIVE)
2407 switch (creq->bRequestType & USB_RECIP_MASK) {
2408 case USB_RECIP_INTERFACE:
2409 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2410 if (unlikely(ret < 0))
2414 case USB_RECIP_ENDPOINT:
2415 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2416 if (unlikely(ret < 0))
2424 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2425 ffs->ev.setup = *creq;
2426 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2427 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2428 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2433 static void ffs_func_suspend(struct usb_function *f)
2436 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2439 static void ffs_func_resume(struct usb_function *f)
2442 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2446 /* Endpoint and interface numbers reverse mapping ***************************/
2448 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2450 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2451 return num ? num : -EDOM;
2454 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2456 short *nums = func->interfaces_nums;
2457 unsigned count = func->ffs->interfaces_count;
2459 for (; count; --count, ++nums) {
2460 if (*nums >= 0 && *nums == intf)
2461 return nums - func->interfaces_nums;
2468 /* Misc helper functions ****************************************************/
2470 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2473 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2474 : mutex_lock_interruptible(mutex);
2477 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
2484 data = kmalloc(len, GFP_KERNEL);
2485 if (unlikely(!data))
2486 return ERR_PTR(-ENOMEM);
2488 if (unlikely(__copy_from_user(data, buf, len))) {
2490 return ERR_PTR(-EFAULT);
2493 pr_vdebug("Buffer from user space:\n");
2494 ffs_dump_mem("", data, len);