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 struct ffs_desc_helper {
159 struct ffs_data *ffs;
160 unsigned interfaces_count;
164 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
165 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
167 static struct dentry *
168 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
169 const struct file_operations *fops);
171 /* Devices management *******************************************************/
173 DEFINE_MUTEX(ffs_lock);
174 EXPORT_SYMBOL_GPL(ffs_lock);
176 static struct ffs_dev *_ffs_find_dev(const char *name);
177 static struct ffs_dev *_ffs_alloc_dev(void);
178 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
179 static void _ffs_free_dev(struct ffs_dev *dev);
180 static void *ffs_acquire_dev(const char *dev_name);
181 static void ffs_release_dev(struct ffs_data *ffs_data);
182 static int ffs_ready(struct ffs_data *ffs);
183 static void ffs_closed(struct ffs_data *ffs);
185 /* Misc helper functions ****************************************************/
187 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
188 __attribute__((warn_unused_result, nonnull));
189 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
190 __attribute__((warn_unused_result, nonnull));
193 /* Control file aka ep0 *****************************************************/
195 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
197 struct ffs_data *ffs = req->context;
199 complete_all(&ffs->ep0req_completion);
202 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
204 struct usb_request *req = ffs->ep0req;
207 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
209 spin_unlock_irq(&ffs->ev.waitq.lock);
215 * UDC layer requires to provide a buffer even for ZLP, but should
216 * not use it at all. Let's provide some poisoned pointer to catch
217 * possible bug in the driver.
219 if (req->buf == NULL)
220 req->buf = (void *)0xDEADBABE;
222 reinit_completion(&ffs->ep0req_completion);
224 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
225 if (unlikely(ret < 0))
228 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
230 usb_ep_dequeue(ffs->gadget->ep0, req);
234 ffs->setup_state = FFS_NO_SETUP;
235 return req->status ? req->status : req->actual;
238 static int __ffs_ep0_stall(struct ffs_data *ffs)
240 if (ffs->ev.can_stall) {
241 pr_vdebug("ep0 stall\n");
242 usb_ep_set_halt(ffs->gadget->ep0);
243 ffs->setup_state = FFS_NO_SETUP;
246 pr_debug("bogus ep0 stall!\n");
251 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
252 size_t len, loff_t *ptr)
254 struct ffs_data *ffs = file->private_data;
260 /* Fast check if setup was canceled */
261 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
265 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
266 if (unlikely(ret < 0))
270 switch (ffs->state) {
271 case FFS_READ_DESCRIPTORS:
272 case FFS_READ_STRINGS:
274 if (unlikely(len < 16)) {
279 data = ffs_prepare_buffer(buf, len);
286 if (ffs->state == FFS_READ_DESCRIPTORS) {
287 pr_info("read descriptors\n");
288 ret = __ffs_data_got_descs(ffs, data, len);
289 if (unlikely(ret < 0))
292 ffs->state = FFS_READ_STRINGS;
295 pr_info("read strings\n");
296 ret = __ffs_data_got_strings(ffs, data, len);
297 if (unlikely(ret < 0))
300 ret = ffs_epfiles_create(ffs);
302 ffs->state = FFS_CLOSING;
306 ffs->state = FFS_ACTIVE;
307 mutex_unlock(&ffs->mutex);
309 ret = ffs_ready(ffs);
310 if (unlikely(ret < 0)) {
311 ffs->state = FFS_CLOSING;
315 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
323 * We're called from user space, we can use _irq
324 * rather then _irqsave
326 spin_lock_irq(&ffs->ev.waitq.lock);
327 switch (ffs_setup_state_clear_cancelled(ffs)) {
328 case FFS_SETUP_CANCELLED:
336 case FFS_SETUP_PENDING:
340 /* FFS_SETUP_PENDING */
341 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
342 spin_unlock_irq(&ffs->ev.waitq.lock);
343 ret = __ffs_ep0_stall(ffs);
347 /* FFS_SETUP_PENDING and not stall */
348 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
350 spin_unlock_irq(&ffs->ev.waitq.lock);
352 data = ffs_prepare_buffer(buf, len);
358 spin_lock_irq(&ffs->ev.waitq.lock);
361 * We are guaranteed to be still in FFS_ACTIVE state
362 * but the state of setup could have changed from
363 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
364 * to check for that. If that happened we copied data
365 * from user space in vain but it's unlikely.
367 * For sure we are not in FFS_NO_SETUP since this is
368 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
369 * transition can be performed and it's protected by
372 if (ffs_setup_state_clear_cancelled(ffs) ==
373 FFS_SETUP_CANCELLED) {
376 spin_unlock_irq(&ffs->ev.waitq.lock);
378 /* unlocks spinlock */
379 ret = __ffs_ep0_queue_wait(ffs, data, len);
389 mutex_unlock(&ffs->mutex);
393 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
397 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
400 struct usb_functionfs_event events[n];
403 memset(events, 0, sizeof events);
406 events[i].type = ffs->ev.types[i];
407 if (events[i].type == FUNCTIONFS_SETUP) {
408 events[i].u.setup = ffs->ev.setup;
409 ffs->setup_state = FFS_SETUP_PENDING;
413 if (n < ffs->ev.count) {
415 memmove(ffs->ev.types, ffs->ev.types + n,
416 ffs->ev.count * sizeof *ffs->ev.types);
421 spin_unlock_irq(&ffs->ev.waitq.lock);
422 mutex_unlock(&ffs->mutex);
424 return unlikely(__copy_to_user(buf, events, sizeof events))
425 ? -EFAULT : sizeof events;
428 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
429 size_t len, loff_t *ptr)
431 struct ffs_data *ffs = file->private_data;
438 /* Fast check if setup was canceled */
439 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
443 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
444 if (unlikely(ret < 0))
448 if (ffs->state != FFS_ACTIVE) {
454 * We're called from user space, we can use _irq rather then
457 spin_lock_irq(&ffs->ev.waitq.lock);
459 switch (ffs_setup_state_clear_cancelled(ffs)) {
460 case FFS_SETUP_CANCELLED:
465 n = len / sizeof(struct usb_functionfs_event);
471 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
476 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
482 return __ffs_ep0_read_events(ffs, buf,
483 min(n, (size_t)ffs->ev.count));
485 case FFS_SETUP_PENDING:
486 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
487 spin_unlock_irq(&ffs->ev.waitq.lock);
488 ret = __ffs_ep0_stall(ffs);
492 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
494 spin_unlock_irq(&ffs->ev.waitq.lock);
497 data = kmalloc(len, GFP_KERNEL);
498 if (unlikely(!data)) {
504 spin_lock_irq(&ffs->ev.waitq.lock);
506 /* See ffs_ep0_write() */
507 if (ffs_setup_state_clear_cancelled(ffs) ==
508 FFS_SETUP_CANCELLED) {
513 /* unlocks spinlock */
514 ret = __ffs_ep0_queue_wait(ffs, data, len);
515 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
524 spin_unlock_irq(&ffs->ev.waitq.lock);
526 mutex_unlock(&ffs->mutex);
531 static int ffs_ep0_open(struct inode *inode, struct file *file)
533 struct ffs_data *ffs = inode->i_private;
537 if (unlikely(ffs->state == FFS_CLOSING))
540 file->private_data = ffs;
541 ffs_data_opened(ffs);
546 static int ffs_ep0_release(struct inode *inode, struct file *file)
548 struct ffs_data *ffs = file->private_data;
552 ffs_data_closed(ffs);
557 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
559 struct ffs_data *ffs = file->private_data;
560 struct usb_gadget *gadget = ffs->gadget;
565 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
566 struct ffs_function *func = ffs->func;
567 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
568 } else if (gadget && gadget->ops->ioctl) {
569 ret = gadget->ops->ioctl(gadget, code, value);
577 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
579 struct ffs_data *ffs = file->private_data;
580 unsigned int mask = POLLWRNORM;
583 poll_wait(file, &ffs->ev.waitq, wait);
585 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
586 if (unlikely(ret < 0))
589 switch (ffs->state) {
590 case FFS_READ_DESCRIPTORS:
591 case FFS_READ_STRINGS:
596 switch (ffs->setup_state) {
602 case FFS_SETUP_PENDING:
603 case FFS_SETUP_CANCELLED:
604 mask |= (POLLIN | POLLOUT);
611 mutex_unlock(&ffs->mutex);
616 static const struct file_operations ffs_ep0_operations = {
619 .open = ffs_ep0_open,
620 .write = ffs_ep0_write,
621 .read = ffs_ep0_read,
622 .release = ffs_ep0_release,
623 .unlocked_ioctl = ffs_ep0_ioctl,
624 .poll = ffs_ep0_poll,
628 /* "Normal" endpoints operations ********************************************/
630 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
633 if (likely(req->context)) {
634 struct ffs_ep *ep = _ep->driver_data;
635 ep->status = req->status ? req->status : req->actual;
636 complete(req->context);
640 static void ffs_user_copy_worker(struct work_struct *work)
642 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
644 int ret = io_data->req->status ? io_data->req->status :
645 io_data->req->actual;
647 if (io_data->read && ret > 0) {
651 for (i = 0; i < io_data->nr_segs; i++) {
652 if (unlikely(copy_to_user(io_data->iovec[i].iov_base,
654 io_data->iovec[i].iov_len))) {
658 pos += io_data->iovec[i].iov_len;
660 unuse_mm(io_data->mm);
663 aio_complete(io_data->kiocb, ret, ret);
665 usb_ep_free_request(io_data->ep, io_data->req);
667 io_data->kiocb->private = NULL;
669 kfree(io_data->iovec);
674 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
675 struct usb_request *req)
677 struct ffs_io_data *io_data = req->context;
681 INIT_WORK(&io_data->work, ffs_user_copy_worker);
682 schedule_work(&io_data->work);
685 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
687 struct ffs_epfile *epfile = file->private_data;
690 ssize_t ret, data_len;
693 /* Are we still active? */
694 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
699 /* Wait for endpoint to be enabled */
702 if (file->f_flags & O_NONBLOCK) {
707 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
715 halt = (!io_data->read == !epfile->in);
716 if (halt && epfile->isoc) {
721 /* Allocate & copy */
724 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
725 * before the waiting completes, so do not assign to 'gadget' earlier
727 struct usb_gadget *gadget = epfile->ffs->gadget;
729 spin_lock_irq(&epfile->ffs->eps_lock);
730 /* In the meantime, endpoint got disabled or changed. */
731 if (epfile->ep != ep) {
732 spin_unlock_irq(&epfile->ffs->eps_lock);
736 * Controller may require buffer size to be aligned to
737 * maxpacketsize of an out endpoint.
739 data_len = io_data->read ?
740 usb_ep_align_maybe(gadget, ep->ep, io_data->len) :
742 spin_unlock_irq(&epfile->ffs->eps_lock);
744 data = kmalloc(data_len, GFP_KERNEL);
747 if (io_data->aio && !io_data->read) {
750 for (i = 0; i < io_data->nr_segs; i++) {
751 if (unlikely(copy_from_user(&data[pos],
752 io_data->iovec[i].iov_base,
753 io_data->iovec[i].iov_len))) {
757 pos += io_data->iovec[i].iov_len;
760 if (!io_data->read &&
761 unlikely(__copy_from_user(data, io_data->buf,
769 /* We will be using request */
770 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
774 spin_lock_irq(&epfile->ffs->eps_lock);
776 if (epfile->ep != ep) {
777 /* In the meantime, endpoint got disabled or changed. */
779 spin_unlock_irq(&epfile->ffs->eps_lock);
782 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
783 usb_ep_set_halt(ep->ep);
784 spin_unlock_irq(&epfile->ffs->eps_lock);
787 /* Fire the request */
788 struct usb_request *req;
791 req = usb_ep_alloc_request(ep->ep, GFP_KERNEL);
796 req->length = io_data->len;
799 io_data->ep = ep->ep;
802 req->context = io_data;
803 req->complete = ffs_epfile_async_io_complete;
805 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
807 usb_ep_free_request(ep->ep, req);
812 spin_unlock_irq(&epfile->ffs->eps_lock);
814 DECLARE_COMPLETION_ONSTACK(done);
818 req->length = io_data->len;
820 req->context = &done;
821 req->complete = ffs_epfile_io_complete;
823 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
825 spin_unlock_irq(&epfile->ffs->eps_lock);
827 if (unlikely(ret < 0)) {
830 wait_for_completion_interruptible(&done))) {
832 usb_ep_dequeue(ep->ep, req);
835 * XXX We may end up silently droping data
836 * here. Since data_len (i.e. req->length) may
837 * be bigger than len (after being rounded up
838 * to maxpacketsize), we may end up with more
839 * data then user space has space for.
842 if (io_data->read && ret > 0) {
843 ret = min_t(size_t, ret, io_data->len);
845 if (unlikely(copy_to_user(io_data->buf,
854 mutex_unlock(&epfile->mutex);
858 spin_unlock_irq(&epfile->ffs->eps_lock);
859 mutex_unlock(&epfile->mutex);
866 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
869 struct ffs_io_data io_data;
874 io_data.read = false;
875 io_data.buf = (char * __user)buf;
878 return ffs_epfile_io(file, &io_data);
882 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
884 struct ffs_io_data io_data;
893 return ffs_epfile_io(file, &io_data);
897 ffs_epfile_open(struct inode *inode, struct file *file)
899 struct ffs_epfile *epfile = inode->i_private;
903 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
906 file->private_data = epfile;
907 ffs_data_opened(epfile->ffs);
912 static int ffs_aio_cancel(struct kiocb *kiocb)
914 struct ffs_io_data *io_data = kiocb->private;
915 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
920 spin_lock_irq(&epfile->ffs->eps_lock);
922 if (likely(io_data && io_data->ep && io_data->req))
923 value = usb_ep_dequeue(io_data->ep, io_data->req);
927 spin_unlock_irq(&epfile->ffs->eps_lock);
932 static ssize_t ffs_epfile_aio_write(struct kiocb *kiocb,
933 const struct iovec *iovec,
934 unsigned long nr_segs, loff_t loff)
936 struct ffs_io_data *io_data;
940 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
941 if (unlikely(!io_data))
945 io_data->read = false;
946 io_data->kiocb = kiocb;
947 io_data->iovec = iovec;
948 io_data->nr_segs = nr_segs;
949 io_data->len = kiocb->ki_nbytes;
950 io_data->mm = current->mm;
952 kiocb->private = io_data;
954 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
956 return ffs_epfile_io(kiocb->ki_filp, io_data);
959 static ssize_t ffs_epfile_aio_read(struct kiocb *kiocb,
960 const struct iovec *iovec,
961 unsigned long nr_segs, loff_t loff)
963 struct ffs_io_data *io_data;
964 struct iovec *iovec_copy;
968 iovec_copy = kmalloc_array(nr_segs, sizeof(*iovec_copy), GFP_KERNEL);
969 if (unlikely(!iovec_copy))
972 memcpy(iovec_copy, iovec, sizeof(struct iovec)*nr_segs);
974 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
975 if (unlikely(!io_data)) {
981 io_data->read = true;
982 io_data->kiocb = kiocb;
983 io_data->iovec = iovec_copy;
984 io_data->nr_segs = nr_segs;
985 io_data->len = kiocb->ki_nbytes;
986 io_data->mm = current->mm;
988 kiocb->private = io_data;
990 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
992 return ffs_epfile_io(kiocb->ki_filp, io_data);
996 ffs_epfile_release(struct inode *inode, struct file *file)
998 struct ffs_epfile *epfile = inode->i_private;
1002 ffs_data_closed(epfile->ffs);
1007 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1008 unsigned long value)
1010 struct ffs_epfile *epfile = file->private_data;
1015 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1018 spin_lock_irq(&epfile->ffs->eps_lock);
1019 if (likely(epfile->ep)) {
1021 case FUNCTIONFS_FIFO_STATUS:
1022 ret = usb_ep_fifo_status(epfile->ep->ep);
1024 case FUNCTIONFS_FIFO_FLUSH:
1025 usb_ep_fifo_flush(epfile->ep->ep);
1028 case FUNCTIONFS_CLEAR_HALT:
1029 ret = usb_ep_clear_halt(epfile->ep->ep);
1031 case FUNCTIONFS_ENDPOINT_REVMAP:
1032 ret = epfile->ep->num;
1040 spin_unlock_irq(&epfile->ffs->eps_lock);
1045 static const struct file_operations ffs_epfile_operations = {
1046 .llseek = no_llseek,
1048 .open = ffs_epfile_open,
1049 .write = ffs_epfile_write,
1050 .read = ffs_epfile_read,
1051 .aio_write = ffs_epfile_aio_write,
1052 .aio_read = ffs_epfile_aio_read,
1053 .release = ffs_epfile_release,
1054 .unlocked_ioctl = ffs_epfile_ioctl,
1058 /* File system and super block operations ***********************************/
1061 * Mounting the file system creates a controller file, used first for
1062 * function configuration then later for event monitoring.
1065 static struct inode *__must_check
1066 ffs_sb_make_inode(struct super_block *sb, void *data,
1067 const struct file_operations *fops,
1068 const struct inode_operations *iops,
1069 struct ffs_file_perms *perms)
1071 struct inode *inode;
1075 inode = new_inode(sb);
1077 if (likely(inode)) {
1078 struct timespec current_time = CURRENT_TIME;
1080 inode->i_ino = get_next_ino();
1081 inode->i_mode = perms->mode;
1082 inode->i_uid = perms->uid;
1083 inode->i_gid = perms->gid;
1084 inode->i_atime = current_time;
1085 inode->i_mtime = current_time;
1086 inode->i_ctime = current_time;
1087 inode->i_private = data;
1089 inode->i_fop = fops;
1097 /* Create "regular" file */
1098 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1099 const char *name, void *data,
1100 const struct file_operations *fops)
1102 struct ffs_data *ffs = sb->s_fs_info;
1103 struct dentry *dentry;
1104 struct inode *inode;
1108 dentry = d_alloc_name(sb->s_root, name);
1109 if (unlikely(!dentry))
1112 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1113 if (unlikely(!inode)) {
1118 d_add(dentry, inode);
1123 static const struct super_operations ffs_sb_operations = {
1124 .statfs = simple_statfs,
1125 .drop_inode = generic_delete_inode,
1128 struct ffs_sb_fill_data {
1129 struct ffs_file_perms perms;
1131 const char *dev_name;
1132 struct ffs_data *ffs_data;
1135 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1137 struct ffs_sb_fill_data *data = _data;
1138 struct inode *inode;
1139 struct ffs_data *ffs = data->ffs_data;
1144 data->ffs_data = NULL;
1145 sb->s_fs_info = ffs;
1146 sb->s_blocksize = PAGE_CACHE_SIZE;
1147 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1148 sb->s_magic = FUNCTIONFS_MAGIC;
1149 sb->s_op = &ffs_sb_operations;
1150 sb->s_time_gran = 1;
1153 data->perms.mode = data->root_mode;
1154 inode = ffs_sb_make_inode(sb, NULL,
1155 &simple_dir_operations,
1156 &simple_dir_inode_operations,
1158 sb->s_root = d_make_root(inode);
1159 if (unlikely(!sb->s_root))
1163 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1164 &ffs_ep0_operations)))
1170 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1174 if (!opts || !*opts)
1178 unsigned long value;
1182 comma = strchr(opts, ',');
1187 eq = strchr(opts, '=');
1188 if (unlikely(!eq)) {
1189 pr_err("'=' missing in %s\n", opts);
1195 if (kstrtoul(eq + 1, 0, &value)) {
1196 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1200 /* Interpret option */
1201 switch (eq - opts) {
1203 if (!memcmp(opts, "rmode", 5))
1204 data->root_mode = (value & 0555) | S_IFDIR;
1205 else if (!memcmp(opts, "fmode", 5))
1206 data->perms.mode = (value & 0666) | S_IFREG;
1212 if (!memcmp(opts, "mode", 4)) {
1213 data->root_mode = (value & 0555) | S_IFDIR;
1214 data->perms.mode = (value & 0666) | S_IFREG;
1221 if (!memcmp(opts, "uid", 3)) {
1222 data->perms.uid = make_kuid(current_user_ns(), value);
1223 if (!uid_valid(data->perms.uid)) {
1224 pr_err("%s: unmapped value: %lu\n", opts, value);
1227 } else if (!memcmp(opts, "gid", 3)) {
1228 data->perms.gid = make_kgid(current_user_ns(), value);
1229 if (!gid_valid(data->perms.gid)) {
1230 pr_err("%s: unmapped value: %lu\n", opts, value);
1240 pr_err("%s: invalid option\n", opts);
1244 /* Next iteration */
1253 /* "mount -t functionfs dev_name /dev/function" ends up here */
1255 static struct dentry *
1256 ffs_fs_mount(struct file_system_type *t, int flags,
1257 const char *dev_name, void *opts)
1259 struct ffs_sb_fill_data data = {
1261 .mode = S_IFREG | 0600,
1262 .uid = GLOBAL_ROOT_UID,
1263 .gid = GLOBAL_ROOT_GID,
1265 .root_mode = S_IFDIR | 0500,
1270 struct ffs_data *ffs;
1274 ret = ffs_fs_parse_opts(&data, opts);
1275 if (unlikely(ret < 0))
1276 return ERR_PTR(ret);
1278 ffs = ffs_data_new();
1280 return ERR_PTR(-ENOMEM);
1281 ffs->file_perms = data.perms;
1283 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1284 if (unlikely(!ffs->dev_name)) {
1286 return ERR_PTR(-ENOMEM);
1289 ffs_dev = ffs_acquire_dev(dev_name);
1290 if (IS_ERR(ffs_dev)) {
1292 return ERR_CAST(ffs_dev);
1294 ffs->private_data = ffs_dev;
1295 data.ffs_data = ffs;
1297 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1298 if (IS_ERR(rv) && data.ffs_data) {
1299 ffs_release_dev(data.ffs_data);
1300 ffs_data_put(data.ffs_data);
1306 ffs_fs_kill_sb(struct super_block *sb)
1310 kill_litter_super(sb);
1311 if (sb->s_fs_info) {
1312 ffs_release_dev(sb->s_fs_info);
1313 ffs_data_put(sb->s_fs_info);
1317 static struct file_system_type ffs_fs_type = {
1318 .owner = THIS_MODULE,
1319 .name = "functionfs",
1320 .mount = ffs_fs_mount,
1321 .kill_sb = ffs_fs_kill_sb,
1323 MODULE_ALIAS_FS("functionfs");
1326 /* Driver's main init/cleanup functions *************************************/
1328 static int functionfs_init(void)
1334 ret = register_filesystem(&ffs_fs_type);
1336 pr_info("file system registered\n");
1338 pr_err("failed registering file system (%d)\n", ret);
1343 static void functionfs_cleanup(void)
1347 pr_info("unloading\n");
1348 unregister_filesystem(&ffs_fs_type);
1352 /* ffs_data and ffs_function construction and destruction code **************/
1354 static void ffs_data_clear(struct ffs_data *ffs);
1355 static void ffs_data_reset(struct ffs_data *ffs);
1357 static void ffs_data_get(struct ffs_data *ffs)
1361 atomic_inc(&ffs->ref);
1364 static void ffs_data_opened(struct ffs_data *ffs)
1368 atomic_inc(&ffs->ref);
1369 atomic_inc(&ffs->opened);
1372 static void ffs_data_put(struct ffs_data *ffs)
1376 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1377 pr_info("%s(): freeing\n", __func__);
1378 ffs_data_clear(ffs);
1379 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1380 waitqueue_active(&ffs->ep0req_completion.wait));
1381 kfree(ffs->dev_name);
1386 static void ffs_data_closed(struct ffs_data *ffs)
1390 if (atomic_dec_and_test(&ffs->opened)) {
1391 ffs->state = FFS_CLOSING;
1392 ffs_data_reset(ffs);
1398 static struct ffs_data *ffs_data_new(void)
1400 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1406 atomic_set(&ffs->ref, 1);
1407 atomic_set(&ffs->opened, 0);
1408 ffs->state = FFS_READ_DESCRIPTORS;
1409 mutex_init(&ffs->mutex);
1410 spin_lock_init(&ffs->eps_lock);
1411 init_waitqueue_head(&ffs->ev.waitq);
1412 init_completion(&ffs->ep0req_completion);
1414 /* XXX REVISIT need to update it in some places, or do we? */
1415 ffs->ev.can_stall = 1;
1420 static void ffs_data_clear(struct ffs_data *ffs)
1424 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1427 BUG_ON(ffs->gadget);
1430 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1432 kfree(ffs->raw_descs_data);
1433 kfree(ffs->raw_strings);
1434 kfree(ffs->stringtabs);
1437 static void ffs_data_reset(struct ffs_data *ffs)
1441 ffs_data_clear(ffs);
1443 ffs->epfiles = NULL;
1444 ffs->raw_descs_data = NULL;
1445 ffs->raw_descs = NULL;
1446 ffs->raw_strings = NULL;
1447 ffs->stringtabs = NULL;
1449 ffs->raw_descs_length = 0;
1450 ffs->fs_descs_count = 0;
1451 ffs->hs_descs_count = 0;
1452 ffs->ss_descs_count = 0;
1454 ffs->strings_count = 0;
1455 ffs->interfaces_count = 0;
1460 ffs->state = FFS_READ_DESCRIPTORS;
1461 ffs->setup_state = FFS_NO_SETUP;
1466 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1468 struct usb_gadget_strings **lang;
1473 if (WARN_ON(ffs->state != FFS_ACTIVE
1474 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1477 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1478 if (unlikely(first_id < 0))
1481 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1482 if (unlikely(!ffs->ep0req))
1484 ffs->ep0req->complete = ffs_ep0_complete;
1485 ffs->ep0req->context = ffs;
1487 lang = ffs->stringtabs;
1489 for (; *lang; ++lang) {
1490 struct usb_string *str = (*lang)->strings;
1492 for (; str->s; ++id, ++str)
1497 ffs->gadget = cdev->gadget;
1502 static void functionfs_unbind(struct ffs_data *ffs)
1506 if (!WARN_ON(!ffs->gadget)) {
1507 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1510 clear_bit(FFS_FL_BOUND, &ffs->flags);
1515 static int ffs_epfiles_create(struct ffs_data *ffs)
1517 struct ffs_epfile *epfile, *epfiles;
1522 count = ffs->eps_count;
1523 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1528 for (i = 1; i <= count; ++i, ++epfile) {
1530 mutex_init(&epfile->mutex);
1531 init_waitqueue_head(&epfile->wait);
1532 sprintf(epfiles->name, "ep%u", i);
1533 epfile->dentry = ffs_sb_create_file(ffs->sb, epfiles->name,
1535 &ffs_epfile_operations);
1536 if (unlikely(!epfile->dentry)) {
1537 ffs_epfiles_destroy(epfiles, i - 1);
1542 ffs->epfiles = epfiles;
1546 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1548 struct ffs_epfile *epfile = epfiles;
1552 for (; count; --count, ++epfile) {
1553 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1554 waitqueue_active(&epfile->wait));
1555 if (epfile->dentry) {
1556 d_delete(epfile->dentry);
1557 dput(epfile->dentry);
1558 epfile->dentry = NULL;
1566 static void ffs_func_eps_disable(struct ffs_function *func)
1568 struct ffs_ep *ep = func->eps;
1569 struct ffs_epfile *epfile = func->ffs->epfiles;
1570 unsigned count = func->ffs->eps_count;
1571 unsigned long flags;
1573 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1575 /* pending requests get nuked */
1577 usb_ep_disable(ep->ep);
1583 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1586 static int ffs_func_eps_enable(struct ffs_function *func)
1588 struct ffs_data *ffs = func->ffs;
1589 struct ffs_ep *ep = func->eps;
1590 struct ffs_epfile *epfile = ffs->epfiles;
1591 unsigned count = ffs->eps_count;
1592 unsigned long flags;
1595 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1597 struct usb_endpoint_descriptor *ds;
1600 if (ffs->gadget->speed == USB_SPEED_SUPER)
1602 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1607 /* fall-back to lower speed if desc missing for current speed */
1609 ds = ep->descs[desc_idx];
1610 } while (!ds && --desc_idx >= 0);
1617 ep->ep->driver_data = ep;
1619 ret = usb_ep_enable(ep->ep);
1622 epfile->in = usb_endpoint_dir_in(ds);
1623 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1628 wake_up(&epfile->wait);
1633 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1639 /* Parsing and building descriptors and strings *****************************/
1642 * This validates if data pointed by data is a valid USB descriptor as
1643 * well as record how many interfaces, endpoints and strings are
1644 * required by given configuration. Returns address after the
1645 * descriptor or NULL if data is invalid.
1648 enum ffs_entity_type {
1649 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1652 enum ffs_os_desc_type {
1653 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1656 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1658 struct usb_descriptor_header *desc,
1661 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1662 struct usb_os_desc_header *h, void *data,
1663 unsigned len, void *priv);
1665 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1666 ffs_entity_callback entity,
1669 struct usb_descriptor_header *_ds = (void *)data;
1675 /* At least two bytes are required: length and type */
1677 pr_vdebug("descriptor too short\n");
1681 /* If we have at least as many bytes as the descriptor takes? */
1682 length = _ds->bLength;
1684 pr_vdebug("descriptor longer then available data\n");
1688 #define __entity_check_INTERFACE(val) 1
1689 #define __entity_check_STRING(val) (val)
1690 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1691 #define __entity(type, val) do { \
1692 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1693 if (unlikely(!__entity_check_ ##type(val))) { \
1694 pr_vdebug("invalid entity's value\n"); \
1697 ret = entity(FFS_ ##type, &val, _ds, priv); \
1698 if (unlikely(ret < 0)) { \
1699 pr_debug("entity " #type "(%02x); ret = %d\n", \
1705 /* Parse descriptor depending on type. */
1706 switch (_ds->bDescriptorType) {
1710 case USB_DT_DEVICE_QUALIFIER:
1711 /* function can't have any of those */
1712 pr_vdebug("descriptor reserved for gadget: %d\n",
1713 _ds->bDescriptorType);
1716 case USB_DT_INTERFACE: {
1717 struct usb_interface_descriptor *ds = (void *)_ds;
1718 pr_vdebug("interface descriptor\n");
1719 if (length != sizeof *ds)
1722 __entity(INTERFACE, ds->bInterfaceNumber);
1724 __entity(STRING, ds->iInterface);
1728 case USB_DT_ENDPOINT: {
1729 struct usb_endpoint_descriptor *ds = (void *)_ds;
1730 pr_vdebug("endpoint descriptor\n");
1731 if (length != USB_DT_ENDPOINT_SIZE &&
1732 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1734 __entity(ENDPOINT, ds->bEndpointAddress);
1739 pr_vdebug("hid descriptor\n");
1740 if (length != sizeof(struct hid_descriptor))
1745 if (length != sizeof(struct usb_otg_descriptor))
1749 case USB_DT_INTERFACE_ASSOCIATION: {
1750 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1751 pr_vdebug("interface association descriptor\n");
1752 if (length != sizeof *ds)
1755 __entity(STRING, ds->iFunction);
1759 case USB_DT_SS_ENDPOINT_COMP:
1760 pr_vdebug("EP SS companion descriptor\n");
1761 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1765 case USB_DT_OTHER_SPEED_CONFIG:
1766 case USB_DT_INTERFACE_POWER:
1768 case USB_DT_SECURITY:
1769 case USB_DT_CS_RADIO_CONTROL:
1771 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1775 /* We should never be here */
1776 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1780 pr_vdebug("invalid length: %d (descriptor %d)\n",
1781 _ds->bLength, _ds->bDescriptorType);
1786 #undef __entity_check_DESCRIPTOR
1787 #undef __entity_check_INTERFACE
1788 #undef __entity_check_STRING
1789 #undef __entity_check_ENDPOINT
1794 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1795 ffs_entity_callback entity, void *priv)
1797 const unsigned _len = len;
1798 unsigned long num = 0;
1808 /* Record "descriptor" entity */
1809 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1810 if (unlikely(ret < 0)) {
1811 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1819 ret = ffs_do_single_desc(data, len, entity, priv);
1820 if (unlikely(ret < 0)) {
1821 pr_debug("%s returns %d\n", __func__, ret);
1831 static int __ffs_data_do_entity(enum ffs_entity_type type,
1832 u8 *valuep, struct usb_descriptor_header *desc,
1835 struct ffs_desc_helper *helper = priv;
1836 struct usb_endpoint_descriptor *d;
1841 case FFS_DESCRIPTOR:
1846 * Interfaces are indexed from zero so if we
1847 * encountered interface "n" then there are at least
1850 if (*valuep >= helper->interfaces_count)
1851 helper->interfaces_count = *valuep + 1;
1856 * Strings are indexed from 1 (0 is magic ;) reserved
1857 * for languages list or some such)
1859 if (*valuep > helper->ffs->strings_count)
1860 helper->ffs->strings_count = *valuep;
1865 helper->eps_count++;
1866 if (helper->eps_count >= 15)
1868 /* Check if descriptors for any speed were already parsed */
1869 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
1870 helper->ffs->eps_addrmap[helper->eps_count] =
1871 d->bEndpointAddress;
1872 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
1873 d->bEndpointAddress)
1881 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1882 struct usb_os_desc_header *desc)
1884 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1885 u16 w_index = le16_to_cpu(desc->wIndex);
1887 if (bcd_version != 1) {
1888 pr_vdebug("unsupported os descriptors version: %d",
1894 *next_type = FFS_OS_DESC_EXT_COMPAT;
1897 *next_type = FFS_OS_DESC_EXT_PROP;
1900 pr_vdebug("unsupported os descriptor type: %d", w_index);
1904 return sizeof(*desc);
1908 * Process all extended compatibility/extended property descriptors
1909 * of a feature descriptor
1911 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1912 enum ffs_os_desc_type type,
1914 ffs_os_desc_callback entity,
1916 struct usb_os_desc_header *h)
1919 const unsigned _len = len;
1923 /* loop over all ext compat/ext prop descriptors */
1924 while (feature_count--) {
1925 ret = entity(type, h, data, len, priv);
1926 if (unlikely(ret < 0)) {
1927 pr_debug("bad OS descriptor, type: %d\n", type);
1936 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1937 static int __must_check ffs_do_os_descs(unsigned count,
1938 char *data, unsigned len,
1939 ffs_os_desc_callback entity, void *priv)
1941 const unsigned _len = len;
1942 unsigned long num = 0;
1946 for (num = 0; num < count; ++num) {
1948 enum ffs_os_desc_type type;
1950 struct usb_os_desc_header *desc = (void *)data;
1952 if (len < sizeof(*desc))
1956 * Record "descriptor" entity.
1957 * Process dwLength, bcdVersion, wIndex, get b/wCount.
1958 * Move the data pointer to the beginning of extended
1959 * compatibilities proper or extended properties proper
1960 * portions of the data
1962 if (le32_to_cpu(desc->dwLength) > len)
1965 ret = __ffs_do_os_desc_header(&type, desc);
1966 if (unlikely(ret < 0)) {
1967 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
1972 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
1974 feature_count = le16_to_cpu(desc->wCount);
1975 if (type == FFS_OS_DESC_EXT_COMPAT &&
1976 (feature_count > 255 || desc->Reserved))
1982 * Process all function/property descriptors
1983 * of this Feature Descriptor
1985 ret = ffs_do_single_os_desc(data, len, type,
1986 feature_count, entity, priv, desc);
1987 if (unlikely(ret < 0)) {
1988 pr_debug("%s returns %d\n", __func__, ret);
1999 * Validate contents of the buffer from userspace related to OS descriptors.
2001 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2002 struct usb_os_desc_header *h, void *data,
2003 unsigned len, void *priv)
2005 struct ffs_data *ffs = priv;
2011 case FFS_OS_DESC_EXT_COMPAT: {
2012 struct usb_ext_compat_desc *d = data;
2015 if (len < sizeof(*d) ||
2016 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2019 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2020 if (d->Reserved2[i])
2023 length = sizeof(struct usb_ext_compat_desc);
2026 case FFS_OS_DESC_EXT_PROP: {
2027 struct usb_ext_prop_desc *d = data;
2031 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2033 length = le32_to_cpu(d->dwSize);
2034 type = le32_to_cpu(d->dwPropertyDataType);
2035 if (type < USB_EXT_PROP_UNICODE ||
2036 type > USB_EXT_PROP_UNICODE_MULTI) {
2037 pr_vdebug("unsupported os descriptor property type: %d",
2041 pnl = le16_to_cpu(d->wPropertyNameLength);
2042 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2043 if (length != 14 + pnl + pdl) {
2044 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2045 length, pnl, pdl, type);
2048 ++ffs->ms_os_descs_ext_prop_count;
2049 /* property name reported to the host as "WCHAR"s */
2050 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2051 ffs->ms_os_descs_ext_prop_data_len += pdl;
2055 pr_vdebug("unknown descriptor: %d\n", type);
2061 static int __ffs_data_got_descs(struct ffs_data *ffs,
2062 char *const _data, size_t len)
2064 char *data = _data, *raw_descs;
2065 unsigned os_descs_count = 0, counts[3], flags;
2066 int ret = -EINVAL, i;
2067 struct ffs_desc_helper helper;
2071 if (get_unaligned_le32(data + 4) != len)
2074 switch (get_unaligned_le32(data)) {
2075 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2076 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2080 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2081 flags = get_unaligned_le32(data + 8);
2082 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2083 FUNCTIONFS_HAS_HS_DESC |
2084 FUNCTIONFS_HAS_SS_DESC |
2085 FUNCTIONFS_HAS_MS_OS_DESC)) {
2096 /* Read fs_count, hs_count and ss_count (if present) */
2097 for (i = 0; i < 3; ++i) {
2098 if (!(flags & (1 << i))) {
2100 } else if (len < 4) {
2103 counts[i] = get_unaligned_le32(data);
2108 if (flags & (1 << i)) {
2109 os_descs_count = get_unaligned_le32(data);
2114 /* Read descriptors */
2117 for (i = 0; i < 3; ++i) {
2120 helper.interfaces_count = 0;
2121 helper.eps_count = 0;
2122 ret = ffs_do_descs(counts[i], data, len,
2123 __ffs_data_do_entity, &helper);
2126 if (!ffs->eps_count && !ffs->interfaces_count) {
2127 ffs->eps_count = helper.eps_count;
2128 ffs->interfaces_count = helper.interfaces_count;
2130 if (ffs->eps_count != helper.eps_count) {
2134 if (ffs->interfaces_count != helper.interfaces_count) {
2142 if (os_descs_count) {
2143 ret = ffs_do_os_descs(os_descs_count, data, len,
2144 __ffs_data_do_os_desc, ffs);
2151 if (raw_descs == data || len) {
2156 ffs->raw_descs_data = _data;
2157 ffs->raw_descs = raw_descs;
2158 ffs->raw_descs_length = data - raw_descs;
2159 ffs->fs_descs_count = counts[0];
2160 ffs->hs_descs_count = counts[1];
2161 ffs->ss_descs_count = counts[2];
2162 ffs->ms_os_descs_count = os_descs_count;
2171 static int __ffs_data_got_strings(struct ffs_data *ffs,
2172 char *const _data, size_t len)
2174 u32 str_count, needed_count, lang_count;
2175 struct usb_gadget_strings **stringtabs, *t;
2176 struct usb_string *strings, *s;
2177 const char *data = _data;
2181 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2182 get_unaligned_le32(data + 4) != len))
2184 str_count = get_unaligned_le32(data + 8);
2185 lang_count = get_unaligned_le32(data + 12);
2187 /* if one is zero the other must be zero */
2188 if (unlikely(!str_count != !lang_count))
2191 /* Do we have at least as many strings as descriptors need? */
2192 needed_count = ffs->strings_count;
2193 if (unlikely(str_count < needed_count))
2197 * If we don't need any strings just return and free all
2200 if (!needed_count) {
2205 /* Allocate everything in one chunk so there's less maintenance. */
2209 vla_item(d, struct usb_gadget_strings *, stringtabs,
2211 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2212 vla_item(d, struct usb_string, strings,
2213 lang_count*(needed_count+1));
2215 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2217 if (unlikely(!vlabuf)) {
2222 /* Initialize the VLA pointers */
2223 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2224 t = vla_ptr(vlabuf, d, stringtab);
2227 *stringtabs++ = t++;
2231 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2232 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2233 t = vla_ptr(vlabuf, d, stringtab);
2234 s = vla_ptr(vlabuf, d, strings);
2238 /* For each language */
2242 do { /* lang_count > 0 so we can use do-while */
2243 unsigned needed = needed_count;
2245 if (unlikely(len < 3))
2247 t->language = get_unaligned_le16(data);
2254 /* For each string */
2255 do { /* str_count > 0 so we can use do-while */
2256 size_t length = strnlen(data, len);
2258 if (unlikely(length == len))
2262 * User may provide more strings then we need,
2263 * if that's the case we simply ignore the
2266 if (likely(needed)) {
2268 * s->id will be set while adding
2269 * function to configuration so for
2270 * now just leave garbage here.
2279 } while (--str_count);
2281 s->id = 0; /* terminator */
2285 } while (--lang_count);
2287 /* Some garbage left? */
2292 ffs->stringtabs = stringtabs;
2293 ffs->raw_strings = _data;
2305 /* Events handling and management *******************************************/
2307 static void __ffs_event_add(struct ffs_data *ffs,
2308 enum usb_functionfs_event_type type)
2310 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2314 * Abort any unhandled setup
2316 * We do not need to worry about some cmpxchg() changing value
2317 * of ffs->setup_state without holding the lock because when
2318 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2319 * the source does nothing.
2321 if (ffs->setup_state == FFS_SETUP_PENDING)
2322 ffs->setup_state = FFS_SETUP_CANCELLED;
2325 case FUNCTIONFS_RESUME:
2326 rem_type2 = FUNCTIONFS_SUSPEND;
2328 case FUNCTIONFS_SUSPEND:
2329 case FUNCTIONFS_SETUP:
2331 /* Discard all similar events */
2334 case FUNCTIONFS_BIND:
2335 case FUNCTIONFS_UNBIND:
2336 case FUNCTIONFS_DISABLE:
2337 case FUNCTIONFS_ENABLE:
2338 /* Discard everything other then power management. */
2339 rem_type1 = FUNCTIONFS_SUSPEND;
2340 rem_type2 = FUNCTIONFS_RESUME;
2349 u8 *ev = ffs->ev.types, *out = ev;
2350 unsigned n = ffs->ev.count;
2351 for (; n; --n, ++ev)
2352 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2355 pr_vdebug("purging event %d\n", *ev);
2356 ffs->ev.count = out - ffs->ev.types;
2359 pr_vdebug("adding event %d\n", type);
2360 ffs->ev.types[ffs->ev.count++] = type;
2361 wake_up_locked(&ffs->ev.waitq);
2364 static void ffs_event_add(struct ffs_data *ffs,
2365 enum usb_functionfs_event_type type)
2367 unsigned long flags;
2368 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2369 __ffs_event_add(ffs, type);
2370 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2373 /* Bind/unbind USB function hooks *******************************************/
2375 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2379 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2380 if (ffs->eps_addrmap[i] == endpoint_address)
2385 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2386 struct usb_descriptor_header *desc,
2389 struct usb_endpoint_descriptor *ds = (void *)desc;
2390 struct ffs_function *func = priv;
2391 struct ffs_ep *ffs_ep;
2392 unsigned ep_desc_id, idx;
2393 static const char *speed_names[] = { "full", "high", "super" };
2395 if (type != FFS_DESCRIPTOR)
2399 * If ss_descriptors is not NULL, we are reading super speed
2400 * descriptors; if hs_descriptors is not NULL, we are reading high
2401 * speed descriptors; otherwise, we are reading full speed
2404 if (func->function.ss_descriptors) {
2406 func->function.ss_descriptors[(long)valuep] = desc;
2407 } else if (func->function.hs_descriptors) {
2409 func->function.hs_descriptors[(long)valuep] = desc;
2412 func->function.fs_descriptors[(long)valuep] = desc;
2415 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2418 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2422 ffs_ep = func->eps + idx;
2424 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2425 pr_err("two %sspeed descriptors for EP %d\n",
2426 speed_names[ep_desc_id],
2427 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2430 ffs_ep->descs[ep_desc_id] = ds;
2432 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2434 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2435 if (!ds->wMaxPacketSize)
2436 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2438 struct usb_request *req;
2441 pr_vdebug("autoconfig\n");
2442 ep = usb_ep_autoconfig(func->gadget, ds);
2445 ep->driver_data = func->eps + idx;
2447 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2453 func->eps_revmap[ds->bEndpointAddress &
2454 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2456 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2461 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2462 struct usb_descriptor_header *desc,
2465 struct ffs_function *func = priv;
2471 case FFS_DESCRIPTOR:
2472 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2477 if (func->interfaces_nums[idx] < 0) {
2478 int id = usb_interface_id(func->conf, &func->function);
2479 if (unlikely(id < 0))
2481 func->interfaces_nums[idx] = id;
2483 newValue = func->interfaces_nums[idx];
2487 /* String' IDs are allocated when fsf_data is bound to cdev */
2488 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2493 * USB_DT_ENDPOINT are handled in
2494 * __ffs_func_bind_do_descs().
2496 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2499 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2500 if (unlikely(!func->eps[idx].ep))
2504 struct usb_endpoint_descriptor **descs;
2505 descs = func->eps[idx].descs;
2506 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2511 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2516 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2517 struct usb_os_desc_header *h, void *data,
2518 unsigned len, void *priv)
2520 struct ffs_function *func = priv;
2524 case FFS_OS_DESC_EXT_COMPAT: {
2525 struct usb_ext_compat_desc *desc = data;
2526 struct usb_os_desc_table *t;
2528 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2529 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2530 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2531 ARRAY_SIZE(desc->CompatibleID) +
2532 ARRAY_SIZE(desc->SubCompatibleID));
2533 length = sizeof(*desc);
2536 case FFS_OS_DESC_EXT_PROP: {
2537 struct usb_ext_prop_desc *desc = data;
2538 struct usb_os_desc_table *t;
2539 struct usb_os_desc_ext_prop *ext_prop;
2540 char *ext_prop_name;
2541 char *ext_prop_data;
2543 t = &func->function.os_desc_table[h->interface];
2544 t->if_id = func->interfaces_nums[h->interface];
2546 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2547 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2549 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2550 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2551 ext_prop->data_len = le32_to_cpu(*(u32 *)
2552 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2553 length = ext_prop->name_len + ext_prop->data_len + 14;
2555 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2556 func->ffs->ms_os_descs_ext_prop_name_avail +=
2559 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2560 func->ffs->ms_os_descs_ext_prop_data_avail +=
2562 memcpy(ext_prop_data,
2563 usb_ext_prop_data_ptr(data, ext_prop->name_len),
2564 ext_prop->data_len);
2565 /* unicode data reported to the host as "WCHAR"s */
2566 switch (ext_prop->type) {
2567 case USB_EXT_PROP_UNICODE:
2568 case USB_EXT_PROP_UNICODE_ENV:
2569 case USB_EXT_PROP_UNICODE_LINK:
2570 case USB_EXT_PROP_UNICODE_MULTI:
2571 ext_prop->data_len *= 2;
2574 ext_prop->data = ext_prop_data;
2576 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2577 ext_prop->name_len);
2578 /* property name reported to the host as "WCHAR"s */
2579 ext_prop->name_len *= 2;
2580 ext_prop->name = ext_prop_name;
2582 t->os_desc->ext_prop_len +=
2583 ext_prop->name_len + ext_prop->data_len + 14;
2584 ++t->os_desc->ext_prop_count;
2585 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2589 pr_vdebug("unknown descriptor: %d\n", type);
2595 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2596 struct usb_configuration *c)
2598 struct ffs_function *func = ffs_func_from_usb(f);
2599 struct f_fs_opts *ffs_opts =
2600 container_of(f->fi, struct f_fs_opts, func_inst);
2606 * Legacy gadget triggers binding in functionfs_ready_callback,
2607 * which already uses locking; taking the same lock here would
2610 * Configfs-enabled gadgets however do need ffs_dev_lock.
2612 if (!ffs_opts->no_configfs)
2614 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2615 func->ffs = ffs_opts->dev->ffs_data;
2616 if (!ffs_opts->no_configfs)
2619 return ERR_PTR(ret);
2622 func->gadget = c->cdev->gadget;
2624 ffs_data_get(func->ffs);
2627 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2628 * configurations are bound in sequence with list_for_each_entry,
2629 * in each configuration its functions are bound in sequence
2630 * with list_for_each_entry, so we assume no race condition
2631 * with regard to ffs_opts->bound access
2633 if (!ffs_opts->refcnt) {
2634 ret = functionfs_bind(func->ffs, c->cdev);
2636 return ERR_PTR(ret);
2639 func->function.strings = func->ffs->stringtabs;
2644 static int _ffs_func_bind(struct usb_configuration *c,
2645 struct usb_function *f)
2647 struct ffs_function *func = ffs_func_from_usb(f);
2648 struct ffs_data *ffs = func->ffs;
2650 const int full = !!func->ffs->fs_descs_count;
2651 const int high = gadget_is_dualspeed(func->gadget) &&
2652 func->ffs->hs_descs_count;
2653 const int super = gadget_is_superspeed(func->gadget) &&
2654 func->ffs->ss_descs_count;
2656 int fs_len, hs_len, ss_len, ret, i;
2658 /* Make it a single chunk, less management later on */
2660 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2661 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2662 full ? ffs->fs_descs_count + 1 : 0);
2663 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2664 high ? ffs->hs_descs_count + 1 : 0);
2665 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2666 super ? ffs->ss_descs_count + 1 : 0);
2667 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2668 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2669 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2670 vla_item_with_sz(d, char[16], ext_compat,
2671 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2672 vla_item_with_sz(d, struct usb_os_desc, os_desc,
2673 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2674 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2675 ffs->ms_os_descs_ext_prop_count);
2676 vla_item_with_sz(d, char, ext_prop_name,
2677 ffs->ms_os_descs_ext_prop_name_len);
2678 vla_item_with_sz(d, char, ext_prop_data,
2679 ffs->ms_os_descs_ext_prop_data_len);
2680 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2685 /* Has descriptors only for speeds gadget does not support */
2686 if (unlikely(!(full | high | super)))
2689 /* Allocate a single chunk, less management later on */
2690 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2691 if (unlikely(!vlabuf))
2694 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2695 ffs->ms_os_descs_ext_prop_name_avail =
2696 vla_ptr(vlabuf, d, ext_prop_name);
2697 ffs->ms_os_descs_ext_prop_data_avail =
2698 vla_ptr(vlabuf, d, ext_prop_data);
2700 /* Copy descriptors */
2701 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2702 ffs->raw_descs_length);
2704 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2705 for (ret = ffs->eps_count; ret; --ret) {
2708 ptr = vla_ptr(vlabuf, d, eps);
2713 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2715 func->eps = vla_ptr(vlabuf, d, eps);
2716 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2719 * Go through all the endpoint descriptors and allocate
2720 * endpoints first, so that later we can rewrite the endpoint
2721 * numbers without worrying that it may be described later on.
2724 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2725 fs_len = ffs_do_descs(ffs->fs_descs_count,
2726 vla_ptr(vlabuf, d, raw_descs),
2728 __ffs_func_bind_do_descs, func);
2729 if (unlikely(fs_len < 0)) {
2738 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2739 hs_len = ffs_do_descs(ffs->hs_descs_count,
2740 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2741 d_raw_descs__sz - fs_len,
2742 __ffs_func_bind_do_descs, func);
2743 if (unlikely(hs_len < 0)) {
2751 if (likely(super)) {
2752 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2753 ss_len = ffs_do_descs(ffs->ss_descs_count,
2754 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2755 d_raw_descs__sz - fs_len - hs_len,
2756 __ffs_func_bind_do_descs, func);
2757 if (unlikely(ss_len < 0)) {
2766 * Now handle interface numbers allocation and interface and
2767 * endpoint numbers rewriting. We can do that in one go
2770 ret = ffs_do_descs(ffs->fs_descs_count +
2771 (high ? ffs->hs_descs_count : 0) +
2772 (super ? ffs->ss_descs_count : 0),
2773 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2774 __ffs_func_bind_do_nums, func);
2775 if (unlikely(ret < 0))
2778 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2779 if (c->cdev->use_os_string)
2780 for (i = 0; i < ffs->interfaces_count; ++i) {
2781 struct usb_os_desc *desc;
2783 desc = func->function.os_desc_table[i].os_desc =
2784 vla_ptr(vlabuf, d, os_desc) +
2785 i * sizeof(struct usb_os_desc);
2786 desc->ext_compat_id =
2787 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2788 INIT_LIST_HEAD(&desc->ext_prop);
2790 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2791 vla_ptr(vlabuf, d, raw_descs) +
2792 fs_len + hs_len + ss_len,
2793 d_raw_descs__sz - fs_len - hs_len - ss_len,
2794 __ffs_func_bind_do_os_desc, func);
2795 if (unlikely(ret < 0))
2797 func->function.os_desc_n =
2798 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2800 /* And we're done */
2801 ffs_event_add(ffs, FUNCTIONFS_BIND);
2805 /* XXX Do we need to release all claimed endpoints here? */
2809 static int ffs_func_bind(struct usb_configuration *c,
2810 struct usb_function *f)
2812 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2814 if (IS_ERR(ffs_opts))
2815 return PTR_ERR(ffs_opts);
2817 return _ffs_func_bind(c, f);
2821 /* Other USB function hooks *************************************************/
2823 static int ffs_func_set_alt(struct usb_function *f,
2824 unsigned interface, unsigned alt)
2826 struct ffs_function *func = ffs_func_from_usb(f);
2827 struct ffs_data *ffs = func->ffs;
2830 if (alt != (unsigned)-1) {
2831 intf = ffs_func_revmap_intf(func, interface);
2832 if (unlikely(intf < 0))
2837 ffs_func_eps_disable(ffs->func);
2839 if (ffs->state != FFS_ACTIVE)
2842 if (alt == (unsigned)-1) {
2844 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2849 ret = ffs_func_eps_enable(func);
2850 if (likely(ret >= 0))
2851 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2855 static void ffs_func_disable(struct usb_function *f)
2857 ffs_func_set_alt(f, 0, (unsigned)-1);
2860 static int ffs_func_setup(struct usb_function *f,
2861 const struct usb_ctrlrequest *creq)
2863 struct ffs_function *func = ffs_func_from_usb(f);
2864 struct ffs_data *ffs = func->ffs;
2865 unsigned long flags;
2870 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2871 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2872 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2873 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2874 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2877 * Most requests directed to interface go through here
2878 * (notable exceptions are set/get interface) so we need to
2879 * handle them. All other either handled by composite or
2880 * passed to usb_configuration->setup() (if one is set). No
2881 * matter, we will handle requests directed to endpoint here
2882 * as well (as it's straightforward) but what to do with any
2885 if (ffs->state != FFS_ACTIVE)
2888 switch (creq->bRequestType & USB_RECIP_MASK) {
2889 case USB_RECIP_INTERFACE:
2890 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2891 if (unlikely(ret < 0))
2895 case USB_RECIP_ENDPOINT:
2896 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2897 if (unlikely(ret < 0))
2905 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2906 ffs->ev.setup = *creq;
2907 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2908 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2909 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2914 static void ffs_func_suspend(struct usb_function *f)
2917 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2920 static void ffs_func_resume(struct usb_function *f)
2923 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2927 /* Endpoint and interface numbers reverse mapping ***************************/
2929 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2931 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2932 return num ? num : -EDOM;
2935 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2937 short *nums = func->interfaces_nums;
2938 unsigned count = func->ffs->interfaces_count;
2940 for (; count; --count, ++nums) {
2941 if (*nums >= 0 && *nums == intf)
2942 return nums - func->interfaces_nums;
2949 /* Devices management *******************************************************/
2951 static LIST_HEAD(ffs_devices);
2953 static struct ffs_dev *_ffs_do_find_dev(const char *name)
2955 struct ffs_dev *dev;
2957 list_for_each_entry(dev, &ffs_devices, entry) {
2958 if (!dev->name || !name)
2960 if (strcmp(dev->name, name) == 0)
2968 * ffs_lock must be taken by the caller of this function
2970 static struct ffs_dev *_ffs_get_single_dev(void)
2972 struct ffs_dev *dev;
2974 if (list_is_singular(&ffs_devices)) {
2975 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
2984 * ffs_lock must be taken by the caller of this function
2986 static struct ffs_dev *_ffs_find_dev(const char *name)
2988 struct ffs_dev *dev;
2990 dev = _ffs_get_single_dev();
2994 return _ffs_do_find_dev(name);
2997 /* Configfs support *********************************************************/
2999 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3001 return container_of(to_config_group(item), struct f_fs_opts,
3005 static void ffs_attr_release(struct config_item *item)
3007 struct f_fs_opts *opts = to_ffs_opts(item);
3009 usb_put_function_instance(&opts->func_inst);
3012 static struct configfs_item_operations ffs_item_ops = {
3013 .release = ffs_attr_release,
3016 static struct config_item_type ffs_func_type = {
3017 .ct_item_ops = &ffs_item_ops,
3018 .ct_owner = THIS_MODULE,
3022 /* Function registration interface ******************************************/
3024 static void ffs_free_inst(struct usb_function_instance *f)
3026 struct f_fs_opts *opts;
3028 opts = to_f_fs_opts(f);
3030 _ffs_free_dev(opts->dev);
3035 #define MAX_INST_NAME_LEN 40
3037 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3039 struct f_fs_opts *opts;
3044 name_len = strlen(name) + 1;
3045 if (name_len > MAX_INST_NAME_LEN)
3046 return -ENAMETOOLONG;
3048 ptr = kstrndup(name, name_len, GFP_KERNEL);
3052 opts = to_f_fs_opts(fi);
3057 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3058 ret = _ffs_name_dev(opts->dev, ptr);
3064 opts->dev->name_allocated = true;
3073 static struct usb_function_instance *ffs_alloc_inst(void)
3075 struct f_fs_opts *opts;
3076 struct ffs_dev *dev;
3078 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3080 return ERR_PTR(-ENOMEM);
3082 opts->func_inst.set_inst_name = ffs_set_inst_name;
3083 opts->func_inst.free_func_inst = ffs_free_inst;
3085 dev = _ffs_alloc_dev();
3089 return ERR_CAST(dev);
3094 config_group_init_type_name(&opts->func_inst.group, "",
3096 return &opts->func_inst;
3099 static void ffs_free(struct usb_function *f)
3101 kfree(ffs_func_from_usb(f));
3104 static void ffs_func_unbind(struct usb_configuration *c,
3105 struct usb_function *f)
3107 struct ffs_function *func = ffs_func_from_usb(f);
3108 struct ffs_data *ffs = func->ffs;
3109 struct f_fs_opts *opts =
3110 container_of(f->fi, struct f_fs_opts, func_inst);
3111 struct ffs_ep *ep = func->eps;
3112 unsigned count = ffs->eps_count;
3113 unsigned long flags;
3116 if (ffs->func == func) {
3117 ffs_func_eps_disable(func);
3121 if (!--opts->refcnt)
3122 functionfs_unbind(ffs);
3124 /* cleanup after autoconfig */
3125 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3127 if (ep->ep && ep->req)
3128 usb_ep_free_request(ep->ep, ep->req);
3132 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3136 * eps, descriptors and interfaces_nums are allocated in the
3137 * same chunk so only one free is required.
3139 func->function.fs_descriptors = NULL;
3140 func->function.hs_descriptors = NULL;
3141 func->function.ss_descriptors = NULL;
3142 func->interfaces_nums = NULL;
3144 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3147 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3149 struct ffs_function *func;
3153 func = kzalloc(sizeof(*func), GFP_KERNEL);
3154 if (unlikely(!func))
3155 return ERR_PTR(-ENOMEM);
3157 func->function.name = "Function FS Gadget";
3159 func->function.bind = ffs_func_bind;
3160 func->function.unbind = ffs_func_unbind;
3161 func->function.set_alt = ffs_func_set_alt;
3162 func->function.disable = ffs_func_disable;
3163 func->function.setup = ffs_func_setup;
3164 func->function.suspend = ffs_func_suspend;
3165 func->function.resume = ffs_func_resume;
3166 func->function.free_func = ffs_free;
3168 return &func->function;
3172 * ffs_lock must be taken by the caller of this function
3174 static struct ffs_dev *_ffs_alloc_dev(void)
3176 struct ffs_dev *dev;
3179 if (_ffs_get_single_dev())
3180 return ERR_PTR(-EBUSY);
3182 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3184 return ERR_PTR(-ENOMEM);
3186 if (list_empty(&ffs_devices)) {
3187 ret = functionfs_init();
3190 return ERR_PTR(ret);
3194 list_add(&dev->entry, &ffs_devices);
3200 * ffs_lock must be taken by the caller of this function
3201 * The caller is responsible for "name" being available whenever f_fs needs it
3203 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3205 struct ffs_dev *existing;
3207 existing = _ffs_do_find_dev(name);
3217 * The caller is responsible for "name" being available whenever f_fs needs it
3219 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3224 ret = _ffs_name_dev(dev, name);
3229 EXPORT_SYMBOL_GPL(ffs_name_dev);
3231 int ffs_single_dev(struct ffs_dev *dev)
3238 if (!list_is_singular(&ffs_devices))
3246 EXPORT_SYMBOL_GPL(ffs_single_dev);
3249 * ffs_lock must be taken by the caller of this function
3251 static void _ffs_free_dev(struct ffs_dev *dev)
3253 list_del(&dev->entry);
3254 if (dev->name_allocated)
3257 if (list_empty(&ffs_devices))
3258 functionfs_cleanup();
3261 static void *ffs_acquire_dev(const char *dev_name)
3263 struct ffs_dev *ffs_dev;
3268 ffs_dev = _ffs_find_dev(dev_name);
3270 ffs_dev = ERR_PTR(-ENOENT);
3271 else if (ffs_dev->mounted)
3272 ffs_dev = ERR_PTR(-EBUSY);
3273 else if (ffs_dev->ffs_acquire_dev_callback &&
3274 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3275 ffs_dev = ERR_PTR(-ENOENT);
3277 ffs_dev->mounted = true;
3283 static void ffs_release_dev(struct ffs_data *ffs_data)
3285 struct ffs_dev *ffs_dev;
3290 ffs_dev = ffs_data->private_data;
3292 ffs_dev->mounted = false;
3294 if (ffs_dev->ffs_release_dev_callback)
3295 ffs_dev->ffs_release_dev_callback(ffs_dev);
3301 static int ffs_ready(struct ffs_data *ffs)
3303 struct ffs_dev *ffs_obj;
3309 ffs_obj = ffs->private_data;
3314 if (WARN_ON(ffs_obj->desc_ready)) {
3319 ffs_obj->desc_ready = true;
3320 ffs_obj->ffs_data = ffs;
3322 if (ffs_obj->ffs_ready_callback)
3323 ret = ffs_obj->ffs_ready_callback(ffs);
3330 static void ffs_closed(struct ffs_data *ffs)
3332 struct ffs_dev *ffs_obj;
3337 ffs_obj = ffs->private_data;
3341 ffs_obj->desc_ready = false;
3343 if (ffs_obj->ffs_closed_callback)
3344 ffs_obj->ffs_closed_callback(ffs);
3346 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
3347 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
3350 unregister_gadget_item(ffs_obj->opts->
3351 func_inst.group.cg_item.ci_parent->ci_parent);
3356 /* Misc helper functions ****************************************************/
3358 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3361 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3362 : mutex_lock_interruptible(mutex);
3365 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3372 data = kmalloc(len, GFP_KERNEL);
3373 if (unlikely(!data))
3374 return ERR_PTR(-ENOMEM);
3376 if (unlikely(__copy_from_user(data, buf, len))) {
3378 return ERR_PTR(-EFAULT);
3381 pr_vdebug("Buffer from user space:\n");
3382 ffs_dump_mem("", data, len);
3387 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3388 MODULE_LICENSE("GPL");
3389 MODULE_AUTHOR("Michal Nazarewicz");