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;
325 * We're called from user space, we can use _irq
326 * rather then _irqsave
328 spin_lock_irq(&ffs->ev.waitq.lock);
329 switch (ffs_setup_state_clear_cancelled(ffs)) {
330 case FFS_SETUP_CANCELLED:
338 case FFS_SETUP_PENDING:
342 /* FFS_SETUP_PENDING */
343 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
344 spin_unlock_irq(&ffs->ev.waitq.lock);
345 ret = __ffs_ep0_stall(ffs);
349 /* FFS_SETUP_PENDING and not stall */
350 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
352 spin_unlock_irq(&ffs->ev.waitq.lock);
354 data = ffs_prepare_buffer(buf, len);
360 spin_lock_irq(&ffs->ev.waitq.lock);
363 * We are guaranteed to be still in FFS_ACTIVE state
364 * but the state of setup could have changed from
365 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
366 * to check for that. If that happened we copied data
367 * from user space in vain but it's unlikely.
369 * For sure we are not in FFS_NO_SETUP since this is
370 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
371 * transition can be performed and it's protected by
374 if (ffs_setup_state_clear_cancelled(ffs) ==
375 FFS_SETUP_CANCELLED) {
378 spin_unlock_irq(&ffs->ev.waitq.lock);
380 /* unlocks spinlock */
381 ret = __ffs_ep0_queue_wait(ffs, data, len);
391 mutex_unlock(&ffs->mutex);
395 /* Called with ffs->ev.waitq.lock and ffs->mutex held, both released on exit. */
396 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
400 * n cannot be bigger than ffs->ev.count, which cannot be bigger than
401 * size of ffs->ev.types array (which is four) so that's how much space
404 struct usb_functionfs_event events[ARRAY_SIZE(ffs->ev.types)];
405 const size_t size = n * sizeof *events;
408 memset(events, 0, size);
411 events[i].type = ffs->ev.types[i];
412 if (events[i].type == FUNCTIONFS_SETUP) {
413 events[i].u.setup = ffs->ev.setup;
414 ffs->setup_state = FFS_SETUP_PENDING;
420 memmove(ffs->ev.types, ffs->ev.types + n,
421 ffs->ev.count * sizeof *ffs->ev.types);
423 spin_unlock_irq(&ffs->ev.waitq.lock);
424 mutex_unlock(&ffs->mutex);
426 return unlikely(copy_to_user(buf, events, size)) ? -EFAULT : size;
429 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
430 size_t len, loff_t *ptr)
432 struct ffs_data *ffs = file->private_data;
439 /* Fast check if setup was canceled */
440 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
444 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
445 if (unlikely(ret < 0))
449 if (ffs->state != FFS_ACTIVE) {
455 * We're called from user space, we can use _irq rather then
458 spin_lock_irq(&ffs->ev.waitq.lock);
460 switch (ffs_setup_state_clear_cancelled(ffs)) {
461 case FFS_SETUP_CANCELLED:
466 n = len / sizeof(struct usb_functionfs_event);
472 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
477 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
483 return __ffs_ep0_read_events(ffs, buf,
484 min(n, (size_t)ffs->ev.count));
486 case FFS_SETUP_PENDING:
487 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
488 spin_unlock_irq(&ffs->ev.waitq.lock);
489 ret = __ffs_ep0_stall(ffs);
493 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
495 spin_unlock_irq(&ffs->ev.waitq.lock);
498 data = kmalloc(len, GFP_KERNEL);
499 if (unlikely(!data)) {
505 spin_lock_irq(&ffs->ev.waitq.lock);
507 /* See ffs_ep0_write() */
508 if (ffs_setup_state_clear_cancelled(ffs) ==
509 FFS_SETUP_CANCELLED) {
514 /* unlocks spinlock */
515 ret = __ffs_ep0_queue_wait(ffs, data, len);
516 if (likely(ret > 0) && unlikely(copy_to_user(buf, data, len)))
525 spin_unlock_irq(&ffs->ev.waitq.lock);
527 mutex_unlock(&ffs->mutex);
532 static int ffs_ep0_open(struct inode *inode, struct file *file)
534 struct ffs_data *ffs = inode->i_private;
538 if (unlikely(ffs->state == FFS_CLOSING))
541 file->private_data = ffs;
542 ffs_data_opened(ffs);
547 static int ffs_ep0_release(struct inode *inode, struct file *file)
549 struct ffs_data *ffs = file->private_data;
553 ffs_data_closed(ffs);
558 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
560 struct ffs_data *ffs = file->private_data;
561 struct usb_gadget *gadget = ffs->gadget;
566 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
567 struct ffs_function *func = ffs->func;
568 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
569 } else if (gadget && gadget->ops->ioctl) {
570 ret = gadget->ops->ioctl(gadget, code, value);
578 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
580 struct ffs_data *ffs = file->private_data;
581 unsigned int mask = POLLWRNORM;
584 poll_wait(file, &ffs->ev.waitq, wait);
586 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
587 if (unlikely(ret < 0))
590 switch (ffs->state) {
591 case FFS_READ_DESCRIPTORS:
592 case FFS_READ_STRINGS:
597 switch (ffs->setup_state) {
603 case FFS_SETUP_PENDING:
604 case FFS_SETUP_CANCELLED:
605 mask |= (POLLIN | POLLOUT);
610 case FFS_DEACTIVATED:
614 mutex_unlock(&ffs->mutex);
619 static const struct file_operations ffs_ep0_operations = {
622 .open = ffs_ep0_open,
623 .write = ffs_ep0_write,
624 .read = ffs_ep0_read,
625 .release = ffs_ep0_release,
626 .unlocked_ioctl = ffs_ep0_ioctl,
627 .poll = ffs_ep0_poll,
631 /* "Normal" endpoints operations ********************************************/
633 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
636 if (likely(req->context)) {
637 struct ffs_ep *ep = _ep->driver_data;
638 ep->status = req->status ? req->status : req->actual;
639 complete(req->context);
643 static void ffs_user_copy_worker(struct work_struct *work)
645 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
647 int ret = io_data->req->status ? io_data->req->status :
648 io_data->req->actual;
650 if (io_data->read && ret > 0) {
652 ret = copy_to_iter(io_data->buf, ret, &io_data->data);
653 if (iov_iter_count(&io_data->data))
655 unuse_mm(io_data->mm);
658 io_data->kiocb->ki_complete(io_data->kiocb, ret, ret);
660 if (io_data->ffs->ffs_eventfd &&
661 !(io_data->kiocb->ki_flags & IOCB_EVENTFD))
662 eventfd_signal(io_data->ffs->ffs_eventfd, 1);
664 usb_ep_free_request(io_data->ep, io_data->req);
666 io_data->kiocb->private = NULL;
668 kfree(io_data->to_free);
673 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
674 struct usb_request *req)
676 struct ffs_io_data *io_data = req->context;
680 INIT_WORK(&io_data->work, ffs_user_copy_worker);
681 schedule_work(&io_data->work);
684 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
686 struct ffs_epfile *epfile = file->private_data;
687 struct usb_request *req;
690 ssize_t ret, data_len = -EINVAL;
693 /* Are we still active? */
694 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
697 /* Wait for endpoint to be enabled */
700 if (file->f_flags & O_NONBLOCK)
703 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
709 halt = (!io_data->read == !epfile->in);
710 if (halt && epfile->isoc)
713 /* Allocate & copy */
716 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
717 * before the waiting completes, so do not assign to 'gadget'
720 struct usb_gadget *gadget = epfile->ffs->gadget;
723 spin_lock_irq(&epfile->ffs->eps_lock);
724 /* In the meantime, endpoint got disabled or changed. */
725 if (epfile->ep != ep) {
726 spin_unlock_irq(&epfile->ffs->eps_lock);
729 data_len = iov_iter_count(&io_data->data);
731 * Controller may require buffer size to be aligned to
732 * maxpacketsize of an out endpoint.
735 data_len = usb_ep_align_maybe(gadget, ep->ep, data_len);
736 spin_unlock_irq(&epfile->ffs->eps_lock);
738 data = kmalloc(data_len, GFP_KERNEL);
741 if (!io_data->read) {
742 copied = copy_from_iter(data, data_len, &io_data->data);
743 if (copied != data_len) {
750 /* We will be using request */
751 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
755 spin_lock_irq(&epfile->ffs->eps_lock);
757 if (epfile->ep != ep) {
758 /* In the meantime, endpoint got disabled or changed. */
762 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
763 usb_ep_set_halt(ep->ep);
765 } else if (unlikely(data_len == -EINVAL)) {
767 * Sanity Check: even though data_len can't be used
768 * uninitialized at the time I write this comment, some
769 * compilers complain about this situation.
770 * In order to keep the code clean from warnings, data_len is
771 * being initialized to -EINVAL during its declaration, which
772 * means we can't rely on compiler anymore to warn no future
773 * changes won't result in data_len being used uninitialized.
774 * For such reason, we're adding this redundant sanity check
777 WARN(1, "%s: data_len == -EINVAL\n", __func__);
779 } else if (!io_data->aio) {
780 DECLARE_COMPLETION_ONSTACK(done);
781 bool interrupted = false;
785 req->length = data_len;
787 req->context = &done;
788 req->complete = ffs_epfile_io_complete;
790 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
791 if (unlikely(ret < 0))
794 spin_unlock_irq(&epfile->ffs->eps_lock);
796 if (unlikely(wait_for_completion_interruptible(&done))) {
798 * To avoid race condition with ffs_epfile_io_complete,
799 * dequeue the request first then check
800 * status. usb_ep_dequeue API should guarantee no race
801 * condition with req->complete callback.
803 usb_ep_dequeue(ep->ep, req);
804 interrupted = ep->status < 0;
808 * XXX We may end up silently droping data here. Since data_len
809 * (i.e. req->length) may be bigger than len (after being
810 * rounded up to maxpacketsize), we may end up with more data
811 * then user space has space for.
813 ret = interrupted ? -EINTR : ep->status;
814 if (io_data->read && ret > 0) {
815 ret = copy_to_iter(data, ret, &io_data->data);
820 } else if (!(req = usb_ep_alloc_request(ep->ep, GFP_KERNEL))) {
824 req->length = data_len;
827 io_data->ep = ep->ep;
829 io_data->ffs = epfile->ffs;
831 req->context = io_data;
832 req->complete = ffs_epfile_async_io_complete;
834 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
836 usb_ep_free_request(ep->ep, req);
842 * Do not kfree the buffer in this function. It will be freed
843 * by ffs_user_copy_worker.
849 spin_unlock_irq(&epfile->ffs->eps_lock);
851 mutex_unlock(&epfile->mutex);
858 ffs_epfile_open(struct inode *inode, struct file *file)
860 struct ffs_epfile *epfile = inode->i_private;
864 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
867 file->private_data = epfile;
868 ffs_data_opened(epfile->ffs);
873 static int ffs_aio_cancel(struct kiocb *kiocb)
875 struct ffs_io_data *io_data = kiocb->private;
876 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
881 spin_lock_irq(&epfile->ffs->eps_lock);
883 if (likely(io_data && io_data->ep && io_data->req))
884 value = usb_ep_dequeue(io_data->ep, io_data->req);
888 spin_unlock_irq(&epfile->ffs->eps_lock);
893 static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
895 struct ffs_io_data io_data, *p = &io_data;
900 if (!is_sync_kiocb(kiocb)) {
901 p = kmalloc(sizeof(io_data), GFP_KERNEL);
917 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
919 res = ffs_epfile_io(kiocb->ki_filp, p);
920 if (res == -EIOCBQUEUED)
929 static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
931 struct ffs_io_data io_data, *p = &io_data;
936 if (!is_sync_kiocb(kiocb)) {
937 p = kmalloc(sizeof(io_data), GFP_KERNEL);
948 p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
962 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
964 res = ffs_epfile_io(kiocb->ki_filp, p);
965 if (res == -EIOCBQUEUED)
978 ffs_epfile_release(struct inode *inode, struct file *file)
980 struct ffs_epfile *epfile = inode->i_private;
984 ffs_data_closed(epfile->ffs);
989 static long ffs_epfile_ioctl(struct file *file, unsigned code,
992 struct ffs_epfile *epfile = file->private_data;
997 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1000 spin_lock_irq(&epfile->ffs->eps_lock);
1001 if (likely(epfile->ep)) {
1003 case FUNCTIONFS_FIFO_STATUS:
1004 ret = usb_ep_fifo_status(epfile->ep->ep);
1006 case FUNCTIONFS_FIFO_FLUSH:
1007 usb_ep_fifo_flush(epfile->ep->ep);
1010 case FUNCTIONFS_CLEAR_HALT:
1011 ret = usb_ep_clear_halt(epfile->ep->ep);
1013 case FUNCTIONFS_ENDPOINT_REVMAP:
1014 ret = epfile->ep->num;
1016 case FUNCTIONFS_ENDPOINT_DESC:
1019 struct usb_endpoint_descriptor *desc;
1021 switch (epfile->ffs->gadget->speed) {
1022 case USB_SPEED_SUPER:
1025 case USB_SPEED_HIGH:
1031 desc = epfile->ep->descs[desc_idx];
1033 spin_unlock_irq(&epfile->ffs->eps_lock);
1034 ret = copy_to_user((void *)value, desc, sizeof(*desc));
1045 spin_unlock_irq(&epfile->ffs->eps_lock);
1050 static const struct file_operations ffs_epfile_operations = {
1051 .llseek = no_llseek,
1053 .open = ffs_epfile_open,
1054 .write_iter = ffs_epfile_write_iter,
1055 .read_iter = ffs_epfile_read_iter,
1056 .release = ffs_epfile_release,
1057 .unlocked_ioctl = ffs_epfile_ioctl,
1061 /* File system and super block operations ***********************************/
1064 * Mounting the file system creates a controller file, used first for
1065 * function configuration then later for event monitoring.
1068 static struct inode *__must_check
1069 ffs_sb_make_inode(struct super_block *sb, void *data,
1070 const struct file_operations *fops,
1071 const struct inode_operations *iops,
1072 struct ffs_file_perms *perms)
1074 struct inode *inode;
1078 inode = new_inode(sb);
1080 if (likely(inode)) {
1081 struct timespec current_time = CURRENT_TIME;
1083 inode->i_ino = get_next_ino();
1084 inode->i_mode = perms->mode;
1085 inode->i_uid = perms->uid;
1086 inode->i_gid = perms->gid;
1087 inode->i_atime = current_time;
1088 inode->i_mtime = current_time;
1089 inode->i_ctime = current_time;
1090 inode->i_private = data;
1092 inode->i_fop = fops;
1100 /* Create "regular" file */
1101 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1102 const char *name, void *data,
1103 const struct file_operations *fops)
1105 struct ffs_data *ffs = sb->s_fs_info;
1106 struct dentry *dentry;
1107 struct inode *inode;
1111 dentry = d_alloc_name(sb->s_root, name);
1112 if (unlikely(!dentry))
1115 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1116 if (unlikely(!inode)) {
1121 d_add(dentry, inode);
1126 static const struct super_operations ffs_sb_operations = {
1127 .statfs = simple_statfs,
1128 .drop_inode = generic_delete_inode,
1131 struct ffs_sb_fill_data {
1132 struct ffs_file_perms perms;
1134 const char *dev_name;
1136 struct ffs_data *ffs_data;
1139 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1141 struct ffs_sb_fill_data *data = _data;
1142 struct inode *inode;
1143 struct ffs_data *ffs = data->ffs_data;
1148 data->ffs_data = NULL;
1149 sb->s_fs_info = ffs;
1150 sb->s_blocksize = PAGE_SIZE;
1151 sb->s_blocksize_bits = PAGE_SHIFT;
1152 sb->s_magic = FUNCTIONFS_MAGIC;
1153 sb->s_op = &ffs_sb_operations;
1154 sb->s_time_gran = 1;
1157 data->perms.mode = data->root_mode;
1158 inode = ffs_sb_make_inode(sb, NULL,
1159 &simple_dir_operations,
1160 &simple_dir_inode_operations,
1162 sb->s_root = d_make_root(inode);
1163 if (unlikely(!sb->s_root))
1167 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1168 &ffs_ep0_operations)))
1174 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1178 if (!opts || !*opts)
1182 unsigned long value;
1186 comma = strchr(opts, ',');
1191 eq = strchr(opts, '=');
1192 if (unlikely(!eq)) {
1193 pr_err("'=' missing in %s\n", opts);
1199 if (kstrtoul(eq + 1, 0, &value)) {
1200 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1204 /* Interpret option */
1205 switch (eq - opts) {
1207 if (!memcmp(opts, "no_disconnect", 13))
1208 data->no_disconnect = !!value;
1213 if (!memcmp(opts, "rmode", 5))
1214 data->root_mode = (value & 0555) | S_IFDIR;
1215 else if (!memcmp(opts, "fmode", 5))
1216 data->perms.mode = (value & 0666) | S_IFREG;
1222 if (!memcmp(opts, "mode", 4)) {
1223 data->root_mode = (value & 0555) | S_IFDIR;
1224 data->perms.mode = (value & 0666) | S_IFREG;
1231 if (!memcmp(opts, "uid", 3)) {
1232 data->perms.uid = make_kuid(current_user_ns(), value);
1233 if (!uid_valid(data->perms.uid)) {
1234 pr_err("%s: unmapped value: %lu\n", opts, value);
1237 } else if (!memcmp(opts, "gid", 3)) {
1238 data->perms.gid = make_kgid(current_user_ns(), value);
1239 if (!gid_valid(data->perms.gid)) {
1240 pr_err("%s: unmapped value: %lu\n", opts, value);
1250 pr_err("%s: invalid option\n", opts);
1254 /* Next iteration */
1263 /* "mount -t functionfs dev_name /dev/function" ends up here */
1265 static struct dentry *
1266 ffs_fs_mount(struct file_system_type *t, int flags,
1267 const char *dev_name, void *opts)
1269 struct ffs_sb_fill_data data = {
1271 .mode = S_IFREG | 0600,
1272 .uid = GLOBAL_ROOT_UID,
1273 .gid = GLOBAL_ROOT_GID,
1275 .root_mode = S_IFDIR | 0500,
1276 .no_disconnect = false,
1281 struct ffs_data *ffs;
1285 ret = ffs_fs_parse_opts(&data, opts);
1286 if (unlikely(ret < 0))
1287 return ERR_PTR(ret);
1289 ffs = ffs_data_new();
1291 return ERR_PTR(-ENOMEM);
1292 ffs->file_perms = data.perms;
1293 ffs->no_disconnect = data.no_disconnect;
1295 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1296 if (unlikely(!ffs->dev_name)) {
1298 return ERR_PTR(-ENOMEM);
1301 ffs_dev = ffs_acquire_dev(dev_name);
1302 if (IS_ERR(ffs_dev)) {
1304 return ERR_CAST(ffs_dev);
1306 ffs->private_data = ffs_dev;
1307 data.ffs_data = ffs;
1309 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1310 if (IS_ERR(rv) && data.ffs_data) {
1311 ffs_release_dev(data.ffs_data);
1312 ffs_data_put(data.ffs_data);
1318 ffs_fs_kill_sb(struct super_block *sb)
1322 kill_litter_super(sb);
1323 if (sb->s_fs_info) {
1324 ffs_release_dev(sb->s_fs_info);
1325 ffs_data_closed(sb->s_fs_info);
1326 ffs_data_put(sb->s_fs_info);
1330 static struct file_system_type ffs_fs_type = {
1331 .owner = THIS_MODULE,
1332 .name = "functionfs",
1333 .mount = ffs_fs_mount,
1334 .kill_sb = ffs_fs_kill_sb,
1336 MODULE_ALIAS_FS("functionfs");
1339 /* Driver's main init/cleanup functions *************************************/
1341 static int functionfs_init(void)
1347 ret = register_filesystem(&ffs_fs_type);
1349 pr_info("file system registered\n");
1351 pr_err("failed registering file system (%d)\n", ret);
1356 static void functionfs_cleanup(void)
1360 pr_info("unloading\n");
1361 unregister_filesystem(&ffs_fs_type);
1365 /* ffs_data and ffs_function construction and destruction code **************/
1367 static void ffs_data_clear(struct ffs_data *ffs);
1368 static void ffs_data_reset(struct ffs_data *ffs);
1370 static void ffs_data_get(struct ffs_data *ffs)
1374 atomic_inc(&ffs->ref);
1377 static void ffs_data_opened(struct ffs_data *ffs)
1381 atomic_inc(&ffs->ref);
1382 if (atomic_add_return(1, &ffs->opened) == 1 &&
1383 ffs->state == FFS_DEACTIVATED) {
1384 ffs->state = FFS_CLOSING;
1385 ffs_data_reset(ffs);
1389 static void ffs_data_put(struct ffs_data *ffs)
1393 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1394 pr_info("%s(): freeing\n", __func__);
1395 ffs_data_clear(ffs);
1396 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1397 waitqueue_active(&ffs->ep0req_completion.wait));
1398 kfree(ffs->dev_name);
1403 static void ffs_data_closed(struct ffs_data *ffs)
1407 if (atomic_dec_and_test(&ffs->opened)) {
1408 if (ffs->no_disconnect) {
1409 ffs->state = FFS_DEACTIVATED;
1411 ffs_epfiles_destroy(ffs->epfiles,
1413 ffs->epfiles = NULL;
1415 if (ffs->setup_state == FFS_SETUP_PENDING)
1416 __ffs_ep0_stall(ffs);
1418 ffs->state = FFS_CLOSING;
1419 ffs_data_reset(ffs);
1422 if (atomic_read(&ffs->opened) < 0) {
1423 ffs->state = FFS_CLOSING;
1424 ffs_data_reset(ffs);
1430 static struct ffs_data *ffs_data_new(void)
1432 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1438 atomic_set(&ffs->ref, 1);
1439 atomic_set(&ffs->opened, 0);
1440 ffs->state = FFS_READ_DESCRIPTORS;
1441 mutex_init(&ffs->mutex);
1442 spin_lock_init(&ffs->eps_lock);
1443 init_waitqueue_head(&ffs->ev.waitq);
1444 init_completion(&ffs->ep0req_completion);
1446 /* XXX REVISIT need to update it in some places, or do we? */
1447 ffs->ev.can_stall = 1;
1452 static void ffs_data_clear(struct ffs_data *ffs)
1458 BUG_ON(ffs->gadget);
1461 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1463 if (ffs->ffs_eventfd)
1464 eventfd_ctx_put(ffs->ffs_eventfd);
1466 kfree(ffs->raw_descs_data);
1467 kfree(ffs->raw_strings);
1468 kfree(ffs->stringtabs);
1471 static void ffs_data_reset(struct ffs_data *ffs)
1475 ffs_data_clear(ffs);
1477 ffs->epfiles = NULL;
1478 ffs->raw_descs_data = NULL;
1479 ffs->raw_descs = NULL;
1480 ffs->raw_strings = NULL;
1481 ffs->stringtabs = NULL;
1483 ffs->raw_descs_length = 0;
1484 ffs->fs_descs_count = 0;
1485 ffs->hs_descs_count = 0;
1486 ffs->ss_descs_count = 0;
1488 ffs->strings_count = 0;
1489 ffs->interfaces_count = 0;
1494 ffs->state = FFS_READ_DESCRIPTORS;
1495 ffs->setup_state = FFS_NO_SETUP;
1500 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1502 struct usb_gadget_strings **lang;
1507 if (WARN_ON(ffs->state != FFS_ACTIVE
1508 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1511 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1512 if (unlikely(first_id < 0))
1515 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1516 if (unlikely(!ffs->ep0req))
1518 ffs->ep0req->complete = ffs_ep0_complete;
1519 ffs->ep0req->context = ffs;
1521 lang = ffs->stringtabs;
1523 for (; *lang; ++lang) {
1524 struct usb_string *str = (*lang)->strings;
1526 for (; str->s; ++id, ++str)
1531 ffs->gadget = cdev->gadget;
1536 static void functionfs_unbind(struct ffs_data *ffs)
1540 if (!WARN_ON(!ffs->gadget)) {
1541 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1544 clear_bit(FFS_FL_BOUND, &ffs->flags);
1549 static int ffs_epfiles_create(struct ffs_data *ffs)
1551 struct ffs_epfile *epfile, *epfiles;
1556 count = ffs->eps_count;
1557 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1562 for (i = 1; i <= count; ++i, ++epfile) {
1564 mutex_init(&epfile->mutex);
1565 init_waitqueue_head(&epfile->wait);
1566 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1567 sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
1569 sprintf(epfile->name, "ep%u", i);
1570 epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
1572 &ffs_epfile_operations);
1573 if (unlikely(!epfile->dentry)) {
1574 ffs_epfiles_destroy(epfiles, i - 1);
1579 ffs->epfiles = epfiles;
1583 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1585 struct ffs_epfile *epfile = epfiles;
1589 for (; count; --count, ++epfile) {
1590 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1591 waitqueue_active(&epfile->wait));
1592 if (epfile->dentry) {
1593 d_delete(epfile->dentry);
1594 dput(epfile->dentry);
1595 epfile->dentry = NULL;
1602 static void ffs_func_eps_disable(struct ffs_function *func)
1604 struct ffs_ep *ep = func->eps;
1605 struct ffs_epfile *epfile = func->ffs->epfiles;
1606 unsigned count = func->ffs->eps_count;
1607 unsigned long flags;
1609 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1611 /* pending requests get nuked */
1613 usb_ep_disable(ep->ep);
1621 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1624 static int ffs_func_eps_enable(struct ffs_function *func)
1626 struct ffs_data *ffs = func->ffs;
1627 struct ffs_ep *ep = func->eps;
1628 struct ffs_epfile *epfile = ffs->epfiles;
1629 unsigned count = ffs->eps_count;
1630 unsigned long flags;
1633 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1635 struct usb_endpoint_descriptor *ds;
1638 if (ffs->gadget->speed == USB_SPEED_SUPER)
1640 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1645 /* fall-back to lower speed if desc missing for current speed */
1647 ds = ep->descs[desc_idx];
1648 } while (!ds && --desc_idx >= 0);
1655 ep->ep->driver_data = ep;
1657 ret = usb_ep_enable(ep->ep);
1660 epfile->in = usb_endpoint_dir_in(ds);
1661 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1666 wake_up(&epfile->wait);
1671 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1677 /* Parsing and building descriptors and strings *****************************/
1680 * This validates if data pointed by data is a valid USB descriptor as
1681 * well as record how many interfaces, endpoints and strings are
1682 * required by given configuration. Returns address after the
1683 * descriptor or NULL if data is invalid.
1686 enum ffs_entity_type {
1687 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1690 enum ffs_os_desc_type {
1691 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1694 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1696 struct usb_descriptor_header *desc,
1699 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1700 struct usb_os_desc_header *h, void *data,
1701 unsigned len, void *priv);
1703 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1704 ffs_entity_callback entity,
1707 struct usb_descriptor_header *_ds = (void *)data;
1713 /* At least two bytes are required: length and type */
1715 pr_vdebug("descriptor too short\n");
1719 /* If we have at least as many bytes as the descriptor takes? */
1720 length = _ds->bLength;
1722 pr_vdebug("descriptor longer then available data\n");
1726 #define __entity_check_INTERFACE(val) 1
1727 #define __entity_check_STRING(val) (val)
1728 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1729 #define __entity(type, val) do { \
1730 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1731 if (unlikely(!__entity_check_ ##type(val))) { \
1732 pr_vdebug("invalid entity's value\n"); \
1735 ret = entity(FFS_ ##type, &val, _ds, priv); \
1736 if (unlikely(ret < 0)) { \
1737 pr_debug("entity " #type "(%02x); ret = %d\n", \
1743 /* Parse descriptor depending on type. */
1744 switch (_ds->bDescriptorType) {
1748 case USB_DT_DEVICE_QUALIFIER:
1749 /* function can't have any of those */
1750 pr_vdebug("descriptor reserved for gadget: %d\n",
1751 _ds->bDescriptorType);
1754 case USB_DT_INTERFACE: {
1755 struct usb_interface_descriptor *ds = (void *)_ds;
1756 pr_vdebug("interface descriptor\n");
1757 if (length != sizeof *ds)
1760 __entity(INTERFACE, ds->bInterfaceNumber);
1762 __entity(STRING, ds->iInterface);
1766 case USB_DT_ENDPOINT: {
1767 struct usb_endpoint_descriptor *ds = (void *)_ds;
1768 pr_vdebug("endpoint descriptor\n");
1769 if (length != USB_DT_ENDPOINT_SIZE &&
1770 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1772 __entity(ENDPOINT, ds->bEndpointAddress);
1777 pr_vdebug("hid descriptor\n");
1778 if (length != sizeof(struct hid_descriptor))
1783 if (length != sizeof(struct usb_otg_descriptor))
1787 case USB_DT_INTERFACE_ASSOCIATION: {
1788 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1789 pr_vdebug("interface association descriptor\n");
1790 if (length != sizeof *ds)
1793 __entity(STRING, ds->iFunction);
1797 case USB_DT_SS_ENDPOINT_COMP:
1798 pr_vdebug("EP SS companion descriptor\n");
1799 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1803 case USB_DT_OTHER_SPEED_CONFIG:
1804 case USB_DT_INTERFACE_POWER:
1806 case USB_DT_SECURITY:
1807 case USB_DT_CS_RADIO_CONTROL:
1809 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1813 /* We should never be here */
1814 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1818 pr_vdebug("invalid length: %d (descriptor %d)\n",
1819 _ds->bLength, _ds->bDescriptorType);
1824 #undef __entity_check_DESCRIPTOR
1825 #undef __entity_check_INTERFACE
1826 #undef __entity_check_STRING
1827 #undef __entity_check_ENDPOINT
1832 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1833 ffs_entity_callback entity, void *priv)
1835 const unsigned _len = len;
1836 unsigned long num = 0;
1846 /* Record "descriptor" entity */
1847 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1848 if (unlikely(ret < 0)) {
1849 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1857 ret = ffs_do_single_desc(data, len, entity, priv);
1858 if (unlikely(ret < 0)) {
1859 pr_debug("%s returns %d\n", __func__, ret);
1869 static int __ffs_data_do_entity(enum ffs_entity_type type,
1870 u8 *valuep, struct usb_descriptor_header *desc,
1873 struct ffs_desc_helper *helper = priv;
1874 struct usb_endpoint_descriptor *d;
1879 case FFS_DESCRIPTOR:
1884 * Interfaces are indexed from zero so if we
1885 * encountered interface "n" then there are at least
1888 if (*valuep >= helper->interfaces_count)
1889 helper->interfaces_count = *valuep + 1;
1894 * Strings are indexed from 1 (0 is magic ;) reserved
1895 * for languages list or some such)
1897 if (*valuep > helper->ffs->strings_count)
1898 helper->ffs->strings_count = *valuep;
1903 helper->eps_count++;
1904 if (helper->eps_count >= 15)
1906 /* Check if descriptors for any speed were already parsed */
1907 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
1908 helper->ffs->eps_addrmap[helper->eps_count] =
1909 d->bEndpointAddress;
1910 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
1911 d->bEndpointAddress)
1919 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1920 struct usb_os_desc_header *desc)
1922 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1923 u16 w_index = le16_to_cpu(desc->wIndex);
1925 if (bcd_version != 1) {
1926 pr_vdebug("unsupported os descriptors version: %d",
1932 *next_type = FFS_OS_DESC_EXT_COMPAT;
1935 *next_type = FFS_OS_DESC_EXT_PROP;
1938 pr_vdebug("unsupported os descriptor type: %d", w_index);
1942 return sizeof(*desc);
1946 * Process all extended compatibility/extended property descriptors
1947 * of a feature descriptor
1949 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1950 enum ffs_os_desc_type type,
1952 ffs_os_desc_callback entity,
1954 struct usb_os_desc_header *h)
1957 const unsigned _len = len;
1961 /* loop over all ext compat/ext prop descriptors */
1962 while (feature_count--) {
1963 ret = entity(type, h, data, len, priv);
1964 if (unlikely(ret < 0)) {
1965 pr_debug("bad OS descriptor, type: %d\n", type);
1974 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1975 static int __must_check ffs_do_os_descs(unsigned count,
1976 char *data, unsigned len,
1977 ffs_os_desc_callback entity, void *priv)
1979 const unsigned _len = len;
1980 unsigned long num = 0;
1984 for (num = 0; num < count; ++num) {
1986 enum ffs_os_desc_type type;
1988 struct usb_os_desc_header *desc = (void *)data;
1990 if (len < sizeof(*desc))
1994 * Record "descriptor" entity.
1995 * Process dwLength, bcdVersion, wIndex, get b/wCount.
1996 * Move the data pointer to the beginning of extended
1997 * compatibilities proper or extended properties proper
1998 * portions of the data
2000 if (le32_to_cpu(desc->dwLength) > len)
2003 ret = __ffs_do_os_desc_header(&type, desc);
2004 if (unlikely(ret < 0)) {
2005 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
2010 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2012 feature_count = le16_to_cpu(desc->wCount);
2013 if (type == FFS_OS_DESC_EXT_COMPAT &&
2014 (feature_count > 255 || desc->Reserved))
2020 * Process all function/property descriptors
2021 * of this Feature Descriptor
2023 ret = ffs_do_single_os_desc(data, len, type,
2024 feature_count, entity, priv, desc);
2025 if (unlikely(ret < 0)) {
2026 pr_debug("%s returns %d\n", __func__, ret);
2037 * Validate contents of the buffer from userspace related to OS descriptors.
2039 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2040 struct usb_os_desc_header *h, void *data,
2041 unsigned len, void *priv)
2043 struct ffs_data *ffs = priv;
2049 case FFS_OS_DESC_EXT_COMPAT: {
2050 struct usb_ext_compat_desc *d = data;
2053 if (len < sizeof(*d) ||
2054 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2057 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2058 if (d->Reserved2[i])
2061 length = sizeof(struct usb_ext_compat_desc);
2064 case FFS_OS_DESC_EXT_PROP: {
2065 struct usb_ext_prop_desc *d = data;
2069 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2071 length = le32_to_cpu(d->dwSize);
2072 type = le32_to_cpu(d->dwPropertyDataType);
2073 if (type < USB_EXT_PROP_UNICODE ||
2074 type > USB_EXT_PROP_UNICODE_MULTI) {
2075 pr_vdebug("unsupported os descriptor property type: %d",
2079 pnl = le16_to_cpu(d->wPropertyNameLength);
2080 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2081 if (length != 14 + pnl + pdl) {
2082 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2083 length, pnl, pdl, type);
2086 ++ffs->ms_os_descs_ext_prop_count;
2087 /* property name reported to the host as "WCHAR"s */
2088 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2089 ffs->ms_os_descs_ext_prop_data_len += pdl;
2093 pr_vdebug("unknown descriptor: %d\n", type);
2099 static int __ffs_data_got_descs(struct ffs_data *ffs,
2100 char *const _data, size_t len)
2102 char *data = _data, *raw_descs;
2103 unsigned os_descs_count = 0, counts[3], flags;
2104 int ret = -EINVAL, i;
2105 struct ffs_desc_helper helper;
2109 if (get_unaligned_le32(data + 4) != len)
2112 switch (get_unaligned_le32(data)) {
2113 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2114 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2118 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2119 flags = get_unaligned_le32(data + 8);
2120 ffs->user_flags = flags;
2121 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2122 FUNCTIONFS_HAS_HS_DESC |
2123 FUNCTIONFS_HAS_SS_DESC |
2124 FUNCTIONFS_HAS_MS_OS_DESC |
2125 FUNCTIONFS_VIRTUAL_ADDR |
2126 FUNCTIONFS_EVENTFD)) {
2137 if (flags & FUNCTIONFS_EVENTFD) {
2141 eventfd_ctx_fdget((int)get_unaligned_le32(data));
2142 if (IS_ERR(ffs->ffs_eventfd)) {
2143 ret = PTR_ERR(ffs->ffs_eventfd);
2144 ffs->ffs_eventfd = NULL;
2151 /* Read fs_count, hs_count and ss_count (if present) */
2152 for (i = 0; i < 3; ++i) {
2153 if (!(flags & (1 << i))) {
2155 } else if (len < 4) {
2158 counts[i] = get_unaligned_le32(data);
2163 if (flags & (1 << i)) {
2164 os_descs_count = get_unaligned_le32(data);
2169 /* Read descriptors */
2172 for (i = 0; i < 3; ++i) {
2175 helper.interfaces_count = 0;
2176 helper.eps_count = 0;
2177 ret = ffs_do_descs(counts[i], data, len,
2178 __ffs_data_do_entity, &helper);
2181 if (!ffs->eps_count && !ffs->interfaces_count) {
2182 ffs->eps_count = helper.eps_count;
2183 ffs->interfaces_count = helper.interfaces_count;
2185 if (ffs->eps_count != helper.eps_count) {
2189 if (ffs->interfaces_count != helper.interfaces_count) {
2197 if (os_descs_count) {
2198 ret = ffs_do_os_descs(os_descs_count, data, len,
2199 __ffs_data_do_os_desc, ffs);
2206 if (raw_descs == data || len) {
2211 ffs->raw_descs_data = _data;
2212 ffs->raw_descs = raw_descs;
2213 ffs->raw_descs_length = data - raw_descs;
2214 ffs->fs_descs_count = counts[0];
2215 ffs->hs_descs_count = counts[1];
2216 ffs->ss_descs_count = counts[2];
2217 ffs->ms_os_descs_count = os_descs_count;
2226 static int __ffs_data_got_strings(struct ffs_data *ffs,
2227 char *const _data, size_t len)
2229 u32 str_count, needed_count, lang_count;
2230 struct usb_gadget_strings **stringtabs, *t;
2231 struct usb_string *strings, *s;
2232 const char *data = _data;
2236 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2237 get_unaligned_le32(data + 4) != len))
2239 str_count = get_unaligned_le32(data + 8);
2240 lang_count = get_unaligned_le32(data + 12);
2242 /* if one is zero the other must be zero */
2243 if (unlikely(!str_count != !lang_count))
2246 /* Do we have at least as many strings as descriptors need? */
2247 needed_count = ffs->strings_count;
2248 if (unlikely(str_count < needed_count))
2252 * If we don't need any strings just return and free all
2255 if (!needed_count) {
2260 /* Allocate everything in one chunk so there's less maintenance. */
2264 vla_item(d, struct usb_gadget_strings *, stringtabs,
2266 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2267 vla_item(d, struct usb_string, strings,
2268 lang_count*(needed_count+1));
2270 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2272 if (unlikely(!vlabuf)) {
2277 /* Initialize the VLA pointers */
2278 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2279 t = vla_ptr(vlabuf, d, stringtab);
2282 *stringtabs++ = t++;
2286 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2287 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2288 t = vla_ptr(vlabuf, d, stringtab);
2289 s = vla_ptr(vlabuf, d, strings);
2293 /* For each language */
2297 do { /* lang_count > 0 so we can use do-while */
2298 unsigned needed = needed_count;
2300 if (unlikely(len < 3))
2302 t->language = get_unaligned_le16(data);
2309 /* For each string */
2310 do { /* str_count > 0 so we can use do-while */
2311 size_t length = strnlen(data, len);
2313 if (unlikely(length == len))
2317 * User may provide more strings then we need,
2318 * if that's the case we simply ignore the
2321 if (likely(needed)) {
2323 * s->id will be set while adding
2324 * function to configuration so for
2325 * now just leave garbage here.
2334 } while (--str_count);
2336 s->id = 0; /* terminator */
2340 } while (--lang_count);
2342 /* Some garbage left? */
2347 ffs->stringtabs = stringtabs;
2348 ffs->raw_strings = _data;
2360 /* Events handling and management *******************************************/
2362 static void __ffs_event_add(struct ffs_data *ffs,
2363 enum usb_functionfs_event_type type)
2365 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2369 * Abort any unhandled setup
2371 * We do not need to worry about some cmpxchg() changing value
2372 * of ffs->setup_state without holding the lock because when
2373 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2374 * the source does nothing.
2376 if (ffs->setup_state == FFS_SETUP_PENDING)
2377 ffs->setup_state = FFS_SETUP_CANCELLED;
2380 * Logic of this function guarantees that there are at most four pending
2381 * evens on ffs->ev.types queue. This is important because the queue
2382 * has space for four elements only and __ffs_ep0_read_events function
2383 * depends on that limit as well. If more event types are added, those
2384 * limits have to be revisited or guaranteed to still hold.
2387 case FUNCTIONFS_RESUME:
2388 rem_type2 = FUNCTIONFS_SUSPEND;
2390 case FUNCTIONFS_SUSPEND:
2391 case FUNCTIONFS_SETUP:
2393 /* Discard all similar events */
2396 case FUNCTIONFS_BIND:
2397 case FUNCTIONFS_UNBIND:
2398 case FUNCTIONFS_DISABLE:
2399 case FUNCTIONFS_ENABLE:
2400 /* Discard everything other then power management. */
2401 rem_type1 = FUNCTIONFS_SUSPEND;
2402 rem_type2 = FUNCTIONFS_RESUME;
2407 WARN(1, "%d: unknown event, this should not happen\n", type);
2412 u8 *ev = ffs->ev.types, *out = ev;
2413 unsigned n = ffs->ev.count;
2414 for (; n; --n, ++ev)
2415 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2418 pr_vdebug("purging event %d\n", *ev);
2419 ffs->ev.count = out - ffs->ev.types;
2422 pr_vdebug("adding event %d\n", type);
2423 ffs->ev.types[ffs->ev.count++] = type;
2424 wake_up_locked(&ffs->ev.waitq);
2425 if (ffs->ffs_eventfd)
2426 eventfd_signal(ffs->ffs_eventfd, 1);
2429 static void ffs_event_add(struct ffs_data *ffs,
2430 enum usb_functionfs_event_type type)
2432 unsigned long flags;
2433 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2434 __ffs_event_add(ffs, type);
2435 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2438 /* Bind/unbind USB function hooks *******************************************/
2440 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2444 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2445 if (ffs->eps_addrmap[i] == endpoint_address)
2450 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2451 struct usb_descriptor_header *desc,
2454 struct usb_endpoint_descriptor *ds = (void *)desc;
2455 struct ffs_function *func = priv;
2456 struct ffs_ep *ffs_ep;
2457 unsigned ep_desc_id;
2459 static const char *speed_names[] = { "full", "high", "super" };
2461 if (type != FFS_DESCRIPTOR)
2465 * If ss_descriptors is not NULL, we are reading super speed
2466 * descriptors; if hs_descriptors is not NULL, we are reading high
2467 * speed descriptors; otherwise, we are reading full speed
2470 if (func->function.ss_descriptors) {
2472 func->function.ss_descriptors[(long)valuep] = desc;
2473 } else if (func->function.hs_descriptors) {
2475 func->function.hs_descriptors[(long)valuep] = desc;
2478 func->function.fs_descriptors[(long)valuep] = desc;
2481 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2484 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2488 ffs_ep = func->eps + idx;
2490 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2491 pr_err("two %sspeed descriptors for EP %d\n",
2492 speed_names[ep_desc_id],
2493 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2496 ffs_ep->descs[ep_desc_id] = ds;
2498 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2500 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2501 if (!ds->wMaxPacketSize)
2502 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2504 struct usb_request *req;
2506 u8 bEndpointAddress;
2509 * We back up bEndpointAddress because autoconfig overwrites
2510 * it with physical endpoint address.
2512 bEndpointAddress = ds->bEndpointAddress;
2513 pr_vdebug("autoconfig\n");
2514 ep = usb_ep_autoconfig(func->gadget, ds);
2517 ep->driver_data = func->eps + idx;
2519 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2525 func->eps_revmap[ds->bEndpointAddress &
2526 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2528 * If we use virtual address mapping, we restore
2529 * original bEndpointAddress value.
2531 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2532 ds->bEndpointAddress = bEndpointAddress;
2534 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2539 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2540 struct usb_descriptor_header *desc,
2543 struct ffs_function *func = priv;
2549 case FFS_DESCRIPTOR:
2550 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2555 if (func->interfaces_nums[idx] < 0) {
2556 int id = usb_interface_id(func->conf, &func->function);
2557 if (unlikely(id < 0))
2559 func->interfaces_nums[idx] = id;
2561 newValue = func->interfaces_nums[idx];
2565 /* String' IDs are allocated when fsf_data is bound to cdev */
2566 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2571 * USB_DT_ENDPOINT are handled in
2572 * __ffs_func_bind_do_descs().
2574 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2577 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2578 if (unlikely(!func->eps[idx].ep))
2582 struct usb_endpoint_descriptor **descs;
2583 descs = func->eps[idx].descs;
2584 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2589 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2594 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2595 struct usb_os_desc_header *h, void *data,
2596 unsigned len, void *priv)
2598 struct ffs_function *func = priv;
2602 case FFS_OS_DESC_EXT_COMPAT: {
2603 struct usb_ext_compat_desc *desc = data;
2604 struct usb_os_desc_table *t;
2606 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2607 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2608 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2609 ARRAY_SIZE(desc->CompatibleID) +
2610 ARRAY_SIZE(desc->SubCompatibleID));
2611 length = sizeof(*desc);
2614 case FFS_OS_DESC_EXT_PROP: {
2615 struct usb_ext_prop_desc *desc = data;
2616 struct usb_os_desc_table *t;
2617 struct usb_os_desc_ext_prop *ext_prop;
2618 char *ext_prop_name;
2619 char *ext_prop_data;
2621 t = &func->function.os_desc_table[h->interface];
2622 t->if_id = func->interfaces_nums[h->interface];
2624 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2625 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2627 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2628 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2629 ext_prop->data_len = le32_to_cpu(*(u32 *)
2630 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2631 length = ext_prop->name_len + ext_prop->data_len + 14;
2633 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2634 func->ffs->ms_os_descs_ext_prop_name_avail +=
2637 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2638 func->ffs->ms_os_descs_ext_prop_data_avail +=
2640 memcpy(ext_prop_data,
2641 usb_ext_prop_data_ptr(data, ext_prop->name_len),
2642 ext_prop->data_len);
2643 /* unicode data reported to the host as "WCHAR"s */
2644 switch (ext_prop->type) {
2645 case USB_EXT_PROP_UNICODE:
2646 case USB_EXT_PROP_UNICODE_ENV:
2647 case USB_EXT_PROP_UNICODE_LINK:
2648 case USB_EXT_PROP_UNICODE_MULTI:
2649 ext_prop->data_len *= 2;
2652 ext_prop->data = ext_prop_data;
2654 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2655 ext_prop->name_len);
2656 /* property name reported to the host as "WCHAR"s */
2657 ext_prop->name_len *= 2;
2658 ext_prop->name = ext_prop_name;
2660 t->os_desc->ext_prop_len +=
2661 ext_prop->name_len + ext_prop->data_len + 14;
2662 ++t->os_desc->ext_prop_count;
2663 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2667 pr_vdebug("unknown descriptor: %d\n", type);
2673 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2674 struct usb_configuration *c)
2676 struct ffs_function *func = ffs_func_from_usb(f);
2677 struct f_fs_opts *ffs_opts =
2678 container_of(f->fi, struct f_fs_opts, func_inst);
2684 * Legacy gadget triggers binding in functionfs_ready_callback,
2685 * which already uses locking; taking the same lock here would
2688 * Configfs-enabled gadgets however do need ffs_dev_lock.
2690 if (!ffs_opts->no_configfs)
2692 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2693 func->ffs = ffs_opts->dev->ffs_data;
2694 if (!ffs_opts->no_configfs)
2697 return ERR_PTR(ret);
2700 func->gadget = c->cdev->gadget;
2703 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2704 * configurations are bound in sequence with list_for_each_entry,
2705 * in each configuration its functions are bound in sequence
2706 * with list_for_each_entry, so we assume no race condition
2707 * with regard to ffs_opts->bound access
2709 if (!ffs_opts->refcnt) {
2710 ret = functionfs_bind(func->ffs, c->cdev);
2712 return ERR_PTR(ret);
2715 func->function.strings = func->ffs->stringtabs;
2720 static int _ffs_func_bind(struct usb_configuration *c,
2721 struct usb_function *f)
2723 struct ffs_function *func = ffs_func_from_usb(f);
2724 struct ffs_data *ffs = func->ffs;
2726 const int full = !!func->ffs->fs_descs_count;
2727 const int high = gadget_is_dualspeed(func->gadget) &&
2728 func->ffs->hs_descs_count;
2729 const int super = gadget_is_superspeed(func->gadget) &&
2730 func->ffs->ss_descs_count;
2732 int fs_len, hs_len, ss_len, ret, i;
2734 /* Make it a single chunk, less management later on */
2736 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2737 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2738 full ? ffs->fs_descs_count + 1 : 0);
2739 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2740 high ? ffs->hs_descs_count + 1 : 0);
2741 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2742 super ? ffs->ss_descs_count + 1 : 0);
2743 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2744 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2745 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2746 vla_item_with_sz(d, char[16], ext_compat,
2747 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2748 vla_item_with_sz(d, struct usb_os_desc, os_desc,
2749 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2750 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2751 ffs->ms_os_descs_ext_prop_count);
2752 vla_item_with_sz(d, char, ext_prop_name,
2753 ffs->ms_os_descs_ext_prop_name_len);
2754 vla_item_with_sz(d, char, ext_prop_data,
2755 ffs->ms_os_descs_ext_prop_data_len);
2756 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2761 /* Has descriptors only for speeds gadget does not support */
2762 if (unlikely(!(full | high | super)))
2765 /* Allocate a single chunk, less management later on */
2766 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2767 if (unlikely(!vlabuf))
2770 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2771 ffs->ms_os_descs_ext_prop_name_avail =
2772 vla_ptr(vlabuf, d, ext_prop_name);
2773 ffs->ms_os_descs_ext_prop_data_avail =
2774 vla_ptr(vlabuf, d, ext_prop_data);
2776 /* Copy descriptors */
2777 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2778 ffs->raw_descs_length);
2780 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2781 for (ret = ffs->eps_count; ret; --ret) {
2784 ptr = vla_ptr(vlabuf, d, eps);
2789 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2791 func->eps = vla_ptr(vlabuf, d, eps);
2792 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2795 * Go through all the endpoint descriptors and allocate
2796 * endpoints first, so that later we can rewrite the endpoint
2797 * numbers without worrying that it may be described later on.
2800 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2801 fs_len = ffs_do_descs(ffs->fs_descs_count,
2802 vla_ptr(vlabuf, d, raw_descs),
2804 __ffs_func_bind_do_descs, func);
2805 if (unlikely(fs_len < 0)) {
2814 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2815 hs_len = ffs_do_descs(ffs->hs_descs_count,
2816 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2817 d_raw_descs__sz - fs_len,
2818 __ffs_func_bind_do_descs, func);
2819 if (unlikely(hs_len < 0)) {
2827 if (likely(super)) {
2828 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2829 ss_len = ffs_do_descs(ffs->ss_descs_count,
2830 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2831 d_raw_descs__sz - fs_len - hs_len,
2832 __ffs_func_bind_do_descs, func);
2833 if (unlikely(ss_len < 0)) {
2842 * Now handle interface numbers allocation and interface and
2843 * endpoint numbers rewriting. We can do that in one go
2846 ret = ffs_do_descs(ffs->fs_descs_count +
2847 (high ? ffs->hs_descs_count : 0) +
2848 (super ? ffs->ss_descs_count : 0),
2849 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2850 __ffs_func_bind_do_nums, func);
2851 if (unlikely(ret < 0))
2854 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2855 if (c->cdev->use_os_string)
2856 for (i = 0; i < ffs->interfaces_count; ++i) {
2857 struct usb_os_desc *desc;
2859 desc = func->function.os_desc_table[i].os_desc =
2860 vla_ptr(vlabuf, d, os_desc) +
2861 i * sizeof(struct usb_os_desc);
2862 desc->ext_compat_id =
2863 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2864 INIT_LIST_HEAD(&desc->ext_prop);
2866 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2867 vla_ptr(vlabuf, d, raw_descs) +
2868 fs_len + hs_len + ss_len,
2869 d_raw_descs__sz - fs_len - hs_len - ss_len,
2870 __ffs_func_bind_do_os_desc, func);
2871 if (unlikely(ret < 0))
2873 func->function.os_desc_n =
2874 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2876 /* And we're done */
2877 ffs_event_add(ffs, FUNCTIONFS_BIND);
2881 /* XXX Do we need to release all claimed endpoints here? */
2885 static int ffs_func_bind(struct usb_configuration *c,
2886 struct usb_function *f)
2888 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2889 struct ffs_function *func = ffs_func_from_usb(f);
2892 if (IS_ERR(ffs_opts))
2893 return PTR_ERR(ffs_opts);
2895 ret = _ffs_func_bind(c, f);
2896 if (ret && !--ffs_opts->refcnt)
2897 functionfs_unbind(func->ffs);
2903 /* Other USB function hooks *************************************************/
2905 static void ffs_reset_work(struct work_struct *work)
2907 struct ffs_data *ffs = container_of(work,
2908 struct ffs_data, reset_work);
2909 ffs_data_reset(ffs);
2912 static int ffs_func_set_alt(struct usb_function *f,
2913 unsigned interface, unsigned alt)
2915 struct ffs_function *func = ffs_func_from_usb(f);
2916 struct ffs_data *ffs = func->ffs;
2919 if (alt != (unsigned)-1) {
2920 intf = ffs_func_revmap_intf(func, interface);
2921 if (unlikely(intf < 0))
2926 ffs_func_eps_disable(ffs->func);
2928 if (ffs->state == FFS_DEACTIVATED) {
2929 ffs->state = FFS_CLOSING;
2930 INIT_WORK(&ffs->reset_work, ffs_reset_work);
2931 schedule_work(&ffs->reset_work);
2935 if (ffs->state != FFS_ACTIVE)
2938 if (alt == (unsigned)-1) {
2940 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2945 ret = ffs_func_eps_enable(func);
2946 if (likely(ret >= 0))
2947 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2951 static void ffs_func_disable(struct usb_function *f)
2953 ffs_func_set_alt(f, 0, (unsigned)-1);
2956 static int ffs_func_setup(struct usb_function *f,
2957 const struct usb_ctrlrequest *creq)
2959 struct ffs_function *func = ffs_func_from_usb(f);
2960 struct ffs_data *ffs = func->ffs;
2961 unsigned long flags;
2966 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2967 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2968 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2969 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2970 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2973 * Most requests directed to interface go through here
2974 * (notable exceptions are set/get interface) so we need to
2975 * handle them. All other either handled by composite or
2976 * passed to usb_configuration->setup() (if one is set). No
2977 * matter, we will handle requests directed to endpoint here
2978 * as well (as it's straightforward) but what to do with any
2981 if (ffs->state != FFS_ACTIVE)
2984 switch (creq->bRequestType & USB_RECIP_MASK) {
2985 case USB_RECIP_INTERFACE:
2986 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2987 if (unlikely(ret < 0))
2991 case USB_RECIP_ENDPOINT:
2992 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2993 if (unlikely(ret < 0))
2995 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2996 ret = func->ffs->eps_addrmap[ret];
3003 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
3004 ffs->ev.setup = *creq;
3005 ffs->ev.setup.wIndex = cpu_to_le16(ret);
3006 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
3007 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
3012 static void ffs_func_suspend(struct usb_function *f)
3015 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
3018 static void ffs_func_resume(struct usb_function *f)
3021 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
3025 /* Endpoint and interface numbers reverse mapping ***************************/
3027 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
3029 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
3030 return num ? num : -EDOM;
3033 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
3035 short *nums = func->interfaces_nums;
3036 unsigned count = func->ffs->interfaces_count;
3038 for (; count; --count, ++nums) {
3039 if (*nums >= 0 && *nums == intf)
3040 return nums - func->interfaces_nums;
3047 /* Devices management *******************************************************/
3049 static LIST_HEAD(ffs_devices);
3051 static struct ffs_dev *_ffs_do_find_dev(const char *name)
3053 struct ffs_dev *dev;
3055 list_for_each_entry(dev, &ffs_devices, entry) {
3056 if (!dev->name || !name)
3058 if (strcmp(dev->name, name) == 0)
3066 * ffs_lock must be taken by the caller of this function
3068 static struct ffs_dev *_ffs_get_single_dev(void)
3070 struct ffs_dev *dev;
3072 if (list_is_singular(&ffs_devices)) {
3073 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3082 * ffs_lock must be taken by the caller of this function
3084 static struct ffs_dev *_ffs_find_dev(const char *name)
3086 struct ffs_dev *dev;
3088 dev = _ffs_get_single_dev();
3092 return _ffs_do_find_dev(name);
3095 /* Configfs support *********************************************************/
3097 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3099 return container_of(to_config_group(item), struct f_fs_opts,
3103 static void ffs_attr_release(struct config_item *item)
3105 struct f_fs_opts *opts = to_ffs_opts(item);
3107 usb_put_function_instance(&opts->func_inst);
3110 static struct configfs_item_operations ffs_item_ops = {
3111 .release = ffs_attr_release,
3114 static struct config_item_type ffs_func_type = {
3115 .ct_item_ops = &ffs_item_ops,
3116 .ct_owner = THIS_MODULE,
3120 /* Function registration interface ******************************************/
3122 static void ffs_free_inst(struct usb_function_instance *f)
3124 struct f_fs_opts *opts;
3126 opts = to_f_fs_opts(f);
3128 _ffs_free_dev(opts->dev);
3133 #define MAX_INST_NAME_LEN 40
3135 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3137 struct f_fs_opts *opts;
3142 name_len = strlen(name) + 1;
3143 if (name_len > MAX_INST_NAME_LEN)
3144 return -ENAMETOOLONG;
3146 ptr = kstrndup(name, name_len, GFP_KERNEL);
3150 opts = to_f_fs_opts(fi);
3155 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3156 ret = _ffs_name_dev(opts->dev, ptr);
3162 opts->dev->name_allocated = true;
3171 static struct usb_function_instance *ffs_alloc_inst(void)
3173 struct f_fs_opts *opts;
3174 struct ffs_dev *dev;
3176 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3178 return ERR_PTR(-ENOMEM);
3180 opts->func_inst.set_inst_name = ffs_set_inst_name;
3181 opts->func_inst.free_func_inst = ffs_free_inst;
3183 dev = _ffs_alloc_dev();
3187 return ERR_CAST(dev);
3192 config_group_init_type_name(&opts->func_inst.group, "",
3194 return &opts->func_inst;
3197 static void ffs_free(struct usb_function *f)
3199 kfree(ffs_func_from_usb(f));
3202 static void ffs_func_unbind(struct usb_configuration *c,
3203 struct usb_function *f)
3205 struct ffs_function *func = ffs_func_from_usb(f);
3206 struct ffs_data *ffs = func->ffs;
3207 struct f_fs_opts *opts =
3208 container_of(f->fi, struct f_fs_opts, func_inst);
3209 struct ffs_ep *ep = func->eps;
3210 unsigned count = ffs->eps_count;
3211 unsigned long flags;
3214 if (ffs->func == func) {
3215 ffs_func_eps_disable(func);
3219 if (!--opts->refcnt)
3220 functionfs_unbind(ffs);
3222 /* cleanup after autoconfig */
3223 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3225 if (ep->ep && ep->req)
3226 usb_ep_free_request(ep->ep, ep->req);
3230 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3234 * eps, descriptors and interfaces_nums are allocated in the
3235 * same chunk so only one free is required.
3237 func->function.fs_descriptors = NULL;
3238 func->function.hs_descriptors = NULL;
3239 func->function.ss_descriptors = NULL;
3240 func->interfaces_nums = NULL;
3242 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3245 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3247 struct ffs_function *func;
3251 func = kzalloc(sizeof(*func), GFP_KERNEL);
3252 if (unlikely(!func))
3253 return ERR_PTR(-ENOMEM);
3255 func->function.name = "Function FS Gadget";
3257 func->function.bind = ffs_func_bind;
3258 func->function.unbind = ffs_func_unbind;
3259 func->function.set_alt = ffs_func_set_alt;
3260 func->function.disable = ffs_func_disable;
3261 func->function.setup = ffs_func_setup;
3262 func->function.suspend = ffs_func_suspend;
3263 func->function.resume = ffs_func_resume;
3264 func->function.free_func = ffs_free;
3266 return &func->function;
3270 * ffs_lock must be taken by the caller of this function
3272 static struct ffs_dev *_ffs_alloc_dev(void)
3274 struct ffs_dev *dev;
3277 if (_ffs_get_single_dev())
3278 return ERR_PTR(-EBUSY);
3280 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3282 return ERR_PTR(-ENOMEM);
3284 if (list_empty(&ffs_devices)) {
3285 ret = functionfs_init();
3288 return ERR_PTR(ret);
3292 list_add(&dev->entry, &ffs_devices);
3298 * ffs_lock must be taken by the caller of this function
3299 * The caller is responsible for "name" being available whenever f_fs needs it
3301 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3303 struct ffs_dev *existing;
3305 existing = _ffs_do_find_dev(name);
3315 * The caller is responsible for "name" being available whenever f_fs needs it
3317 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3322 ret = _ffs_name_dev(dev, name);
3327 EXPORT_SYMBOL_GPL(ffs_name_dev);
3329 int ffs_single_dev(struct ffs_dev *dev)
3336 if (!list_is_singular(&ffs_devices))
3344 EXPORT_SYMBOL_GPL(ffs_single_dev);
3347 * ffs_lock must be taken by the caller of this function
3349 static void _ffs_free_dev(struct ffs_dev *dev)
3351 list_del(&dev->entry);
3352 if (dev->name_allocated)
3355 if (list_empty(&ffs_devices))
3356 functionfs_cleanup();
3359 static void *ffs_acquire_dev(const char *dev_name)
3361 struct ffs_dev *ffs_dev;
3366 ffs_dev = _ffs_find_dev(dev_name);
3368 ffs_dev = ERR_PTR(-ENOENT);
3369 else if (ffs_dev->mounted)
3370 ffs_dev = ERR_PTR(-EBUSY);
3371 else if (ffs_dev->ffs_acquire_dev_callback &&
3372 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3373 ffs_dev = ERR_PTR(-ENOENT);
3375 ffs_dev->mounted = true;
3381 static void ffs_release_dev(struct ffs_data *ffs_data)
3383 struct ffs_dev *ffs_dev;
3388 ffs_dev = ffs_data->private_data;
3390 ffs_dev->mounted = false;
3392 if (ffs_dev->ffs_release_dev_callback)
3393 ffs_dev->ffs_release_dev_callback(ffs_dev);
3399 static int ffs_ready(struct ffs_data *ffs)
3401 struct ffs_dev *ffs_obj;
3407 ffs_obj = ffs->private_data;
3412 if (WARN_ON(ffs_obj->desc_ready)) {
3417 ffs_obj->desc_ready = true;
3418 ffs_obj->ffs_data = ffs;
3420 if (ffs_obj->ffs_ready_callback) {
3421 ret = ffs_obj->ffs_ready_callback(ffs);
3426 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
3432 static void ffs_closed(struct ffs_data *ffs)
3434 struct ffs_dev *ffs_obj;
3435 struct f_fs_opts *opts;
3440 ffs_obj = ffs->private_data;
3444 ffs_obj->desc_ready = false;
3446 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags) &&
3447 ffs_obj->ffs_closed_callback)
3448 ffs_obj->ffs_closed_callback(ffs);
3451 opts = ffs_obj->opts;
3455 if (opts->no_configfs || !opts->func_inst.group.cg_item.ci_parent
3456 || !atomic_read(&opts->func_inst.group.cg_item.ci_kref.refcount))
3459 unregister_gadget_item(ffs_obj->opts->
3460 func_inst.group.cg_item.ci_parent->ci_parent);
3465 /* Misc helper functions ****************************************************/
3467 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3470 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3471 : mutex_lock_interruptible(mutex);
3474 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3481 data = kmalloc(len, GFP_KERNEL);
3482 if (unlikely(!data))
3483 return ERR_PTR(-ENOMEM);
3485 if (unlikely(copy_from_user(data, buf, len))) {
3487 return ERR_PTR(-EFAULT);
3490 pr_vdebug("Buffer from user space:\n");
3491 ffs_dump_mem("", data, len);
3496 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3497 MODULE_LICENSE("GPL");
3498 MODULE_AUTHOR("Michal Nazarewicz");