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) {
652 * Since req->length may be bigger than io_data->len (after
653 * being rounded up to maxpacketsize), we may end up with more
654 * data then user space has space for.
656 ret = min_t(int, ret, io_data->len);
659 for (i = 0; i < io_data->nr_segs; i++) {
660 size_t len = min_t(size_t, ret - pos,
661 io_data->iovec[i].iov_len);
664 if (unlikely(copy_to_user(io_data->iovec[i].iov_base,
665 &io_data->buf[pos], len))) {
671 unuse_mm(io_data->mm);
674 aio_complete(io_data->kiocb, ret, ret);
676 usb_ep_free_request(io_data->ep, io_data->req);
678 io_data->kiocb->private = NULL;
680 kfree(io_data->iovec);
685 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
686 struct usb_request *req)
688 struct ffs_io_data *io_data = req->context;
692 INIT_WORK(&io_data->work, ffs_user_copy_worker);
693 schedule_work(&io_data->work);
696 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
698 struct ffs_epfile *epfile = file->private_data;
701 ssize_t ret, data_len = -EINVAL;
704 /* Are we still active? */
705 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
710 /* Wait for endpoint to be enabled */
713 if (file->f_flags & O_NONBLOCK) {
718 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
726 halt = (!io_data->read == !epfile->in);
727 if (halt && epfile->isoc) {
732 /* Allocate & copy */
735 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
736 * before the waiting completes, so do not assign to 'gadget' earlier
738 struct usb_gadget *gadget = epfile->ffs->gadget;
740 spin_lock_irq(&epfile->ffs->eps_lock);
741 /* In the meantime, endpoint got disabled or changed. */
742 if (epfile->ep != ep) {
743 spin_unlock_irq(&epfile->ffs->eps_lock);
747 * Controller may require buffer size to be aligned to
748 * maxpacketsize of an out endpoint.
750 data_len = io_data->read ?
751 usb_ep_align_maybe(gadget, ep->ep, io_data->len) :
753 spin_unlock_irq(&epfile->ffs->eps_lock);
755 data = kmalloc(data_len, GFP_KERNEL);
758 if (io_data->aio && !io_data->read) {
761 for (i = 0; i < io_data->nr_segs; i++) {
762 if (unlikely(copy_from_user(&data[pos],
763 io_data->iovec[i].iov_base,
764 io_data->iovec[i].iov_len))) {
768 pos += io_data->iovec[i].iov_len;
771 if (!io_data->read &&
772 unlikely(__copy_from_user(data, io_data->buf,
780 /* We will be using request */
781 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
785 spin_lock_irq(&epfile->ffs->eps_lock);
787 if (epfile->ep != ep) {
788 /* In the meantime, endpoint got disabled or changed. */
790 spin_unlock_irq(&epfile->ffs->eps_lock);
793 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
794 usb_ep_set_halt(ep->ep);
795 spin_unlock_irq(&epfile->ffs->eps_lock);
798 /* Fire the request */
799 struct usb_request *req;
802 * Sanity Check: even though data_len can't be used
803 * uninitialized at the time I write this comment, some
804 * compilers complain about this situation.
805 * In order to keep the code clean from warnings, data_len is
806 * being initialized to -EINVAL during its declaration, which
807 * means we can't rely on compiler anymore to warn no future
808 * changes won't result in data_len being used uninitialized.
809 * For such reason, we're adding this redundant sanity check
812 if (unlikely(data_len == -EINVAL)) {
813 WARN(1, "%s: data_len == -EINVAL\n", __func__);
819 req = usb_ep_alloc_request(ep->ep, GFP_KERNEL);
824 req->length = data_len;
827 io_data->ep = ep->ep;
830 req->context = io_data;
831 req->complete = ffs_epfile_async_io_complete;
833 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
835 usb_ep_free_request(ep->ep, req);
840 spin_unlock_irq(&epfile->ffs->eps_lock);
842 DECLARE_COMPLETION_ONSTACK(done);
846 req->length = data_len;
848 req->context = &done;
849 req->complete = ffs_epfile_io_complete;
851 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
853 spin_unlock_irq(&epfile->ffs->eps_lock);
855 if (unlikely(ret < 0)) {
858 wait_for_completion_interruptible(&done))) {
860 usb_ep_dequeue(ep->ep, req);
863 * XXX We may end up silently droping data
864 * here. Since data_len (i.e. req->length) may
865 * be bigger than len (after being rounded up
866 * to maxpacketsize), we may end up with more
867 * data then user space has space for.
870 if (io_data->read && ret > 0) {
871 ret = min_t(size_t, ret, io_data->len);
873 if (unlikely(copy_to_user(io_data->buf,
882 mutex_unlock(&epfile->mutex);
886 spin_unlock_irq(&epfile->ffs->eps_lock);
887 mutex_unlock(&epfile->mutex);
894 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
897 struct ffs_io_data io_data;
902 io_data.read = false;
903 io_data.buf = (char * __user)buf;
906 return ffs_epfile_io(file, &io_data);
910 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
912 struct ffs_io_data io_data;
921 return ffs_epfile_io(file, &io_data);
925 ffs_epfile_open(struct inode *inode, struct file *file)
927 struct ffs_epfile *epfile = inode->i_private;
931 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
934 file->private_data = epfile;
935 ffs_data_opened(epfile->ffs);
940 static int ffs_aio_cancel(struct kiocb *kiocb)
942 struct ffs_io_data *io_data = kiocb->private;
943 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
948 spin_lock_irq(&epfile->ffs->eps_lock);
950 if (likely(io_data && io_data->ep && io_data->req))
951 value = usb_ep_dequeue(io_data->ep, io_data->req);
955 spin_unlock_irq(&epfile->ffs->eps_lock);
960 static ssize_t ffs_epfile_aio_write(struct kiocb *kiocb,
961 const struct iovec *iovec,
962 unsigned long nr_segs, loff_t loff)
964 struct ffs_io_data *io_data;
968 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
969 if (unlikely(!io_data))
973 io_data->read = false;
974 io_data->kiocb = kiocb;
975 io_data->iovec = iovec;
976 io_data->nr_segs = nr_segs;
977 io_data->len = kiocb->ki_nbytes;
978 io_data->mm = current->mm;
980 kiocb->private = io_data;
982 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
984 return ffs_epfile_io(kiocb->ki_filp, io_data);
987 static ssize_t ffs_epfile_aio_read(struct kiocb *kiocb,
988 const struct iovec *iovec,
989 unsigned long nr_segs, loff_t loff)
991 struct ffs_io_data *io_data;
992 struct iovec *iovec_copy;
996 iovec_copy = kmalloc_array(nr_segs, sizeof(*iovec_copy), GFP_KERNEL);
997 if (unlikely(!iovec_copy))
1000 memcpy(iovec_copy, iovec, sizeof(struct iovec)*nr_segs);
1002 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
1003 if (unlikely(!io_data)) {
1008 io_data->aio = true;
1009 io_data->read = true;
1010 io_data->kiocb = kiocb;
1011 io_data->iovec = iovec_copy;
1012 io_data->nr_segs = nr_segs;
1013 io_data->len = kiocb->ki_nbytes;
1014 io_data->mm = current->mm;
1016 kiocb->private = io_data;
1018 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1020 return ffs_epfile_io(kiocb->ki_filp, io_data);
1024 ffs_epfile_release(struct inode *inode, struct file *file)
1026 struct ffs_epfile *epfile = inode->i_private;
1030 ffs_data_closed(epfile->ffs);
1035 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1036 unsigned long value)
1038 struct ffs_epfile *epfile = file->private_data;
1043 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1046 spin_lock_irq(&epfile->ffs->eps_lock);
1047 if (likely(epfile->ep)) {
1049 case FUNCTIONFS_FIFO_STATUS:
1050 ret = usb_ep_fifo_status(epfile->ep->ep);
1052 case FUNCTIONFS_FIFO_FLUSH:
1053 usb_ep_fifo_flush(epfile->ep->ep);
1056 case FUNCTIONFS_CLEAR_HALT:
1057 ret = usb_ep_clear_halt(epfile->ep->ep);
1059 case FUNCTIONFS_ENDPOINT_REVMAP:
1060 ret = epfile->ep->num;
1062 case FUNCTIONFS_ENDPOINT_DESC:
1065 struct usb_endpoint_descriptor *desc;
1067 switch (epfile->ffs->gadget->speed) {
1068 case USB_SPEED_SUPER:
1071 case USB_SPEED_HIGH:
1077 desc = epfile->ep->descs[desc_idx];
1079 spin_unlock_irq(&epfile->ffs->eps_lock);
1080 ret = copy_to_user((void *)value, desc, sizeof(*desc));
1091 spin_unlock_irq(&epfile->ffs->eps_lock);
1096 static const struct file_operations ffs_epfile_operations = {
1097 .llseek = no_llseek,
1099 .open = ffs_epfile_open,
1100 .write = ffs_epfile_write,
1101 .read = ffs_epfile_read,
1102 .aio_write = ffs_epfile_aio_write,
1103 .aio_read = ffs_epfile_aio_read,
1104 .release = ffs_epfile_release,
1105 .unlocked_ioctl = ffs_epfile_ioctl,
1109 /* File system and super block operations ***********************************/
1112 * Mounting the file system creates a controller file, used first for
1113 * function configuration then later for event monitoring.
1116 static struct inode *__must_check
1117 ffs_sb_make_inode(struct super_block *sb, void *data,
1118 const struct file_operations *fops,
1119 const struct inode_operations *iops,
1120 struct ffs_file_perms *perms)
1122 struct inode *inode;
1126 inode = new_inode(sb);
1128 if (likely(inode)) {
1129 struct timespec current_time = CURRENT_TIME;
1131 inode->i_ino = get_next_ino();
1132 inode->i_mode = perms->mode;
1133 inode->i_uid = perms->uid;
1134 inode->i_gid = perms->gid;
1135 inode->i_atime = current_time;
1136 inode->i_mtime = current_time;
1137 inode->i_ctime = current_time;
1138 inode->i_private = data;
1140 inode->i_fop = fops;
1148 /* Create "regular" file */
1149 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1150 const char *name, void *data,
1151 const struct file_operations *fops)
1153 struct ffs_data *ffs = sb->s_fs_info;
1154 struct dentry *dentry;
1155 struct inode *inode;
1159 dentry = d_alloc_name(sb->s_root, name);
1160 if (unlikely(!dentry))
1163 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1164 if (unlikely(!inode)) {
1169 d_add(dentry, inode);
1174 static const struct super_operations ffs_sb_operations = {
1175 .statfs = simple_statfs,
1176 .drop_inode = generic_delete_inode,
1179 struct ffs_sb_fill_data {
1180 struct ffs_file_perms perms;
1182 const char *dev_name;
1183 struct ffs_data *ffs_data;
1186 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1188 struct ffs_sb_fill_data *data = _data;
1189 struct inode *inode;
1190 struct ffs_data *ffs = data->ffs_data;
1195 data->ffs_data = NULL;
1196 sb->s_fs_info = ffs;
1197 sb->s_blocksize = PAGE_CACHE_SIZE;
1198 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1199 sb->s_magic = FUNCTIONFS_MAGIC;
1200 sb->s_op = &ffs_sb_operations;
1201 sb->s_time_gran = 1;
1204 data->perms.mode = data->root_mode;
1205 inode = ffs_sb_make_inode(sb, NULL,
1206 &simple_dir_operations,
1207 &simple_dir_inode_operations,
1209 sb->s_root = d_make_root(inode);
1210 if (unlikely(!sb->s_root))
1214 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1215 &ffs_ep0_operations)))
1221 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1225 if (!opts || !*opts)
1229 unsigned long value;
1233 comma = strchr(opts, ',');
1238 eq = strchr(opts, '=');
1239 if (unlikely(!eq)) {
1240 pr_err("'=' missing in %s\n", opts);
1246 if (kstrtoul(eq + 1, 0, &value)) {
1247 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1251 /* Interpret option */
1252 switch (eq - opts) {
1254 if (!memcmp(opts, "rmode", 5))
1255 data->root_mode = (value & 0555) | S_IFDIR;
1256 else if (!memcmp(opts, "fmode", 5))
1257 data->perms.mode = (value & 0666) | S_IFREG;
1263 if (!memcmp(opts, "mode", 4)) {
1264 data->root_mode = (value & 0555) | S_IFDIR;
1265 data->perms.mode = (value & 0666) | S_IFREG;
1272 if (!memcmp(opts, "uid", 3)) {
1273 data->perms.uid = make_kuid(current_user_ns(), value);
1274 if (!uid_valid(data->perms.uid)) {
1275 pr_err("%s: unmapped value: %lu\n", opts, value);
1278 } else if (!memcmp(opts, "gid", 3)) {
1279 data->perms.gid = make_kgid(current_user_ns(), value);
1280 if (!gid_valid(data->perms.gid)) {
1281 pr_err("%s: unmapped value: %lu\n", opts, value);
1291 pr_err("%s: invalid option\n", opts);
1295 /* Next iteration */
1304 /* "mount -t functionfs dev_name /dev/function" ends up here */
1306 static struct dentry *
1307 ffs_fs_mount(struct file_system_type *t, int flags,
1308 const char *dev_name, void *opts)
1310 struct ffs_sb_fill_data data = {
1312 .mode = S_IFREG | 0600,
1313 .uid = GLOBAL_ROOT_UID,
1314 .gid = GLOBAL_ROOT_GID,
1316 .root_mode = S_IFDIR | 0500,
1321 struct ffs_data *ffs;
1325 ret = ffs_fs_parse_opts(&data, opts);
1326 if (unlikely(ret < 0))
1327 return ERR_PTR(ret);
1329 ffs = ffs_data_new();
1331 return ERR_PTR(-ENOMEM);
1332 ffs->file_perms = data.perms;
1334 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1335 if (unlikely(!ffs->dev_name)) {
1337 return ERR_PTR(-ENOMEM);
1340 ffs_dev = ffs_acquire_dev(dev_name);
1341 if (IS_ERR(ffs_dev)) {
1343 return ERR_CAST(ffs_dev);
1345 ffs->private_data = ffs_dev;
1346 data.ffs_data = ffs;
1348 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1349 if (IS_ERR(rv) && data.ffs_data) {
1350 ffs_release_dev(data.ffs_data);
1351 ffs_data_put(data.ffs_data);
1357 ffs_fs_kill_sb(struct super_block *sb)
1361 kill_litter_super(sb);
1362 if (sb->s_fs_info) {
1363 ffs_release_dev(sb->s_fs_info);
1364 ffs_data_put(sb->s_fs_info);
1368 static struct file_system_type ffs_fs_type = {
1369 .owner = THIS_MODULE,
1370 .name = "functionfs",
1371 .mount = ffs_fs_mount,
1372 .kill_sb = ffs_fs_kill_sb,
1374 MODULE_ALIAS_FS("functionfs");
1377 /* Driver's main init/cleanup functions *************************************/
1379 static int functionfs_init(void)
1385 ret = register_filesystem(&ffs_fs_type);
1387 pr_info("file system registered\n");
1389 pr_err("failed registering file system (%d)\n", ret);
1394 static void functionfs_cleanup(void)
1398 pr_info("unloading\n");
1399 unregister_filesystem(&ffs_fs_type);
1403 /* ffs_data and ffs_function construction and destruction code **************/
1405 static void ffs_data_clear(struct ffs_data *ffs);
1406 static void ffs_data_reset(struct ffs_data *ffs);
1408 static void ffs_data_get(struct ffs_data *ffs)
1412 atomic_inc(&ffs->ref);
1415 static void ffs_data_opened(struct ffs_data *ffs)
1419 atomic_inc(&ffs->ref);
1420 atomic_inc(&ffs->opened);
1423 static void ffs_data_put(struct ffs_data *ffs)
1427 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1428 pr_info("%s(): freeing\n", __func__);
1429 ffs_data_clear(ffs);
1430 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1431 waitqueue_active(&ffs->ep0req_completion.wait));
1432 kfree(ffs->dev_name);
1437 static void ffs_data_closed(struct ffs_data *ffs)
1441 if (atomic_dec_and_test(&ffs->opened)) {
1442 ffs->state = FFS_CLOSING;
1443 ffs_data_reset(ffs);
1449 static struct ffs_data *ffs_data_new(void)
1451 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1457 atomic_set(&ffs->ref, 1);
1458 atomic_set(&ffs->opened, 0);
1459 ffs->state = FFS_READ_DESCRIPTORS;
1460 mutex_init(&ffs->mutex);
1461 spin_lock_init(&ffs->eps_lock);
1462 init_waitqueue_head(&ffs->ev.waitq);
1463 init_completion(&ffs->ep0req_completion);
1465 /* XXX REVISIT need to update it in some places, or do we? */
1466 ffs->ev.can_stall = 1;
1471 static void ffs_data_clear(struct ffs_data *ffs)
1475 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1478 BUG_ON(ffs->gadget);
1481 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1483 kfree(ffs->raw_descs_data);
1484 kfree(ffs->raw_strings);
1485 kfree(ffs->stringtabs);
1488 static void ffs_data_reset(struct ffs_data *ffs)
1492 ffs_data_clear(ffs);
1494 ffs->epfiles = NULL;
1495 ffs->raw_descs_data = NULL;
1496 ffs->raw_descs = NULL;
1497 ffs->raw_strings = NULL;
1498 ffs->stringtabs = NULL;
1500 ffs->raw_descs_length = 0;
1501 ffs->fs_descs_count = 0;
1502 ffs->hs_descs_count = 0;
1503 ffs->ss_descs_count = 0;
1505 ffs->strings_count = 0;
1506 ffs->interfaces_count = 0;
1511 ffs->state = FFS_READ_DESCRIPTORS;
1512 ffs->setup_state = FFS_NO_SETUP;
1517 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1519 struct usb_gadget_strings **lang;
1524 if (WARN_ON(ffs->state != FFS_ACTIVE
1525 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1528 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1529 if (unlikely(first_id < 0))
1532 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1533 if (unlikely(!ffs->ep0req))
1535 ffs->ep0req->complete = ffs_ep0_complete;
1536 ffs->ep0req->context = ffs;
1538 lang = ffs->stringtabs;
1540 for (; *lang; ++lang) {
1541 struct usb_string *str = (*lang)->strings;
1543 for (; str->s; ++id, ++str)
1548 ffs->gadget = cdev->gadget;
1553 static void functionfs_unbind(struct ffs_data *ffs)
1557 if (!WARN_ON(!ffs->gadget)) {
1558 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1561 clear_bit(FFS_FL_BOUND, &ffs->flags);
1566 static int ffs_epfiles_create(struct ffs_data *ffs)
1568 struct ffs_epfile *epfile, *epfiles;
1573 count = ffs->eps_count;
1574 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1579 for (i = 1; i <= count; ++i, ++epfile) {
1581 mutex_init(&epfile->mutex);
1582 init_waitqueue_head(&epfile->wait);
1583 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1584 sprintf(epfiles->name, "ep%02x", ffs->eps_addrmap[i]);
1586 sprintf(epfiles->name, "ep%u", i);
1587 epfile->dentry = ffs_sb_create_file(ffs->sb, epfiles->name,
1589 &ffs_epfile_operations);
1590 if (unlikely(!epfile->dentry)) {
1591 ffs_epfiles_destroy(epfiles, i - 1);
1596 ffs->epfiles = epfiles;
1600 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1602 struct ffs_epfile *epfile = epfiles;
1606 for (; count; --count, ++epfile) {
1607 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1608 waitqueue_active(&epfile->wait));
1609 if (epfile->dentry) {
1610 d_delete(epfile->dentry);
1611 dput(epfile->dentry);
1612 epfile->dentry = NULL;
1620 static void ffs_func_eps_disable(struct ffs_function *func)
1622 struct ffs_ep *ep = func->eps;
1623 struct ffs_epfile *epfile = func->ffs->epfiles;
1624 unsigned count = func->ffs->eps_count;
1625 unsigned long flags;
1627 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1629 /* pending requests get nuked */
1631 usb_ep_disable(ep->ep);
1637 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1640 static int ffs_func_eps_enable(struct ffs_function *func)
1642 struct ffs_data *ffs = func->ffs;
1643 struct ffs_ep *ep = func->eps;
1644 struct ffs_epfile *epfile = ffs->epfiles;
1645 unsigned count = ffs->eps_count;
1646 unsigned long flags;
1649 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1651 struct usb_endpoint_descriptor *ds;
1654 if (ffs->gadget->speed == USB_SPEED_SUPER)
1656 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1661 /* fall-back to lower speed if desc missing for current speed */
1663 ds = ep->descs[desc_idx];
1664 } while (!ds && --desc_idx >= 0);
1671 ep->ep->driver_data = ep;
1673 ret = usb_ep_enable(ep->ep);
1676 epfile->in = usb_endpoint_dir_in(ds);
1677 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1682 wake_up(&epfile->wait);
1687 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1693 /* Parsing and building descriptors and strings *****************************/
1696 * This validates if data pointed by data is a valid USB descriptor as
1697 * well as record how many interfaces, endpoints and strings are
1698 * required by given configuration. Returns address after the
1699 * descriptor or NULL if data is invalid.
1702 enum ffs_entity_type {
1703 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1706 enum ffs_os_desc_type {
1707 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1710 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1712 struct usb_descriptor_header *desc,
1715 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1716 struct usb_os_desc_header *h, void *data,
1717 unsigned len, void *priv);
1719 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1720 ffs_entity_callback entity,
1723 struct usb_descriptor_header *_ds = (void *)data;
1729 /* At least two bytes are required: length and type */
1731 pr_vdebug("descriptor too short\n");
1735 /* If we have at least as many bytes as the descriptor takes? */
1736 length = _ds->bLength;
1738 pr_vdebug("descriptor longer then available data\n");
1742 #define __entity_check_INTERFACE(val) 1
1743 #define __entity_check_STRING(val) (val)
1744 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1745 #define __entity(type, val) do { \
1746 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1747 if (unlikely(!__entity_check_ ##type(val))) { \
1748 pr_vdebug("invalid entity's value\n"); \
1751 ret = entity(FFS_ ##type, &val, _ds, priv); \
1752 if (unlikely(ret < 0)) { \
1753 pr_debug("entity " #type "(%02x); ret = %d\n", \
1759 /* Parse descriptor depending on type. */
1760 switch (_ds->bDescriptorType) {
1764 case USB_DT_DEVICE_QUALIFIER:
1765 /* function can't have any of those */
1766 pr_vdebug("descriptor reserved for gadget: %d\n",
1767 _ds->bDescriptorType);
1770 case USB_DT_INTERFACE: {
1771 struct usb_interface_descriptor *ds = (void *)_ds;
1772 pr_vdebug("interface descriptor\n");
1773 if (length != sizeof *ds)
1776 __entity(INTERFACE, ds->bInterfaceNumber);
1778 __entity(STRING, ds->iInterface);
1782 case USB_DT_ENDPOINT: {
1783 struct usb_endpoint_descriptor *ds = (void *)_ds;
1784 pr_vdebug("endpoint descriptor\n");
1785 if (length != USB_DT_ENDPOINT_SIZE &&
1786 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1788 __entity(ENDPOINT, ds->bEndpointAddress);
1793 pr_vdebug("hid descriptor\n");
1794 if (length != sizeof(struct hid_descriptor))
1799 if (length != sizeof(struct usb_otg_descriptor))
1803 case USB_DT_INTERFACE_ASSOCIATION: {
1804 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1805 pr_vdebug("interface association descriptor\n");
1806 if (length != sizeof *ds)
1809 __entity(STRING, ds->iFunction);
1813 case USB_DT_SS_ENDPOINT_COMP:
1814 pr_vdebug("EP SS companion descriptor\n");
1815 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1819 case USB_DT_OTHER_SPEED_CONFIG:
1820 case USB_DT_INTERFACE_POWER:
1822 case USB_DT_SECURITY:
1823 case USB_DT_CS_RADIO_CONTROL:
1825 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1829 /* We should never be here */
1830 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1834 pr_vdebug("invalid length: %d (descriptor %d)\n",
1835 _ds->bLength, _ds->bDescriptorType);
1840 #undef __entity_check_DESCRIPTOR
1841 #undef __entity_check_INTERFACE
1842 #undef __entity_check_STRING
1843 #undef __entity_check_ENDPOINT
1848 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1849 ffs_entity_callback entity, void *priv)
1851 const unsigned _len = len;
1852 unsigned long num = 0;
1862 /* Record "descriptor" entity */
1863 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1864 if (unlikely(ret < 0)) {
1865 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1873 ret = ffs_do_single_desc(data, len, entity, priv);
1874 if (unlikely(ret < 0)) {
1875 pr_debug("%s returns %d\n", __func__, ret);
1885 static int __ffs_data_do_entity(enum ffs_entity_type type,
1886 u8 *valuep, struct usb_descriptor_header *desc,
1889 struct ffs_desc_helper *helper = priv;
1890 struct usb_endpoint_descriptor *d;
1895 case FFS_DESCRIPTOR:
1900 * Interfaces are indexed from zero so if we
1901 * encountered interface "n" then there are at least
1904 if (*valuep >= helper->interfaces_count)
1905 helper->interfaces_count = *valuep + 1;
1910 * Strings are indexed from 1 (0 is magic ;) reserved
1911 * for languages list or some such)
1913 if (*valuep > helper->ffs->strings_count)
1914 helper->ffs->strings_count = *valuep;
1919 helper->eps_count++;
1920 if (helper->eps_count >= 15)
1922 /* Check if descriptors for any speed were already parsed */
1923 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
1924 helper->ffs->eps_addrmap[helper->eps_count] =
1925 d->bEndpointAddress;
1926 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
1927 d->bEndpointAddress)
1935 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1936 struct usb_os_desc_header *desc)
1938 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1939 u16 w_index = le16_to_cpu(desc->wIndex);
1941 if (bcd_version != 1) {
1942 pr_vdebug("unsupported os descriptors version: %d",
1948 *next_type = FFS_OS_DESC_EXT_COMPAT;
1951 *next_type = FFS_OS_DESC_EXT_PROP;
1954 pr_vdebug("unsupported os descriptor type: %d", w_index);
1958 return sizeof(*desc);
1962 * Process all extended compatibility/extended property descriptors
1963 * of a feature descriptor
1965 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1966 enum ffs_os_desc_type type,
1968 ffs_os_desc_callback entity,
1970 struct usb_os_desc_header *h)
1973 const unsigned _len = len;
1977 /* loop over all ext compat/ext prop descriptors */
1978 while (feature_count--) {
1979 ret = entity(type, h, data, len, priv);
1980 if (unlikely(ret < 0)) {
1981 pr_debug("bad OS descriptor, type: %d\n", type);
1990 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1991 static int __must_check ffs_do_os_descs(unsigned count,
1992 char *data, unsigned len,
1993 ffs_os_desc_callback entity, void *priv)
1995 const unsigned _len = len;
1996 unsigned long num = 0;
2000 for (num = 0; num < count; ++num) {
2002 enum ffs_os_desc_type type;
2004 struct usb_os_desc_header *desc = (void *)data;
2006 if (len < sizeof(*desc))
2010 * Record "descriptor" entity.
2011 * Process dwLength, bcdVersion, wIndex, get b/wCount.
2012 * Move the data pointer to the beginning of extended
2013 * compatibilities proper or extended properties proper
2014 * portions of the data
2016 if (le32_to_cpu(desc->dwLength) > len)
2019 ret = __ffs_do_os_desc_header(&type, desc);
2020 if (unlikely(ret < 0)) {
2021 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
2026 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2028 feature_count = le16_to_cpu(desc->wCount);
2029 if (type == FFS_OS_DESC_EXT_COMPAT &&
2030 (feature_count > 255 || desc->Reserved))
2036 * Process all function/property descriptors
2037 * of this Feature Descriptor
2039 ret = ffs_do_single_os_desc(data, len, type,
2040 feature_count, entity, priv, desc);
2041 if (unlikely(ret < 0)) {
2042 pr_debug("%s returns %d\n", __func__, ret);
2053 * Validate contents of the buffer from userspace related to OS descriptors.
2055 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2056 struct usb_os_desc_header *h, void *data,
2057 unsigned len, void *priv)
2059 struct ffs_data *ffs = priv;
2065 case FFS_OS_DESC_EXT_COMPAT: {
2066 struct usb_ext_compat_desc *d = data;
2069 if (len < sizeof(*d) ||
2070 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2073 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2074 if (d->Reserved2[i])
2077 length = sizeof(struct usb_ext_compat_desc);
2080 case FFS_OS_DESC_EXT_PROP: {
2081 struct usb_ext_prop_desc *d = data;
2085 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2087 length = le32_to_cpu(d->dwSize);
2088 type = le32_to_cpu(d->dwPropertyDataType);
2089 if (type < USB_EXT_PROP_UNICODE ||
2090 type > USB_EXT_PROP_UNICODE_MULTI) {
2091 pr_vdebug("unsupported os descriptor property type: %d",
2095 pnl = le16_to_cpu(d->wPropertyNameLength);
2096 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2097 if (length != 14 + pnl + pdl) {
2098 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2099 length, pnl, pdl, type);
2102 ++ffs->ms_os_descs_ext_prop_count;
2103 /* property name reported to the host as "WCHAR"s */
2104 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2105 ffs->ms_os_descs_ext_prop_data_len += pdl;
2109 pr_vdebug("unknown descriptor: %d\n", type);
2115 static int __ffs_data_got_descs(struct ffs_data *ffs,
2116 char *const _data, size_t len)
2118 char *data = _data, *raw_descs;
2119 unsigned os_descs_count = 0, counts[3], flags;
2120 int ret = -EINVAL, i;
2121 struct ffs_desc_helper helper;
2125 if (get_unaligned_le32(data + 4) != len)
2128 switch (get_unaligned_le32(data)) {
2129 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2130 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2134 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2135 flags = get_unaligned_le32(data + 8);
2136 ffs->user_flags = flags;
2137 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2138 FUNCTIONFS_HAS_HS_DESC |
2139 FUNCTIONFS_HAS_SS_DESC |
2140 FUNCTIONFS_HAS_MS_OS_DESC |
2141 FUNCTIONFS_VIRTUAL_ADDR)) {
2152 /* Read fs_count, hs_count and ss_count (if present) */
2153 for (i = 0; i < 3; ++i) {
2154 if (!(flags & (1 << i))) {
2156 } else if (len < 4) {
2159 counts[i] = get_unaligned_le32(data);
2164 if (flags & (1 << i)) {
2165 os_descs_count = get_unaligned_le32(data);
2170 /* Read descriptors */
2173 for (i = 0; i < 3; ++i) {
2176 helper.interfaces_count = 0;
2177 helper.eps_count = 0;
2178 ret = ffs_do_descs(counts[i], data, len,
2179 __ffs_data_do_entity, &helper);
2182 if (!ffs->eps_count && !ffs->interfaces_count) {
2183 ffs->eps_count = helper.eps_count;
2184 ffs->interfaces_count = helper.interfaces_count;
2186 if (ffs->eps_count != helper.eps_count) {
2190 if (ffs->interfaces_count != helper.interfaces_count) {
2198 if (os_descs_count) {
2199 ret = ffs_do_os_descs(os_descs_count, data, len,
2200 __ffs_data_do_os_desc, ffs);
2207 if (raw_descs == data || len) {
2212 ffs->raw_descs_data = _data;
2213 ffs->raw_descs = raw_descs;
2214 ffs->raw_descs_length = data - raw_descs;
2215 ffs->fs_descs_count = counts[0];
2216 ffs->hs_descs_count = counts[1];
2217 ffs->ss_descs_count = counts[2];
2218 ffs->ms_os_descs_count = os_descs_count;
2227 static int __ffs_data_got_strings(struct ffs_data *ffs,
2228 char *const _data, size_t len)
2230 u32 str_count, needed_count, lang_count;
2231 struct usb_gadget_strings **stringtabs, *t;
2232 struct usb_string *strings, *s;
2233 const char *data = _data;
2237 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2238 get_unaligned_le32(data + 4) != len))
2240 str_count = get_unaligned_le32(data + 8);
2241 lang_count = get_unaligned_le32(data + 12);
2243 /* if one is zero the other must be zero */
2244 if (unlikely(!str_count != !lang_count))
2247 /* Do we have at least as many strings as descriptors need? */
2248 needed_count = ffs->strings_count;
2249 if (unlikely(str_count < needed_count))
2253 * If we don't need any strings just return and free all
2256 if (!needed_count) {
2261 /* Allocate everything in one chunk so there's less maintenance. */
2265 vla_item(d, struct usb_gadget_strings *, stringtabs,
2267 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2268 vla_item(d, struct usb_string, strings,
2269 lang_count*(needed_count+1));
2271 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2273 if (unlikely(!vlabuf)) {
2278 /* Initialize the VLA pointers */
2279 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2280 t = vla_ptr(vlabuf, d, stringtab);
2283 *stringtabs++ = t++;
2287 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2288 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2289 t = vla_ptr(vlabuf, d, stringtab);
2290 s = vla_ptr(vlabuf, d, strings);
2294 /* For each language */
2298 do { /* lang_count > 0 so we can use do-while */
2299 unsigned needed = needed_count;
2301 if (unlikely(len < 3))
2303 t->language = get_unaligned_le16(data);
2310 /* For each string */
2311 do { /* str_count > 0 so we can use do-while */
2312 size_t length = strnlen(data, len);
2314 if (unlikely(length == len))
2318 * User may provide more strings then we need,
2319 * if that's the case we simply ignore the
2322 if (likely(needed)) {
2324 * s->id will be set while adding
2325 * function to configuration so for
2326 * now just leave garbage here.
2335 } while (--str_count);
2337 s->id = 0; /* terminator */
2341 } while (--lang_count);
2343 /* Some garbage left? */
2348 ffs->stringtabs = stringtabs;
2349 ffs->raw_strings = _data;
2361 /* Events handling and management *******************************************/
2363 static void __ffs_event_add(struct ffs_data *ffs,
2364 enum usb_functionfs_event_type type)
2366 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2370 * Abort any unhandled setup
2372 * We do not need to worry about some cmpxchg() changing value
2373 * of ffs->setup_state without holding the lock because when
2374 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2375 * the source does nothing.
2377 if (ffs->setup_state == FFS_SETUP_PENDING)
2378 ffs->setup_state = FFS_SETUP_CANCELLED;
2381 case FUNCTIONFS_RESUME:
2382 rem_type2 = FUNCTIONFS_SUSPEND;
2384 case FUNCTIONFS_SUSPEND:
2385 case FUNCTIONFS_SETUP:
2387 /* Discard all similar events */
2390 case FUNCTIONFS_BIND:
2391 case FUNCTIONFS_UNBIND:
2392 case FUNCTIONFS_DISABLE:
2393 case FUNCTIONFS_ENABLE:
2394 /* Discard everything other then power management. */
2395 rem_type1 = FUNCTIONFS_SUSPEND;
2396 rem_type2 = FUNCTIONFS_RESUME;
2401 WARN(1, "%d: unknown event, this should not happen\n", type);
2406 u8 *ev = ffs->ev.types, *out = ev;
2407 unsigned n = ffs->ev.count;
2408 for (; n; --n, ++ev)
2409 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2412 pr_vdebug("purging event %d\n", *ev);
2413 ffs->ev.count = out - ffs->ev.types;
2416 pr_vdebug("adding event %d\n", type);
2417 ffs->ev.types[ffs->ev.count++] = type;
2418 wake_up_locked(&ffs->ev.waitq);
2421 static void ffs_event_add(struct ffs_data *ffs,
2422 enum usb_functionfs_event_type type)
2424 unsigned long flags;
2425 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2426 __ffs_event_add(ffs, type);
2427 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2430 /* Bind/unbind USB function hooks *******************************************/
2432 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2436 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2437 if (ffs->eps_addrmap[i] == endpoint_address)
2442 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2443 struct usb_descriptor_header *desc,
2446 struct usb_endpoint_descriptor *ds = (void *)desc;
2447 struct ffs_function *func = priv;
2448 struct ffs_ep *ffs_ep;
2449 unsigned ep_desc_id;
2451 static const char *speed_names[] = { "full", "high", "super" };
2453 if (type != FFS_DESCRIPTOR)
2457 * If ss_descriptors is not NULL, we are reading super speed
2458 * descriptors; if hs_descriptors is not NULL, we are reading high
2459 * speed descriptors; otherwise, we are reading full speed
2462 if (func->function.ss_descriptors) {
2464 func->function.ss_descriptors[(long)valuep] = desc;
2465 } else if (func->function.hs_descriptors) {
2467 func->function.hs_descriptors[(long)valuep] = desc;
2470 func->function.fs_descriptors[(long)valuep] = desc;
2473 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2476 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2480 ffs_ep = func->eps + idx;
2482 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2483 pr_err("two %sspeed descriptors for EP %d\n",
2484 speed_names[ep_desc_id],
2485 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2488 ffs_ep->descs[ep_desc_id] = ds;
2490 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2492 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2493 if (!ds->wMaxPacketSize)
2494 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2496 struct usb_request *req;
2498 u8 bEndpointAddress;
2501 * We back up bEndpointAddress because autoconfig overwrites
2502 * it with physical endpoint address.
2504 bEndpointAddress = ds->bEndpointAddress;
2505 pr_vdebug("autoconfig\n");
2506 ep = usb_ep_autoconfig(func->gadget, ds);
2509 ep->driver_data = func->eps + idx;
2511 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2517 func->eps_revmap[ds->bEndpointAddress &
2518 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2520 * If we use virtual address mapping, we restore
2521 * original bEndpointAddress value.
2523 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2524 ds->bEndpointAddress = bEndpointAddress;
2526 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2531 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2532 struct usb_descriptor_header *desc,
2535 struct ffs_function *func = priv;
2541 case FFS_DESCRIPTOR:
2542 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2547 if (func->interfaces_nums[idx] < 0) {
2548 int id = usb_interface_id(func->conf, &func->function);
2549 if (unlikely(id < 0))
2551 func->interfaces_nums[idx] = id;
2553 newValue = func->interfaces_nums[idx];
2557 /* String' IDs are allocated when fsf_data is bound to cdev */
2558 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2563 * USB_DT_ENDPOINT are handled in
2564 * __ffs_func_bind_do_descs().
2566 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2569 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2570 if (unlikely(!func->eps[idx].ep))
2574 struct usb_endpoint_descriptor **descs;
2575 descs = func->eps[idx].descs;
2576 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2581 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2586 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2587 struct usb_os_desc_header *h, void *data,
2588 unsigned len, void *priv)
2590 struct ffs_function *func = priv;
2594 case FFS_OS_DESC_EXT_COMPAT: {
2595 struct usb_ext_compat_desc *desc = data;
2596 struct usb_os_desc_table *t;
2598 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2599 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2600 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2601 ARRAY_SIZE(desc->CompatibleID) +
2602 ARRAY_SIZE(desc->SubCompatibleID));
2603 length = sizeof(*desc);
2606 case FFS_OS_DESC_EXT_PROP: {
2607 struct usb_ext_prop_desc *desc = data;
2608 struct usb_os_desc_table *t;
2609 struct usb_os_desc_ext_prop *ext_prop;
2610 char *ext_prop_name;
2611 char *ext_prop_data;
2613 t = &func->function.os_desc_table[h->interface];
2614 t->if_id = func->interfaces_nums[h->interface];
2616 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2617 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2619 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2620 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2621 ext_prop->data_len = le32_to_cpu(*(u32 *)
2622 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2623 length = ext_prop->name_len + ext_prop->data_len + 14;
2625 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2626 func->ffs->ms_os_descs_ext_prop_name_avail +=
2629 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2630 func->ffs->ms_os_descs_ext_prop_data_avail +=
2632 memcpy(ext_prop_data,
2633 usb_ext_prop_data_ptr(data, ext_prop->name_len),
2634 ext_prop->data_len);
2635 /* unicode data reported to the host as "WCHAR"s */
2636 switch (ext_prop->type) {
2637 case USB_EXT_PROP_UNICODE:
2638 case USB_EXT_PROP_UNICODE_ENV:
2639 case USB_EXT_PROP_UNICODE_LINK:
2640 case USB_EXT_PROP_UNICODE_MULTI:
2641 ext_prop->data_len *= 2;
2644 ext_prop->data = ext_prop_data;
2646 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2647 ext_prop->name_len);
2648 /* property name reported to the host as "WCHAR"s */
2649 ext_prop->name_len *= 2;
2650 ext_prop->name = ext_prop_name;
2652 t->os_desc->ext_prop_len +=
2653 ext_prop->name_len + ext_prop->data_len + 14;
2654 ++t->os_desc->ext_prop_count;
2655 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2659 pr_vdebug("unknown descriptor: %d\n", type);
2665 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2666 struct usb_configuration *c)
2668 struct ffs_function *func = ffs_func_from_usb(f);
2669 struct f_fs_opts *ffs_opts =
2670 container_of(f->fi, struct f_fs_opts, func_inst);
2676 * Legacy gadget triggers binding in functionfs_ready_callback,
2677 * which already uses locking; taking the same lock here would
2680 * Configfs-enabled gadgets however do need ffs_dev_lock.
2682 if (!ffs_opts->no_configfs)
2684 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2685 func->ffs = ffs_opts->dev->ffs_data;
2686 if (!ffs_opts->no_configfs)
2689 return ERR_PTR(ret);
2692 func->gadget = c->cdev->gadget;
2695 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2696 * configurations are bound in sequence with list_for_each_entry,
2697 * in each configuration its functions are bound in sequence
2698 * with list_for_each_entry, so we assume no race condition
2699 * with regard to ffs_opts->bound access
2701 if (!ffs_opts->refcnt) {
2702 ret = functionfs_bind(func->ffs, c->cdev);
2704 return ERR_PTR(ret);
2707 func->function.strings = func->ffs->stringtabs;
2712 static int _ffs_func_bind(struct usb_configuration *c,
2713 struct usb_function *f)
2715 struct ffs_function *func = ffs_func_from_usb(f);
2716 struct ffs_data *ffs = func->ffs;
2718 const int full = !!func->ffs->fs_descs_count;
2719 const int high = gadget_is_dualspeed(func->gadget) &&
2720 func->ffs->hs_descs_count;
2721 const int super = gadget_is_superspeed(func->gadget) &&
2722 func->ffs->ss_descs_count;
2724 int fs_len, hs_len, ss_len, ret, i;
2726 /* Make it a single chunk, less management later on */
2728 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2729 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2730 full ? ffs->fs_descs_count + 1 : 0);
2731 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2732 high ? ffs->hs_descs_count + 1 : 0);
2733 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2734 super ? ffs->ss_descs_count + 1 : 0);
2735 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2736 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2737 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2738 vla_item_with_sz(d, char[16], ext_compat,
2739 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2740 vla_item_with_sz(d, struct usb_os_desc, os_desc,
2741 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2742 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2743 ffs->ms_os_descs_ext_prop_count);
2744 vla_item_with_sz(d, char, ext_prop_name,
2745 ffs->ms_os_descs_ext_prop_name_len);
2746 vla_item_with_sz(d, char, ext_prop_data,
2747 ffs->ms_os_descs_ext_prop_data_len);
2748 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2753 /* Has descriptors only for speeds gadget does not support */
2754 if (unlikely(!(full | high | super)))
2757 /* Allocate a single chunk, less management later on */
2758 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2759 if (unlikely(!vlabuf))
2762 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2763 ffs->ms_os_descs_ext_prop_name_avail =
2764 vla_ptr(vlabuf, d, ext_prop_name);
2765 ffs->ms_os_descs_ext_prop_data_avail =
2766 vla_ptr(vlabuf, d, ext_prop_data);
2768 /* Copy descriptors */
2769 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2770 ffs->raw_descs_length);
2772 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2773 for (ret = ffs->eps_count; ret; --ret) {
2776 ptr = vla_ptr(vlabuf, d, eps);
2781 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2783 func->eps = vla_ptr(vlabuf, d, eps);
2784 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2787 * Go through all the endpoint descriptors and allocate
2788 * endpoints first, so that later we can rewrite the endpoint
2789 * numbers without worrying that it may be described later on.
2792 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2793 fs_len = ffs_do_descs(ffs->fs_descs_count,
2794 vla_ptr(vlabuf, d, raw_descs),
2796 __ffs_func_bind_do_descs, func);
2797 if (unlikely(fs_len < 0)) {
2806 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2807 hs_len = ffs_do_descs(ffs->hs_descs_count,
2808 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2809 d_raw_descs__sz - fs_len,
2810 __ffs_func_bind_do_descs, func);
2811 if (unlikely(hs_len < 0)) {
2819 if (likely(super)) {
2820 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2821 ss_len = ffs_do_descs(ffs->ss_descs_count,
2822 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2823 d_raw_descs__sz - fs_len - hs_len,
2824 __ffs_func_bind_do_descs, func);
2825 if (unlikely(ss_len < 0)) {
2834 * Now handle interface numbers allocation and interface and
2835 * endpoint numbers rewriting. We can do that in one go
2838 ret = ffs_do_descs(ffs->fs_descs_count +
2839 (high ? ffs->hs_descs_count : 0) +
2840 (super ? ffs->ss_descs_count : 0),
2841 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2842 __ffs_func_bind_do_nums, func);
2843 if (unlikely(ret < 0))
2846 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2847 if (c->cdev->use_os_string)
2848 for (i = 0; i < ffs->interfaces_count; ++i) {
2849 struct usb_os_desc *desc;
2851 desc = func->function.os_desc_table[i].os_desc =
2852 vla_ptr(vlabuf, d, os_desc) +
2853 i * sizeof(struct usb_os_desc);
2854 desc->ext_compat_id =
2855 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2856 INIT_LIST_HEAD(&desc->ext_prop);
2858 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2859 vla_ptr(vlabuf, d, raw_descs) +
2860 fs_len + hs_len + ss_len,
2861 d_raw_descs__sz - fs_len - hs_len - ss_len,
2862 __ffs_func_bind_do_os_desc, func);
2863 if (unlikely(ret < 0))
2865 func->function.os_desc_n =
2866 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2868 /* And we're done */
2869 ffs_event_add(ffs, FUNCTIONFS_BIND);
2873 /* XXX Do we need to release all claimed endpoints here? */
2877 static int ffs_func_bind(struct usb_configuration *c,
2878 struct usb_function *f)
2880 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2882 if (IS_ERR(ffs_opts))
2883 return PTR_ERR(ffs_opts);
2885 return _ffs_func_bind(c, f);
2889 /* Other USB function hooks *************************************************/
2891 static int ffs_func_set_alt(struct usb_function *f,
2892 unsigned interface, unsigned alt)
2894 struct ffs_function *func = ffs_func_from_usb(f);
2895 struct ffs_data *ffs = func->ffs;
2898 if (alt != (unsigned)-1) {
2899 intf = ffs_func_revmap_intf(func, interface);
2900 if (unlikely(intf < 0))
2905 ffs_func_eps_disable(ffs->func);
2907 if (ffs->state != FFS_ACTIVE)
2910 if (alt == (unsigned)-1) {
2912 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2917 ret = ffs_func_eps_enable(func);
2918 if (likely(ret >= 0))
2919 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2923 static void ffs_func_disable(struct usb_function *f)
2925 ffs_func_set_alt(f, 0, (unsigned)-1);
2928 static int ffs_func_setup(struct usb_function *f,
2929 const struct usb_ctrlrequest *creq)
2931 struct ffs_function *func = ffs_func_from_usb(f);
2932 struct ffs_data *ffs = func->ffs;
2933 unsigned long flags;
2938 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2939 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2940 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2941 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2942 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2945 * Most requests directed to interface go through here
2946 * (notable exceptions are set/get interface) so we need to
2947 * handle them. All other either handled by composite or
2948 * passed to usb_configuration->setup() (if one is set). No
2949 * matter, we will handle requests directed to endpoint here
2950 * as well (as it's straightforward) but what to do with any
2953 if (ffs->state != FFS_ACTIVE)
2956 switch (creq->bRequestType & USB_RECIP_MASK) {
2957 case USB_RECIP_INTERFACE:
2958 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2959 if (unlikely(ret < 0))
2963 case USB_RECIP_ENDPOINT:
2964 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2965 if (unlikely(ret < 0))
2967 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2968 ret = func->ffs->eps_addrmap[ret];
2975 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2976 ffs->ev.setup = *creq;
2977 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2978 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2979 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2984 static void ffs_func_suspend(struct usb_function *f)
2987 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2990 static void ffs_func_resume(struct usb_function *f)
2993 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2997 /* Endpoint and interface numbers reverse mapping ***************************/
2999 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
3001 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
3002 return num ? num : -EDOM;
3005 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
3007 short *nums = func->interfaces_nums;
3008 unsigned count = func->ffs->interfaces_count;
3010 for (; count; --count, ++nums) {
3011 if (*nums >= 0 && *nums == intf)
3012 return nums - func->interfaces_nums;
3019 /* Devices management *******************************************************/
3021 static LIST_HEAD(ffs_devices);
3023 static struct ffs_dev *_ffs_do_find_dev(const char *name)
3025 struct ffs_dev *dev;
3027 list_for_each_entry(dev, &ffs_devices, entry) {
3028 if (!dev->name || !name)
3030 if (strcmp(dev->name, name) == 0)
3038 * ffs_lock must be taken by the caller of this function
3040 static struct ffs_dev *_ffs_get_single_dev(void)
3042 struct ffs_dev *dev;
3044 if (list_is_singular(&ffs_devices)) {
3045 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3054 * ffs_lock must be taken by the caller of this function
3056 static struct ffs_dev *_ffs_find_dev(const char *name)
3058 struct ffs_dev *dev;
3060 dev = _ffs_get_single_dev();
3064 return _ffs_do_find_dev(name);
3067 /* Configfs support *********************************************************/
3069 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3071 return container_of(to_config_group(item), struct f_fs_opts,
3075 static void ffs_attr_release(struct config_item *item)
3077 struct f_fs_opts *opts = to_ffs_opts(item);
3079 usb_put_function_instance(&opts->func_inst);
3082 static struct configfs_item_operations ffs_item_ops = {
3083 .release = ffs_attr_release,
3086 static struct config_item_type ffs_func_type = {
3087 .ct_item_ops = &ffs_item_ops,
3088 .ct_owner = THIS_MODULE,
3092 /* Function registration interface ******************************************/
3094 static void ffs_free_inst(struct usb_function_instance *f)
3096 struct f_fs_opts *opts;
3098 opts = to_f_fs_opts(f);
3100 _ffs_free_dev(opts->dev);
3105 #define MAX_INST_NAME_LEN 40
3107 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3109 struct f_fs_opts *opts;
3114 name_len = strlen(name) + 1;
3115 if (name_len > MAX_INST_NAME_LEN)
3116 return -ENAMETOOLONG;
3118 ptr = kstrndup(name, name_len, GFP_KERNEL);
3122 opts = to_f_fs_opts(fi);
3127 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3128 ret = _ffs_name_dev(opts->dev, ptr);
3134 opts->dev->name_allocated = true;
3143 static struct usb_function_instance *ffs_alloc_inst(void)
3145 struct f_fs_opts *opts;
3146 struct ffs_dev *dev;
3148 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3150 return ERR_PTR(-ENOMEM);
3152 opts->func_inst.set_inst_name = ffs_set_inst_name;
3153 opts->func_inst.free_func_inst = ffs_free_inst;
3155 dev = _ffs_alloc_dev();
3159 return ERR_CAST(dev);
3164 config_group_init_type_name(&opts->func_inst.group, "",
3166 return &opts->func_inst;
3169 static void ffs_free(struct usb_function *f)
3171 kfree(ffs_func_from_usb(f));
3174 static void ffs_func_unbind(struct usb_configuration *c,
3175 struct usb_function *f)
3177 struct ffs_function *func = ffs_func_from_usb(f);
3178 struct ffs_data *ffs = func->ffs;
3179 struct f_fs_opts *opts =
3180 container_of(f->fi, struct f_fs_opts, func_inst);
3181 struct ffs_ep *ep = func->eps;
3182 unsigned count = ffs->eps_count;
3183 unsigned long flags;
3186 if (ffs->func == func) {
3187 ffs_func_eps_disable(func);
3191 if (!--opts->refcnt)
3192 functionfs_unbind(ffs);
3194 /* cleanup after autoconfig */
3195 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3197 if (ep->ep && ep->req)
3198 usb_ep_free_request(ep->ep, ep->req);
3202 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3206 * eps, descriptors and interfaces_nums are allocated in the
3207 * same chunk so only one free is required.
3209 func->function.fs_descriptors = NULL;
3210 func->function.hs_descriptors = NULL;
3211 func->function.ss_descriptors = NULL;
3212 func->interfaces_nums = NULL;
3214 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3217 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3219 struct ffs_function *func;
3223 func = kzalloc(sizeof(*func), GFP_KERNEL);
3224 if (unlikely(!func))
3225 return ERR_PTR(-ENOMEM);
3227 func->function.name = "Function FS Gadget";
3229 func->function.bind = ffs_func_bind;
3230 func->function.unbind = ffs_func_unbind;
3231 func->function.set_alt = ffs_func_set_alt;
3232 func->function.disable = ffs_func_disable;
3233 func->function.setup = ffs_func_setup;
3234 func->function.suspend = ffs_func_suspend;
3235 func->function.resume = ffs_func_resume;
3236 func->function.free_func = ffs_free;
3238 return &func->function;
3242 * ffs_lock must be taken by the caller of this function
3244 static struct ffs_dev *_ffs_alloc_dev(void)
3246 struct ffs_dev *dev;
3249 if (_ffs_get_single_dev())
3250 return ERR_PTR(-EBUSY);
3252 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3254 return ERR_PTR(-ENOMEM);
3256 if (list_empty(&ffs_devices)) {
3257 ret = functionfs_init();
3260 return ERR_PTR(ret);
3264 list_add(&dev->entry, &ffs_devices);
3270 * ffs_lock must be taken by the caller of this function
3271 * The caller is responsible for "name" being available whenever f_fs needs it
3273 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3275 struct ffs_dev *existing;
3277 existing = _ffs_do_find_dev(name);
3287 * The caller is responsible for "name" being available whenever f_fs needs it
3289 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3294 ret = _ffs_name_dev(dev, name);
3299 EXPORT_SYMBOL_GPL(ffs_name_dev);
3301 int ffs_single_dev(struct ffs_dev *dev)
3308 if (!list_is_singular(&ffs_devices))
3316 EXPORT_SYMBOL_GPL(ffs_single_dev);
3319 * ffs_lock must be taken by the caller of this function
3321 static void _ffs_free_dev(struct ffs_dev *dev)
3323 list_del(&dev->entry);
3324 if (dev->name_allocated)
3327 if (list_empty(&ffs_devices))
3328 functionfs_cleanup();
3331 static void *ffs_acquire_dev(const char *dev_name)
3333 struct ffs_dev *ffs_dev;
3338 ffs_dev = _ffs_find_dev(dev_name);
3340 ffs_dev = ERR_PTR(-ENOENT);
3341 else if (ffs_dev->mounted)
3342 ffs_dev = ERR_PTR(-EBUSY);
3343 else if (ffs_dev->ffs_acquire_dev_callback &&
3344 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3345 ffs_dev = ERR_PTR(-ENOENT);
3347 ffs_dev->mounted = true;
3353 static void ffs_release_dev(struct ffs_data *ffs_data)
3355 struct ffs_dev *ffs_dev;
3360 ffs_dev = ffs_data->private_data;
3362 ffs_dev->mounted = false;
3364 if (ffs_dev->ffs_release_dev_callback)
3365 ffs_dev->ffs_release_dev_callback(ffs_dev);
3371 static int ffs_ready(struct ffs_data *ffs)
3373 struct ffs_dev *ffs_obj;
3379 ffs_obj = ffs->private_data;
3384 if (WARN_ON(ffs_obj->desc_ready)) {
3389 ffs_obj->desc_ready = true;
3390 ffs_obj->ffs_data = ffs;
3392 if (ffs_obj->ffs_ready_callback)
3393 ret = ffs_obj->ffs_ready_callback(ffs);
3400 static void ffs_closed(struct ffs_data *ffs)
3402 struct ffs_dev *ffs_obj;
3407 ffs_obj = ffs->private_data;
3411 ffs_obj->desc_ready = false;
3413 if (ffs_obj->ffs_closed_callback)
3414 ffs_obj->ffs_closed_callback(ffs);
3416 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
3417 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
3420 unregister_gadget_item(ffs_obj->opts->
3421 func_inst.group.cg_item.ci_parent->ci_parent);
3426 /* Misc helper functions ****************************************************/
3428 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3431 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3432 : mutex_lock_interruptible(mutex);
3435 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3442 data = kmalloc(len, GFP_KERNEL);
3443 if (unlikely(!data))
3444 return ERR_PTR(-ENOMEM);
3446 if (unlikely(__copy_from_user(data, buf, len))) {
3448 return ERR_PTR(-EFAULT);
3451 pr_vdebug("Buffer from user space:\n");
3452 ffs_dump_mem("", data, len);
3457 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3458 MODULE_LICENSE("GPL");
3459 MODULE_AUTHOR("Michal Nazarewicz");