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 <linux/uio.h>
27 #include <asm/unaligned.h>
29 #include <linux/usb/composite.h>
30 #include <linux/usb/functionfs.h>
32 #include <linux/aio.h>
33 #include <linux/mmu_context.h>
34 #include <linux/poll.h>
35 #include <linux/eventfd.h>
39 #include "u_os_desc.h"
42 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
44 /* Reference counter handling */
45 static void ffs_data_get(struct ffs_data *ffs);
46 static void ffs_data_put(struct ffs_data *ffs);
47 /* Creates new ffs_data object. */
48 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
50 /* Opened counter handling. */
51 static void ffs_data_opened(struct ffs_data *ffs);
52 static void ffs_data_closed(struct ffs_data *ffs);
54 /* Called with ffs->mutex held; take over ownership of data. */
55 static int __must_check
56 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
57 static int __must_check
58 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
61 /* The function structure ***************************************************/
66 struct usb_configuration *conf;
67 struct usb_gadget *gadget;
72 short *interfaces_nums;
74 struct usb_function function;
78 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
80 return container_of(f, struct ffs_function, function);
84 static inline enum ffs_setup_state
85 ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
87 return (enum ffs_setup_state)
88 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
92 static void ffs_func_eps_disable(struct ffs_function *func);
93 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
95 static int ffs_func_bind(struct usb_configuration *,
96 struct usb_function *);
97 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
98 static void ffs_func_disable(struct usb_function *);
99 static int ffs_func_setup(struct usb_function *,
100 const struct usb_ctrlrequest *);
101 static void ffs_func_suspend(struct usb_function *);
102 static void ffs_func_resume(struct usb_function *);
105 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
106 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
109 /* The endpoints structures *************************************************/
112 struct usb_ep *ep; /* P: ffs->eps_lock */
113 struct usb_request *req; /* P: epfile->mutex */
115 /* [0]: full speed, [1]: high speed, [2]: super speed */
116 struct usb_endpoint_descriptor *descs[3];
120 int status; /* P: epfile->mutex */
124 /* Protects ep->ep and ep->req. */
126 wait_queue_head_t wait;
128 struct ffs_data *ffs;
129 struct ffs_ep *ep; /* P: ffs->eps_lock */
131 struct dentry *dentry;
135 unsigned char in; /* P: ffs->eps_lock */
136 unsigned char isoc; /* P: ffs->eps_lock */
141 /* ffs_io_data structure ***************************************************/
148 struct iov_iter data;
152 struct mm_struct *mm;
153 struct work_struct work;
156 struct usb_request *req;
158 struct ffs_data *ffs;
161 struct ffs_desc_helper {
162 struct ffs_data *ffs;
163 unsigned interfaces_count;
167 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
168 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
170 static struct dentry *
171 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
172 const struct file_operations *fops);
174 /* Devices management *******************************************************/
176 DEFINE_MUTEX(ffs_lock);
177 EXPORT_SYMBOL_GPL(ffs_lock);
179 static struct ffs_dev *_ffs_find_dev(const char *name);
180 static struct ffs_dev *_ffs_alloc_dev(void);
181 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
182 static void _ffs_free_dev(struct ffs_dev *dev);
183 static void *ffs_acquire_dev(const char *dev_name);
184 static void ffs_release_dev(struct ffs_data *ffs_data);
185 static int ffs_ready(struct ffs_data *ffs);
186 static void ffs_closed(struct ffs_data *ffs);
188 /* Misc helper functions ****************************************************/
190 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
191 __attribute__((warn_unused_result, nonnull));
192 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
193 __attribute__((warn_unused_result, nonnull));
196 /* Control file aka ep0 *****************************************************/
198 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
200 struct ffs_data *ffs = req->context;
202 complete_all(&ffs->ep0req_completion);
205 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
207 struct usb_request *req = ffs->ep0req;
210 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
212 spin_unlock_irq(&ffs->ev.waitq.lock);
218 * UDC layer requires to provide a buffer even for ZLP, but should
219 * not use it at all. Let's provide some poisoned pointer to catch
220 * possible bug in the driver.
222 if (req->buf == NULL)
223 req->buf = (void *)0xDEADBABE;
225 reinit_completion(&ffs->ep0req_completion);
227 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
228 if (unlikely(ret < 0))
231 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
233 usb_ep_dequeue(ffs->gadget->ep0, req);
237 ffs->setup_state = FFS_NO_SETUP;
238 return req->status ? req->status : req->actual;
241 static int __ffs_ep0_stall(struct ffs_data *ffs)
243 if (ffs->ev.can_stall) {
244 pr_vdebug("ep0 stall\n");
245 usb_ep_set_halt(ffs->gadget->ep0);
246 ffs->setup_state = FFS_NO_SETUP;
249 pr_debug("bogus ep0 stall!\n");
254 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
255 size_t len, loff_t *ptr)
257 struct ffs_data *ffs = file->private_data;
263 /* Fast check if setup was canceled */
264 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
268 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
269 if (unlikely(ret < 0))
273 switch (ffs->state) {
274 case FFS_READ_DESCRIPTORS:
275 case FFS_READ_STRINGS:
277 if (unlikely(len < 16)) {
282 data = ffs_prepare_buffer(buf, len);
289 if (ffs->state == FFS_READ_DESCRIPTORS) {
290 pr_info("read descriptors\n");
291 ret = __ffs_data_got_descs(ffs, data, len);
292 if (unlikely(ret < 0))
295 ffs->state = FFS_READ_STRINGS;
298 pr_info("read strings\n");
299 ret = __ffs_data_got_strings(ffs, data, len);
300 if (unlikely(ret < 0))
303 ret = ffs_epfiles_create(ffs);
305 ffs->state = FFS_CLOSING;
309 ffs->state = FFS_ACTIVE;
310 mutex_unlock(&ffs->mutex);
312 ret = ffs_ready(ffs);
313 if (unlikely(ret < 0)) {
314 ffs->state = FFS_CLOSING;
318 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
326 * We're called from user space, we can use _irq
327 * rather then _irqsave
329 spin_lock_irq(&ffs->ev.waitq.lock);
330 switch (ffs_setup_state_clear_cancelled(ffs)) {
331 case FFS_SETUP_CANCELLED:
339 case FFS_SETUP_PENDING:
343 /* FFS_SETUP_PENDING */
344 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
345 spin_unlock_irq(&ffs->ev.waitq.lock);
346 ret = __ffs_ep0_stall(ffs);
350 /* FFS_SETUP_PENDING and not stall */
351 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
353 spin_unlock_irq(&ffs->ev.waitq.lock);
355 data = ffs_prepare_buffer(buf, len);
361 spin_lock_irq(&ffs->ev.waitq.lock);
364 * We are guaranteed to be still in FFS_ACTIVE state
365 * but the state of setup could have changed from
366 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
367 * to check for that. If that happened we copied data
368 * from user space in vain but it's unlikely.
370 * For sure we are not in FFS_NO_SETUP since this is
371 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
372 * transition can be performed and it's protected by
375 if (ffs_setup_state_clear_cancelled(ffs) ==
376 FFS_SETUP_CANCELLED) {
379 spin_unlock_irq(&ffs->ev.waitq.lock);
381 /* unlocks spinlock */
382 ret = __ffs_ep0_queue_wait(ffs, data, len);
392 mutex_unlock(&ffs->mutex);
396 /* Called with ffs->ev.waitq.lock and ffs->mutex held, both released on exit. */
397 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
401 * n cannot be bigger than ffs->ev.count, which cannot be bigger than
402 * size of ffs->ev.types array (which is four) so that's how much space
405 struct usb_functionfs_event events[ARRAY_SIZE(ffs->ev.types)];
406 const size_t size = n * sizeof *events;
409 memset(events, 0, size);
412 events[i].type = ffs->ev.types[i];
413 if (events[i].type == FUNCTIONFS_SETUP) {
414 events[i].u.setup = ffs->ev.setup;
415 ffs->setup_state = FFS_SETUP_PENDING;
421 memmove(ffs->ev.types, ffs->ev.types + n,
422 ffs->ev.count * sizeof *ffs->ev.types);
424 spin_unlock_irq(&ffs->ev.waitq.lock);
425 mutex_unlock(&ffs->mutex);
427 return unlikely(__copy_to_user(buf, events, size)) ? -EFAULT : size;
430 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
431 size_t len, loff_t *ptr)
433 struct ffs_data *ffs = file->private_data;
440 /* Fast check if setup was canceled */
441 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
445 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
446 if (unlikely(ret < 0))
450 if (ffs->state != FFS_ACTIVE) {
456 * We're called from user space, we can use _irq rather then
459 spin_lock_irq(&ffs->ev.waitq.lock);
461 switch (ffs_setup_state_clear_cancelled(ffs)) {
462 case FFS_SETUP_CANCELLED:
467 n = len / sizeof(struct usb_functionfs_event);
473 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
478 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
484 return __ffs_ep0_read_events(ffs, buf,
485 min(n, (size_t)ffs->ev.count));
487 case FFS_SETUP_PENDING:
488 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
489 spin_unlock_irq(&ffs->ev.waitq.lock);
490 ret = __ffs_ep0_stall(ffs);
494 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
496 spin_unlock_irq(&ffs->ev.waitq.lock);
499 data = kmalloc(len, GFP_KERNEL);
500 if (unlikely(!data)) {
506 spin_lock_irq(&ffs->ev.waitq.lock);
508 /* See ffs_ep0_write() */
509 if (ffs_setup_state_clear_cancelled(ffs) ==
510 FFS_SETUP_CANCELLED) {
515 /* unlocks spinlock */
516 ret = __ffs_ep0_queue_wait(ffs, data, len);
517 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
526 spin_unlock_irq(&ffs->ev.waitq.lock);
528 mutex_unlock(&ffs->mutex);
533 static int ffs_ep0_open(struct inode *inode, struct file *file)
535 struct ffs_data *ffs = inode->i_private;
539 if (unlikely(ffs->state == FFS_CLOSING))
542 file->private_data = ffs;
543 ffs_data_opened(ffs);
548 static int ffs_ep0_release(struct inode *inode, struct file *file)
550 struct ffs_data *ffs = file->private_data;
554 ffs_data_closed(ffs);
559 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
561 struct ffs_data *ffs = file->private_data;
562 struct usb_gadget *gadget = ffs->gadget;
567 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
568 struct ffs_function *func = ffs->func;
569 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
570 } else if (gadget && gadget->ops->ioctl) {
571 ret = gadget->ops->ioctl(gadget, code, value);
579 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
581 struct ffs_data *ffs = file->private_data;
582 unsigned int mask = POLLWRNORM;
585 poll_wait(file, &ffs->ev.waitq, wait);
587 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
588 if (unlikely(ret < 0))
591 switch (ffs->state) {
592 case FFS_READ_DESCRIPTORS:
593 case FFS_READ_STRINGS:
598 switch (ffs->setup_state) {
604 case FFS_SETUP_PENDING:
605 case FFS_SETUP_CANCELLED:
606 mask |= (POLLIN | POLLOUT);
611 case FFS_DEACTIVATED:
615 mutex_unlock(&ffs->mutex);
620 static const struct file_operations ffs_ep0_operations = {
623 .open = ffs_ep0_open,
624 .write = ffs_ep0_write,
625 .read = ffs_ep0_read,
626 .release = ffs_ep0_release,
627 .unlocked_ioctl = ffs_ep0_ioctl,
628 .poll = ffs_ep0_poll,
632 /* "Normal" endpoints operations ********************************************/
634 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
637 if (likely(req->context)) {
638 struct ffs_ep *ep = _ep->driver_data;
639 ep->status = req->status ? req->status : req->actual;
640 complete(req->context);
644 static void ffs_user_copy_worker(struct work_struct *work)
646 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
648 int ret = io_data->req->status ? io_data->req->status :
649 io_data->req->actual;
651 if (io_data->read && ret > 0) {
653 ret = copy_to_iter(io_data->buf, ret, &io_data->data);
654 if (iov_iter_count(&io_data->data))
656 unuse_mm(io_data->mm);
659 io_data->kiocb->ki_complete(io_data->kiocb, ret, ret);
661 if (io_data->ffs->ffs_eventfd &&
662 !(io_data->kiocb->ki_flags & IOCB_EVENTFD))
663 eventfd_signal(io_data->ffs->ffs_eventfd, 1);
665 usb_ep_free_request(io_data->ep, io_data->req);
667 io_data->kiocb->private = NULL;
669 kfree(io_data->to_free);
674 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
675 struct usb_request *req)
677 struct ffs_io_data *io_data = req->context;
681 INIT_WORK(&io_data->work, ffs_user_copy_worker);
682 schedule_work(&io_data->work);
685 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
687 struct ffs_epfile *epfile = file->private_data;
690 ssize_t ret, data_len = -EINVAL;
693 /* Are we still active? */
694 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
699 /* Wait for endpoint to be enabled */
702 if (file->f_flags & O_NONBLOCK) {
707 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
715 halt = (!io_data->read == !epfile->in);
716 if (halt && epfile->isoc) {
721 /* Allocate & copy */
724 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
725 * before the waiting completes, so do not assign to 'gadget' earlier
727 struct usb_gadget *gadget = epfile->ffs->gadget;
730 spin_lock_irq(&epfile->ffs->eps_lock);
731 /* In the meantime, endpoint got disabled or changed. */
732 if (epfile->ep != ep) {
733 spin_unlock_irq(&epfile->ffs->eps_lock);
736 data_len = iov_iter_count(&io_data->data);
738 * Controller may require buffer size to be aligned to
739 * maxpacketsize of an out endpoint.
742 data_len = usb_ep_align_maybe(gadget, ep->ep, data_len);
743 spin_unlock_irq(&epfile->ffs->eps_lock);
745 data = kmalloc(data_len, GFP_KERNEL);
748 if (!io_data->read) {
749 copied = copy_from_iter(data, data_len, &io_data->data);
750 if (copied != data_len) {
757 /* We will be using request */
758 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
762 spin_lock_irq(&epfile->ffs->eps_lock);
764 if (epfile->ep != ep) {
765 /* In the meantime, endpoint got disabled or changed. */
767 spin_unlock_irq(&epfile->ffs->eps_lock);
770 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
771 usb_ep_set_halt(ep->ep);
772 spin_unlock_irq(&epfile->ffs->eps_lock);
775 /* Fire the request */
776 struct usb_request *req;
779 * Sanity Check: even though data_len can't be used
780 * uninitialized at the time I write this comment, some
781 * compilers complain about this situation.
782 * In order to keep the code clean from warnings, data_len is
783 * being initialized to -EINVAL during its declaration, which
784 * means we can't rely on compiler anymore to warn no future
785 * changes won't result in data_len being used uninitialized.
786 * For such reason, we're adding this redundant sanity check
789 if (unlikely(data_len == -EINVAL)) {
790 WARN(1, "%s: data_len == -EINVAL\n", __func__);
796 req = usb_ep_alloc_request(ep->ep, GFP_KERNEL);
801 req->length = data_len;
804 io_data->ep = ep->ep;
806 io_data->ffs = epfile->ffs;
808 req->context = io_data;
809 req->complete = ffs_epfile_async_io_complete;
811 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
813 usb_ep_free_request(ep->ep, req);
818 spin_unlock_irq(&epfile->ffs->eps_lock);
820 DECLARE_COMPLETION_ONSTACK(done);
824 req->length = data_len;
826 req->context = &done;
827 req->complete = ffs_epfile_io_complete;
829 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
831 spin_unlock_irq(&epfile->ffs->eps_lock);
833 if (unlikely(ret < 0)) {
836 wait_for_completion_interruptible(&done))) {
838 usb_ep_dequeue(ep->ep, req);
841 * XXX We may end up silently droping data
842 * here. Since data_len (i.e. req->length) may
843 * be bigger than len (after being rounded up
844 * to maxpacketsize), we may end up with more
845 * data then user space has space for.
848 if (io_data->read && ret > 0) {
849 ret = copy_to_iter(data, ret, &io_data->data);
850 if (unlikely(iov_iter_count(&io_data->data)))
858 mutex_unlock(&epfile->mutex);
862 spin_unlock_irq(&epfile->ffs->eps_lock);
863 mutex_unlock(&epfile->mutex);
870 ffs_epfile_open(struct inode *inode, struct file *file)
872 struct ffs_epfile *epfile = inode->i_private;
876 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
879 file->private_data = epfile;
880 ffs_data_opened(epfile->ffs);
885 static int ffs_aio_cancel(struct kiocb *kiocb)
887 struct ffs_io_data *io_data = kiocb->private;
888 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
893 spin_lock_irq(&epfile->ffs->eps_lock);
895 if (likely(io_data && io_data->ep && io_data->req))
896 value = usb_ep_dequeue(io_data->ep, io_data->req);
900 spin_unlock_irq(&epfile->ffs->eps_lock);
905 static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
907 struct ffs_io_data io_data, *p = &io_data;
912 if (!is_sync_kiocb(kiocb)) {
913 p = kmalloc(sizeof(io_data), GFP_KERNEL);
928 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
930 res = ffs_epfile_io(kiocb->ki_filp, p);
931 if (res == -EIOCBQUEUED)
940 static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
942 struct ffs_io_data io_data, *p = &io_data;
947 if (!is_sync_kiocb(kiocb)) {
948 p = kmalloc(sizeof(io_data), GFP_KERNEL);
959 p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
972 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
974 res = ffs_epfile_io(kiocb->ki_filp, p);
975 if (res == -EIOCBQUEUED)
988 ffs_epfile_release(struct inode *inode, struct file *file)
990 struct ffs_epfile *epfile = inode->i_private;
994 ffs_data_closed(epfile->ffs);
999 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1000 unsigned long value)
1002 struct ffs_epfile *epfile = file->private_data;
1007 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1010 spin_lock_irq(&epfile->ffs->eps_lock);
1011 if (likely(epfile->ep)) {
1013 case FUNCTIONFS_FIFO_STATUS:
1014 ret = usb_ep_fifo_status(epfile->ep->ep);
1016 case FUNCTIONFS_FIFO_FLUSH:
1017 usb_ep_fifo_flush(epfile->ep->ep);
1020 case FUNCTIONFS_CLEAR_HALT:
1021 ret = usb_ep_clear_halt(epfile->ep->ep);
1023 case FUNCTIONFS_ENDPOINT_REVMAP:
1024 ret = epfile->ep->num;
1026 case FUNCTIONFS_ENDPOINT_DESC:
1029 struct usb_endpoint_descriptor *desc;
1031 switch (epfile->ffs->gadget->speed) {
1032 case USB_SPEED_SUPER:
1035 case USB_SPEED_HIGH:
1041 desc = epfile->ep->descs[desc_idx];
1043 spin_unlock_irq(&epfile->ffs->eps_lock);
1044 ret = copy_to_user((void *)value, desc, sizeof(*desc));
1055 spin_unlock_irq(&epfile->ffs->eps_lock);
1060 static const struct file_operations ffs_epfile_operations = {
1061 .llseek = no_llseek,
1063 .open = ffs_epfile_open,
1064 .write = new_sync_write,
1065 .read = new_sync_read,
1066 .write_iter = ffs_epfile_write_iter,
1067 .read_iter = ffs_epfile_read_iter,
1068 .release = ffs_epfile_release,
1069 .unlocked_ioctl = ffs_epfile_ioctl,
1073 /* File system and super block operations ***********************************/
1076 * Mounting the file system creates a controller file, used first for
1077 * function configuration then later for event monitoring.
1080 static struct inode *__must_check
1081 ffs_sb_make_inode(struct super_block *sb, void *data,
1082 const struct file_operations *fops,
1083 const struct inode_operations *iops,
1084 struct ffs_file_perms *perms)
1086 struct inode *inode;
1090 inode = new_inode(sb);
1092 if (likely(inode)) {
1093 struct timespec current_time = CURRENT_TIME;
1095 inode->i_ino = get_next_ino();
1096 inode->i_mode = perms->mode;
1097 inode->i_uid = perms->uid;
1098 inode->i_gid = perms->gid;
1099 inode->i_atime = current_time;
1100 inode->i_mtime = current_time;
1101 inode->i_ctime = current_time;
1102 inode->i_private = data;
1104 inode->i_fop = fops;
1112 /* Create "regular" file */
1113 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1114 const char *name, void *data,
1115 const struct file_operations *fops)
1117 struct ffs_data *ffs = sb->s_fs_info;
1118 struct dentry *dentry;
1119 struct inode *inode;
1123 dentry = d_alloc_name(sb->s_root, name);
1124 if (unlikely(!dentry))
1127 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1128 if (unlikely(!inode)) {
1133 d_add(dentry, inode);
1138 static const struct super_operations ffs_sb_operations = {
1139 .statfs = simple_statfs,
1140 .drop_inode = generic_delete_inode,
1143 struct ffs_sb_fill_data {
1144 struct ffs_file_perms perms;
1146 const char *dev_name;
1148 struct ffs_data *ffs_data;
1151 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1153 struct ffs_sb_fill_data *data = _data;
1154 struct inode *inode;
1155 struct ffs_data *ffs = data->ffs_data;
1160 data->ffs_data = NULL;
1161 sb->s_fs_info = ffs;
1162 sb->s_blocksize = PAGE_CACHE_SIZE;
1163 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1164 sb->s_magic = FUNCTIONFS_MAGIC;
1165 sb->s_op = &ffs_sb_operations;
1166 sb->s_time_gran = 1;
1169 data->perms.mode = data->root_mode;
1170 inode = ffs_sb_make_inode(sb, NULL,
1171 &simple_dir_operations,
1172 &simple_dir_inode_operations,
1174 sb->s_root = d_make_root(inode);
1175 if (unlikely(!sb->s_root))
1179 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1180 &ffs_ep0_operations)))
1186 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1190 if (!opts || !*opts)
1194 unsigned long value;
1198 comma = strchr(opts, ',');
1203 eq = strchr(opts, '=');
1204 if (unlikely(!eq)) {
1205 pr_err("'=' missing in %s\n", opts);
1211 if (kstrtoul(eq + 1, 0, &value)) {
1212 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1216 /* Interpret option */
1217 switch (eq - opts) {
1219 if (!memcmp(opts, "no_disconnect", 13))
1220 data->no_disconnect = !!value;
1225 if (!memcmp(opts, "rmode", 5))
1226 data->root_mode = (value & 0555) | S_IFDIR;
1227 else if (!memcmp(opts, "fmode", 5))
1228 data->perms.mode = (value & 0666) | S_IFREG;
1234 if (!memcmp(opts, "mode", 4)) {
1235 data->root_mode = (value & 0555) | S_IFDIR;
1236 data->perms.mode = (value & 0666) | S_IFREG;
1243 if (!memcmp(opts, "uid", 3)) {
1244 data->perms.uid = make_kuid(current_user_ns(), value);
1245 if (!uid_valid(data->perms.uid)) {
1246 pr_err("%s: unmapped value: %lu\n", opts, value);
1249 } else if (!memcmp(opts, "gid", 3)) {
1250 data->perms.gid = make_kgid(current_user_ns(), value);
1251 if (!gid_valid(data->perms.gid)) {
1252 pr_err("%s: unmapped value: %lu\n", opts, value);
1262 pr_err("%s: invalid option\n", opts);
1266 /* Next iteration */
1275 /* "mount -t functionfs dev_name /dev/function" ends up here */
1277 static struct dentry *
1278 ffs_fs_mount(struct file_system_type *t, int flags,
1279 const char *dev_name, void *opts)
1281 struct ffs_sb_fill_data data = {
1283 .mode = S_IFREG | 0600,
1284 .uid = GLOBAL_ROOT_UID,
1285 .gid = GLOBAL_ROOT_GID,
1287 .root_mode = S_IFDIR | 0500,
1288 .no_disconnect = false,
1293 struct ffs_data *ffs;
1297 ret = ffs_fs_parse_opts(&data, opts);
1298 if (unlikely(ret < 0))
1299 return ERR_PTR(ret);
1301 ffs = ffs_data_new();
1303 return ERR_PTR(-ENOMEM);
1304 ffs->file_perms = data.perms;
1305 ffs->no_disconnect = data.no_disconnect;
1307 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1308 if (unlikely(!ffs->dev_name)) {
1310 return ERR_PTR(-ENOMEM);
1313 ffs_dev = ffs_acquire_dev(dev_name);
1314 if (IS_ERR(ffs_dev)) {
1316 return ERR_CAST(ffs_dev);
1318 ffs->private_data = ffs_dev;
1319 data.ffs_data = ffs;
1321 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1322 if (IS_ERR(rv) && data.ffs_data) {
1323 ffs_release_dev(data.ffs_data);
1324 ffs_data_put(data.ffs_data);
1330 ffs_fs_kill_sb(struct super_block *sb)
1334 kill_litter_super(sb);
1335 if (sb->s_fs_info) {
1336 ffs_release_dev(sb->s_fs_info);
1337 ffs_data_closed(sb->s_fs_info);
1338 ffs_data_put(sb->s_fs_info);
1342 static struct file_system_type ffs_fs_type = {
1343 .owner = THIS_MODULE,
1344 .name = "functionfs",
1345 .mount = ffs_fs_mount,
1346 .kill_sb = ffs_fs_kill_sb,
1348 MODULE_ALIAS_FS("functionfs");
1351 /* Driver's main init/cleanup functions *************************************/
1353 static int functionfs_init(void)
1359 ret = register_filesystem(&ffs_fs_type);
1361 pr_info("file system registered\n");
1363 pr_err("failed registering file system (%d)\n", ret);
1368 static void functionfs_cleanup(void)
1372 pr_info("unloading\n");
1373 unregister_filesystem(&ffs_fs_type);
1377 /* ffs_data and ffs_function construction and destruction code **************/
1379 static void ffs_data_clear(struct ffs_data *ffs);
1380 static void ffs_data_reset(struct ffs_data *ffs);
1382 static void ffs_data_get(struct ffs_data *ffs)
1386 atomic_inc(&ffs->ref);
1389 static void ffs_data_opened(struct ffs_data *ffs)
1393 atomic_inc(&ffs->ref);
1394 if (atomic_add_return(1, &ffs->opened) == 1 &&
1395 ffs->state == FFS_DEACTIVATED) {
1396 ffs->state = FFS_CLOSING;
1397 ffs_data_reset(ffs);
1401 static void ffs_data_put(struct ffs_data *ffs)
1405 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1406 pr_info("%s(): freeing\n", __func__);
1407 ffs_data_clear(ffs);
1408 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1409 waitqueue_active(&ffs->ep0req_completion.wait));
1410 kfree(ffs->dev_name);
1415 static void ffs_data_closed(struct ffs_data *ffs)
1419 if (atomic_dec_and_test(&ffs->opened)) {
1420 if (ffs->no_disconnect) {
1421 ffs->state = FFS_DEACTIVATED;
1423 ffs_epfiles_destroy(ffs->epfiles,
1425 ffs->epfiles = NULL;
1427 if (ffs->setup_state == FFS_SETUP_PENDING)
1428 __ffs_ep0_stall(ffs);
1430 ffs->state = FFS_CLOSING;
1431 ffs_data_reset(ffs);
1434 if (atomic_read(&ffs->opened) < 0) {
1435 ffs->state = FFS_CLOSING;
1436 ffs_data_reset(ffs);
1442 static struct ffs_data *ffs_data_new(void)
1444 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1450 atomic_set(&ffs->ref, 1);
1451 atomic_set(&ffs->opened, 0);
1452 ffs->state = FFS_READ_DESCRIPTORS;
1453 mutex_init(&ffs->mutex);
1454 spin_lock_init(&ffs->eps_lock);
1455 init_waitqueue_head(&ffs->ev.waitq);
1456 init_completion(&ffs->ep0req_completion);
1458 /* XXX REVISIT need to update it in some places, or do we? */
1459 ffs->ev.can_stall = 1;
1464 static void ffs_data_clear(struct ffs_data *ffs)
1468 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1471 BUG_ON(ffs->gadget);
1474 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1476 if (ffs->ffs_eventfd)
1477 eventfd_ctx_put(ffs->ffs_eventfd);
1479 kfree(ffs->raw_descs_data);
1480 kfree(ffs->raw_strings);
1481 kfree(ffs->stringtabs);
1484 static void ffs_data_reset(struct ffs_data *ffs)
1488 ffs_data_clear(ffs);
1490 ffs->epfiles = NULL;
1491 ffs->raw_descs_data = NULL;
1492 ffs->raw_descs = NULL;
1493 ffs->raw_strings = NULL;
1494 ffs->stringtabs = NULL;
1496 ffs->raw_descs_length = 0;
1497 ffs->fs_descs_count = 0;
1498 ffs->hs_descs_count = 0;
1499 ffs->ss_descs_count = 0;
1501 ffs->strings_count = 0;
1502 ffs->interfaces_count = 0;
1507 ffs->state = FFS_READ_DESCRIPTORS;
1508 ffs->setup_state = FFS_NO_SETUP;
1513 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1515 struct usb_gadget_strings **lang;
1520 if (WARN_ON(ffs->state != FFS_ACTIVE
1521 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1524 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1525 if (unlikely(first_id < 0))
1528 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1529 if (unlikely(!ffs->ep0req))
1531 ffs->ep0req->complete = ffs_ep0_complete;
1532 ffs->ep0req->context = ffs;
1534 lang = ffs->stringtabs;
1536 for (; *lang; ++lang) {
1537 struct usb_string *str = (*lang)->strings;
1539 for (; str->s; ++id, ++str)
1544 ffs->gadget = cdev->gadget;
1549 static void functionfs_unbind(struct ffs_data *ffs)
1553 if (!WARN_ON(!ffs->gadget)) {
1554 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1557 clear_bit(FFS_FL_BOUND, &ffs->flags);
1562 static int ffs_epfiles_create(struct ffs_data *ffs)
1564 struct ffs_epfile *epfile, *epfiles;
1569 count = ffs->eps_count;
1570 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1575 for (i = 1; i <= count; ++i, ++epfile) {
1577 mutex_init(&epfile->mutex);
1578 init_waitqueue_head(&epfile->wait);
1579 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1580 sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
1582 sprintf(epfile->name, "ep%u", i);
1583 epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
1585 &ffs_epfile_operations);
1586 if (unlikely(!epfile->dentry)) {
1587 ffs_epfiles_destroy(epfiles, i - 1);
1592 ffs->epfiles = epfiles;
1596 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1598 struct ffs_epfile *epfile = epfiles;
1602 for (; count; --count, ++epfile) {
1603 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1604 waitqueue_active(&epfile->wait));
1605 if (epfile->dentry) {
1606 d_delete(epfile->dentry);
1607 dput(epfile->dentry);
1608 epfile->dentry = NULL;
1615 static void ffs_func_eps_disable(struct ffs_function *func)
1617 struct ffs_ep *ep = func->eps;
1618 struct ffs_epfile *epfile = func->ffs->epfiles;
1619 unsigned count = func->ffs->eps_count;
1620 unsigned long flags;
1622 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1624 /* pending requests get nuked */
1626 usb_ep_disable(ep->ep);
1634 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1637 static int ffs_func_eps_enable(struct ffs_function *func)
1639 struct ffs_data *ffs = func->ffs;
1640 struct ffs_ep *ep = func->eps;
1641 struct ffs_epfile *epfile = ffs->epfiles;
1642 unsigned count = ffs->eps_count;
1643 unsigned long flags;
1646 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1648 struct usb_endpoint_descriptor *ds;
1651 if (ffs->gadget->speed == USB_SPEED_SUPER)
1653 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1658 /* fall-back to lower speed if desc missing for current speed */
1660 ds = ep->descs[desc_idx];
1661 } while (!ds && --desc_idx >= 0);
1668 ep->ep->driver_data = ep;
1670 ret = usb_ep_enable(ep->ep);
1673 epfile->in = usb_endpoint_dir_in(ds);
1674 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1679 wake_up(&epfile->wait);
1684 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1690 /* Parsing and building descriptors and strings *****************************/
1693 * This validates if data pointed by data is a valid USB descriptor as
1694 * well as record how many interfaces, endpoints and strings are
1695 * required by given configuration. Returns address after the
1696 * descriptor or NULL if data is invalid.
1699 enum ffs_entity_type {
1700 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1703 enum ffs_os_desc_type {
1704 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1707 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1709 struct usb_descriptor_header *desc,
1712 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1713 struct usb_os_desc_header *h, void *data,
1714 unsigned len, void *priv);
1716 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1717 ffs_entity_callback entity,
1720 struct usb_descriptor_header *_ds = (void *)data;
1726 /* At least two bytes are required: length and type */
1728 pr_vdebug("descriptor too short\n");
1732 /* If we have at least as many bytes as the descriptor takes? */
1733 length = _ds->bLength;
1735 pr_vdebug("descriptor longer then available data\n");
1739 #define __entity_check_INTERFACE(val) 1
1740 #define __entity_check_STRING(val) (val)
1741 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1742 #define __entity(type, val) do { \
1743 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1744 if (unlikely(!__entity_check_ ##type(val))) { \
1745 pr_vdebug("invalid entity's value\n"); \
1748 ret = entity(FFS_ ##type, &val, _ds, priv); \
1749 if (unlikely(ret < 0)) { \
1750 pr_debug("entity " #type "(%02x); ret = %d\n", \
1756 /* Parse descriptor depending on type. */
1757 switch (_ds->bDescriptorType) {
1761 case USB_DT_DEVICE_QUALIFIER:
1762 /* function can't have any of those */
1763 pr_vdebug("descriptor reserved for gadget: %d\n",
1764 _ds->bDescriptorType);
1767 case USB_DT_INTERFACE: {
1768 struct usb_interface_descriptor *ds = (void *)_ds;
1769 pr_vdebug("interface descriptor\n");
1770 if (length != sizeof *ds)
1773 __entity(INTERFACE, ds->bInterfaceNumber);
1775 __entity(STRING, ds->iInterface);
1779 case USB_DT_ENDPOINT: {
1780 struct usb_endpoint_descriptor *ds = (void *)_ds;
1781 pr_vdebug("endpoint descriptor\n");
1782 if (length != USB_DT_ENDPOINT_SIZE &&
1783 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1785 __entity(ENDPOINT, ds->bEndpointAddress);
1790 pr_vdebug("hid descriptor\n");
1791 if (length != sizeof(struct hid_descriptor))
1796 if (length != sizeof(struct usb_otg_descriptor))
1800 case USB_DT_INTERFACE_ASSOCIATION: {
1801 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1802 pr_vdebug("interface association descriptor\n");
1803 if (length != sizeof *ds)
1806 __entity(STRING, ds->iFunction);
1810 case USB_DT_SS_ENDPOINT_COMP:
1811 pr_vdebug("EP SS companion descriptor\n");
1812 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1816 case USB_DT_OTHER_SPEED_CONFIG:
1817 case USB_DT_INTERFACE_POWER:
1819 case USB_DT_SECURITY:
1820 case USB_DT_CS_RADIO_CONTROL:
1822 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1826 /* We should never be here */
1827 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1831 pr_vdebug("invalid length: %d (descriptor %d)\n",
1832 _ds->bLength, _ds->bDescriptorType);
1837 #undef __entity_check_DESCRIPTOR
1838 #undef __entity_check_INTERFACE
1839 #undef __entity_check_STRING
1840 #undef __entity_check_ENDPOINT
1845 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1846 ffs_entity_callback entity, void *priv)
1848 const unsigned _len = len;
1849 unsigned long num = 0;
1859 /* Record "descriptor" entity */
1860 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1861 if (unlikely(ret < 0)) {
1862 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1870 ret = ffs_do_single_desc(data, len, entity, priv);
1871 if (unlikely(ret < 0)) {
1872 pr_debug("%s returns %d\n", __func__, ret);
1882 static int __ffs_data_do_entity(enum ffs_entity_type type,
1883 u8 *valuep, struct usb_descriptor_header *desc,
1886 struct ffs_desc_helper *helper = priv;
1887 struct usb_endpoint_descriptor *d;
1892 case FFS_DESCRIPTOR:
1897 * Interfaces are indexed from zero so if we
1898 * encountered interface "n" then there are at least
1901 if (*valuep >= helper->interfaces_count)
1902 helper->interfaces_count = *valuep + 1;
1907 * Strings are indexed from 1 (0 is magic ;) reserved
1908 * for languages list or some such)
1910 if (*valuep > helper->ffs->strings_count)
1911 helper->ffs->strings_count = *valuep;
1916 helper->eps_count++;
1917 if (helper->eps_count >= 15)
1919 /* Check if descriptors for any speed were already parsed */
1920 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
1921 helper->ffs->eps_addrmap[helper->eps_count] =
1922 d->bEndpointAddress;
1923 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
1924 d->bEndpointAddress)
1932 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1933 struct usb_os_desc_header *desc)
1935 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1936 u16 w_index = le16_to_cpu(desc->wIndex);
1938 if (bcd_version != 1) {
1939 pr_vdebug("unsupported os descriptors version: %d",
1945 *next_type = FFS_OS_DESC_EXT_COMPAT;
1948 *next_type = FFS_OS_DESC_EXT_PROP;
1951 pr_vdebug("unsupported os descriptor type: %d", w_index);
1955 return sizeof(*desc);
1959 * Process all extended compatibility/extended property descriptors
1960 * of a feature descriptor
1962 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1963 enum ffs_os_desc_type type,
1965 ffs_os_desc_callback entity,
1967 struct usb_os_desc_header *h)
1970 const unsigned _len = len;
1974 /* loop over all ext compat/ext prop descriptors */
1975 while (feature_count--) {
1976 ret = entity(type, h, data, len, priv);
1977 if (unlikely(ret < 0)) {
1978 pr_debug("bad OS descriptor, type: %d\n", type);
1987 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1988 static int __must_check ffs_do_os_descs(unsigned count,
1989 char *data, unsigned len,
1990 ffs_os_desc_callback entity, void *priv)
1992 const unsigned _len = len;
1993 unsigned long num = 0;
1997 for (num = 0; num < count; ++num) {
1999 enum ffs_os_desc_type type;
2001 struct usb_os_desc_header *desc = (void *)data;
2003 if (len < sizeof(*desc))
2007 * Record "descriptor" entity.
2008 * Process dwLength, bcdVersion, wIndex, get b/wCount.
2009 * Move the data pointer to the beginning of extended
2010 * compatibilities proper or extended properties proper
2011 * portions of the data
2013 if (le32_to_cpu(desc->dwLength) > len)
2016 ret = __ffs_do_os_desc_header(&type, desc);
2017 if (unlikely(ret < 0)) {
2018 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
2023 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2025 feature_count = le16_to_cpu(desc->wCount);
2026 if (type == FFS_OS_DESC_EXT_COMPAT &&
2027 (feature_count > 255 || desc->Reserved))
2033 * Process all function/property descriptors
2034 * of this Feature Descriptor
2036 ret = ffs_do_single_os_desc(data, len, type,
2037 feature_count, entity, priv, desc);
2038 if (unlikely(ret < 0)) {
2039 pr_debug("%s returns %d\n", __func__, ret);
2050 * Validate contents of the buffer from userspace related to OS descriptors.
2052 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2053 struct usb_os_desc_header *h, void *data,
2054 unsigned len, void *priv)
2056 struct ffs_data *ffs = priv;
2062 case FFS_OS_DESC_EXT_COMPAT: {
2063 struct usb_ext_compat_desc *d = data;
2066 if (len < sizeof(*d) ||
2067 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2070 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2071 if (d->Reserved2[i])
2074 length = sizeof(struct usb_ext_compat_desc);
2077 case FFS_OS_DESC_EXT_PROP: {
2078 struct usb_ext_prop_desc *d = data;
2082 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2084 length = le32_to_cpu(d->dwSize);
2085 type = le32_to_cpu(d->dwPropertyDataType);
2086 if (type < USB_EXT_PROP_UNICODE ||
2087 type > USB_EXT_PROP_UNICODE_MULTI) {
2088 pr_vdebug("unsupported os descriptor property type: %d",
2092 pnl = le16_to_cpu(d->wPropertyNameLength);
2093 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2094 if (length != 14 + pnl + pdl) {
2095 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2096 length, pnl, pdl, type);
2099 ++ffs->ms_os_descs_ext_prop_count;
2100 /* property name reported to the host as "WCHAR"s */
2101 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2102 ffs->ms_os_descs_ext_prop_data_len += pdl;
2106 pr_vdebug("unknown descriptor: %d\n", type);
2112 static int __ffs_data_got_descs(struct ffs_data *ffs,
2113 char *const _data, size_t len)
2115 char *data = _data, *raw_descs;
2116 unsigned os_descs_count = 0, counts[3], flags;
2117 int ret = -EINVAL, i;
2118 struct ffs_desc_helper helper;
2122 if (get_unaligned_le32(data + 4) != len)
2125 switch (get_unaligned_le32(data)) {
2126 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2127 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2131 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2132 flags = get_unaligned_le32(data + 8);
2133 ffs->user_flags = flags;
2134 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2135 FUNCTIONFS_HAS_HS_DESC |
2136 FUNCTIONFS_HAS_SS_DESC |
2137 FUNCTIONFS_HAS_MS_OS_DESC |
2138 FUNCTIONFS_VIRTUAL_ADDR |
2139 FUNCTIONFS_EVENTFD)) {
2150 if (flags & FUNCTIONFS_EVENTFD) {
2154 eventfd_ctx_fdget((int)get_unaligned_le32(data));
2155 if (IS_ERR(ffs->ffs_eventfd)) {
2156 ret = PTR_ERR(ffs->ffs_eventfd);
2157 ffs->ffs_eventfd = NULL;
2164 /* Read fs_count, hs_count and ss_count (if present) */
2165 for (i = 0; i < 3; ++i) {
2166 if (!(flags & (1 << i))) {
2168 } else if (len < 4) {
2171 counts[i] = get_unaligned_le32(data);
2176 if (flags & (1 << i)) {
2177 os_descs_count = get_unaligned_le32(data);
2182 /* Read descriptors */
2185 for (i = 0; i < 3; ++i) {
2188 helper.interfaces_count = 0;
2189 helper.eps_count = 0;
2190 ret = ffs_do_descs(counts[i], data, len,
2191 __ffs_data_do_entity, &helper);
2194 if (!ffs->eps_count && !ffs->interfaces_count) {
2195 ffs->eps_count = helper.eps_count;
2196 ffs->interfaces_count = helper.interfaces_count;
2198 if (ffs->eps_count != helper.eps_count) {
2202 if (ffs->interfaces_count != helper.interfaces_count) {
2210 if (os_descs_count) {
2211 ret = ffs_do_os_descs(os_descs_count, data, len,
2212 __ffs_data_do_os_desc, ffs);
2219 if (raw_descs == data || len) {
2224 ffs->raw_descs_data = _data;
2225 ffs->raw_descs = raw_descs;
2226 ffs->raw_descs_length = data - raw_descs;
2227 ffs->fs_descs_count = counts[0];
2228 ffs->hs_descs_count = counts[1];
2229 ffs->ss_descs_count = counts[2];
2230 ffs->ms_os_descs_count = os_descs_count;
2239 static int __ffs_data_got_strings(struct ffs_data *ffs,
2240 char *const _data, size_t len)
2242 u32 str_count, needed_count, lang_count;
2243 struct usb_gadget_strings **stringtabs, *t;
2244 struct usb_string *strings, *s;
2245 const char *data = _data;
2249 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2250 get_unaligned_le32(data + 4) != len))
2252 str_count = get_unaligned_le32(data + 8);
2253 lang_count = get_unaligned_le32(data + 12);
2255 /* if one is zero the other must be zero */
2256 if (unlikely(!str_count != !lang_count))
2259 /* Do we have at least as many strings as descriptors need? */
2260 needed_count = ffs->strings_count;
2261 if (unlikely(str_count < needed_count))
2265 * If we don't need any strings just return and free all
2268 if (!needed_count) {
2273 /* Allocate everything in one chunk so there's less maintenance. */
2277 vla_item(d, struct usb_gadget_strings *, stringtabs,
2279 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2280 vla_item(d, struct usb_string, strings,
2281 lang_count*(needed_count+1));
2283 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2285 if (unlikely(!vlabuf)) {
2290 /* Initialize the VLA pointers */
2291 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2292 t = vla_ptr(vlabuf, d, stringtab);
2295 *stringtabs++ = t++;
2299 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2300 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2301 t = vla_ptr(vlabuf, d, stringtab);
2302 s = vla_ptr(vlabuf, d, strings);
2306 /* For each language */
2310 do { /* lang_count > 0 so we can use do-while */
2311 unsigned needed = needed_count;
2313 if (unlikely(len < 3))
2315 t->language = get_unaligned_le16(data);
2322 /* For each string */
2323 do { /* str_count > 0 so we can use do-while */
2324 size_t length = strnlen(data, len);
2326 if (unlikely(length == len))
2330 * User may provide more strings then we need,
2331 * if that's the case we simply ignore the
2334 if (likely(needed)) {
2336 * s->id will be set while adding
2337 * function to configuration so for
2338 * now just leave garbage here.
2347 } while (--str_count);
2349 s->id = 0; /* terminator */
2353 } while (--lang_count);
2355 /* Some garbage left? */
2360 ffs->stringtabs = stringtabs;
2361 ffs->raw_strings = _data;
2373 /* Events handling and management *******************************************/
2375 static void __ffs_event_add(struct ffs_data *ffs,
2376 enum usb_functionfs_event_type type)
2378 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2382 * Abort any unhandled setup
2384 * We do not need to worry about some cmpxchg() changing value
2385 * of ffs->setup_state without holding the lock because when
2386 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2387 * the source does nothing.
2389 if (ffs->setup_state == FFS_SETUP_PENDING)
2390 ffs->setup_state = FFS_SETUP_CANCELLED;
2393 * Logic of this function guarantees that there are at most four pending
2394 * evens on ffs->ev.types queue. This is important because the queue
2395 * has space for four elements only and __ffs_ep0_read_events function
2396 * depends on that limit as well. If more event types are added, those
2397 * limits have to be revisited or guaranteed to still hold.
2400 case FUNCTIONFS_RESUME:
2401 rem_type2 = FUNCTIONFS_SUSPEND;
2403 case FUNCTIONFS_SUSPEND:
2404 case FUNCTIONFS_SETUP:
2406 /* Discard all similar events */
2409 case FUNCTIONFS_BIND:
2410 case FUNCTIONFS_UNBIND:
2411 case FUNCTIONFS_DISABLE:
2412 case FUNCTIONFS_ENABLE:
2413 /* Discard everything other then power management. */
2414 rem_type1 = FUNCTIONFS_SUSPEND;
2415 rem_type2 = FUNCTIONFS_RESUME;
2420 WARN(1, "%d: unknown event, this should not happen\n", type);
2425 u8 *ev = ffs->ev.types, *out = ev;
2426 unsigned n = ffs->ev.count;
2427 for (; n; --n, ++ev)
2428 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2431 pr_vdebug("purging event %d\n", *ev);
2432 ffs->ev.count = out - ffs->ev.types;
2435 pr_vdebug("adding event %d\n", type);
2436 ffs->ev.types[ffs->ev.count++] = type;
2437 wake_up_locked(&ffs->ev.waitq);
2438 if (ffs->ffs_eventfd)
2439 eventfd_signal(ffs->ffs_eventfd, 1);
2442 static void ffs_event_add(struct ffs_data *ffs,
2443 enum usb_functionfs_event_type type)
2445 unsigned long flags;
2446 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2447 __ffs_event_add(ffs, type);
2448 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2451 /* Bind/unbind USB function hooks *******************************************/
2453 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2457 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2458 if (ffs->eps_addrmap[i] == endpoint_address)
2463 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2464 struct usb_descriptor_header *desc,
2467 struct usb_endpoint_descriptor *ds = (void *)desc;
2468 struct ffs_function *func = priv;
2469 struct ffs_ep *ffs_ep;
2470 unsigned ep_desc_id;
2472 static const char *speed_names[] = { "full", "high", "super" };
2474 if (type != FFS_DESCRIPTOR)
2478 * If ss_descriptors is not NULL, we are reading super speed
2479 * descriptors; if hs_descriptors is not NULL, we are reading high
2480 * speed descriptors; otherwise, we are reading full speed
2483 if (func->function.ss_descriptors) {
2485 func->function.ss_descriptors[(long)valuep] = desc;
2486 } else if (func->function.hs_descriptors) {
2488 func->function.hs_descriptors[(long)valuep] = desc;
2491 func->function.fs_descriptors[(long)valuep] = desc;
2494 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2497 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2501 ffs_ep = func->eps + idx;
2503 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2504 pr_err("two %sspeed descriptors for EP %d\n",
2505 speed_names[ep_desc_id],
2506 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2509 ffs_ep->descs[ep_desc_id] = ds;
2511 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2513 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2514 if (!ds->wMaxPacketSize)
2515 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2517 struct usb_request *req;
2519 u8 bEndpointAddress;
2522 * We back up bEndpointAddress because autoconfig overwrites
2523 * it with physical endpoint address.
2525 bEndpointAddress = ds->bEndpointAddress;
2526 pr_vdebug("autoconfig\n");
2527 ep = usb_ep_autoconfig(func->gadget, ds);
2530 ep->driver_data = func->eps + idx;
2532 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2538 func->eps_revmap[ds->bEndpointAddress &
2539 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2541 * If we use virtual address mapping, we restore
2542 * original bEndpointAddress value.
2544 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2545 ds->bEndpointAddress = bEndpointAddress;
2547 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2552 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2553 struct usb_descriptor_header *desc,
2556 struct ffs_function *func = priv;
2562 case FFS_DESCRIPTOR:
2563 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2568 if (func->interfaces_nums[idx] < 0) {
2569 int id = usb_interface_id(func->conf, &func->function);
2570 if (unlikely(id < 0))
2572 func->interfaces_nums[idx] = id;
2574 newValue = func->interfaces_nums[idx];
2578 /* String' IDs are allocated when fsf_data is bound to cdev */
2579 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2584 * USB_DT_ENDPOINT are handled in
2585 * __ffs_func_bind_do_descs().
2587 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2590 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2591 if (unlikely(!func->eps[idx].ep))
2595 struct usb_endpoint_descriptor **descs;
2596 descs = func->eps[idx].descs;
2597 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2602 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2607 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2608 struct usb_os_desc_header *h, void *data,
2609 unsigned len, void *priv)
2611 struct ffs_function *func = priv;
2615 case FFS_OS_DESC_EXT_COMPAT: {
2616 struct usb_ext_compat_desc *desc = data;
2617 struct usb_os_desc_table *t;
2619 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2620 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2621 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2622 ARRAY_SIZE(desc->CompatibleID) +
2623 ARRAY_SIZE(desc->SubCompatibleID));
2624 length = sizeof(*desc);
2627 case FFS_OS_DESC_EXT_PROP: {
2628 struct usb_ext_prop_desc *desc = data;
2629 struct usb_os_desc_table *t;
2630 struct usb_os_desc_ext_prop *ext_prop;
2631 char *ext_prop_name;
2632 char *ext_prop_data;
2634 t = &func->function.os_desc_table[h->interface];
2635 t->if_id = func->interfaces_nums[h->interface];
2637 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2638 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2640 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2641 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2642 ext_prop->data_len = le32_to_cpu(*(u32 *)
2643 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2644 length = ext_prop->name_len + ext_prop->data_len + 14;
2646 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2647 func->ffs->ms_os_descs_ext_prop_name_avail +=
2650 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2651 func->ffs->ms_os_descs_ext_prop_data_avail +=
2653 memcpy(ext_prop_data,
2654 usb_ext_prop_data_ptr(data, ext_prop->name_len),
2655 ext_prop->data_len);
2656 /* unicode data reported to the host as "WCHAR"s */
2657 switch (ext_prop->type) {
2658 case USB_EXT_PROP_UNICODE:
2659 case USB_EXT_PROP_UNICODE_ENV:
2660 case USB_EXT_PROP_UNICODE_LINK:
2661 case USB_EXT_PROP_UNICODE_MULTI:
2662 ext_prop->data_len *= 2;
2665 ext_prop->data = ext_prop_data;
2667 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2668 ext_prop->name_len);
2669 /* property name reported to the host as "WCHAR"s */
2670 ext_prop->name_len *= 2;
2671 ext_prop->name = ext_prop_name;
2673 t->os_desc->ext_prop_len +=
2674 ext_prop->name_len + ext_prop->data_len + 14;
2675 ++t->os_desc->ext_prop_count;
2676 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2680 pr_vdebug("unknown descriptor: %d\n", type);
2686 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2687 struct usb_configuration *c)
2689 struct ffs_function *func = ffs_func_from_usb(f);
2690 struct f_fs_opts *ffs_opts =
2691 container_of(f->fi, struct f_fs_opts, func_inst);
2697 * Legacy gadget triggers binding in functionfs_ready_callback,
2698 * which already uses locking; taking the same lock here would
2701 * Configfs-enabled gadgets however do need ffs_dev_lock.
2703 if (!ffs_opts->no_configfs)
2705 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2706 func->ffs = ffs_opts->dev->ffs_data;
2707 if (!ffs_opts->no_configfs)
2710 return ERR_PTR(ret);
2713 func->gadget = c->cdev->gadget;
2716 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2717 * configurations are bound in sequence with list_for_each_entry,
2718 * in each configuration its functions are bound in sequence
2719 * with list_for_each_entry, so we assume no race condition
2720 * with regard to ffs_opts->bound access
2722 if (!ffs_opts->refcnt) {
2723 ret = functionfs_bind(func->ffs, c->cdev);
2725 return ERR_PTR(ret);
2728 func->function.strings = func->ffs->stringtabs;
2733 static int _ffs_func_bind(struct usb_configuration *c,
2734 struct usb_function *f)
2736 struct ffs_function *func = ffs_func_from_usb(f);
2737 struct ffs_data *ffs = func->ffs;
2739 const int full = !!func->ffs->fs_descs_count;
2740 const int high = gadget_is_dualspeed(func->gadget) &&
2741 func->ffs->hs_descs_count;
2742 const int super = gadget_is_superspeed(func->gadget) &&
2743 func->ffs->ss_descs_count;
2745 int fs_len, hs_len, ss_len, ret, i;
2747 /* Make it a single chunk, less management later on */
2749 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2750 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2751 full ? ffs->fs_descs_count + 1 : 0);
2752 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2753 high ? ffs->hs_descs_count + 1 : 0);
2754 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2755 super ? ffs->ss_descs_count + 1 : 0);
2756 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2757 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2758 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2759 vla_item_with_sz(d, char[16], ext_compat,
2760 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2761 vla_item_with_sz(d, struct usb_os_desc, os_desc,
2762 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2763 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2764 ffs->ms_os_descs_ext_prop_count);
2765 vla_item_with_sz(d, char, ext_prop_name,
2766 ffs->ms_os_descs_ext_prop_name_len);
2767 vla_item_with_sz(d, char, ext_prop_data,
2768 ffs->ms_os_descs_ext_prop_data_len);
2769 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2774 /* Has descriptors only for speeds gadget does not support */
2775 if (unlikely(!(full | high | super)))
2778 /* Allocate a single chunk, less management later on */
2779 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2780 if (unlikely(!vlabuf))
2783 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2784 ffs->ms_os_descs_ext_prop_name_avail =
2785 vla_ptr(vlabuf, d, ext_prop_name);
2786 ffs->ms_os_descs_ext_prop_data_avail =
2787 vla_ptr(vlabuf, d, ext_prop_data);
2789 /* Copy descriptors */
2790 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2791 ffs->raw_descs_length);
2793 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2794 for (ret = ffs->eps_count; ret; --ret) {
2797 ptr = vla_ptr(vlabuf, d, eps);
2802 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2804 func->eps = vla_ptr(vlabuf, d, eps);
2805 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2808 * Go through all the endpoint descriptors and allocate
2809 * endpoints first, so that later we can rewrite the endpoint
2810 * numbers without worrying that it may be described later on.
2813 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2814 fs_len = ffs_do_descs(ffs->fs_descs_count,
2815 vla_ptr(vlabuf, d, raw_descs),
2817 __ffs_func_bind_do_descs, func);
2818 if (unlikely(fs_len < 0)) {
2827 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2828 hs_len = ffs_do_descs(ffs->hs_descs_count,
2829 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2830 d_raw_descs__sz - fs_len,
2831 __ffs_func_bind_do_descs, func);
2832 if (unlikely(hs_len < 0)) {
2840 if (likely(super)) {
2841 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2842 ss_len = ffs_do_descs(ffs->ss_descs_count,
2843 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2844 d_raw_descs__sz - fs_len - hs_len,
2845 __ffs_func_bind_do_descs, func);
2846 if (unlikely(ss_len < 0)) {
2855 * Now handle interface numbers allocation and interface and
2856 * endpoint numbers rewriting. We can do that in one go
2859 ret = ffs_do_descs(ffs->fs_descs_count +
2860 (high ? ffs->hs_descs_count : 0) +
2861 (super ? ffs->ss_descs_count : 0),
2862 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2863 __ffs_func_bind_do_nums, func);
2864 if (unlikely(ret < 0))
2867 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2868 if (c->cdev->use_os_string)
2869 for (i = 0; i < ffs->interfaces_count; ++i) {
2870 struct usb_os_desc *desc;
2872 desc = func->function.os_desc_table[i].os_desc =
2873 vla_ptr(vlabuf, d, os_desc) +
2874 i * sizeof(struct usb_os_desc);
2875 desc->ext_compat_id =
2876 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2877 INIT_LIST_HEAD(&desc->ext_prop);
2879 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2880 vla_ptr(vlabuf, d, raw_descs) +
2881 fs_len + hs_len + ss_len,
2882 d_raw_descs__sz - fs_len - hs_len - ss_len,
2883 __ffs_func_bind_do_os_desc, func);
2884 if (unlikely(ret < 0))
2886 func->function.os_desc_n =
2887 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2889 /* And we're done */
2890 ffs_event_add(ffs, FUNCTIONFS_BIND);
2894 /* XXX Do we need to release all claimed endpoints here? */
2898 static int ffs_func_bind(struct usb_configuration *c,
2899 struct usb_function *f)
2901 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2903 if (IS_ERR(ffs_opts))
2904 return PTR_ERR(ffs_opts);
2906 return _ffs_func_bind(c, f);
2910 /* Other USB function hooks *************************************************/
2912 static void ffs_reset_work(struct work_struct *work)
2914 struct ffs_data *ffs = container_of(work,
2915 struct ffs_data, reset_work);
2916 ffs_data_reset(ffs);
2919 static int ffs_func_set_alt(struct usb_function *f,
2920 unsigned interface, unsigned alt)
2922 struct ffs_function *func = ffs_func_from_usb(f);
2923 struct ffs_data *ffs = func->ffs;
2926 if (alt != (unsigned)-1) {
2927 intf = ffs_func_revmap_intf(func, interface);
2928 if (unlikely(intf < 0))
2933 ffs_func_eps_disable(ffs->func);
2935 if (ffs->state == FFS_DEACTIVATED) {
2936 ffs->state = FFS_CLOSING;
2937 INIT_WORK(&ffs->reset_work, ffs_reset_work);
2938 schedule_work(&ffs->reset_work);
2942 if (ffs->state != FFS_ACTIVE)
2945 if (alt == (unsigned)-1) {
2947 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2952 ret = ffs_func_eps_enable(func);
2953 if (likely(ret >= 0))
2954 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2958 static void ffs_func_disable(struct usb_function *f)
2960 ffs_func_set_alt(f, 0, (unsigned)-1);
2963 static int ffs_func_setup(struct usb_function *f,
2964 const struct usb_ctrlrequest *creq)
2966 struct ffs_function *func = ffs_func_from_usb(f);
2967 struct ffs_data *ffs = func->ffs;
2968 unsigned long flags;
2973 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2974 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2975 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2976 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2977 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2980 * Most requests directed to interface go through here
2981 * (notable exceptions are set/get interface) so we need to
2982 * handle them. All other either handled by composite or
2983 * passed to usb_configuration->setup() (if one is set). No
2984 * matter, we will handle requests directed to endpoint here
2985 * as well (as it's straightforward) but what to do with any
2988 if (ffs->state != FFS_ACTIVE)
2991 switch (creq->bRequestType & USB_RECIP_MASK) {
2992 case USB_RECIP_INTERFACE:
2993 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2994 if (unlikely(ret < 0))
2998 case USB_RECIP_ENDPOINT:
2999 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
3000 if (unlikely(ret < 0))
3002 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3003 ret = func->ffs->eps_addrmap[ret];
3010 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
3011 ffs->ev.setup = *creq;
3012 ffs->ev.setup.wIndex = cpu_to_le16(ret);
3013 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
3014 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
3019 static void ffs_func_suspend(struct usb_function *f)
3022 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
3025 static void ffs_func_resume(struct usb_function *f)
3028 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
3032 /* Endpoint and interface numbers reverse mapping ***************************/
3034 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
3036 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
3037 return num ? num : -EDOM;
3040 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
3042 short *nums = func->interfaces_nums;
3043 unsigned count = func->ffs->interfaces_count;
3045 for (; count; --count, ++nums) {
3046 if (*nums >= 0 && *nums == intf)
3047 return nums - func->interfaces_nums;
3054 /* Devices management *******************************************************/
3056 static LIST_HEAD(ffs_devices);
3058 static struct ffs_dev *_ffs_do_find_dev(const char *name)
3060 struct ffs_dev *dev;
3062 list_for_each_entry(dev, &ffs_devices, entry) {
3063 if (!dev->name || !name)
3065 if (strcmp(dev->name, name) == 0)
3073 * ffs_lock must be taken by the caller of this function
3075 static struct ffs_dev *_ffs_get_single_dev(void)
3077 struct ffs_dev *dev;
3079 if (list_is_singular(&ffs_devices)) {
3080 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3089 * ffs_lock must be taken by the caller of this function
3091 static struct ffs_dev *_ffs_find_dev(const char *name)
3093 struct ffs_dev *dev;
3095 dev = _ffs_get_single_dev();
3099 return _ffs_do_find_dev(name);
3102 /* Configfs support *********************************************************/
3104 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3106 return container_of(to_config_group(item), struct f_fs_opts,
3110 static void ffs_attr_release(struct config_item *item)
3112 struct f_fs_opts *opts = to_ffs_opts(item);
3114 usb_put_function_instance(&opts->func_inst);
3117 static struct configfs_item_operations ffs_item_ops = {
3118 .release = ffs_attr_release,
3121 static struct config_item_type ffs_func_type = {
3122 .ct_item_ops = &ffs_item_ops,
3123 .ct_owner = THIS_MODULE,
3127 /* Function registration interface ******************************************/
3129 static void ffs_free_inst(struct usb_function_instance *f)
3131 struct f_fs_opts *opts;
3133 opts = to_f_fs_opts(f);
3135 _ffs_free_dev(opts->dev);
3140 #define MAX_INST_NAME_LEN 40
3142 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3144 struct f_fs_opts *opts;
3149 name_len = strlen(name) + 1;
3150 if (name_len > MAX_INST_NAME_LEN)
3151 return -ENAMETOOLONG;
3153 ptr = kstrndup(name, name_len, GFP_KERNEL);
3157 opts = to_f_fs_opts(fi);
3162 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3163 ret = _ffs_name_dev(opts->dev, ptr);
3169 opts->dev->name_allocated = true;
3178 static struct usb_function_instance *ffs_alloc_inst(void)
3180 struct f_fs_opts *opts;
3181 struct ffs_dev *dev;
3183 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3185 return ERR_PTR(-ENOMEM);
3187 opts->func_inst.set_inst_name = ffs_set_inst_name;
3188 opts->func_inst.free_func_inst = ffs_free_inst;
3190 dev = _ffs_alloc_dev();
3194 return ERR_CAST(dev);
3199 config_group_init_type_name(&opts->func_inst.group, "",
3201 return &opts->func_inst;
3204 static void ffs_free(struct usb_function *f)
3206 kfree(ffs_func_from_usb(f));
3209 static void ffs_func_unbind(struct usb_configuration *c,
3210 struct usb_function *f)
3212 struct ffs_function *func = ffs_func_from_usb(f);
3213 struct ffs_data *ffs = func->ffs;
3214 struct f_fs_opts *opts =
3215 container_of(f->fi, struct f_fs_opts, func_inst);
3216 struct ffs_ep *ep = func->eps;
3217 unsigned count = ffs->eps_count;
3218 unsigned long flags;
3221 if (ffs->func == func) {
3222 ffs_func_eps_disable(func);
3226 if (!--opts->refcnt)
3227 functionfs_unbind(ffs);
3229 /* cleanup after autoconfig */
3230 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3232 if (ep->ep && ep->req)
3233 usb_ep_free_request(ep->ep, ep->req);
3237 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3241 * eps, descriptors and interfaces_nums are allocated in the
3242 * same chunk so only one free is required.
3244 func->function.fs_descriptors = NULL;
3245 func->function.hs_descriptors = NULL;
3246 func->function.ss_descriptors = NULL;
3247 func->interfaces_nums = NULL;
3249 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3252 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3254 struct ffs_function *func;
3258 func = kzalloc(sizeof(*func), GFP_KERNEL);
3259 if (unlikely(!func))
3260 return ERR_PTR(-ENOMEM);
3262 func->function.name = "Function FS Gadget";
3264 func->function.bind = ffs_func_bind;
3265 func->function.unbind = ffs_func_unbind;
3266 func->function.set_alt = ffs_func_set_alt;
3267 func->function.disable = ffs_func_disable;
3268 func->function.setup = ffs_func_setup;
3269 func->function.suspend = ffs_func_suspend;
3270 func->function.resume = ffs_func_resume;
3271 func->function.free_func = ffs_free;
3273 return &func->function;
3277 * ffs_lock must be taken by the caller of this function
3279 static struct ffs_dev *_ffs_alloc_dev(void)
3281 struct ffs_dev *dev;
3284 if (_ffs_get_single_dev())
3285 return ERR_PTR(-EBUSY);
3287 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3289 return ERR_PTR(-ENOMEM);
3291 if (list_empty(&ffs_devices)) {
3292 ret = functionfs_init();
3295 return ERR_PTR(ret);
3299 list_add(&dev->entry, &ffs_devices);
3305 * ffs_lock must be taken by the caller of this function
3306 * The caller is responsible for "name" being available whenever f_fs needs it
3308 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3310 struct ffs_dev *existing;
3312 existing = _ffs_do_find_dev(name);
3322 * The caller is responsible for "name" being available whenever f_fs needs it
3324 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3329 ret = _ffs_name_dev(dev, name);
3334 EXPORT_SYMBOL_GPL(ffs_name_dev);
3336 int ffs_single_dev(struct ffs_dev *dev)
3343 if (!list_is_singular(&ffs_devices))
3351 EXPORT_SYMBOL_GPL(ffs_single_dev);
3354 * ffs_lock must be taken by the caller of this function
3356 static void _ffs_free_dev(struct ffs_dev *dev)
3358 list_del(&dev->entry);
3359 if (dev->name_allocated)
3362 if (list_empty(&ffs_devices))
3363 functionfs_cleanup();
3366 static void *ffs_acquire_dev(const char *dev_name)
3368 struct ffs_dev *ffs_dev;
3373 ffs_dev = _ffs_find_dev(dev_name);
3375 ffs_dev = ERR_PTR(-ENOENT);
3376 else if (ffs_dev->mounted)
3377 ffs_dev = ERR_PTR(-EBUSY);
3378 else if (ffs_dev->ffs_acquire_dev_callback &&
3379 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3380 ffs_dev = ERR_PTR(-ENOENT);
3382 ffs_dev->mounted = true;
3388 static void ffs_release_dev(struct ffs_data *ffs_data)
3390 struct ffs_dev *ffs_dev;
3395 ffs_dev = ffs_data->private_data;
3397 ffs_dev->mounted = false;
3399 if (ffs_dev->ffs_release_dev_callback)
3400 ffs_dev->ffs_release_dev_callback(ffs_dev);
3406 static int ffs_ready(struct ffs_data *ffs)
3408 struct ffs_dev *ffs_obj;
3414 ffs_obj = ffs->private_data;
3419 if (WARN_ON(ffs_obj->desc_ready)) {
3424 ffs_obj->desc_ready = true;
3425 ffs_obj->ffs_data = ffs;
3427 if (ffs_obj->ffs_ready_callback)
3428 ret = ffs_obj->ffs_ready_callback(ffs);
3435 static void ffs_closed(struct ffs_data *ffs)
3437 struct ffs_dev *ffs_obj;
3442 ffs_obj = ffs->private_data;
3446 ffs_obj->desc_ready = false;
3448 if (ffs_obj->ffs_closed_callback)
3449 ffs_obj->ffs_closed_callback(ffs);
3451 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
3452 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
3455 unregister_gadget_item(ffs_obj->opts->
3456 func_inst.group.cg_item.ci_parent->ci_parent);
3461 /* Misc helper functions ****************************************************/
3463 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3466 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3467 : mutex_lock_interruptible(mutex);
3470 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3477 data = kmalloc(len, GFP_KERNEL);
3478 if (unlikely(!data))
3479 return ERR_PTR(-ENOMEM);
3481 if (unlikely(__copy_from_user(data, buf, len))) {
3483 return ERR_PTR(-EFAULT);
3486 pr_vdebug("Buffer from user space:\n");
3487 ffs_dump_mem("", data, len);
3492 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3493 MODULE_LICENSE("GPL");
3494 MODULE_AUTHOR("Michal Nazarewicz");