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 <linux/module.h>
26 #include <asm/unaligned.h>
28 #include <linux/usb/composite.h>
29 #include <linux/usb/functionfs.h>
34 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
36 /* Variable Length Array Macros **********************************************/
37 #define vla_group(groupname) size_t groupname##__next = 0
38 #define vla_group_size(groupname) groupname##__next
40 #define vla_item(groupname, type, name, n) \
41 size_t groupname##_##name##__offset = ({ \
42 size_t align_mask = __alignof__(type) - 1; \
43 size_t offset = (groupname##__next + align_mask) & ~align_mask;\
44 size_t size = (n) * sizeof(type); \
45 groupname##__next = offset + size; \
49 #define vla_item_with_sz(groupname, type, name, n) \
50 size_t groupname##_##name##__sz = (n) * sizeof(type); \
51 size_t groupname##_##name##__offset = ({ \
52 size_t align_mask = __alignof__(type) - 1; \
53 size_t offset = (groupname##__next + align_mask) & ~align_mask;\
54 size_t size = groupname##_##name##__sz; \
55 groupname##__next = offset + size; \
59 #define vla_ptr(ptr, groupname, name) \
60 ((void *) ((char *)ptr + groupname##_##name##__offset))
62 /* Reference counter handling */
63 static void ffs_data_get(struct ffs_data *ffs);
64 static void ffs_data_put(struct ffs_data *ffs);
65 /* Creates new ffs_data object. */
66 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
68 /* Opened counter handling. */
69 static void ffs_data_opened(struct ffs_data *ffs);
70 static void ffs_data_closed(struct ffs_data *ffs);
72 /* Called with ffs->mutex held; take over ownership of data. */
73 static int __must_check
74 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
75 static int __must_check
76 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
79 /* The function structure ***************************************************/
84 struct usb_configuration *conf;
85 struct usb_gadget *gadget;
90 short *interfaces_nums;
92 struct usb_function function;
96 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
98 return container_of(f, struct ffs_function, function);
102 static inline enum ffs_setup_state
103 ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
105 return (enum ffs_setup_state)
106 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
110 static void ffs_func_eps_disable(struct ffs_function *func);
111 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
113 static int ffs_func_bind(struct usb_configuration *,
114 struct usb_function *);
115 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
116 static void ffs_func_disable(struct usb_function *);
117 static int ffs_func_setup(struct usb_function *,
118 const struct usb_ctrlrequest *);
119 static void ffs_func_suspend(struct usb_function *);
120 static void ffs_func_resume(struct usb_function *);
123 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
124 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
127 /* The endpoints structures *************************************************/
130 struct usb_ep *ep; /* P: ffs->eps_lock */
131 struct usb_request *req; /* P: epfile->mutex */
133 /* [0]: full speed, [1]: high speed */
134 struct usb_endpoint_descriptor *descs[2];
138 int status; /* P: epfile->mutex */
142 /* Protects ep->ep and ep->req. */
144 wait_queue_head_t wait;
146 struct ffs_data *ffs;
147 struct ffs_ep *ep; /* P: ffs->eps_lock */
149 struct dentry *dentry;
153 unsigned char in; /* P: ffs->eps_lock */
154 unsigned char isoc; /* P: ffs->eps_lock */
159 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
160 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
162 static struct inode *__must_check
163 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
164 const struct file_operations *fops,
165 struct dentry **dentry_p);
167 /* Devices management *******************************************************/
169 DEFINE_MUTEX(ffs_lock);
170 EXPORT_SYMBOL(ffs_lock);
172 static struct ffs_dev *_ffs_find_dev(const char *name);
173 static struct ffs_dev *_ffs_alloc_dev(void);
174 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
175 static void _ffs_free_dev(struct ffs_dev *dev);
176 static void *ffs_acquire_dev(const char *dev_name);
177 static void ffs_release_dev(struct ffs_data *ffs_data);
178 static int ffs_ready(struct ffs_data *ffs);
179 static void ffs_closed(struct ffs_data *ffs);
181 /* Misc helper functions ****************************************************/
183 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
184 __attribute__((warn_unused_result, nonnull));
185 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
186 __attribute__((warn_unused_result, nonnull));
189 /* Control file aka ep0 *****************************************************/
191 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
193 struct ffs_data *ffs = req->context;
195 complete_all(&ffs->ep0req_completion);
198 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
200 struct usb_request *req = ffs->ep0req;
203 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
205 spin_unlock_irq(&ffs->ev.waitq.lock);
211 * UDC layer requires to provide a buffer even for ZLP, but should
212 * not use it at all. Let's provide some poisoned pointer to catch
213 * possible bug in the driver.
215 if (req->buf == NULL)
216 req->buf = (void *)0xDEADBABE;
218 reinit_completion(&ffs->ep0req_completion);
220 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
221 if (unlikely(ret < 0))
224 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
226 usb_ep_dequeue(ffs->gadget->ep0, req);
230 ffs->setup_state = FFS_NO_SETUP;
231 return ffs->ep0req_status;
234 static int __ffs_ep0_stall(struct ffs_data *ffs)
236 if (ffs->ev.can_stall) {
237 pr_vdebug("ep0 stall\n");
238 usb_ep_set_halt(ffs->gadget->ep0);
239 ffs->setup_state = FFS_NO_SETUP;
242 pr_debug("bogus ep0 stall!\n");
247 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
248 size_t len, loff_t *ptr)
250 struct ffs_data *ffs = file->private_data;
256 /* Fast check if setup was canceled */
257 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
261 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
262 if (unlikely(ret < 0))
266 switch (ffs->state) {
267 case FFS_READ_DESCRIPTORS:
268 case FFS_READ_STRINGS:
270 if (unlikely(len < 16)) {
275 data = ffs_prepare_buffer(buf, len);
282 if (ffs->state == FFS_READ_DESCRIPTORS) {
283 pr_info("read descriptors\n");
284 ret = __ffs_data_got_descs(ffs, data, len);
285 if (unlikely(ret < 0))
288 ffs->state = FFS_READ_STRINGS;
291 pr_info("read strings\n");
292 ret = __ffs_data_got_strings(ffs, data, len);
293 if (unlikely(ret < 0))
296 ret = ffs_epfiles_create(ffs);
298 ffs->state = FFS_CLOSING;
302 ffs->state = FFS_ACTIVE;
303 mutex_unlock(&ffs->mutex);
305 ret = ffs_ready(ffs);
306 if (unlikely(ret < 0)) {
307 ffs->state = FFS_CLOSING;
311 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
319 * We're called from user space, we can use _irq
320 * rather then _irqsave
322 spin_lock_irq(&ffs->ev.waitq.lock);
323 switch (ffs_setup_state_clear_cancelled(ffs)) {
324 case FFS_SETUP_CANCELLED:
332 case FFS_SETUP_PENDING:
336 /* FFS_SETUP_PENDING */
337 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
338 spin_unlock_irq(&ffs->ev.waitq.lock);
339 ret = __ffs_ep0_stall(ffs);
343 /* FFS_SETUP_PENDING and not stall */
344 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
346 spin_unlock_irq(&ffs->ev.waitq.lock);
348 data = ffs_prepare_buffer(buf, len);
354 spin_lock_irq(&ffs->ev.waitq.lock);
357 * We are guaranteed to be still in FFS_ACTIVE state
358 * but the state of setup could have changed from
359 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
360 * to check for that. If that happened we copied data
361 * from user space in vain but it's unlikely.
363 * For sure we are not in FFS_NO_SETUP since this is
364 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
365 * transition can be performed and it's protected by
368 if (ffs_setup_state_clear_cancelled(ffs) ==
369 FFS_SETUP_CANCELLED) {
372 spin_unlock_irq(&ffs->ev.waitq.lock);
374 /* unlocks spinlock */
375 ret = __ffs_ep0_queue_wait(ffs, data, len);
385 mutex_unlock(&ffs->mutex);
389 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
393 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
396 struct usb_functionfs_event events[n];
399 memset(events, 0, sizeof events);
402 events[i].type = ffs->ev.types[i];
403 if (events[i].type == FUNCTIONFS_SETUP) {
404 events[i].u.setup = ffs->ev.setup;
405 ffs->setup_state = FFS_SETUP_PENDING;
409 if (n < ffs->ev.count) {
411 memmove(ffs->ev.types, ffs->ev.types + n,
412 ffs->ev.count * sizeof *ffs->ev.types);
417 spin_unlock_irq(&ffs->ev.waitq.lock);
418 mutex_unlock(&ffs->mutex);
420 return unlikely(__copy_to_user(buf, events, sizeof events))
421 ? -EFAULT : sizeof events;
424 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
425 size_t len, loff_t *ptr)
427 struct ffs_data *ffs = file->private_data;
434 /* Fast check if setup was canceled */
435 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
439 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
440 if (unlikely(ret < 0))
444 if (ffs->state != FFS_ACTIVE) {
450 * We're called from user space, we can use _irq rather then
453 spin_lock_irq(&ffs->ev.waitq.lock);
455 switch (ffs_setup_state_clear_cancelled(ffs)) {
456 case FFS_SETUP_CANCELLED:
461 n = len / sizeof(struct usb_functionfs_event);
467 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
472 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
478 return __ffs_ep0_read_events(ffs, buf,
479 min(n, (size_t)ffs->ev.count));
481 case FFS_SETUP_PENDING:
482 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
483 spin_unlock_irq(&ffs->ev.waitq.lock);
484 ret = __ffs_ep0_stall(ffs);
488 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
490 spin_unlock_irq(&ffs->ev.waitq.lock);
493 data = kmalloc(len, GFP_KERNEL);
494 if (unlikely(!data)) {
500 spin_lock_irq(&ffs->ev.waitq.lock);
502 /* See ffs_ep0_write() */
503 if (ffs_setup_state_clear_cancelled(ffs) ==
504 FFS_SETUP_CANCELLED) {
509 /* unlocks spinlock */
510 ret = __ffs_ep0_queue_wait(ffs, data, len);
511 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
520 spin_unlock_irq(&ffs->ev.waitq.lock);
522 mutex_unlock(&ffs->mutex);
527 static int ffs_ep0_open(struct inode *inode, struct file *file)
529 struct ffs_data *ffs = inode->i_private;
533 if (unlikely(ffs->state == FFS_CLOSING))
536 file->private_data = ffs;
537 ffs_data_opened(ffs);
542 static int ffs_ep0_release(struct inode *inode, struct file *file)
544 struct ffs_data *ffs = file->private_data;
548 ffs_data_closed(ffs);
553 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
555 struct ffs_data *ffs = file->private_data;
556 struct usb_gadget *gadget = ffs->gadget;
561 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
562 struct ffs_function *func = ffs->func;
563 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
564 } else if (gadget && gadget->ops->ioctl) {
565 ret = gadget->ops->ioctl(gadget, code, value);
573 static const struct file_operations ffs_ep0_operations = {
576 .open = ffs_ep0_open,
577 .write = ffs_ep0_write,
578 .read = ffs_ep0_read,
579 .release = ffs_ep0_release,
580 .unlocked_ioctl = ffs_ep0_ioctl,
584 /* "Normal" endpoints operations ********************************************/
586 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
589 if (likely(req->context)) {
590 struct ffs_ep *ep = _ep->driver_data;
591 ep->status = req->status ? req->status : req->actual;
592 complete(req->context);
596 static ssize_t ffs_epfile_io(struct file *file,
597 char __user *buf, size_t len, int read)
599 struct ffs_epfile *epfile = file->private_data;
600 struct usb_gadget *gadget = epfile->ffs->gadget;
603 ssize_t ret, data_len;
606 /* Are we still active? */
607 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
612 /* Wait for endpoint to be enabled */
615 if (file->f_flags & O_NONBLOCK) {
620 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
628 halt = !read == !epfile->in;
629 if (halt && epfile->isoc) {
634 /* Allocate & copy */
637 * Controller may require buffer size to be aligned to
638 * maxpacketsize of an out endpoint.
640 data_len = read ? usb_ep_align_maybe(gadget, ep->ep, len) : len;
642 data = kmalloc(data_len, GFP_KERNEL);
646 if (!read && unlikely(copy_from_user(data, buf, len))) {
652 /* We will be using request */
653 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
657 spin_lock_irq(&epfile->ffs->eps_lock);
659 if (epfile->ep != ep) {
660 /* In the meantime, endpoint got disabled or changed. */
662 spin_unlock_irq(&epfile->ffs->eps_lock);
665 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
666 usb_ep_set_halt(ep->ep);
667 spin_unlock_irq(&epfile->ffs->eps_lock);
670 /* Fire the request */
671 DECLARE_COMPLETION_ONSTACK(done);
673 struct usb_request *req = ep->req;
674 req->context = &done;
675 req->complete = ffs_epfile_io_complete;
677 req->length = data_len;
679 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
681 spin_unlock_irq(&epfile->ffs->eps_lock);
683 if (unlikely(ret < 0)) {
685 } else if (unlikely(wait_for_completion_interruptible(&done))) {
687 usb_ep_dequeue(ep->ep, req);
690 * XXX We may end up silently droping data here.
691 * Since data_len (i.e. req->length) may be bigger
692 * than len (after being rounded up to maxpacketsize),
693 * we may end up with more data then user space has
697 if (read && ret > 0 &&
698 unlikely(copy_to_user(buf, data,
699 min_t(size_t, ret, len))))
704 mutex_unlock(&epfile->mutex);
711 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
716 return ffs_epfile_io(file, (char __user *)buf, len, 0);
720 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
724 return ffs_epfile_io(file, buf, len, 1);
728 ffs_epfile_open(struct inode *inode, struct file *file)
730 struct ffs_epfile *epfile = inode->i_private;
734 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
737 file->private_data = epfile;
738 ffs_data_opened(epfile->ffs);
744 ffs_epfile_release(struct inode *inode, struct file *file)
746 struct ffs_epfile *epfile = inode->i_private;
750 ffs_data_closed(epfile->ffs);
755 static long ffs_epfile_ioctl(struct file *file, unsigned code,
758 struct ffs_epfile *epfile = file->private_data;
763 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
766 spin_lock_irq(&epfile->ffs->eps_lock);
767 if (likely(epfile->ep)) {
769 case FUNCTIONFS_FIFO_STATUS:
770 ret = usb_ep_fifo_status(epfile->ep->ep);
772 case FUNCTIONFS_FIFO_FLUSH:
773 usb_ep_fifo_flush(epfile->ep->ep);
776 case FUNCTIONFS_CLEAR_HALT:
777 ret = usb_ep_clear_halt(epfile->ep->ep);
779 case FUNCTIONFS_ENDPOINT_REVMAP:
780 ret = epfile->ep->num;
788 spin_unlock_irq(&epfile->ffs->eps_lock);
793 static const struct file_operations ffs_epfile_operations = {
796 .open = ffs_epfile_open,
797 .write = ffs_epfile_write,
798 .read = ffs_epfile_read,
799 .release = ffs_epfile_release,
800 .unlocked_ioctl = ffs_epfile_ioctl,
804 /* File system and super block operations ***********************************/
807 * Mounting the file system creates a controller file, used first for
808 * function configuration then later for event monitoring.
811 static struct inode *__must_check
812 ffs_sb_make_inode(struct super_block *sb, void *data,
813 const struct file_operations *fops,
814 const struct inode_operations *iops,
815 struct ffs_file_perms *perms)
821 inode = new_inode(sb);
824 struct timespec current_time = CURRENT_TIME;
826 inode->i_ino = get_next_ino();
827 inode->i_mode = perms->mode;
828 inode->i_uid = perms->uid;
829 inode->i_gid = perms->gid;
830 inode->i_atime = current_time;
831 inode->i_mtime = current_time;
832 inode->i_ctime = current_time;
833 inode->i_private = data;
843 /* Create "regular" file */
844 static struct inode *ffs_sb_create_file(struct super_block *sb,
845 const char *name, void *data,
846 const struct file_operations *fops,
847 struct dentry **dentry_p)
849 struct ffs_data *ffs = sb->s_fs_info;
850 struct dentry *dentry;
855 dentry = d_alloc_name(sb->s_root, name);
856 if (unlikely(!dentry))
859 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
860 if (unlikely(!inode)) {
865 d_add(dentry, inode);
873 static const struct super_operations ffs_sb_operations = {
874 .statfs = simple_statfs,
875 .drop_inode = generic_delete_inode,
878 struct ffs_sb_fill_data {
879 struct ffs_file_perms perms;
881 const char *dev_name;
882 struct ffs_data *ffs_data;
885 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
887 struct ffs_sb_fill_data *data = _data;
889 struct ffs_data *ffs = data->ffs_data;
894 data->ffs_data = NULL;
896 sb->s_blocksize = PAGE_CACHE_SIZE;
897 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
898 sb->s_magic = FUNCTIONFS_MAGIC;
899 sb->s_op = &ffs_sb_operations;
903 data->perms.mode = data->root_mode;
904 inode = ffs_sb_make_inode(sb, NULL,
905 &simple_dir_operations,
906 &simple_dir_inode_operations,
908 sb->s_root = d_make_root(inode);
909 if (unlikely(!sb->s_root))
913 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
914 &ffs_ep0_operations, NULL)))
920 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
932 comma = strchr(opts, ',');
937 eq = strchr(opts, '=');
939 pr_err("'=' missing in %s\n", opts);
945 if (kstrtoul(eq + 1, 0, &value)) {
946 pr_err("%s: invalid value: %s\n", opts, eq + 1);
950 /* Interpret option */
953 if (!memcmp(opts, "rmode", 5))
954 data->root_mode = (value & 0555) | S_IFDIR;
955 else if (!memcmp(opts, "fmode", 5))
956 data->perms.mode = (value & 0666) | S_IFREG;
962 if (!memcmp(opts, "mode", 4)) {
963 data->root_mode = (value & 0555) | S_IFDIR;
964 data->perms.mode = (value & 0666) | S_IFREG;
971 if (!memcmp(opts, "uid", 3)) {
972 data->perms.uid = make_kuid(current_user_ns(), value);
973 if (!uid_valid(data->perms.uid)) {
974 pr_err("%s: unmapped value: %lu\n", opts, value);
977 } else if (!memcmp(opts, "gid", 3)) {
978 data->perms.gid = make_kgid(current_user_ns(), value);
979 if (!gid_valid(data->perms.gid)) {
980 pr_err("%s: unmapped value: %lu\n", opts, value);
990 pr_err("%s: invalid option\n", opts);
1003 /* "mount -t functionfs dev_name /dev/function" ends up here */
1005 static struct dentry *
1006 ffs_fs_mount(struct file_system_type *t, int flags,
1007 const char *dev_name, void *opts)
1009 struct ffs_sb_fill_data data = {
1011 .mode = S_IFREG | 0600,
1012 .uid = GLOBAL_ROOT_UID,
1013 .gid = GLOBAL_ROOT_GID,
1015 .root_mode = S_IFDIR | 0500,
1020 struct ffs_data *ffs;
1024 ret = ffs_fs_parse_opts(&data, opts);
1025 if (unlikely(ret < 0))
1026 return ERR_PTR(ret);
1028 ffs = ffs_data_new();
1030 return ERR_PTR(-ENOMEM);
1031 ffs->file_perms = data.perms;
1033 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1034 if (unlikely(!ffs->dev_name)) {
1036 return ERR_PTR(-ENOMEM);
1039 ffs_dev = ffs_acquire_dev(dev_name);
1040 if (IS_ERR(ffs_dev)) {
1042 return ERR_CAST(ffs_dev);
1044 ffs->private_data = ffs_dev;
1045 data.ffs_data = ffs;
1047 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1048 if (IS_ERR(rv) && data.ffs_data) {
1049 ffs_release_dev(data.ffs_data);
1050 ffs_data_put(data.ffs_data);
1056 ffs_fs_kill_sb(struct super_block *sb)
1060 kill_litter_super(sb);
1061 if (sb->s_fs_info) {
1062 ffs_release_dev(sb->s_fs_info);
1063 ffs_data_put(sb->s_fs_info);
1067 static struct file_system_type ffs_fs_type = {
1068 .owner = THIS_MODULE,
1069 .name = "functionfs",
1070 .mount = ffs_fs_mount,
1071 .kill_sb = ffs_fs_kill_sb,
1073 MODULE_ALIAS_FS("functionfs");
1076 /* Driver's main init/cleanup functions *************************************/
1078 static int functionfs_init(void)
1084 ret = register_filesystem(&ffs_fs_type);
1086 pr_info("file system registered\n");
1088 pr_err("failed registering file system (%d)\n", ret);
1093 static void functionfs_cleanup(void)
1097 pr_info("unloading\n");
1098 unregister_filesystem(&ffs_fs_type);
1102 /* ffs_data and ffs_function construction and destruction code **************/
1104 static void ffs_data_clear(struct ffs_data *ffs);
1105 static void ffs_data_reset(struct ffs_data *ffs);
1107 static void ffs_data_get(struct ffs_data *ffs)
1111 atomic_inc(&ffs->ref);
1114 static void ffs_data_opened(struct ffs_data *ffs)
1118 atomic_inc(&ffs->ref);
1119 atomic_inc(&ffs->opened);
1122 static void ffs_data_put(struct ffs_data *ffs)
1126 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1127 pr_info("%s(): freeing\n", __func__);
1128 ffs_data_clear(ffs);
1129 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1130 waitqueue_active(&ffs->ep0req_completion.wait));
1131 kfree(ffs->dev_name);
1136 static void ffs_data_closed(struct ffs_data *ffs)
1140 if (atomic_dec_and_test(&ffs->opened)) {
1141 ffs->state = FFS_CLOSING;
1142 ffs_data_reset(ffs);
1148 static struct ffs_data *ffs_data_new(void)
1150 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1156 atomic_set(&ffs->ref, 1);
1157 atomic_set(&ffs->opened, 0);
1158 ffs->state = FFS_READ_DESCRIPTORS;
1159 mutex_init(&ffs->mutex);
1160 spin_lock_init(&ffs->eps_lock);
1161 init_waitqueue_head(&ffs->ev.waitq);
1162 init_completion(&ffs->ep0req_completion);
1164 /* XXX REVISIT need to update it in some places, or do we? */
1165 ffs->ev.can_stall = 1;
1170 static void ffs_data_clear(struct ffs_data *ffs)
1174 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1177 BUG_ON(ffs->gadget);
1180 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1182 kfree(ffs->raw_descs);
1183 kfree(ffs->raw_strings);
1184 kfree(ffs->stringtabs);
1187 static void ffs_data_reset(struct ffs_data *ffs)
1191 ffs_data_clear(ffs);
1193 ffs->epfiles = NULL;
1194 ffs->raw_descs = NULL;
1195 ffs->raw_strings = NULL;
1196 ffs->stringtabs = NULL;
1198 ffs->raw_descs_length = 0;
1199 ffs->raw_fs_descs_length = 0;
1200 ffs->fs_descs_count = 0;
1201 ffs->hs_descs_count = 0;
1203 ffs->strings_count = 0;
1204 ffs->interfaces_count = 0;
1209 ffs->state = FFS_READ_DESCRIPTORS;
1210 ffs->setup_state = FFS_NO_SETUP;
1215 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1217 struct usb_gadget_strings **lang;
1222 if (WARN_ON(ffs->state != FFS_ACTIVE
1223 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1226 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1227 if (unlikely(first_id < 0))
1230 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1231 if (unlikely(!ffs->ep0req))
1233 ffs->ep0req->complete = ffs_ep0_complete;
1234 ffs->ep0req->context = ffs;
1236 lang = ffs->stringtabs;
1237 for (lang = ffs->stringtabs; *lang; ++lang) {
1238 struct usb_string *str = (*lang)->strings;
1240 for (; str->s; ++id, ++str)
1244 ffs->gadget = cdev->gadget;
1249 static void functionfs_unbind(struct ffs_data *ffs)
1253 if (!WARN_ON(!ffs->gadget)) {
1254 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1257 clear_bit(FFS_FL_BOUND, &ffs->flags);
1262 static int ffs_epfiles_create(struct ffs_data *ffs)
1264 struct ffs_epfile *epfile, *epfiles;
1269 count = ffs->eps_count;
1270 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1275 for (i = 1; i <= count; ++i, ++epfile) {
1277 mutex_init(&epfile->mutex);
1278 init_waitqueue_head(&epfile->wait);
1279 sprintf(epfiles->name, "ep%u", i);
1280 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1281 &ffs_epfile_operations,
1282 &epfile->dentry))) {
1283 ffs_epfiles_destroy(epfiles, i - 1);
1288 ffs->epfiles = epfiles;
1292 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1294 struct ffs_epfile *epfile = epfiles;
1298 for (; count; --count, ++epfile) {
1299 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1300 waitqueue_active(&epfile->wait));
1301 if (epfile->dentry) {
1302 d_delete(epfile->dentry);
1303 dput(epfile->dentry);
1304 epfile->dentry = NULL;
1312 static void ffs_func_eps_disable(struct ffs_function *func)
1314 struct ffs_ep *ep = func->eps;
1315 struct ffs_epfile *epfile = func->ffs->epfiles;
1316 unsigned count = func->ffs->eps_count;
1317 unsigned long flags;
1319 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1321 /* pending requests get nuked */
1323 usb_ep_disable(ep->ep);
1329 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1332 static int ffs_func_eps_enable(struct ffs_function *func)
1334 struct ffs_data *ffs = func->ffs;
1335 struct ffs_ep *ep = func->eps;
1336 struct ffs_epfile *epfile = ffs->epfiles;
1337 unsigned count = ffs->eps_count;
1338 unsigned long flags;
1341 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1343 struct usb_endpoint_descriptor *ds;
1344 ds = ep->descs[ep->descs[1] ? 1 : 0];
1346 ep->ep->driver_data = ep;
1348 ret = usb_ep_enable(ep->ep);
1351 epfile->in = usb_endpoint_dir_in(ds);
1352 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1357 wake_up(&epfile->wait);
1362 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1368 /* Parsing and building descriptors and strings *****************************/
1371 * This validates if data pointed by data is a valid USB descriptor as
1372 * well as record how many interfaces, endpoints and strings are
1373 * required by given configuration. Returns address after the
1374 * descriptor or NULL if data is invalid.
1377 enum ffs_entity_type {
1378 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1381 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1383 struct usb_descriptor_header *desc,
1386 static int __must_check ffs_do_desc(char *data, unsigned len,
1387 ffs_entity_callback entity, void *priv)
1389 struct usb_descriptor_header *_ds = (void *)data;
1395 /* At least two bytes are required: length and type */
1397 pr_vdebug("descriptor too short\n");
1401 /* If we have at least as many bytes as the descriptor takes? */
1402 length = _ds->bLength;
1404 pr_vdebug("descriptor longer then available data\n");
1408 #define __entity_check_INTERFACE(val) 1
1409 #define __entity_check_STRING(val) (val)
1410 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1411 #define __entity(type, val) do { \
1412 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1413 if (unlikely(!__entity_check_ ##type(val))) { \
1414 pr_vdebug("invalid entity's value\n"); \
1417 ret = entity(FFS_ ##type, &val, _ds, priv); \
1418 if (unlikely(ret < 0)) { \
1419 pr_debug("entity " #type "(%02x); ret = %d\n", \
1425 /* Parse descriptor depending on type. */
1426 switch (_ds->bDescriptorType) {
1430 case USB_DT_DEVICE_QUALIFIER:
1431 /* function can't have any of those */
1432 pr_vdebug("descriptor reserved for gadget: %d\n",
1433 _ds->bDescriptorType);
1436 case USB_DT_INTERFACE: {
1437 struct usb_interface_descriptor *ds = (void *)_ds;
1438 pr_vdebug("interface descriptor\n");
1439 if (length != sizeof *ds)
1442 __entity(INTERFACE, ds->bInterfaceNumber);
1444 __entity(STRING, ds->iInterface);
1448 case USB_DT_ENDPOINT: {
1449 struct usb_endpoint_descriptor *ds = (void *)_ds;
1450 pr_vdebug("endpoint descriptor\n");
1451 if (length != USB_DT_ENDPOINT_SIZE &&
1452 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1454 __entity(ENDPOINT, ds->bEndpointAddress);
1459 pr_vdebug("hid descriptor\n");
1460 if (length != sizeof(struct hid_descriptor))
1465 if (length != sizeof(struct usb_otg_descriptor))
1469 case USB_DT_INTERFACE_ASSOCIATION: {
1470 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1471 pr_vdebug("interface association descriptor\n");
1472 if (length != sizeof *ds)
1475 __entity(STRING, ds->iFunction);
1479 case USB_DT_OTHER_SPEED_CONFIG:
1480 case USB_DT_INTERFACE_POWER:
1482 case USB_DT_SECURITY:
1483 case USB_DT_CS_RADIO_CONTROL:
1485 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1489 /* We should never be here */
1490 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1494 pr_vdebug("invalid length: %d (descriptor %d)\n",
1495 _ds->bLength, _ds->bDescriptorType);
1500 #undef __entity_check_DESCRIPTOR
1501 #undef __entity_check_INTERFACE
1502 #undef __entity_check_STRING
1503 #undef __entity_check_ENDPOINT
1508 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1509 ffs_entity_callback entity, void *priv)
1511 const unsigned _len = len;
1512 unsigned long num = 0;
1522 /* Record "descriptor" entity */
1523 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1524 if (unlikely(ret < 0)) {
1525 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1533 ret = ffs_do_desc(data, len, entity, priv);
1534 if (unlikely(ret < 0)) {
1535 pr_debug("%s returns %d\n", __func__, ret);
1545 static int __ffs_data_do_entity(enum ffs_entity_type type,
1546 u8 *valuep, struct usb_descriptor_header *desc,
1549 struct ffs_data *ffs = priv;
1554 case FFS_DESCRIPTOR:
1559 * Interfaces are indexed from zero so if we
1560 * encountered interface "n" then there are at least
1563 if (*valuep >= ffs->interfaces_count)
1564 ffs->interfaces_count = *valuep + 1;
1569 * Strings are indexed from 1 (0 is magic ;) reserved
1570 * for languages list or some such)
1572 if (*valuep > ffs->strings_count)
1573 ffs->strings_count = *valuep;
1577 /* Endpoints are indexed from 1 as well. */
1578 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1579 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1586 static int __ffs_data_got_descs(struct ffs_data *ffs,
1587 char *const _data, size_t len)
1589 unsigned fs_count, hs_count;
1590 int fs_len, ret = -EINVAL;
1595 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
1596 get_unaligned_le32(data + 4) != len))
1598 fs_count = get_unaligned_le32(data + 8);
1599 hs_count = get_unaligned_le32(data + 12);
1601 if (!fs_count && !hs_count)
1607 if (likely(fs_count)) {
1608 fs_len = ffs_do_descs(fs_count, data, len,
1609 __ffs_data_do_entity, ffs);
1610 if (unlikely(fs_len < 0)) {
1621 if (likely(hs_count)) {
1622 ret = ffs_do_descs(hs_count, data, len,
1623 __ffs_data_do_entity, ffs);
1624 if (unlikely(ret < 0))
1630 if (unlikely(len != ret))
1633 ffs->raw_fs_descs_length = fs_len;
1634 ffs->raw_descs_length = fs_len + ret;
1635 ffs->raw_descs = _data;
1636 ffs->fs_descs_count = fs_count;
1637 ffs->hs_descs_count = hs_count;
1648 static int __ffs_data_got_strings(struct ffs_data *ffs,
1649 char *const _data, size_t len)
1651 u32 str_count, needed_count, lang_count;
1652 struct usb_gadget_strings **stringtabs, *t;
1653 struct usb_string *strings, *s;
1654 const char *data = _data;
1658 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1659 get_unaligned_le32(data + 4) != len))
1661 str_count = get_unaligned_le32(data + 8);
1662 lang_count = get_unaligned_le32(data + 12);
1664 /* if one is zero the other must be zero */
1665 if (unlikely(!str_count != !lang_count))
1668 /* Do we have at least as many strings as descriptors need? */
1669 needed_count = ffs->strings_count;
1670 if (unlikely(str_count < needed_count))
1674 * If we don't need any strings just return and free all
1677 if (!needed_count) {
1682 /* Allocate everything in one chunk so there's less maintenance. */
1686 vla_item(d, struct usb_gadget_strings *, stringtabs,
1688 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
1689 vla_item(d, struct usb_string, strings,
1690 lang_count*(needed_count+1));
1692 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
1694 if (unlikely(!vlabuf)) {
1699 /* Initialize the VLA pointers */
1700 stringtabs = vla_ptr(vlabuf, d, stringtabs);
1701 t = vla_ptr(vlabuf, d, stringtab);
1704 *stringtabs++ = t++;
1708 /* stringtabs = vlabuf = d_stringtabs for later kfree */
1709 stringtabs = vla_ptr(vlabuf, d, stringtabs);
1710 t = vla_ptr(vlabuf, d, stringtab);
1711 s = vla_ptr(vlabuf, d, strings);
1715 /* For each language */
1719 do { /* lang_count > 0 so we can use do-while */
1720 unsigned needed = needed_count;
1722 if (unlikely(len < 3))
1724 t->language = get_unaligned_le16(data);
1731 /* For each string */
1732 do { /* str_count > 0 so we can use do-while */
1733 size_t length = strnlen(data, len);
1735 if (unlikely(length == len))
1739 * User may provide more strings then we need,
1740 * if that's the case we simply ignore the
1743 if (likely(needed)) {
1745 * s->id will be set while adding
1746 * function to configuration so for
1747 * now just leave garbage here.
1756 } while (--str_count);
1758 s->id = 0; /* terminator */
1762 } while (--lang_count);
1764 /* Some garbage left? */
1769 ffs->stringtabs = stringtabs;
1770 ffs->raw_strings = _data;
1782 /* Events handling and management *******************************************/
1784 static void __ffs_event_add(struct ffs_data *ffs,
1785 enum usb_functionfs_event_type type)
1787 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
1791 * Abort any unhandled setup
1793 * We do not need to worry about some cmpxchg() changing value
1794 * of ffs->setup_state without holding the lock because when
1795 * state is FFS_SETUP_PENDING cmpxchg() in several places in
1796 * the source does nothing.
1798 if (ffs->setup_state == FFS_SETUP_PENDING)
1799 ffs->setup_state = FFS_SETUP_CANCELLED;
1802 case FUNCTIONFS_RESUME:
1803 rem_type2 = FUNCTIONFS_SUSPEND;
1805 case FUNCTIONFS_SUSPEND:
1806 case FUNCTIONFS_SETUP:
1808 /* Discard all similar events */
1811 case FUNCTIONFS_BIND:
1812 case FUNCTIONFS_UNBIND:
1813 case FUNCTIONFS_DISABLE:
1814 case FUNCTIONFS_ENABLE:
1815 /* Discard everything other then power management. */
1816 rem_type1 = FUNCTIONFS_SUSPEND;
1817 rem_type2 = FUNCTIONFS_RESUME;
1826 u8 *ev = ffs->ev.types, *out = ev;
1827 unsigned n = ffs->ev.count;
1828 for (; n; --n, ++ev)
1829 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
1832 pr_vdebug("purging event %d\n", *ev);
1833 ffs->ev.count = out - ffs->ev.types;
1836 pr_vdebug("adding event %d\n", type);
1837 ffs->ev.types[ffs->ev.count++] = type;
1838 wake_up_locked(&ffs->ev.waitq);
1841 static void ffs_event_add(struct ffs_data *ffs,
1842 enum usb_functionfs_event_type type)
1844 unsigned long flags;
1845 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
1846 __ffs_event_add(ffs, type);
1847 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
1851 /* Bind/unbind USB function hooks *******************************************/
1853 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
1854 struct usb_descriptor_header *desc,
1857 struct usb_endpoint_descriptor *ds = (void *)desc;
1858 struct ffs_function *func = priv;
1859 struct ffs_ep *ffs_ep;
1862 * If hs_descriptors is not NULL then we are reading hs
1865 const int isHS = func->function.hs_descriptors != NULL;
1868 if (type != FFS_DESCRIPTOR)
1872 func->function.hs_descriptors[(long)valuep] = desc;
1874 func->function.fs_descriptors[(long)valuep] = desc;
1876 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
1879 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
1880 ffs_ep = func->eps + idx;
1882 if (unlikely(ffs_ep->descs[isHS])) {
1883 pr_vdebug("two %sspeed descriptors for EP %d\n",
1884 isHS ? "high" : "full",
1885 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
1888 ffs_ep->descs[isHS] = ds;
1890 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
1892 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
1893 if (!ds->wMaxPacketSize)
1894 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
1896 struct usb_request *req;
1899 pr_vdebug("autoconfig\n");
1900 ep = usb_ep_autoconfig(func->gadget, ds);
1903 ep->driver_data = func->eps + idx;
1905 req = usb_ep_alloc_request(ep, GFP_KERNEL);
1911 func->eps_revmap[ds->bEndpointAddress &
1912 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
1914 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
1919 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
1920 struct usb_descriptor_header *desc,
1923 struct ffs_function *func = priv;
1929 case FFS_DESCRIPTOR:
1930 /* Handled in previous pass by __ffs_func_bind_do_descs() */
1935 if (func->interfaces_nums[idx] < 0) {
1936 int id = usb_interface_id(func->conf, &func->function);
1937 if (unlikely(id < 0))
1939 func->interfaces_nums[idx] = id;
1941 newValue = func->interfaces_nums[idx];
1945 /* String' IDs are allocated when fsf_data is bound to cdev */
1946 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
1951 * USB_DT_ENDPOINT are handled in
1952 * __ffs_func_bind_do_descs().
1954 if (desc->bDescriptorType == USB_DT_ENDPOINT)
1957 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
1958 if (unlikely(!func->eps[idx].ep))
1962 struct usb_endpoint_descriptor **descs;
1963 descs = func->eps[idx].descs;
1964 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
1969 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
1974 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
1975 struct usb_configuration *c)
1977 struct ffs_function *func = ffs_func_from_usb(f);
1978 struct f_fs_opts *ffs_opts =
1979 container_of(f->fi, struct f_fs_opts, func_inst);
1985 * Legacy gadget triggers binding in functionfs_ready_callback,
1986 * which already uses locking; taking the same lock here would
1989 * Configfs-enabled gadgets however do need ffs_dev_lock.
1991 if (!ffs_opts->no_configfs)
1993 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
1994 func->ffs = ffs_opts->dev->ffs_data;
1995 if (!ffs_opts->no_configfs)
1998 return ERR_PTR(ret);
2001 func->gadget = c->cdev->gadget;
2003 ffs_data_get(func->ffs);
2006 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2007 * configurations are bound in sequence with list_for_each_entry,
2008 * in each configuration its functions are bound in sequence
2009 * with list_for_each_entry, so we assume no race condition
2010 * with regard to ffs_opts->bound access
2012 if (!ffs_opts->refcnt) {
2013 ret = functionfs_bind(func->ffs, c->cdev);
2015 return ERR_PTR(ret);
2018 func->function.strings = func->ffs->stringtabs;
2023 static int _ffs_func_bind(struct usb_configuration *c,
2024 struct usb_function *f)
2026 struct ffs_function *func = ffs_func_from_usb(f);
2027 struct ffs_data *ffs = func->ffs;
2029 const int full = !!func->ffs->fs_descs_count;
2030 const int high = gadget_is_dualspeed(func->gadget) &&
2031 func->ffs->hs_descs_count;
2035 /* Make it a single chunk, less management later on */
2037 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2038 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2039 full ? ffs->fs_descs_count + 1 : 0);
2040 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2041 high ? ffs->hs_descs_count + 1 : 0);
2042 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2043 vla_item_with_sz(d, char, raw_descs,
2044 high ? ffs->raw_descs_length : ffs->raw_fs_descs_length);
2049 /* Only high speed but not supported by gadget? */
2050 if (unlikely(!(full | high)))
2053 /* Allocate a single chunk, less management later on */
2054 vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2055 if (unlikely(!vlabuf))
2059 memset(vla_ptr(vlabuf, d, eps), 0, d_eps__sz);
2060 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs + 16,
2062 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2063 for (ret = ffs->eps_count; ret; --ret) {
2066 ptr = vla_ptr(vlabuf, d, eps);
2071 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2073 func->eps = vla_ptr(vlabuf, d, eps);
2074 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2077 * Go through all the endpoint descriptors and allocate
2078 * endpoints first, so that later we can rewrite the endpoint
2079 * numbers without worrying that it may be described later on.
2082 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2083 ret = ffs_do_descs(ffs->fs_descs_count,
2084 vla_ptr(vlabuf, d, raw_descs),
2086 __ffs_func_bind_do_descs, func);
2087 if (unlikely(ret < 0))
2094 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2095 ret = ffs_do_descs(ffs->hs_descs_count,
2096 vla_ptr(vlabuf, d, raw_descs) + ret,
2097 d_raw_descs__sz - ret,
2098 __ffs_func_bind_do_descs, func);
2099 if (unlikely(ret < 0))
2104 * Now handle interface numbers allocation and interface and
2105 * endpoint numbers rewriting. We can do that in one go
2108 ret = ffs_do_descs(ffs->fs_descs_count +
2109 (high ? ffs->hs_descs_count : 0),
2110 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2111 __ffs_func_bind_do_nums, func);
2112 if (unlikely(ret < 0))
2115 /* And we're done */
2116 ffs_event_add(ffs, FUNCTIONFS_BIND);
2120 /* XXX Do we need to release all claimed endpoints here? */
2124 static int ffs_func_bind(struct usb_configuration *c,
2125 struct usb_function *f)
2127 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2129 if (IS_ERR(ffs_opts))
2130 return PTR_ERR(ffs_opts);
2132 return _ffs_func_bind(c, f);
2136 /* Other USB function hooks *************************************************/
2138 static int ffs_func_set_alt(struct usb_function *f,
2139 unsigned interface, unsigned alt)
2141 struct ffs_function *func = ffs_func_from_usb(f);
2142 struct ffs_data *ffs = func->ffs;
2145 if (alt != (unsigned)-1) {
2146 intf = ffs_func_revmap_intf(func, interface);
2147 if (unlikely(intf < 0))
2152 ffs_func_eps_disable(ffs->func);
2154 if (ffs->state != FFS_ACTIVE)
2157 if (alt == (unsigned)-1) {
2159 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2164 ret = ffs_func_eps_enable(func);
2165 if (likely(ret >= 0))
2166 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2170 static void ffs_func_disable(struct usb_function *f)
2172 ffs_func_set_alt(f, 0, (unsigned)-1);
2175 static int ffs_func_setup(struct usb_function *f,
2176 const struct usb_ctrlrequest *creq)
2178 struct ffs_function *func = ffs_func_from_usb(f);
2179 struct ffs_data *ffs = func->ffs;
2180 unsigned long flags;
2185 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2186 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2187 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2188 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2189 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2192 * Most requests directed to interface go through here
2193 * (notable exceptions are set/get interface) so we need to
2194 * handle them. All other either handled by composite or
2195 * passed to usb_configuration->setup() (if one is set). No
2196 * matter, we will handle requests directed to endpoint here
2197 * as well (as it's straightforward) but what to do with any
2200 if (ffs->state != FFS_ACTIVE)
2203 switch (creq->bRequestType & USB_RECIP_MASK) {
2204 case USB_RECIP_INTERFACE:
2205 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2206 if (unlikely(ret < 0))
2210 case USB_RECIP_ENDPOINT:
2211 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2212 if (unlikely(ret < 0))
2220 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2221 ffs->ev.setup = *creq;
2222 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2223 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2224 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2229 static void ffs_func_suspend(struct usb_function *f)
2232 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2235 static void ffs_func_resume(struct usb_function *f)
2238 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2242 /* Endpoint and interface numbers reverse mapping ***************************/
2244 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2246 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2247 return num ? num : -EDOM;
2250 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2252 short *nums = func->interfaces_nums;
2253 unsigned count = func->ffs->interfaces_count;
2255 for (; count; --count, ++nums) {
2256 if (*nums >= 0 && *nums == intf)
2257 return nums - func->interfaces_nums;
2264 /* Devices management *******************************************************/
2266 static LIST_HEAD(ffs_devices);
2268 static struct ffs_dev *_ffs_do_find_dev(const char *name)
2270 struct ffs_dev *dev;
2272 list_for_each_entry(dev, &ffs_devices, entry) {
2273 if (!dev->name || !name)
2275 if (strcmp(dev->name, name) == 0)
2283 * ffs_lock must be taken by the caller of this function
2285 static struct ffs_dev *_ffs_get_single_dev(void)
2287 struct ffs_dev *dev;
2289 if (list_is_singular(&ffs_devices)) {
2290 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
2299 * ffs_lock must be taken by the caller of this function
2301 static struct ffs_dev *_ffs_find_dev(const char *name)
2303 struct ffs_dev *dev;
2305 dev = _ffs_get_single_dev();
2309 return _ffs_do_find_dev(name);
2312 /* Configfs support *********************************************************/
2314 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
2316 return container_of(to_config_group(item), struct f_fs_opts,
2320 static void ffs_attr_release(struct config_item *item)
2322 struct f_fs_opts *opts = to_ffs_opts(item);
2324 usb_put_function_instance(&opts->func_inst);
2327 static struct configfs_item_operations ffs_item_ops = {
2328 .release = ffs_attr_release,
2331 static struct config_item_type ffs_func_type = {
2332 .ct_item_ops = &ffs_item_ops,
2333 .ct_owner = THIS_MODULE,
2337 /* Function registration interface ******************************************/
2339 static void ffs_free_inst(struct usb_function_instance *f)
2341 struct f_fs_opts *opts;
2343 opts = to_f_fs_opts(f);
2345 _ffs_free_dev(opts->dev);
2350 #define MAX_INST_NAME_LEN 40
2352 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
2354 struct f_fs_opts *opts;
2359 name_len = strlen(name) + 1;
2360 if (name_len > MAX_INST_NAME_LEN)
2361 return -ENAMETOOLONG;
2363 ptr = kstrndup(name, name_len, GFP_KERNEL);
2367 opts = to_f_fs_opts(fi);
2372 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
2373 ret = _ffs_name_dev(opts->dev, ptr);
2379 opts->dev->name_allocated = true;
2388 static struct usb_function_instance *ffs_alloc_inst(void)
2390 struct f_fs_opts *opts;
2391 struct ffs_dev *dev;
2393 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2395 return ERR_PTR(-ENOMEM);
2397 opts->func_inst.set_inst_name = ffs_set_inst_name;
2398 opts->func_inst.free_func_inst = ffs_free_inst;
2400 dev = _ffs_alloc_dev();
2404 return ERR_CAST(dev);
2409 config_group_init_type_name(&opts->func_inst.group, "",
2411 return &opts->func_inst;
2414 static void ffs_free(struct usb_function *f)
2416 kfree(ffs_func_from_usb(f));
2419 static void ffs_func_unbind(struct usb_configuration *c,
2420 struct usb_function *f)
2422 struct ffs_function *func = ffs_func_from_usb(f);
2423 struct ffs_data *ffs = func->ffs;
2424 struct f_fs_opts *opts =
2425 container_of(f->fi, struct f_fs_opts, func_inst);
2426 struct ffs_ep *ep = func->eps;
2427 unsigned count = ffs->eps_count;
2428 unsigned long flags;
2431 if (ffs->func == func) {
2432 ffs_func_eps_disable(func);
2436 if (!--opts->refcnt)
2437 functionfs_unbind(ffs);
2439 /* cleanup after autoconfig */
2440 spin_lock_irqsave(&func->ffs->eps_lock, flags);
2442 if (ep->ep && ep->req)
2443 usb_ep_free_request(ep->ep, ep->req);
2447 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2451 * eps, descriptors and interfaces_nums are allocated in the
2452 * same chunk so only one free is required.
2454 func->function.fs_descriptors = NULL;
2455 func->function.hs_descriptors = NULL;
2456 func->interfaces_nums = NULL;
2458 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2461 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
2463 struct ffs_function *func;
2467 func = kzalloc(sizeof(*func), GFP_KERNEL);
2468 if (unlikely(!func))
2469 return ERR_PTR(-ENOMEM);
2471 func->function.name = "Function FS Gadget";
2473 func->function.bind = ffs_func_bind;
2474 func->function.unbind = ffs_func_unbind;
2475 func->function.set_alt = ffs_func_set_alt;
2476 func->function.disable = ffs_func_disable;
2477 func->function.setup = ffs_func_setup;
2478 func->function.suspend = ffs_func_suspend;
2479 func->function.resume = ffs_func_resume;
2480 func->function.free_func = ffs_free;
2482 return &func->function;
2486 * ffs_lock must be taken by the caller of this function
2488 static struct ffs_dev *_ffs_alloc_dev(void)
2490 struct ffs_dev *dev;
2493 if (_ffs_get_single_dev())
2494 return ERR_PTR(-EBUSY);
2496 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2498 return ERR_PTR(-ENOMEM);
2500 if (list_empty(&ffs_devices)) {
2501 ret = functionfs_init();
2504 return ERR_PTR(ret);
2508 list_add(&dev->entry, &ffs_devices);
2514 * ffs_lock must be taken by the caller of this function
2515 * The caller is responsible for "name" being available whenever f_fs needs it
2517 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
2519 struct ffs_dev *existing;
2521 existing = _ffs_do_find_dev(name);
2531 * The caller is responsible for "name" being available whenever f_fs needs it
2533 int ffs_name_dev(struct ffs_dev *dev, const char *name)
2538 ret = _ffs_name_dev(dev, name);
2543 EXPORT_SYMBOL(ffs_name_dev);
2545 int ffs_single_dev(struct ffs_dev *dev)
2552 if (!list_is_singular(&ffs_devices))
2560 EXPORT_SYMBOL(ffs_single_dev);
2563 * ffs_lock must be taken by the caller of this function
2565 static void _ffs_free_dev(struct ffs_dev *dev)
2567 list_del(&dev->entry);
2568 if (dev->name_allocated)
2571 if (list_empty(&ffs_devices))
2572 functionfs_cleanup();
2575 static void *ffs_acquire_dev(const char *dev_name)
2577 struct ffs_dev *ffs_dev;
2582 ffs_dev = _ffs_find_dev(dev_name);
2584 ffs_dev = ERR_PTR(-ENODEV);
2585 else if (ffs_dev->mounted)
2586 ffs_dev = ERR_PTR(-EBUSY);
2587 else if (ffs_dev->ffs_acquire_dev_callback &&
2588 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
2589 ffs_dev = ERR_PTR(-ENODEV);
2591 ffs_dev->mounted = true;
2597 static void ffs_release_dev(struct ffs_data *ffs_data)
2599 struct ffs_dev *ffs_dev;
2604 ffs_dev = ffs_data->private_data;
2606 ffs_dev->mounted = false;
2608 if (ffs_dev->ffs_release_dev_callback)
2609 ffs_dev->ffs_release_dev_callback(ffs_dev);
2615 static int ffs_ready(struct ffs_data *ffs)
2617 struct ffs_dev *ffs_obj;
2623 ffs_obj = ffs->private_data;
2628 if (WARN_ON(ffs_obj->desc_ready)) {
2633 ffs_obj->desc_ready = true;
2634 ffs_obj->ffs_data = ffs;
2636 if (ffs_obj->ffs_ready_callback)
2637 ret = ffs_obj->ffs_ready_callback(ffs);
2644 static void ffs_closed(struct ffs_data *ffs)
2646 struct ffs_dev *ffs_obj;
2651 ffs_obj = ffs->private_data;
2655 ffs_obj->desc_ready = false;
2657 if (ffs_obj->ffs_closed_callback)
2658 ffs_obj->ffs_closed_callback(ffs);
2660 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
2661 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
2664 unregister_gadget_item(ffs_obj->opts->
2665 func_inst.group.cg_item.ci_parent->ci_parent);
2670 /* Misc helper functions ****************************************************/
2672 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2675 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2676 : mutex_lock_interruptible(mutex);
2679 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
2686 data = kmalloc(len, GFP_KERNEL);
2687 if (unlikely(!data))
2688 return ERR_PTR(-ENOMEM);
2690 if (unlikely(__copy_from_user(data, buf, len))) {
2692 return ERR_PTR(-EFAULT);
2695 pr_vdebug("Buffer from user space:\n");
2696 ffs_dump_mem("", data, len);
2701 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
2702 MODULE_LICENSE("GPL");
2703 MODULE_AUTHOR("Michal Nazarewicz");