2 * f_fs.c -- user mode file system API for USB composite function controllers
4 * Copyright (C) 2010 Samsung Electronics
5 * Author: Michal Nazarewicz <mina86@mina86.com>
7 * Based on inode.c (GadgetFS) which was:
8 * Copyright (C) 2003-2004 David Brownell
9 * Copyright (C) 2003 Agilent Technologies
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
19 /* #define VERBOSE_DEBUG */
21 #include <linux/blkdev.h>
22 #include <linux/pagemap.h>
23 #include <linux/export.h>
24 #include <linux/hid.h>
25 #include <linux/module.h>
26 #include <asm/unaligned.h>
28 #include <linux/usb/composite.h>
29 #include <linux/usb/functionfs.h>
31 #include <linux/aio.h>
32 #include <linux/mmu_context.h>
33 #include <linux/poll.h>
37 #include "u_os_desc.h"
40 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
42 /* Reference counter handling */
43 static void ffs_data_get(struct ffs_data *ffs);
44 static void ffs_data_put(struct ffs_data *ffs);
45 /* Creates new ffs_data object. */
46 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
48 /* Opened counter handling. */
49 static void ffs_data_opened(struct ffs_data *ffs);
50 static void ffs_data_closed(struct ffs_data *ffs);
52 /* Called with ffs->mutex held; take over ownership of data. */
53 static int __must_check
54 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
55 static int __must_check
56 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
59 /* The function structure ***************************************************/
64 struct usb_configuration *conf;
65 struct usb_gadget *gadget;
70 short *interfaces_nums;
72 struct usb_function function;
76 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
78 return container_of(f, struct ffs_function, function);
82 static inline enum ffs_setup_state
83 ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
85 return (enum ffs_setup_state)
86 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
90 static void ffs_func_eps_disable(struct ffs_function *func);
91 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
93 static int ffs_func_bind(struct usb_configuration *,
94 struct usb_function *);
95 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
96 static void ffs_func_disable(struct usb_function *);
97 static int ffs_func_setup(struct usb_function *,
98 const struct usb_ctrlrequest *);
99 static void ffs_func_suspend(struct usb_function *);
100 static void ffs_func_resume(struct usb_function *);
103 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
104 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
107 /* The endpoints structures *************************************************/
110 struct usb_ep *ep; /* P: ffs->eps_lock */
111 struct usb_request *req; /* P: epfile->mutex */
113 /* [0]: full speed, [1]: high speed, [2]: super speed */
114 struct usb_endpoint_descriptor *descs[3];
118 int status; /* P: epfile->mutex */
122 /* Protects ep->ep and ep->req. */
124 wait_queue_head_t wait;
126 struct ffs_data *ffs;
127 struct ffs_ep *ep; /* P: ffs->eps_lock */
129 struct dentry *dentry;
133 unsigned char in; /* P: ffs->eps_lock */
134 unsigned char isoc; /* P: ffs->eps_lock */
139 /* ffs_io_data structure ***************************************************/
146 const struct iovec *iovec;
147 unsigned long nr_segs;
151 struct mm_struct *mm;
152 struct work_struct work;
155 struct usb_request *req;
158 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
159 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
161 static struct inode *__must_check
162 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
163 const struct file_operations *fops,
164 struct dentry **dentry_p);
166 /* Devices management *******************************************************/
168 DEFINE_MUTEX(ffs_lock);
169 EXPORT_SYMBOL_GPL(ffs_lock);
171 static struct ffs_dev *_ffs_find_dev(const char *name);
172 static struct ffs_dev *_ffs_alloc_dev(void);
173 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
174 static void _ffs_free_dev(struct ffs_dev *dev);
175 static void *ffs_acquire_dev(const char *dev_name);
176 static void ffs_release_dev(struct ffs_data *ffs_data);
177 static int ffs_ready(struct ffs_data *ffs);
178 static void ffs_closed(struct ffs_data *ffs);
180 /* Misc helper functions ****************************************************/
182 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
183 __attribute__((warn_unused_result, nonnull));
184 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
185 __attribute__((warn_unused_result, nonnull));
188 /* Control file aka ep0 *****************************************************/
190 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
192 struct ffs_data *ffs = req->context;
194 complete_all(&ffs->ep0req_completion);
197 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
199 struct usb_request *req = ffs->ep0req;
202 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
204 spin_unlock_irq(&ffs->ev.waitq.lock);
210 * UDC layer requires to provide a buffer even for ZLP, but should
211 * not use it at all. Let's provide some poisoned pointer to catch
212 * possible bug in the driver.
214 if (req->buf == NULL)
215 req->buf = (void *)0xDEADBABE;
217 reinit_completion(&ffs->ep0req_completion);
219 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
220 if (unlikely(ret < 0))
223 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
225 usb_ep_dequeue(ffs->gadget->ep0, req);
229 ffs->setup_state = FFS_NO_SETUP;
230 return req->status ? req->status : req->actual;
233 static int __ffs_ep0_stall(struct ffs_data *ffs)
235 if (ffs->ev.can_stall) {
236 pr_vdebug("ep0 stall\n");
237 usb_ep_set_halt(ffs->gadget->ep0);
238 ffs->setup_state = FFS_NO_SETUP;
241 pr_debug("bogus ep0 stall!\n");
246 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
247 size_t len, loff_t *ptr)
249 struct ffs_data *ffs = file->private_data;
255 /* Fast check if setup was canceled */
256 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
260 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
261 if (unlikely(ret < 0))
265 switch (ffs->state) {
266 case FFS_READ_DESCRIPTORS:
267 case FFS_READ_STRINGS:
269 if (unlikely(len < 16)) {
274 data = ffs_prepare_buffer(buf, len);
281 if (ffs->state == FFS_READ_DESCRIPTORS) {
282 pr_info("read descriptors\n");
283 ret = __ffs_data_got_descs(ffs, data, len);
284 if (unlikely(ret < 0))
287 ffs->state = FFS_READ_STRINGS;
290 pr_info("read strings\n");
291 ret = __ffs_data_got_strings(ffs, data, len);
292 if (unlikely(ret < 0))
295 ret = ffs_epfiles_create(ffs);
297 ffs->state = FFS_CLOSING;
301 ffs->state = FFS_ACTIVE;
302 mutex_unlock(&ffs->mutex);
304 ret = ffs_ready(ffs);
305 if (unlikely(ret < 0)) {
306 ffs->state = FFS_CLOSING;
310 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
318 * We're called from user space, we can use _irq
319 * rather then _irqsave
321 spin_lock_irq(&ffs->ev.waitq.lock);
322 switch (ffs_setup_state_clear_cancelled(ffs)) {
323 case FFS_SETUP_CANCELLED:
331 case FFS_SETUP_PENDING:
335 /* FFS_SETUP_PENDING */
336 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
337 spin_unlock_irq(&ffs->ev.waitq.lock);
338 ret = __ffs_ep0_stall(ffs);
342 /* FFS_SETUP_PENDING and not stall */
343 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
345 spin_unlock_irq(&ffs->ev.waitq.lock);
347 data = ffs_prepare_buffer(buf, len);
353 spin_lock_irq(&ffs->ev.waitq.lock);
356 * We are guaranteed to be still in FFS_ACTIVE state
357 * but the state of setup could have changed from
358 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
359 * to check for that. If that happened we copied data
360 * from user space in vain but it's unlikely.
362 * For sure we are not in FFS_NO_SETUP since this is
363 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
364 * transition can be performed and it's protected by
367 if (ffs_setup_state_clear_cancelled(ffs) ==
368 FFS_SETUP_CANCELLED) {
371 spin_unlock_irq(&ffs->ev.waitq.lock);
373 /* unlocks spinlock */
374 ret = __ffs_ep0_queue_wait(ffs, data, len);
384 mutex_unlock(&ffs->mutex);
388 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
392 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
395 struct usb_functionfs_event events[n];
398 memset(events, 0, sizeof events);
401 events[i].type = ffs->ev.types[i];
402 if (events[i].type == FUNCTIONFS_SETUP) {
403 events[i].u.setup = ffs->ev.setup;
404 ffs->setup_state = FFS_SETUP_PENDING;
408 if (n < ffs->ev.count) {
410 memmove(ffs->ev.types, ffs->ev.types + n,
411 ffs->ev.count * sizeof *ffs->ev.types);
416 spin_unlock_irq(&ffs->ev.waitq.lock);
417 mutex_unlock(&ffs->mutex);
419 return unlikely(__copy_to_user(buf, events, sizeof events))
420 ? -EFAULT : sizeof events;
423 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
424 size_t len, loff_t *ptr)
426 struct ffs_data *ffs = file->private_data;
433 /* Fast check if setup was canceled */
434 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
438 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
439 if (unlikely(ret < 0))
443 if (ffs->state != FFS_ACTIVE) {
449 * We're called from user space, we can use _irq rather then
452 spin_lock_irq(&ffs->ev.waitq.lock);
454 switch (ffs_setup_state_clear_cancelled(ffs)) {
455 case FFS_SETUP_CANCELLED:
460 n = len / sizeof(struct usb_functionfs_event);
466 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
471 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
477 return __ffs_ep0_read_events(ffs, buf,
478 min(n, (size_t)ffs->ev.count));
480 case FFS_SETUP_PENDING:
481 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
482 spin_unlock_irq(&ffs->ev.waitq.lock);
483 ret = __ffs_ep0_stall(ffs);
487 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
489 spin_unlock_irq(&ffs->ev.waitq.lock);
492 data = kmalloc(len, GFP_KERNEL);
493 if (unlikely(!data)) {
499 spin_lock_irq(&ffs->ev.waitq.lock);
501 /* See ffs_ep0_write() */
502 if (ffs_setup_state_clear_cancelled(ffs) ==
503 FFS_SETUP_CANCELLED) {
508 /* unlocks spinlock */
509 ret = __ffs_ep0_queue_wait(ffs, data, len);
510 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
519 spin_unlock_irq(&ffs->ev.waitq.lock);
521 mutex_unlock(&ffs->mutex);
526 static int ffs_ep0_open(struct inode *inode, struct file *file)
528 struct ffs_data *ffs = inode->i_private;
532 if (unlikely(ffs->state == FFS_CLOSING))
535 file->private_data = ffs;
536 ffs_data_opened(ffs);
541 static int ffs_ep0_release(struct inode *inode, struct file *file)
543 struct ffs_data *ffs = file->private_data;
547 ffs_data_closed(ffs);
552 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
554 struct ffs_data *ffs = file->private_data;
555 struct usb_gadget *gadget = ffs->gadget;
560 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
561 struct ffs_function *func = ffs->func;
562 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
563 } else if (gadget && gadget->ops->ioctl) {
564 ret = gadget->ops->ioctl(gadget, code, value);
572 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
574 struct ffs_data *ffs = file->private_data;
575 unsigned int mask = POLLWRNORM;
578 poll_wait(file, &ffs->ev.waitq, wait);
580 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
581 if (unlikely(ret < 0))
584 switch (ffs->state) {
585 case FFS_READ_DESCRIPTORS:
586 case FFS_READ_STRINGS:
591 switch (ffs->setup_state) {
597 case FFS_SETUP_PENDING:
598 case FFS_SETUP_CANCELLED:
599 mask |= (POLLIN | POLLOUT);
606 mutex_unlock(&ffs->mutex);
611 static const struct file_operations ffs_ep0_operations = {
614 .open = ffs_ep0_open,
615 .write = ffs_ep0_write,
616 .read = ffs_ep0_read,
617 .release = ffs_ep0_release,
618 .unlocked_ioctl = ffs_ep0_ioctl,
619 .poll = ffs_ep0_poll,
623 /* "Normal" endpoints operations ********************************************/
625 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
628 if (likely(req->context)) {
629 struct ffs_ep *ep = _ep->driver_data;
630 ep->status = req->status ? req->status : req->actual;
631 complete(req->context);
635 static void ffs_user_copy_worker(struct work_struct *work)
637 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
639 int ret = io_data->req->status ? io_data->req->status :
640 io_data->req->actual;
642 if (io_data->read && ret > 0) {
646 for (i = 0; i < io_data->nr_segs; i++) {
647 if (unlikely(copy_to_user(io_data->iovec[i].iov_base,
649 io_data->iovec[i].iov_len))) {
653 pos += io_data->iovec[i].iov_len;
655 unuse_mm(io_data->mm);
658 aio_complete(io_data->kiocb, ret, ret);
660 usb_ep_free_request(io_data->ep, io_data->req);
662 io_data->kiocb->private = NULL;
664 kfree(io_data->iovec);
669 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
670 struct usb_request *req)
672 struct ffs_io_data *io_data = req->context;
676 INIT_WORK(&io_data->work, ffs_user_copy_worker);
677 schedule_work(&io_data->work);
680 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
682 struct ffs_epfile *epfile = file->private_data;
685 ssize_t ret, data_len;
688 /* Are we still active? */
689 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
694 /* Wait for endpoint to be enabled */
697 if (file->f_flags & O_NONBLOCK) {
702 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
710 halt = (!io_data->read == !epfile->in);
711 if (halt && epfile->isoc) {
716 /* Allocate & copy */
719 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
720 * before the waiting completes, so do not assign to 'gadget' earlier
722 struct usb_gadget *gadget = epfile->ffs->gadget;
724 spin_lock_irq(&epfile->ffs->eps_lock);
725 /* In the meantime, endpoint got disabled or changed. */
726 if (epfile->ep != ep) {
727 spin_unlock_irq(&epfile->ffs->eps_lock);
731 * Controller may require buffer size to be aligned to
732 * maxpacketsize of an out endpoint.
734 data_len = io_data->read ?
735 usb_ep_align_maybe(gadget, ep->ep, io_data->len) :
737 spin_unlock_irq(&epfile->ffs->eps_lock);
739 data = kmalloc(data_len, GFP_KERNEL);
742 if (io_data->aio && !io_data->read) {
745 for (i = 0; i < io_data->nr_segs; i++) {
746 if (unlikely(copy_from_user(&data[pos],
747 io_data->iovec[i].iov_base,
748 io_data->iovec[i].iov_len))) {
752 pos += io_data->iovec[i].iov_len;
755 if (!io_data->read &&
756 unlikely(__copy_from_user(data, io_data->buf,
764 /* We will be using request */
765 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
769 spin_lock_irq(&epfile->ffs->eps_lock);
771 if (epfile->ep != ep) {
772 /* In the meantime, endpoint got disabled or changed. */
774 spin_unlock_irq(&epfile->ffs->eps_lock);
777 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
778 usb_ep_set_halt(ep->ep);
779 spin_unlock_irq(&epfile->ffs->eps_lock);
782 /* Fire the request */
783 struct usb_request *req;
786 req = usb_ep_alloc_request(ep->ep, GFP_KERNEL);
791 req->length = io_data->len;
794 io_data->ep = ep->ep;
797 req->context = io_data;
798 req->complete = ffs_epfile_async_io_complete;
800 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
802 usb_ep_free_request(ep->ep, req);
807 spin_unlock_irq(&epfile->ffs->eps_lock);
809 DECLARE_COMPLETION_ONSTACK(done);
813 req->length = io_data->len;
815 req->context = &done;
816 req->complete = ffs_epfile_io_complete;
818 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
820 spin_unlock_irq(&epfile->ffs->eps_lock);
822 if (unlikely(ret < 0)) {
825 wait_for_completion_interruptible(&done))) {
827 usb_ep_dequeue(ep->ep, req);
830 * XXX We may end up silently droping data
831 * here. Since data_len (i.e. req->length) may
832 * be bigger than len (after being rounded up
833 * to maxpacketsize), we may end up with more
834 * data then user space has space for.
837 if (io_data->read && ret > 0) {
838 ret = min_t(size_t, ret, io_data->len);
840 if (unlikely(copy_to_user(io_data->buf,
849 mutex_unlock(&epfile->mutex);
853 spin_unlock_irq(&epfile->ffs->eps_lock);
854 mutex_unlock(&epfile->mutex);
861 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
864 struct ffs_io_data io_data;
869 io_data.read = false;
870 io_data.buf = (char * __user)buf;
873 return ffs_epfile_io(file, &io_data);
877 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
879 struct ffs_io_data io_data;
888 return ffs_epfile_io(file, &io_data);
892 ffs_epfile_open(struct inode *inode, struct file *file)
894 struct ffs_epfile *epfile = inode->i_private;
898 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
901 file->private_data = epfile;
902 ffs_data_opened(epfile->ffs);
907 static int ffs_aio_cancel(struct kiocb *kiocb)
909 struct ffs_io_data *io_data = kiocb->private;
910 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
915 spin_lock_irq(&epfile->ffs->eps_lock);
917 if (likely(io_data && io_data->ep && io_data->req))
918 value = usb_ep_dequeue(io_data->ep, io_data->req);
922 spin_unlock_irq(&epfile->ffs->eps_lock);
927 static ssize_t ffs_epfile_aio_write(struct kiocb *kiocb,
928 const struct iovec *iovec,
929 unsigned long nr_segs, loff_t loff)
931 struct ffs_io_data *io_data;
935 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
936 if (unlikely(!io_data))
940 io_data->read = false;
941 io_data->kiocb = kiocb;
942 io_data->iovec = iovec;
943 io_data->nr_segs = nr_segs;
944 io_data->len = kiocb->ki_nbytes;
945 io_data->mm = current->mm;
947 kiocb->private = io_data;
949 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
951 return ffs_epfile_io(kiocb->ki_filp, io_data);
954 static ssize_t ffs_epfile_aio_read(struct kiocb *kiocb,
955 const struct iovec *iovec,
956 unsigned long nr_segs, loff_t loff)
958 struct ffs_io_data *io_data;
959 struct iovec *iovec_copy;
963 iovec_copy = kmalloc_array(nr_segs, sizeof(*iovec_copy), GFP_KERNEL);
964 if (unlikely(!iovec_copy))
967 memcpy(iovec_copy, iovec, sizeof(struct iovec)*nr_segs);
969 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
970 if (unlikely(!io_data)) {
976 io_data->read = true;
977 io_data->kiocb = kiocb;
978 io_data->iovec = iovec_copy;
979 io_data->nr_segs = nr_segs;
980 io_data->len = kiocb->ki_nbytes;
981 io_data->mm = current->mm;
983 kiocb->private = io_data;
985 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
987 return ffs_epfile_io(kiocb->ki_filp, io_data);
991 ffs_epfile_release(struct inode *inode, struct file *file)
993 struct ffs_epfile *epfile = inode->i_private;
997 ffs_data_closed(epfile->ffs);
1002 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1003 unsigned long value)
1005 struct ffs_epfile *epfile = file->private_data;
1010 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1013 spin_lock_irq(&epfile->ffs->eps_lock);
1014 if (likely(epfile->ep)) {
1016 case FUNCTIONFS_FIFO_STATUS:
1017 ret = usb_ep_fifo_status(epfile->ep->ep);
1019 case FUNCTIONFS_FIFO_FLUSH:
1020 usb_ep_fifo_flush(epfile->ep->ep);
1023 case FUNCTIONFS_CLEAR_HALT:
1024 ret = usb_ep_clear_halt(epfile->ep->ep);
1026 case FUNCTIONFS_ENDPOINT_REVMAP:
1027 ret = epfile->ep->num;
1035 spin_unlock_irq(&epfile->ffs->eps_lock);
1040 static const struct file_operations ffs_epfile_operations = {
1041 .llseek = no_llseek,
1043 .open = ffs_epfile_open,
1044 .write = ffs_epfile_write,
1045 .read = ffs_epfile_read,
1046 .aio_write = ffs_epfile_aio_write,
1047 .aio_read = ffs_epfile_aio_read,
1048 .release = ffs_epfile_release,
1049 .unlocked_ioctl = ffs_epfile_ioctl,
1053 /* File system and super block operations ***********************************/
1056 * Mounting the file system creates a controller file, used first for
1057 * function configuration then later for event monitoring.
1060 static struct inode *__must_check
1061 ffs_sb_make_inode(struct super_block *sb, void *data,
1062 const struct file_operations *fops,
1063 const struct inode_operations *iops,
1064 struct ffs_file_perms *perms)
1066 struct inode *inode;
1070 inode = new_inode(sb);
1072 if (likely(inode)) {
1073 struct timespec current_time = CURRENT_TIME;
1075 inode->i_ino = get_next_ino();
1076 inode->i_mode = perms->mode;
1077 inode->i_uid = perms->uid;
1078 inode->i_gid = perms->gid;
1079 inode->i_atime = current_time;
1080 inode->i_mtime = current_time;
1081 inode->i_ctime = current_time;
1082 inode->i_private = data;
1084 inode->i_fop = fops;
1092 /* Create "regular" file */
1093 static struct inode *ffs_sb_create_file(struct super_block *sb,
1094 const char *name, void *data,
1095 const struct file_operations *fops,
1096 struct dentry **dentry_p)
1098 struct ffs_data *ffs = sb->s_fs_info;
1099 struct dentry *dentry;
1100 struct inode *inode;
1104 dentry = d_alloc_name(sb->s_root, name);
1105 if (unlikely(!dentry))
1108 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1109 if (unlikely(!inode)) {
1114 d_add(dentry, inode);
1122 static const struct super_operations ffs_sb_operations = {
1123 .statfs = simple_statfs,
1124 .drop_inode = generic_delete_inode,
1127 struct ffs_sb_fill_data {
1128 struct ffs_file_perms perms;
1130 const char *dev_name;
1131 struct ffs_data *ffs_data;
1134 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1136 struct ffs_sb_fill_data *data = _data;
1137 struct inode *inode;
1138 struct ffs_data *ffs = data->ffs_data;
1143 data->ffs_data = NULL;
1144 sb->s_fs_info = ffs;
1145 sb->s_blocksize = PAGE_CACHE_SIZE;
1146 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1147 sb->s_magic = FUNCTIONFS_MAGIC;
1148 sb->s_op = &ffs_sb_operations;
1149 sb->s_time_gran = 1;
1152 data->perms.mode = data->root_mode;
1153 inode = ffs_sb_make_inode(sb, NULL,
1154 &simple_dir_operations,
1155 &simple_dir_inode_operations,
1157 sb->s_root = d_make_root(inode);
1158 if (unlikely(!sb->s_root))
1162 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1163 &ffs_ep0_operations, NULL)))
1169 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1173 if (!opts || !*opts)
1177 unsigned long value;
1181 comma = strchr(opts, ',');
1186 eq = strchr(opts, '=');
1187 if (unlikely(!eq)) {
1188 pr_err("'=' missing in %s\n", opts);
1194 if (kstrtoul(eq + 1, 0, &value)) {
1195 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1199 /* Interpret option */
1200 switch (eq - opts) {
1202 if (!memcmp(opts, "rmode", 5))
1203 data->root_mode = (value & 0555) | S_IFDIR;
1204 else if (!memcmp(opts, "fmode", 5))
1205 data->perms.mode = (value & 0666) | S_IFREG;
1211 if (!memcmp(opts, "mode", 4)) {
1212 data->root_mode = (value & 0555) | S_IFDIR;
1213 data->perms.mode = (value & 0666) | S_IFREG;
1220 if (!memcmp(opts, "uid", 3)) {
1221 data->perms.uid = make_kuid(current_user_ns(), value);
1222 if (!uid_valid(data->perms.uid)) {
1223 pr_err("%s: unmapped value: %lu\n", opts, value);
1226 } else if (!memcmp(opts, "gid", 3)) {
1227 data->perms.gid = make_kgid(current_user_ns(), value);
1228 if (!gid_valid(data->perms.gid)) {
1229 pr_err("%s: unmapped value: %lu\n", opts, value);
1239 pr_err("%s: invalid option\n", opts);
1243 /* Next iteration */
1252 /* "mount -t functionfs dev_name /dev/function" ends up here */
1254 static struct dentry *
1255 ffs_fs_mount(struct file_system_type *t, int flags,
1256 const char *dev_name, void *opts)
1258 struct ffs_sb_fill_data data = {
1260 .mode = S_IFREG | 0600,
1261 .uid = GLOBAL_ROOT_UID,
1262 .gid = GLOBAL_ROOT_GID,
1264 .root_mode = S_IFDIR | 0500,
1269 struct ffs_data *ffs;
1273 ret = ffs_fs_parse_opts(&data, opts);
1274 if (unlikely(ret < 0))
1275 return ERR_PTR(ret);
1277 ffs = ffs_data_new();
1279 return ERR_PTR(-ENOMEM);
1280 ffs->file_perms = data.perms;
1282 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1283 if (unlikely(!ffs->dev_name)) {
1285 return ERR_PTR(-ENOMEM);
1288 ffs_dev = ffs_acquire_dev(dev_name);
1289 if (IS_ERR(ffs_dev)) {
1291 return ERR_CAST(ffs_dev);
1293 ffs->private_data = ffs_dev;
1294 data.ffs_data = ffs;
1296 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1297 if (IS_ERR(rv) && data.ffs_data) {
1298 ffs_release_dev(data.ffs_data);
1299 ffs_data_put(data.ffs_data);
1305 ffs_fs_kill_sb(struct super_block *sb)
1309 kill_litter_super(sb);
1310 if (sb->s_fs_info) {
1311 ffs_release_dev(sb->s_fs_info);
1312 ffs_data_put(sb->s_fs_info);
1316 static struct file_system_type ffs_fs_type = {
1317 .owner = THIS_MODULE,
1318 .name = "functionfs",
1319 .mount = ffs_fs_mount,
1320 .kill_sb = ffs_fs_kill_sb,
1322 MODULE_ALIAS_FS("functionfs");
1325 /* Driver's main init/cleanup functions *************************************/
1327 static int functionfs_init(void)
1333 ret = register_filesystem(&ffs_fs_type);
1335 pr_info("file system registered\n");
1337 pr_err("failed registering file system (%d)\n", ret);
1342 static void functionfs_cleanup(void)
1346 pr_info("unloading\n");
1347 unregister_filesystem(&ffs_fs_type);
1351 /* ffs_data and ffs_function construction and destruction code **************/
1353 static void ffs_data_clear(struct ffs_data *ffs);
1354 static void ffs_data_reset(struct ffs_data *ffs);
1356 static void ffs_data_get(struct ffs_data *ffs)
1360 atomic_inc(&ffs->ref);
1363 static void ffs_data_opened(struct ffs_data *ffs)
1367 atomic_inc(&ffs->ref);
1368 atomic_inc(&ffs->opened);
1371 static void ffs_data_put(struct ffs_data *ffs)
1375 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1376 pr_info("%s(): freeing\n", __func__);
1377 ffs_data_clear(ffs);
1378 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1379 waitqueue_active(&ffs->ep0req_completion.wait));
1380 kfree(ffs->dev_name);
1385 static void ffs_data_closed(struct ffs_data *ffs)
1389 if (atomic_dec_and_test(&ffs->opened)) {
1390 ffs->state = FFS_CLOSING;
1391 ffs_data_reset(ffs);
1397 static struct ffs_data *ffs_data_new(void)
1399 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1405 atomic_set(&ffs->ref, 1);
1406 atomic_set(&ffs->opened, 0);
1407 ffs->state = FFS_READ_DESCRIPTORS;
1408 mutex_init(&ffs->mutex);
1409 spin_lock_init(&ffs->eps_lock);
1410 init_waitqueue_head(&ffs->ev.waitq);
1411 init_completion(&ffs->ep0req_completion);
1413 /* XXX REVISIT need to update it in some places, or do we? */
1414 ffs->ev.can_stall = 1;
1419 static void ffs_data_clear(struct ffs_data *ffs)
1423 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1426 BUG_ON(ffs->gadget);
1429 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1431 kfree(ffs->raw_descs_data);
1432 kfree(ffs->raw_strings);
1433 kfree(ffs->stringtabs);
1436 static void ffs_data_reset(struct ffs_data *ffs)
1440 ffs_data_clear(ffs);
1442 ffs->epfiles = NULL;
1443 ffs->raw_descs_data = NULL;
1444 ffs->raw_descs = NULL;
1445 ffs->raw_strings = NULL;
1446 ffs->stringtabs = NULL;
1448 ffs->raw_descs_length = 0;
1449 ffs->fs_descs_count = 0;
1450 ffs->hs_descs_count = 0;
1451 ffs->ss_descs_count = 0;
1453 ffs->strings_count = 0;
1454 ffs->interfaces_count = 0;
1459 ffs->state = FFS_READ_DESCRIPTORS;
1460 ffs->setup_state = FFS_NO_SETUP;
1465 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1467 struct usb_gadget_strings **lang;
1472 if (WARN_ON(ffs->state != FFS_ACTIVE
1473 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1476 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1477 if (unlikely(first_id < 0))
1480 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1481 if (unlikely(!ffs->ep0req))
1483 ffs->ep0req->complete = ffs_ep0_complete;
1484 ffs->ep0req->context = ffs;
1486 lang = ffs->stringtabs;
1488 for (; *lang; ++lang) {
1489 struct usb_string *str = (*lang)->strings;
1491 for (; str->s; ++id, ++str)
1496 ffs->gadget = cdev->gadget;
1501 static void functionfs_unbind(struct ffs_data *ffs)
1505 if (!WARN_ON(!ffs->gadget)) {
1506 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1509 clear_bit(FFS_FL_BOUND, &ffs->flags);
1514 static int ffs_epfiles_create(struct ffs_data *ffs)
1516 struct ffs_epfile *epfile, *epfiles;
1521 count = ffs->eps_count;
1522 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1527 for (i = 1; i <= count; ++i, ++epfile) {
1529 mutex_init(&epfile->mutex);
1530 init_waitqueue_head(&epfile->wait);
1531 sprintf(epfiles->name, "ep%u", i);
1532 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1533 &ffs_epfile_operations,
1534 &epfile->dentry))) {
1535 ffs_epfiles_destroy(epfiles, i - 1);
1540 ffs->epfiles = epfiles;
1544 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1546 struct ffs_epfile *epfile = epfiles;
1550 for (; count; --count, ++epfile) {
1551 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1552 waitqueue_active(&epfile->wait));
1553 if (epfile->dentry) {
1554 d_delete(epfile->dentry);
1555 dput(epfile->dentry);
1556 epfile->dentry = NULL;
1564 static void ffs_func_eps_disable(struct ffs_function *func)
1566 struct ffs_ep *ep = func->eps;
1567 struct ffs_epfile *epfile = func->ffs->epfiles;
1568 unsigned count = func->ffs->eps_count;
1569 unsigned long flags;
1571 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1573 /* pending requests get nuked */
1575 usb_ep_disable(ep->ep);
1581 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1584 static int ffs_func_eps_enable(struct ffs_function *func)
1586 struct ffs_data *ffs = func->ffs;
1587 struct ffs_ep *ep = func->eps;
1588 struct ffs_epfile *epfile = ffs->epfiles;
1589 unsigned count = ffs->eps_count;
1590 unsigned long flags;
1593 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1595 struct usb_endpoint_descriptor *ds;
1598 if (ffs->gadget->speed == USB_SPEED_SUPER)
1600 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1605 /* fall-back to lower speed if desc missing for current speed */
1607 ds = ep->descs[desc_idx];
1608 } while (!ds && --desc_idx >= 0);
1615 ep->ep->driver_data = ep;
1617 ret = usb_ep_enable(ep->ep);
1620 epfile->in = usb_endpoint_dir_in(ds);
1621 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1626 wake_up(&epfile->wait);
1631 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1637 /* Parsing and building descriptors and strings *****************************/
1640 * This validates if data pointed by data is a valid USB descriptor as
1641 * well as record how many interfaces, endpoints and strings are
1642 * required by given configuration. Returns address after the
1643 * descriptor or NULL if data is invalid.
1646 enum ffs_entity_type {
1647 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1650 enum ffs_os_desc_type {
1651 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1654 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1656 struct usb_descriptor_header *desc,
1659 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1660 struct usb_os_desc_header *h, void *data,
1661 unsigned len, void *priv);
1663 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1664 ffs_entity_callback entity,
1667 struct usb_descriptor_header *_ds = (void *)data;
1673 /* At least two bytes are required: length and type */
1675 pr_vdebug("descriptor too short\n");
1679 /* If we have at least as many bytes as the descriptor takes? */
1680 length = _ds->bLength;
1682 pr_vdebug("descriptor longer then available data\n");
1686 #define __entity_check_INTERFACE(val) 1
1687 #define __entity_check_STRING(val) (val)
1688 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1689 #define __entity(type, val) do { \
1690 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1691 if (unlikely(!__entity_check_ ##type(val))) { \
1692 pr_vdebug("invalid entity's value\n"); \
1695 ret = entity(FFS_ ##type, &val, _ds, priv); \
1696 if (unlikely(ret < 0)) { \
1697 pr_debug("entity " #type "(%02x); ret = %d\n", \
1703 /* Parse descriptor depending on type. */
1704 switch (_ds->bDescriptorType) {
1708 case USB_DT_DEVICE_QUALIFIER:
1709 /* function can't have any of those */
1710 pr_vdebug("descriptor reserved for gadget: %d\n",
1711 _ds->bDescriptorType);
1714 case USB_DT_INTERFACE: {
1715 struct usb_interface_descriptor *ds = (void *)_ds;
1716 pr_vdebug("interface descriptor\n");
1717 if (length != sizeof *ds)
1720 __entity(INTERFACE, ds->bInterfaceNumber);
1722 __entity(STRING, ds->iInterface);
1726 case USB_DT_ENDPOINT: {
1727 struct usb_endpoint_descriptor *ds = (void *)_ds;
1728 pr_vdebug("endpoint descriptor\n");
1729 if (length != USB_DT_ENDPOINT_SIZE &&
1730 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1732 __entity(ENDPOINT, ds->bEndpointAddress);
1737 pr_vdebug("hid descriptor\n");
1738 if (length != sizeof(struct hid_descriptor))
1743 if (length != sizeof(struct usb_otg_descriptor))
1747 case USB_DT_INTERFACE_ASSOCIATION: {
1748 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1749 pr_vdebug("interface association descriptor\n");
1750 if (length != sizeof *ds)
1753 __entity(STRING, ds->iFunction);
1757 case USB_DT_SS_ENDPOINT_COMP:
1758 pr_vdebug("EP SS companion descriptor\n");
1759 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1763 case USB_DT_OTHER_SPEED_CONFIG:
1764 case USB_DT_INTERFACE_POWER:
1766 case USB_DT_SECURITY:
1767 case USB_DT_CS_RADIO_CONTROL:
1769 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1773 /* We should never be here */
1774 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1778 pr_vdebug("invalid length: %d (descriptor %d)\n",
1779 _ds->bLength, _ds->bDescriptorType);
1784 #undef __entity_check_DESCRIPTOR
1785 #undef __entity_check_INTERFACE
1786 #undef __entity_check_STRING
1787 #undef __entity_check_ENDPOINT
1792 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1793 ffs_entity_callback entity, void *priv)
1795 const unsigned _len = len;
1796 unsigned long num = 0;
1806 /* Record "descriptor" entity */
1807 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1808 if (unlikely(ret < 0)) {
1809 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1817 ret = ffs_do_single_desc(data, len, entity, priv);
1818 if (unlikely(ret < 0)) {
1819 pr_debug("%s returns %d\n", __func__, ret);
1829 static int __ffs_data_do_entity(enum ffs_entity_type type,
1830 u8 *valuep, struct usb_descriptor_header *desc,
1833 struct ffs_data *ffs = priv;
1838 case FFS_DESCRIPTOR:
1843 * Interfaces are indexed from zero so if we
1844 * encountered interface "n" then there are at least
1847 if (*valuep >= ffs->interfaces_count)
1848 ffs->interfaces_count = *valuep + 1;
1853 * Strings are indexed from 1 (0 is magic ;) reserved
1854 * for languages list or some such)
1856 if (*valuep > ffs->strings_count)
1857 ffs->strings_count = *valuep;
1861 /* Endpoints are indexed from 1 as well. */
1862 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1863 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1870 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1871 struct usb_os_desc_header *desc)
1873 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1874 u16 w_index = le16_to_cpu(desc->wIndex);
1876 if (bcd_version != 1) {
1877 pr_vdebug("unsupported os descriptors version: %d",
1883 *next_type = FFS_OS_DESC_EXT_COMPAT;
1886 *next_type = FFS_OS_DESC_EXT_PROP;
1889 pr_vdebug("unsupported os descriptor type: %d", w_index);
1893 return sizeof(*desc);
1897 * Process all extended compatibility/extended property descriptors
1898 * of a feature descriptor
1900 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1901 enum ffs_os_desc_type type,
1903 ffs_os_desc_callback entity,
1905 struct usb_os_desc_header *h)
1908 const unsigned _len = len;
1912 /* loop over all ext compat/ext prop descriptors */
1913 while (feature_count--) {
1914 ret = entity(type, h, data, len, priv);
1915 if (unlikely(ret < 0)) {
1916 pr_debug("bad OS descriptor, type: %d\n", type);
1925 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1926 static int __must_check ffs_do_os_descs(unsigned count,
1927 char *data, unsigned len,
1928 ffs_os_desc_callback entity, void *priv)
1930 const unsigned _len = len;
1931 unsigned long num = 0;
1935 for (num = 0; num < count; ++num) {
1937 enum ffs_os_desc_type type;
1939 struct usb_os_desc_header *desc = (void *)data;
1941 if (len < sizeof(*desc))
1945 * Record "descriptor" entity.
1946 * Process dwLength, bcdVersion, wIndex, get b/wCount.
1947 * Move the data pointer to the beginning of extended
1948 * compatibilities proper or extended properties proper
1949 * portions of the data
1951 if (le32_to_cpu(desc->dwLength) > len)
1954 ret = __ffs_do_os_desc_header(&type, desc);
1955 if (unlikely(ret < 0)) {
1956 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
1961 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
1963 feature_count = le16_to_cpu(desc->wCount);
1964 if (type == FFS_OS_DESC_EXT_COMPAT &&
1965 (feature_count > 255 || desc->Reserved))
1971 * Process all function/property descriptors
1972 * of this Feature Descriptor
1974 ret = ffs_do_single_os_desc(data, len, type,
1975 feature_count, entity, priv, desc);
1976 if (unlikely(ret < 0)) {
1977 pr_debug("%s returns %d\n", __func__, ret);
1988 * Validate contents of the buffer from userspace related to OS descriptors.
1990 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
1991 struct usb_os_desc_header *h, void *data,
1992 unsigned len, void *priv)
1994 struct ffs_data *ffs = priv;
2000 case FFS_OS_DESC_EXT_COMPAT: {
2001 struct usb_ext_compat_desc *d = data;
2004 if (len < sizeof(*d) ||
2005 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2008 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2009 if (d->Reserved2[i])
2012 length = sizeof(struct usb_ext_compat_desc);
2015 case FFS_OS_DESC_EXT_PROP: {
2016 struct usb_ext_prop_desc *d = data;
2020 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2022 length = le32_to_cpu(d->dwSize);
2023 type = le32_to_cpu(d->dwPropertyDataType);
2024 if (type < USB_EXT_PROP_UNICODE ||
2025 type > USB_EXT_PROP_UNICODE_MULTI) {
2026 pr_vdebug("unsupported os descriptor property type: %d",
2030 pnl = le16_to_cpu(d->wPropertyNameLength);
2031 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2032 if (length != 14 + pnl + pdl) {
2033 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2034 length, pnl, pdl, type);
2037 ++ffs->ms_os_descs_ext_prop_count;
2038 /* property name reported to the host as "WCHAR"s */
2039 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2040 ffs->ms_os_descs_ext_prop_data_len += pdl;
2044 pr_vdebug("unknown descriptor: %d\n", type);
2050 static int __ffs_data_got_descs(struct ffs_data *ffs,
2051 char *const _data, size_t len)
2053 char *data = _data, *raw_descs;
2054 unsigned os_descs_count = 0, counts[3], flags;
2055 int ret = -EINVAL, i;
2059 if (get_unaligned_le32(data + 4) != len)
2062 switch (get_unaligned_le32(data)) {
2063 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2064 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2068 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2069 flags = get_unaligned_le32(data + 8);
2070 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2071 FUNCTIONFS_HAS_HS_DESC |
2072 FUNCTIONFS_HAS_SS_DESC |
2073 FUNCTIONFS_HAS_MS_OS_DESC)) {
2084 /* Read fs_count, hs_count and ss_count (if present) */
2085 for (i = 0; i < 3; ++i) {
2086 if (!(flags & (1 << i))) {
2088 } else if (len < 4) {
2091 counts[i] = get_unaligned_le32(data);
2096 if (flags & (1 << i)) {
2097 os_descs_count = get_unaligned_le32(data);
2102 /* Read descriptors */
2104 for (i = 0; i < 3; ++i) {
2107 ret = ffs_do_descs(counts[i], data, len,
2108 __ffs_data_do_entity, ffs);
2114 if (os_descs_count) {
2115 ret = ffs_do_os_descs(os_descs_count, data, len,
2116 __ffs_data_do_os_desc, ffs);
2123 if (raw_descs == data || len) {
2128 ffs->raw_descs_data = _data;
2129 ffs->raw_descs = raw_descs;
2130 ffs->raw_descs_length = data - raw_descs;
2131 ffs->fs_descs_count = counts[0];
2132 ffs->hs_descs_count = counts[1];
2133 ffs->ss_descs_count = counts[2];
2134 ffs->ms_os_descs_count = os_descs_count;
2143 static int __ffs_data_got_strings(struct ffs_data *ffs,
2144 char *const _data, size_t len)
2146 u32 str_count, needed_count, lang_count;
2147 struct usb_gadget_strings **stringtabs, *t;
2148 struct usb_string *strings, *s;
2149 const char *data = _data;
2153 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2154 get_unaligned_le32(data + 4) != len))
2156 str_count = get_unaligned_le32(data + 8);
2157 lang_count = get_unaligned_le32(data + 12);
2159 /* if one is zero the other must be zero */
2160 if (unlikely(!str_count != !lang_count))
2163 /* Do we have at least as many strings as descriptors need? */
2164 needed_count = ffs->strings_count;
2165 if (unlikely(str_count < needed_count))
2169 * If we don't need any strings just return and free all
2172 if (!needed_count) {
2177 /* Allocate everything in one chunk so there's less maintenance. */
2181 vla_item(d, struct usb_gadget_strings *, stringtabs,
2183 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2184 vla_item(d, struct usb_string, strings,
2185 lang_count*(needed_count+1));
2187 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2189 if (unlikely(!vlabuf)) {
2194 /* Initialize the VLA pointers */
2195 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2196 t = vla_ptr(vlabuf, d, stringtab);
2199 *stringtabs++ = t++;
2203 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2204 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2205 t = vla_ptr(vlabuf, d, stringtab);
2206 s = vla_ptr(vlabuf, d, strings);
2210 /* For each language */
2214 do { /* lang_count > 0 so we can use do-while */
2215 unsigned needed = needed_count;
2217 if (unlikely(len < 3))
2219 t->language = get_unaligned_le16(data);
2226 /* For each string */
2227 do { /* str_count > 0 so we can use do-while */
2228 size_t length = strnlen(data, len);
2230 if (unlikely(length == len))
2234 * User may provide more strings then we need,
2235 * if that's the case we simply ignore the
2238 if (likely(needed)) {
2240 * s->id will be set while adding
2241 * function to configuration so for
2242 * now just leave garbage here.
2251 } while (--str_count);
2253 s->id = 0; /* terminator */
2257 } while (--lang_count);
2259 /* Some garbage left? */
2264 ffs->stringtabs = stringtabs;
2265 ffs->raw_strings = _data;
2277 /* Events handling and management *******************************************/
2279 static void __ffs_event_add(struct ffs_data *ffs,
2280 enum usb_functionfs_event_type type)
2282 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2286 * Abort any unhandled setup
2288 * We do not need to worry about some cmpxchg() changing value
2289 * of ffs->setup_state without holding the lock because when
2290 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2291 * the source does nothing.
2293 if (ffs->setup_state == FFS_SETUP_PENDING)
2294 ffs->setup_state = FFS_SETUP_CANCELLED;
2297 case FUNCTIONFS_RESUME:
2298 rem_type2 = FUNCTIONFS_SUSPEND;
2300 case FUNCTIONFS_SUSPEND:
2301 case FUNCTIONFS_SETUP:
2303 /* Discard all similar events */
2306 case FUNCTIONFS_BIND:
2307 case FUNCTIONFS_UNBIND:
2308 case FUNCTIONFS_DISABLE:
2309 case FUNCTIONFS_ENABLE:
2310 /* Discard everything other then power management. */
2311 rem_type1 = FUNCTIONFS_SUSPEND;
2312 rem_type2 = FUNCTIONFS_RESUME;
2321 u8 *ev = ffs->ev.types, *out = ev;
2322 unsigned n = ffs->ev.count;
2323 for (; n; --n, ++ev)
2324 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2327 pr_vdebug("purging event %d\n", *ev);
2328 ffs->ev.count = out - ffs->ev.types;
2331 pr_vdebug("adding event %d\n", type);
2332 ffs->ev.types[ffs->ev.count++] = type;
2333 wake_up_locked(&ffs->ev.waitq);
2336 static void ffs_event_add(struct ffs_data *ffs,
2337 enum usb_functionfs_event_type type)
2339 unsigned long flags;
2340 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2341 __ffs_event_add(ffs, type);
2342 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2346 /* Bind/unbind USB function hooks *******************************************/
2348 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2349 struct usb_descriptor_header *desc,
2352 struct usb_endpoint_descriptor *ds = (void *)desc;
2353 struct ffs_function *func = priv;
2354 struct ffs_ep *ffs_ep;
2355 unsigned ep_desc_id, idx;
2356 static const char *speed_names[] = { "full", "high", "super" };
2358 if (type != FFS_DESCRIPTOR)
2362 * If ss_descriptors is not NULL, we are reading super speed
2363 * descriptors; if hs_descriptors is not NULL, we are reading high
2364 * speed descriptors; otherwise, we are reading full speed
2367 if (func->function.ss_descriptors) {
2369 func->function.ss_descriptors[(long)valuep] = desc;
2370 } else if (func->function.hs_descriptors) {
2372 func->function.hs_descriptors[(long)valuep] = desc;
2375 func->function.fs_descriptors[(long)valuep] = desc;
2378 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2381 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2382 ffs_ep = func->eps + idx;
2384 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2385 pr_err("two %sspeed descriptors for EP %d\n",
2386 speed_names[ep_desc_id],
2387 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2390 ffs_ep->descs[ep_desc_id] = ds;
2392 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2394 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2395 if (!ds->wMaxPacketSize)
2396 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2398 struct usb_request *req;
2401 pr_vdebug("autoconfig\n");
2402 ep = usb_ep_autoconfig(func->gadget, ds);
2405 ep->driver_data = func->eps + idx;
2407 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2413 func->eps_revmap[ds->bEndpointAddress &
2414 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2416 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2421 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2422 struct usb_descriptor_header *desc,
2425 struct ffs_function *func = priv;
2431 case FFS_DESCRIPTOR:
2432 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2437 if (func->interfaces_nums[idx] < 0) {
2438 int id = usb_interface_id(func->conf, &func->function);
2439 if (unlikely(id < 0))
2441 func->interfaces_nums[idx] = id;
2443 newValue = func->interfaces_nums[idx];
2447 /* String' IDs are allocated when fsf_data is bound to cdev */
2448 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2453 * USB_DT_ENDPOINT are handled in
2454 * __ffs_func_bind_do_descs().
2456 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2459 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2460 if (unlikely(!func->eps[idx].ep))
2464 struct usb_endpoint_descriptor **descs;
2465 descs = func->eps[idx].descs;
2466 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2471 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2476 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2477 struct usb_os_desc_header *h, void *data,
2478 unsigned len, void *priv)
2480 struct ffs_function *func = priv;
2484 case FFS_OS_DESC_EXT_COMPAT: {
2485 struct usb_ext_compat_desc *desc = data;
2486 struct usb_os_desc_table *t;
2488 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2489 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2490 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2491 ARRAY_SIZE(desc->CompatibleID) +
2492 ARRAY_SIZE(desc->SubCompatibleID));
2493 length = sizeof(*desc);
2496 case FFS_OS_DESC_EXT_PROP: {
2497 struct usb_ext_prop_desc *desc = data;
2498 struct usb_os_desc_table *t;
2499 struct usb_os_desc_ext_prop *ext_prop;
2500 char *ext_prop_name;
2501 char *ext_prop_data;
2503 t = &func->function.os_desc_table[h->interface];
2504 t->if_id = func->interfaces_nums[h->interface];
2506 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2507 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2509 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2510 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2511 ext_prop->data_len = le32_to_cpu(*(u32 *)
2512 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2513 length = ext_prop->name_len + ext_prop->data_len + 14;
2515 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2516 func->ffs->ms_os_descs_ext_prop_name_avail +=
2519 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2520 func->ffs->ms_os_descs_ext_prop_data_avail +=
2522 memcpy(ext_prop_data,
2523 usb_ext_prop_data_ptr(data, ext_prop->name_len),
2524 ext_prop->data_len);
2525 /* unicode data reported to the host as "WCHAR"s */
2526 switch (ext_prop->type) {
2527 case USB_EXT_PROP_UNICODE:
2528 case USB_EXT_PROP_UNICODE_ENV:
2529 case USB_EXT_PROP_UNICODE_LINK:
2530 case USB_EXT_PROP_UNICODE_MULTI:
2531 ext_prop->data_len *= 2;
2534 ext_prop->data = ext_prop_data;
2536 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2537 ext_prop->name_len);
2538 /* property name reported to the host as "WCHAR"s */
2539 ext_prop->name_len *= 2;
2540 ext_prop->name = ext_prop_name;
2542 t->os_desc->ext_prop_len +=
2543 ext_prop->name_len + ext_prop->data_len + 14;
2544 ++t->os_desc->ext_prop_count;
2545 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2549 pr_vdebug("unknown descriptor: %d\n", type);
2555 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2556 struct usb_configuration *c)
2558 struct ffs_function *func = ffs_func_from_usb(f);
2559 struct f_fs_opts *ffs_opts =
2560 container_of(f->fi, struct f_fs_opts, func_inst);
2566 * Legacy gadget triggers binding in functionfs_ready_callback,
2567 * which already uses locking; taking the same lock here would
2570 * Configfs-enabled gadgets however do need ffs_dev_lock.
2572 if (!ffs_opts->no_configfs)
2574 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2575 func->ffs = ffs_opts->dev->ffs_data;
2576 if (!ffs_opts->no_configfs)
2579 return ERR_PTR(ret);
2582 func->gadget = c->cdev->gadget;
2584 ffs_data_get(func->ffs);
2587 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2588 * configurations are bound in sequence with list_for_each_entry,
2589 * in each configuration its functions are bound in sequence
2590 * with list_for_each_entry, so we assume no race condition
2591 * with regard to ffs_opts->bound access
2593 if (!ffs_opts->refcnt) {
2594 ret = functionfs_bind(func->ffs, c->cdev);
2596 return ERR_PTR(ret);
2599 func->function.strings = func->ffs->stringtabs;
2604 static int _ffs_func_bind(struct usb_configuration *c,
2605 struct usb_function *f)
2607 struct ffs_function *func = ffs_func_from_usb(f);
2608 struct ffs_data *ffs = func->ffs;
2610 const int full = !!func->ffs->fs_descs_count;
2611 const int high = gadget_is_dualspeed(func->gadget) &&
2612 func->ffs->hs_descs_count;
2613 const int super = gadget_is_superspeed(func->gadget) &&
2614 func->ffs->ss_descs_count;
2616 int fs_len, hs_len, ss_len, ret, i;
2618 /* Make it a single chunk, less management later on */
2620 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2621 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2622 full ? ffs->fs_descs_count + 1 : 0);
2623 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2624 high ? ffs->hs_descs_count + 1 : 0);
2625 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2626 super ? ffs->ss_descs_count + 1 : 0);
2627 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2628 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2629 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2630 vla_item_with_sz(d, char[16], ext_compat,
2631 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2632 vla_item_with_sz(d, struct usb_os_desc, os_desc,
2633 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2634 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2635 ffs->ms_os_descs_ext_prop_count);
2636 vla_item_with_sz(d, char, ext_prop_name,
2637 ffs->ms_os_descs_ext_prop_name_len);
2638 vla_item_with_sz(d, char, ext_prop_data,
2639 ffs->ms_os_descs_ext_prop_data_len);
2640 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2645 /* Has descriptors only for speeds gadget does not support */
2646 if (unlikely(!(full | high | super)))
2649 /* Allocate a single chunk, less management later on */
2650 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2651 if (unlikely(!vlabuf))
2654 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2655 ffs->ms_os_descs_ext_prop_name_avail =
2656 vla_ptr(vlabuf, d, ext_prop_name);
2657 ffs->ms_os_descs_ext_prop_data_avail =
2658 vla_ptr(vlabuf, d, ext_prop_data);
2660 /* Copy descriptors */
2661 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2662 ffs->raw_descs_length);
2664 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2665 for (ret = ffs->eps_count; ret; --ret) {
2668 ptr = vla_ptr(vlabuf, d, eps);
2673 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2675 func->eps = vla_ptr(vlabuf, d, eps);
2676 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2679 * Go through all the endpoint descriptors and allocate
2680 * endpoints first, so that later we can rewrite the endpoint
2681 * numbers without worrying that it may be described later on.
2684 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2685 fs_len = ffs_do_descs(ffs->fs_descs_count,
2686 vla_ptr(vlabuf, d, raw_descs),
2688 __ffs_func_bind_do_descs, func);
2689 if (unlikely(fs_len < 0)) {
2698 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2699 hs_len = ffs_do_descs(ffs->hs_descs_count,
2700 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2701 d_raw_descs__sz - fs_len,
2702 __ffs_func_bind_do_descs, func);
2703 if (unlikely(hs_len < 0)) {
2711 if (likely(super)) {
2712 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2713 ss_len = ffs_do_descs(ffs->ss_descs_count,
2714 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2715 d_raw_descs__sz - fs_len - hs_len,
2716 __ffs_func_bind_do_descs, func);
2717 if (unlikely(ss_len < 0)) {
2726 * Now handle interface numbers allocation and interface and
2727 * endpoint numbers rewriting. We can do that in one go
2730 ret = ffs_do_descs(ffs->fs_descs_count +
2731 (high ? ffs->hs_descs_count : 0) +
2732 (super ? ffs->ss_descs_count : 0),
2733 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2734 __ffs_func_bind_do_nums, func);
2735 if (unlikely(ret < 0))
2738 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2739 if (c->cdev->use_os_string)
2740 for (i = 0; i < ffs->interfaces_count; ++i) {
2741 struct usb_os_desc *desc;
2743 desc = func->function.os_desc_table[i].os_desc =
2744 vla_ptr(vlabuf, d, os_desc) +
2745 i * sizeof(struct usb_os_desc);
2746 desc->ext_compat_id =
2747 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2748 INIT_LIST_HEAD(&desc->ext_prop);
2750 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2751 vla_ptr(vlabuf, d, raw_descs) +
2752 fs_len + hs_len + ss_len,
2753 d_raw_descs__sz - fs_len - hs_len - ss_len,
2754 __ffs_func_bind_do_os_desc, func);
2755 if (unlikely(ret < 0))
2757 func->function.os_desc_n =
2758 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2760 /* And we're done */
2761 ffs_event_add(ffs, FUNCTIONFS_BIND);
2765 /* XXX Do we need to release all claimed endpoints here? */
2769 static int ffs_func_bind(struct usb_configuration *c,
2770 struct usb_function *f)
2772 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2774 if (IS_ERR(ffs_opts))
2775 return PTR_ERR(ffs_opts);
2777 return _ffs_func_bind(c, f);
2781 /* Other USB function hooks *************************************************/
2783 static int ffs_func_set_alt(struct usb_function *f,
2784 unsigned interface, unsigned alt)
2786 struct ffs_function *func = ffs_func_from_usb(f);
2787 struct ffs_data *ffs = func->ffs;
2790 if (alt != (unsigned)-1) {
2791 intf = ffs_func_revmap_intf(func, interface);
2792 if (unlikely(intf < 0))
2797 ffs_func_eps_disable(ffs->func);
2799 if (ffs->state != FFS_ACTIVE)
2802 if (alt == (unsigned)-1) {
2804 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2809 ret = ffs_func_eps_enable(func);
2810 if (likely(ret >= 0))
2811 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2815 static void ffs_func_disable(struct usb_function *f)
2817 ffs_func_set_alt(f, 0, (unsigned)-1);
2820 static int ffs_func_setup(struct usb_function *f,
2821 const struct usb_ctrlrequest *creq)
2823 struct ffs_function *func = ffs_func_from_usb(f);
2824 struct ffs_data *ffs = func->ffs;
2825 unsigned long flags;
2830 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2831 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2832 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2833 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2834 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2837 * Most requests directed to interface go through here
2838 * (notable exceptions are set/get interface) so we need to
2839 * handle them. All other either handled by composite or
2840 * passed to usb_configuration->setup() (if one is set). No
2841 * matter, we will handle requests directed to endpoint here
2842 * as well (as it's straightforward) but what to do with any
2845 if (ffs->state != FFS_ACTIVE)
2848 switch (creq->bRequestType & USB_RECIP_MASK) {
2849 case USB_RECIP_INTERFACE:
2850 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2851 if (unlikely(ret < 0))
2855 case USB_RECIP_ENDPOINT:
2856 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2857 if (unlikely(ret < 0))
2865 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2866 ffs->ev.setup = *creq;
2867 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2868 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2869 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2874 static void ffs_func_suspend(struct usb_function *f)
2877 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2880 static void ffs_func_resume(struct usb_function *f)
2883 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2887 /* Endpoint and interface numbers reverse mapping ***************************/
2889 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2891 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2892 return num ? num : -EDOM;
2895 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2897 short *nums = func->interfaces_nums;
2898 unsigned count = func->ffs->interfaces_count;
2900 for (; count; --count, ++nums) {
2901 if (*nums >= 0 && *nums == intf)
2902 return nums - func->interfaces_nums;
2909 /* Devices management *******************************************************/
2911 static LIST_HEAD(ffs_devices);
2913 static struct ffs_dev *_ffs_do_find_dev(const char *name)
2915 struct ffs_dev *dev;
2917 list_for_each_entry(dev, &ffs_devices, entry) {
2918 if (!dev->name || !name)
2920 if (strcmp(dev->name, name) == 0)
2928 * ffs_lock must be taken by the caller of this function
2930 static struct ffs_dev *_ffs_get_single_dev(void)
2932 struct ffs_dev *dev;
2934 if (list_is_singular(&ffs_devices)) {
2935 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
2944 * ffs_lock must be taken by the caller of this function
2946 static struct ffs_dev *_ffs_find_dev(const char *name)
2948 struct ffs_dev *dev;
2950 dev = _ffs_get_single_dev();
2954 return _ffs_do_find_dev(name);
2957 /* Configfs support *********************************************************/
2959 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
2961 return container_of(to_config_group(item), struct f_fs_opts,
2965 static void ffs_attr_release(struct config_item *item)
2967 struct f_fs_opts *opts = to_ffs_opts(item);
2969 usb_put_function_instance(&opts->func_inst);
2972 static struct configfs_item_operations ffs_item_ops = {
2973 .release = ffs_attr_release,
2976 static struct config_item_type ffs_func_type = {
2977 .ct_item_ops = &ffs_item_ops,
2978 .ct_owner = THIS_MODULE,
2982 /* Function registration interface ******************************************/
2984 static void ffs_free_inst(struct usb_function_instance *f)
2986 struct f_fs_opts *opts;
2988 opts = to_f_fs_opts(f);
2990 _ffs_free_dev(opts->dev);
2995 #define MAX_INST_NAME_LEN 40
2997 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
2999 struct f_fs_opts *opts;
3004 name_len = strlen(name) + 1;
3005 if (name_len > MAX_INST_NAME_LEN)
3006 return -ENAMETOOLONG;
3008 ptr = kstrndup(name, name_len, GFP_KERNEL);
3012 opts = to_f_fs_opts(fi);
3017 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3018 ret = _ffs_name_dev(opts->dev, ptr);
3024 opts->dev->name_allocated = true;
3033 static struct usb_function_instance *ffs_alloc_inst(void)
3035 struct f_fs_opts *opts;
3036 struct ffs_dev *dev;
3038 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3040 return ERR_PTR(-ENOMEM);
3042 opts->func_inst.set_inst_name = ffs_set_inst_name;
3043 opts->func_inst.free_func_inst = ffs_free_inst;
3045 dev = _ffs_alloc_dev();
3049 return ERR_CAST(dev);
3054 config_group_init_type_name(&opts->func_inst.group, "",
3056 return &opts->func_inst;
3059 static void ffs_free(struct usb_function *f)
3061 kfree(ffs_func_from_usb(f));
3064 static void ffs_func_unbind(struct usb_configuration *c,
3065 struct usb_function *f)
3067 struct ffs_function *func = ffs_func_from_usb(f);
3068 struct ffs_data *ffs = func->ffs;
3069 struct f_fs_opts *opts =
3070 container_of(f->fi, struct f_fs_opts, func_inst);
3071 struct ffs_ep *ep = func->eps;
3072 unsigned count = ffs->eps_count;
3073 unsigned long flags;
3076 if (ffs->func == func) {
3077 ffs_func_eps_disable(func);
3081 if (!--opts->refcnt)
3082 functionfs_unbind(ffs);
3084 /* cleanup after autoconfig */
3085 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3087 if (ep->ep && ep->req)
3088 usb_ep_free_request(ep->ep, ep->req);
3092 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3096 * eps, descriptors and interfaces_nums are allocated in the
3097 * same chunk so only one free is required.
3099 func->function.fs_descriptors = NULL;
3100 func->function.hs_descriptors = NULL;
3101 func->function.ss_descriptors = NULL;
3102 func->interfaces_nums = NULL;
3104 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3107 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3109 struct ffs_function *func;
3113 func = kzalloc(sizeof(*func), GFP_KERNEL);
3114 if (unlikely(!func))
3115 return ERR_PTR(-ENOMEM);
3117 func->function.name = "Function FS Gadget";
3119 func->function.bind = ffs_func_bind;
3120 func->function.unbind = ffs_func_unbind;
3121 func->function.set_alt = ffs_func_set_alt;
3122 func->function.disable = ffs_func_disable;
3123 func->function.setup = ffs_func_setup;
3124 func->function.suspend = ffs_func_suspend;
3125 func->function.resume = ffs_func_resume;
3126 func->function.free_func = ffs_free;
3128 return &func->function;
3132 * ffs_lock must be taken by the caller of this function
3134 static struct ffs_dev *_ffs_alloc_dev(void)
3136 struct ffs_dev *dev;
3139 if (_ffs_get_single_dev())
3140 return ERR_PTR(-EBUSY);
3142 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3144 return ERR_PTR(-ENOMEM);
3146 if (list_empty(&ffs_devices)) {
3147 ret = functionfs_init();
3150 return ERR_PTR(ret);
3154 list_add(&dev->entry, &ffs_devices);
3160 * ffs_lock must be taken by the caller of this function
3161 * The caller is responsible for "name" being available whenever f_fs needs it
3163 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3165 struct ffs_dev *existing;
3167 existing = _ffs_do_find_dev(name);
3177 * The caller is responsible for "name" being available whenever f_fs needs it
3179 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3184 ret = _ffs_name_dev(dev, name);
3189 EXPORT_SYMBOL_GPL(ffs_name_dev);
3191 int ffs_single_dev(struct ffs_dev *dev)
3198 if (!list_is_singular(&ffs_devices))
3206 EXPORT_SYMBOL_GPL(ffs_single_dev);
3209 * ffs_lock must be taken by the caller of this function
3211 static void _ffs_free_dev(struct ffs_dev *dev)
3213 list_del(&dev->entry);
3214 if (dev->name_allocated)
3217 if (list_empty(&ffs_devices))
3218 functionfs_cleanup();
3221 static void *ffs_acquire_dev(const char *dev_name)
3223 struct ffs_dev *ffs_dev;
3228 ffs_dev = _ffs_find_dev(dev_name);
3230 ffs_dev = ERR_PTR(-ENOENT);
3231 else if (ffs_dev->mounted)
3232 ffs_dev = ERR_PTR(-EBUSY);
3233 else if (ffs_dev->ffs_acquire_dev_callback &&
3234 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3235 ffs_dev = ERR_PTR(-ENOENT);
3237 ffs_dev->mounted = true;
3243 static void ffs_release_dev(struct ffs_data *ffs_data)
3245 struct ffs_dev *ffs_dev;
3250 ffs_dev = ffs_data->private_data;
3252 ffs_dev->mounted = false;
3254 if (ffs_dev->ffs_release_dev_callback)
3255 ffs_dev->ffs_release_dev_callback(ffs_dev);
3261 static int ffs_ready(struct ffs_data *ffs)
3263 struct ffs_dev *ffs_obj;
3269 ffs_obj = ffs->private_data;
3274 if (WARN_ON(ffs_obj->desc_ready)) {
3279 ffs_obj->desc_ready = true;
3280 ffs_obj->ffs_data = ffs;
3282 if (ffs_obj->ffs_ready_callback)
3283 ret = ffs_obj->ffs_ready_callback(ffs);
3290 static void ffs_closed(struct ffs_data *ffs)
3292 struct ffs_dev *ffs_obj;
3297 ffs_obj = ffs->private_data;
3301 ffs_obj->desc_ready = false;
3303 if (ffs_obj->ffs_closed_callback)
3304 ffs_obj->ffs_closed_callback(ffs);
3306 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
3307 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
3310 unregister_gadget_item(ffs_obj->opts->
3311 func_inst.group.cg_item.ci_parent->ci_parent);
3316 /* Misc helper functions ****************************************************/
3318 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3321 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3322 : mutex_lock_interruptible(mutex);
3325 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3332 data = kmalloc(len, GFP_KERNEL);
3333 if (unlikely(!data))
3334 return ERR_PTR(-ENOMEM);
3336 if (unlikely(__copy_from_user(data, buf, len))) {
3338 return ERR_PTR(-EFAULT);
3341 pr_vdebug("Buffer from user space:\n");
3342 ffs_dump_mem("", data, len);
3347 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3348 MODULE_LICENSE("GPL");
3349 MODULE_AUTHOR("Michal Nazarewicz");