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 inode *__must_check
168 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
169 const struct file_operations *fops,
170 struct dentry **dentry_p);
172 /* Devices management *******************************************************/
174 DEFINE_MUTEX(ffs_lock);
175 EXPORT_SYMBOL_GPL(ffs_lock);
177 static struct ffs_dev *_ffs_find_dev(const char *name);
178 static struct ffs_dev *_ffs_alloc_dev(void);
179 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
180 static void _ffs_free_dev(struct ffs_dev *dev);
181 static void *ffs_acquire_dev(const char *dev_name);
182 static void ffs_release_dev(struct ffs_data *ffs_data);
183 static int ffs_ready(struct ffs_data *ffs);
184 static void ffs_closed(struct ffs_data *ffs);
186 /* Misc helper functions ****************************************************/
188 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
189 __attribute__((warn_unused_result, nonnull));
190 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
191 __attribute__((warn_unused_result, nonnull));
194 /* Control file aka ep0 *****************************************************/
196 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
198 struct ffs_data *ffs = req->context;
200 complete_all(&ffs->ep0req_completion);
203 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
205 struct usb_request *req = ffs->ep0req;
208 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
210 spin_unlock_irq(&ffs->ev.waitq.lock);
216 * UDC layer requires to provide a buffer even for ZLP, but should
217 * not use it at all. Let's provide some poisoned pointer to catch
218 * possible bug in the driver.
220 if (req->buf == NULL)
221 req->buf = (void *)0xDEADBABE;
223 reinit_completion(&ffs->ep0req_completion);
225 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
226 if (unlikely(ret < 0))
229 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
231 usb_ep_dequeue(ffs->gadget->ep0, req);
235 ffs->setup_state = FFS_NO_SETUP;
236 return req->status ? req->status : req->actual;
239 static int __ffs_ep0_stall(struct ffs_data *ffs)
241 if (ffs->ev.can_stall) {
242 pr_vdebug("ep0 stall\n");
243 usb_ep_set_halt(ffs->gadget->ep0);
244 ffs->setup_state = FFS_NO_SETUP;
247 pr_debug("bogus ep0 stall!\n");
252 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
253 size_t len, loff_t *ptr)
255 struct ffs_data *ffs = file->private_data;
261 /* Fast check if setup was canceled */
262 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
266 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
267 if (unlikely(ret < 0))
271 switch (ffs->state) {
272 case FFS_READ_DESCRIPTORS:
273 case FFS_READ_STRINGS:
275 if (unlikely(len < 16)) {
280 data = ffs_prepare_buffer(buf, len);
287 if (ffs->state == FFS_READ_DESCRIPTORS) {
288 pr_info("read descriptors\n");
289 ret = __ffs_data_got_descs(ffs, data, len);
290 if (unlikely(ret < 0))
293 ffs->state = FFS_READ_STRINGS;
296 pr_info("read strings\n");
297 ret = __ffs_data_got_strings(ffs, data, len);
298 if (unlikely(ret < 0))
301 ret = ffs_epfiles_create(ffs);
303 ffs->state = FFS_CLOSING;
307 ffs->state = FFS_ACTIVE;
308 mutex_unlock(&ffs->mutex);
310 ret = ffs_ready(ffs);
311 if (unlikely(ret < 0)) {
312 ffs->state = FFS_CLOSING;
316 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
324 * We're called from user space, we can use _irq
325 * rather then _irqsave
327 spin_lock_irq(&ffs->ev.waitq.lock);
328 switch (ffs_setup_state_clear_cancelled(ffs)) {
329 case FFS_SETUP_CANCELLED:
337 case FFS_SETUP_PENDING:
341 /* FFS_SETUP_PENDING */
342 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
343 spin_unlock_irq(&ffs->ev.waitq.lock);
344 ret = __ffs_ep0_stall(ffs);
348 /* FFS_SETUP_PENDING and not stall */
349 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
351 spin_unlock_irq(&ffs->ev.waitq.lock);
353 data = ffs_prepare_buffer(buf, len);
359 spin_lock_irq(&ffs->ev.waitq.lock);
362 * We are guaranteed to be still in FFS_ACTIVE state
363 * but the state of setup could have changed from
364 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
365 * to check for that. If that happened we copied data
366 * from user space in vain but it's unlikely.
368 * For sure we are not in FFS_NO_SETUP since this is
369 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
370 * transition can be performed and it's protected by
373 if (ffs_setup_state_clear_cancelled(ffs) ==
374 FFS_SETUP_CANCELLED) {
377 spin_unlock_irq(&ffs->ev.waitq.lock);
379 /* unlocks spinlock */
380 ret = __ffs_ep0_queue_wait(ffs, data, len);
390 mutex_unlock(&ffs->mutex);
394 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
398 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
401 struct usb_functionfs_event events[n];
404 memset(events, 0, sizeof events);
407 events[i].type = ffs->ev.types[i];
408 if (events[i].type == FUNCTIONFS_SETUP) {
409 events[i].u.setup = ffs->ev.setup;
410 ffs->setup_state = FFS_SETUP_PENDING;
414 if (n < ffs->ev.count) {
416 memmove(ffs->ev.types, ffs->ev.types + n,
417 ffs->ev.count * sizeof *ffs->ev.types);
422 spin_unlock_irq(&ffs->ev.waitq.lock);
423 mutex_unlock(&ffs->mutex);
425 return unlikely(__copy_to_user(buf, events, sizeof events))
426 ? -EFAULT : sizeof events;
429 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
430 size_t len, loff_t *ptr)
432 struct ffs_data *ffs = file->private_data;
439 /* Fast check if setup was canceled */
440 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
444 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
445 if (unlikely(ret < 0))
449 if (ffs->state != FFS_ACTIVE) {
455 * We're called from user space, we can use _irq rather then
458 spin_lock_irq(&ffs->ev.waitq.lock);
460 switch (ffs_setup_state_clear_cancelled(ffs)) {
461 case FFS_SETUP_CANCELLED:
466 n = len / sizeof(struct usb_functionfs_event);
472 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
477 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
483 return __ffs_ep0_read_events(ffs, buf,
484 min(n, (size_t)ffs->ev.count));
486 case FFS_SETUP_PENDING:
487 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
488 spin_unlock_irq(&ffs->ev.waitq.lock);
489 ret = __ffs_ep0_stall(ffs);
493 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
495 spin_unlock_irq(&ffs->ev.waitq.lock);
498 data = kmalloc(len, GFP_KERNEL);
499 if (unlikely(!data)) {
505 spin_lock_irq(&ffs->ev.waitq.lock);
507 /* See ffs_ep0_write() */
508 if (ffs_setup_state_clear_cancelled(ffs) ==
509 FFS_SETUP_CANCELLED) {
514 /* unlocks spinlock */
515 ret = __ffs_ep0_queue_wait(ffs, data, len);
516 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
525 spin_unlock_irq(&ffs->ev.waitq.lock);
527 mutex_unlock(&ffs->mutex);
532 static int ffs_ep0_open(struct inode *inode, struct file *file)
534 struct ffs_data *ffs = inode->i_private;
538 if (unlikely(ffs->state == FFS_CLOSING))
541 file->private_data = ffs;
542 ffs_data_opened(ffs);
547 static int ffs_ep0_release(struct inode *inode, struct file *file)
549 struct ffs_data *ffs = file->private_data;
553 ffs_data_closed(ffs);
558 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
560 struct ffs_data *ffs = file->private_data;
561 struct usb_gadget *gadget = ffs->gadget;
566 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
567 struct ffs_function *func = ffs->func;
568 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
569 } else if (gadget && gadget->ops->ioctl) {
570 ret = gadget->ops->ioctl(gadget, code, value);
578 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
580 struct ffs_data *ffs = file->private_data;
581 unsigned int mask = POLLWRNORM;
584 poll_wait(file, &ffs->ev.waitq, wait);
586 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
587 if (unlikely(ret < 0))
590 switch (ffs->state) {
591 case FFS_READ_DESCRIPTORS:
592 case FFS_READ_STRINGS:
597 switch (ffs->setup_state) {
603 case FFS_SETUP_PENDING:
604 case FFS_SETUP_CANCELLED:
605 mask |= (POLLIN | POLLOUT);
612 mutex_unlock(&ffs->mutex);
617 static const struct file_operations ffs_ep0_operations = {
620 .open = ffs_ep0_open,
621 .write = ffs_ep0_write,
622 .read = ffs_ep0_read,
623 .release = ffs_ep0_release,
624 .unlocked_ioctl = ffs_ep0_ioctl,
625 .poll = ffs_ep0_poll,
629 /* "Normal" endpoints operations ********************************************/
631 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
634 if (likely(req->context)) {
635 struct ffs_ep *ep = _ep->driver_data;
636 ep->status = req->status ? req->status : req->actual;
637 complete(req->context);
641 static void ffs_user_copy_worker(struct work_struct *work)
643 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
645 int ret = io_data->req->status ? io_data->req->status :
646 io_data->req->actual;
648 if (io_data->read && ret > 0) {
652 for (i = 0; i < io_data->nr_segs; i++) {
653 if (unlikely(copy_to_user(io_data->iovec[i].iov_base,
655 io_data->iovec[i].iov_len))) {
659 pos += io_data->iovec[i].iov_len;
661 unuse_mm(io_data->mm);
664 aio_complete(io_data->kiocb, ret, ret);
666 usb_ep_free_request(io_data->ep, io_data->req);
668 io_data->kiocb->private = NULL;
670 kfree(io_data->iovec);
675 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
676 struct usb_request *req)
678 struct ffs_io_data *io_data = req->context;
682 INIT_WORK(&io_data->work, ffs_user_copy_worker);
683 schedule_work(&io_data->work);
686 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
688 struct ffs_epfile *epfile = file->private_data;
691 ssize_t ret, data_len;
694 /* Are we still active? */
695 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
700 /* Wait for endpoint to be enabled */
703 if (file->f_flags & O_NONBLOCK) {
708 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
716 halt = (!io_data->read == !epfile->in);
717 if (halt && epfile->isoc) {
722 /* Allocate & copy */
725 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
726 * before the waiting completes, so do not assign to 'gadget' earlier
728 struct usb_gadget *gadget = epfile->ffs->gadget;
730 spin_lock_irq(&epfile->ffs->eps_lock);
731 /* In the meantime, endpoint got disabled or changed. */
732 if (epfile->ep != ep) {
733 spin_unlock_irq(&epfile->ffs->eps_lock);
737 * Controller may require buffer size to be aligned to
738 * maxpacketsize of an out endpoint.
740 data_len = io_data->read ?
741 usb_ep_align_maybe(gadget, ep->ep, io_data->len) :
743 spin_unlock_irq(&epfile->ffs->eps_lock);
745 data = kmalloc(data_len, GFP_KERNEL);
748 if (io_data->aio && !io_data->read) {
751 for (i = 0; i < io_data->nr_segs; i++) {
752 if (unlikely(copy_from_user(&data[pos],
753 io_data->iovec[i].iov_base,
754 io_data->iovec[i].iov_len))) {
758 pos += io_data->iovec[i].iov_len;
761 if (!io_data->read &&
762 unlikely(__copy_from_user(data, io_data->buf,
770 /* We will be using request */
771 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
775 spin_lock_irq(&epfile->ffs->eps_lock);
777 if (epfile->ep != ep) {
778 /* In the meantime, endpoint got disabled or changed. */
780 spin_unlock_irq(&epfile->ffs->eps_lock);
783 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
784 usb_ep_set_halt(ep->ep);
785 spin_unlock_irq(&epfile->ffs->eps_lock);
788 /* Fire the request */
789 struct usb_request *req;
792 req = usb_ep_alloc_request(ep->ep, GFP_KERNEL);
797 req->length = io_data->len;
800 io_data->ep = ep->ep;
803 req->context = io_data;
804 req->complete = ffs_epfile_async_io_complete;
806 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
808 usb_ep_free_request(ep->ep, req);
813 spin_unlock_irq(&epfile->ffs->eps_lock);
815 DECLARE_COMPLETION_ONSTACK(done);
819 req->length = io_data->len;
821 req->context = &done;
822 req->complete = ffs_epfile_io_complete;
824 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
826 spin_unlock_irq(&epfile->ffs->eps_lock);
828 if (unlikely(ret < 0)) {
831 wait_for_completion_interruptible(&done))) {
833 usb_ep_dequeue(ep->ep, req);
836 * XXX We may end up silently droping data
837 * here. Since data_len (i.e. req->length) may
838 * be bigger than len (after being rounded up
839 * to maxpacketsize), we may end up with more
840 * data then user space has space for.
843 if (io_data->read && ret > 0) {
844 ret = min_t(size_t, ret, io_data->len);
846 if (unlikely(copy_to_user(io_data->buf,
855 mutex_unlock(&epfile->mutex);
859 spin_unlock_irq(&epfile->ffs->eps_lock);
860 mutex_unlock(&epfile->mutex);
867 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
870 struct ffs_io_data io_data;
875 io_data.read = false;
876 io_data.buf = (char * __user)buf;
879 return ffs_epfile_io(file, &io_data);
883 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
885 struct ffs_io_data io_data;
894 return ffs_epfile_io(file, &io_data);
898 ffs_epfile_open(struct inode *inode, struct file *file)
900 struct ffs_epfile *epfile = inode->i_private;
904 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
907 file->private_data = epfile;
908 ffs_data_opened(epfile->ffs);
913 static int ffs_aio_cancel(struct kiocb *kiocb)
915 struct ffs_io_data *io_data = kiocb->private;
916 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
921 spin_lock_irq(&epfile->ffs->eps_lock);
923 if (likely(io_data && io_data->ep && io_data->req))
924 value = usb_ep_dequeue(io_data->ep, io_data->req);
928 spin_unlock_irq(&epfile->ffs->eps_lock);
933 static ssize_t ffs_epfile_aio_write(struct kiocb *kiocb,
934 const struct iovec *iovec,
935 unsigned long nr_segs, loff_t loff)
937 struct ffs_io_data *io_data;
941 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
942 if (unlikely(!io_data))
946 io_data->read = false;
947 io_data->kiocb = kiocb;
948 io_data->iovec = iovec;
949 io_data->nr_segs = nr_segs;
950 io_data->len = kiocb->ki_nbytes;
951 io_data->mm = current->mm;
953 kiocb->private = io_data;
955 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
957 return ffs_epfile_io(kiocb->ki_filp, io_data);
960 static ssize_t ffs_epfile_aio_read(struct kiocb *kiocb,
961 const struct iovec *iovec,
962 unsigned long nr_segs, loff_t loff)
964 struct ffs_io_data *io_data;
965 struct iovec *iovec_copy;
969 iovec_copy = kmalloc_array(nr_segs, sizeof(*iovec_copy), GFP_KERNEL);
970 if (unlikely(!iovec_copy))
973 memcpy(iovec_copy, iovec, sizeof(struct iovec)*nr_segs);
975 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
976 if (unlikely(!io_data)) {
982 io_data->read = true;
983 io_data->kiocb = kiocb;
984 io_data->iovec = iovec_copy;
985 io_data->nr_segs = nr_segs;
986 io_data->len = kiocb->ki_nbytes;
987 io_data->mm = current->mm;
989 kiocb->private = io_data;
991 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
993 return ffs_epfile_io(kiocb->ki_filp, io_data);
997 ffs_epfile_release(struct inode *inode, struct file *file)
999 struct ffs_epfile *epfile = inode->i_private;
1003 ffs_data_closed(epfile->ffs);
1008 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1009 unsigned long value)
1011 struct ffs_epfile *epfile = file->private_data;
1016 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1019 spin_lock_irq(&epfile->ffs->eps_lock);
1020 if (likely(epfile->ep)) {
1022 case FUNCTIONFS_FIFO_STATUS:
1023 ret = usb_ep_fifo_status(epfile->ep->ep);
1025 case FUNCTIONFS_FIFO_FLUSH:
1026 usb_ep_fifo_flush(epfile->ep->ep);
1029 case FUNCTIONFS_CLEAR_HALT:
1030 ret = usb_ep_clear_halt(epfile->ep->ep);
1032 case FUNCTIONFS_ENDPOINT_REVMAP:
1033 ret = epfile->ep->num;
1041 spin_unlock_irq(&epfile->ffs->eps_lock);
1046 static const struct file_operations ffs_epfile_operations = {
1047 .llseek = no_llseek,
1049 .open = ffs_epfile_open,
1050 .write = ffs_epfile_write,
1051 .read = ffs_epfile_read,
1052 .aio_write = ffs_epfile_aio_write,
1053 .aio_read = ffs_epfile_aio_read,
1054 .release = ffs_epfile_release,
1055 .unlocked_ioctl = ffs_epfile_ioctl,
1059 /* File system and super block operations ***********************************/
1062 * Mounting the file system creates a controller file, used first for
1063 * function configuration then later for event monitoring.
1066 static struct inode *__must_check
1067 ffs_sb_make_inode(struct super_block *sb, void *data,
1068 const struct file_operations *fops,
1069 const struct inode_operations *iops,
1070 struct ffs_file_perms *perms)
1072 struct inode *inode;
1076 inode = new_inode(sb);
1078 if (likely(inode)) {
1079 struct timespec current_time = CURRENT_TIME;
1081 inode->i_ino = get_next_ino();
1082 inode->i_mode = perms->mode;
1083 inode->i_uid = perms->uid;
1084 inode->i_gid = perms->gid;
1085 inode->i_atime = current_time;
1086 inode->i_mtime = current_time;
1087 inode->i_ctime = current_time;
1088 inode->i_private = data;
1090 inode->i_fop = fops;
1098 /* Create "regular" file */
1099 static struct inode *ffs_sb_create_file(struct super_block *sb,
1100 const char *name, void *data,
1101 const struct file_operations *fops,
1102 struct dentry **dentry_p)
1104 struct ffs_data *ffs = sb->s_fs_info;
1105 struct dentry *dentry;
1106 struct inode *inode;
1110 dentry = d_alloc_name(sb->s_root, name);
1111 if (unlikely(!dentry))
1114 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1115 if (unlikely(!inode)) {
1120 d_add(dentry, inode);
1128 static const struct super_operations ffs_sb_operations = {
1129 .statfs = simple_statfs,
1130 .drop_inode = generic_delete_inode,
1133 struct ffs_sb_fill_data {
1134 struct ffs_file_perms perms;
1136 const char *dev_name;
1137 struct ffs_data *ffs_data;
1140 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1142 struct ffs_sb_fill_data *data = _data;
1143 struct inode *inode;
1144 struct ffs_data *ffs = data->ffs_data;
1149 data->ffs_data = NULL;
1150 sb->s_fs_info = ffs;
1151 sb->s_blocksize = PAGE_CACHE_SIZE;
1152 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1153 sb->s_magic = FUNCTIONFS_MAGIC;
1154 sb->s_op = &ffs_sb_operations;
1155 sb->s_time_gran = 1;
1158 data->perms.mode = data->root_mode;
1159 inode = ffs_sb_make_inode(sb, NULL,
1160 &simple_dir_operations,
1161 &simple_dir_inode_operations,
1163 sb->s_root = d_make_root(inode);
1164 if (unlikely(!sb->s_root))
1168 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1169 &ffs_ep0_operations, NULL)))
1175 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1179 if (!opts || !*opts)
1183 unsigned long value;
1187 comma = strchr(opts, ',');
1192 eq = strchr(opts, '=');
1193 if (unlikely(!eq)) {
1194 pr_err("'=' missing in %s\n", opts);
1200 if (kstrtoul(eq + 1, 0, &value)) {
1201 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1205 /* Interpret option */
1206 switch (eq - opts) {
1208 if (!memcmp(opts, "rmode", 5))
1209 data->root_mode = (value & 0555) | S_IFDIR;
1210 else if (!memcmp(opts, "fmode", 5))
1211 data->perms.mode = (value & 0666) | S_IFREG;
1217 if (!memcmp(opts, "mode", 4)) {
1218 data->root_mode = (value & 0555) | S_IFDIR;
1219 data->perms.mode = (value & 0666) | S_IFREG;
1226 if (!memcmp(opts, "uid", 3)) {
1227 data->perms.uid = make_kuid(current_user_ns(), value);
1228 if (!uid_valid(data->perms.uid)) {
1229 pr_err("%s: unmapped value: %lu\n", opts, value);
1232 } else if (!memcmp(opts, "gid", 3)) {
1233 data->perms.gid = make_kgid(current_user_ns(), value);
1234 if (!gid_valid(data->perms.gid)) {
1235 pr_err("%s: unmapped value: %lu\n", opts, value);
1245 pr_err("%s: invalid option\n", opts);
1249 /* Next iteration */
1258 /* "mount -t functionfs dev_name /dev/function" ends up here */
1260 static struct dentry *
1261 ffs_fs_mount(struct file_system_type *t, int flags,
1262 const char *dev_name, void *opts)
1264 struct ffs_sb_fill_data data = {
1266 .mode = S_IFREG | 0600,
1267 .uid = GLOBAL_ROOT_UID,
1268 .gid = GLOBAL_ROOT_GID,
1270 .root_mode = S_IFDIR | 0500,
1275 struct ffs_data *ffs;
1279 ret = ffs_fs_parse_opts(&data, opts);
1280 if (unlikely(ret < 0))
1281 return ERR_PTR(ret);
1283 ffs = ffs_data_new();
1285 return ERR_PTR(-ENOMEM);
1286 ffs->file_perms = data.perms;
1288 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1289 if (unlikely(!ffs->dev_name)) {
1291 return ERR_PTR(-ENOMEM);
1294 ffs_dev = ffs_acquire_dev(dev_name);
1295 if (IS_ERR(ffs_dev)) {
1297 return ERR_CAST(ffs_dev);
1299 ffs->private_data = ffs_dev;
1300 data.ffs_data = ffs;
1302 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1303 if (IS_ERR(rv) && data.ffs_data) {
1304 ffs_release_dev(data.ffs_data);
1305 ffs_data_put(data.ffs_data);
1311 ffs_fs_kill_sb(struct super_block *sb)
1315 kill_litter_super(sb);
1316 if (sb->s_fs_info) {
1317 ffs_release_dev(sb->s_fs_info);
1318 ffs_data_put(sb->s_fs_info);
1322 static struct file_system_type ffs_fs_type = {
1323 .owner = THIS_MODULE,
1324 .name = "functionfs",
1325 .mount = ffs_fs_mount,
1326 .kill_sb = ffs_fs_kill_sb,
1328 MODULE_ALIAS_FS("functionfs");
1331 /* Driver's main init/cleanup functions *************************************/
1333 static int functionfs_init(void)
1339 ret = register_filesystem(&ffs_fs_type);
1341 pr_info("file system registered\n");
1343 pr_err("failed registering file system (%d)\n", ret);
1348 static void functionfs_cleanup(void)
1352 pr_info("unloading\n");
1353 unregister_filesystem(&ffs_fs_type);
1357 /* ffs_data and ffs_function construction and destruction code **************/
1359 static void ffs_data_clear(struct ffs_data *ffs);
1360 static void ffs_data_reset(struct ffs_data *ffs);
1362 static void ffs_data_get(struct ffs_data *ffs)
1366 atomic_inc(&ffs->ref);
1369 static void ffs_data_opened(struct ffs_data *ffs)
1373 atomic_inc(&ffs->ref);
1374 atomic_inc(&ffs->opened);
1377 static void ffs_data_put(struct ffs_data *ffs)
1381 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1382 pr_info("%s(): freeing\n", __func__);
1383 ffs_data_clear(ffs);
1384 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1385 waitqueue_active(&ffs->ep0req_completion.wait));
1386 kfree(ffs->dev_name);
1391 static void ffs_data_closed(struct ffs_data *ffs)
1395 if (atomic_dec_and_test(&ffs->opened)) {
1396 ffs->state = FFS_CLOSING;
1397 ffs_data_reset(ffs);
1403 static struct ffs_data *ffs_data_new(void)
1405 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1411 atomic_set(&ffs->ref, 1);
1412 atomic_set(&ffs->opened, 0);
1413 ffs->state = FFS_READ_DESCRIPTORS;
1414 mutex_init(&ffs->mutex);
1415 spin_lock_init(&ffs->eps_lock);
1416 init_waitqueue_head(&ffs->ev.waitq);
1417 init_completion(&ffs->ep0req_completion);
1419 /* XXX REVISIT need to update it in some places, or do we? */
1420 ffs->ev.can_stall = 1;
1425 static void ffs_data_clear(struct ffs_data *ffs)
1429 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1432 BUG_ON(ffs->gadget);
1435 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1437 kfree(ffs->raw_descs_data);
1438 kfree(ffs->raw_strings);
1439 kfree(ffs->stringtabs);
1442 static void ffs_data_reset(struct ffs_data *ffs)
1446 ffs_data_clear(ffs);
1448 ffs->epfiles = NULL;
1449 ffs->raw_descs_data = NULL;
1450 ffs->raw_descs = NULL;
1451 ffs->raw_strings = NULL;
1452 ffs->stringtabs = NULL;
1454 ffs->raw_descs_length = 0;
1455 ffs->fs_descs_count = 0;
1456 ffs->hs_descs_count = 0;
1457 ffs->ss_descs_count = 0;
1459 ffs->strings_count = 0;
1460 ffs->interfaces_count = 0;
1465 ffs->state = FFS_READ_DESCRIPTORS;
1466 ffs->setup_state = FFS_NO_SETUP;
1471 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1473 struct usb_gadget_strings **lang;
1478 if (WARN_ON(ffs->state != FFS_ACTIVE
1479 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1482 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1483 if (unlikely(first_id < 0))
1486 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1487 if (unlikely(!ffs->ep0req))
1489 ffs->ep0req->complete = ffs_ep0_complete;
1490 ffs->ep0req->context = ffs;
1492 lang = ffs->stringtabs;
1494 for (; *lang; ++lang) {
1495 struct usb_string *str = (*lang)->strings;
1497 for (; str->s; ++id, ++str)
1502 ffs->gadget = cdev->gadget;
1507 static void functionfs_unbind(struct ffs_data *ffs)
1511 if (!WARN_ON(!ffs->gadget)) {
1512 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1515 clear_bit(FFS_FL_BOUND, &ffs->flags);
1520 static int ffs_epfiles_create(struct ffs_data *ffs)
1522 struct ffs_epfile *epfile, *epfiles;
1527 count = ffs->eps_count;
1528 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1533 for (i = 1; i <= count; ++i, ++epfile) {
1535 mutex_init(&epfile->mutex);
1536 init_waitqueue_head(&epfile->wait);
1537 sprintf(epfiles->name, "ep%u", i);
1538 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1539 &ffs_epfile_operations,
1540 &epfile->dentry))) {
1541 ffs_epfiles_destroy(epfiles, i - 1);
1546 ffs->epfiles = epfiles;
1550 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1552 struct ffs_epfile *epfile = epfiles;
1556 for (; count; --count, ++epfile) {
1557 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1558 waitqueue_active(&epfile->wait));
1559 if (epfile->dentry) {
1560 d_delete(epfile->dentry);
1561 dput(epfile->dentry);
1562 epfile->dentry = NULL;
1570 static void ffs_func_eps_disable(struct ffs_function *func)
1572 struct ffs_ep *ep = func->eps;
1573 struct ffs_epfile *epfile = func->ffs->epfiles;
1574 unsigned count = func->ffs->eps_count;
1575 unsigned long flags;
1577 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1579 /* pending requests get nuked */
1581 usb_ep_disable(ep->ep);
1587 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1590 static int ffs_func_eps_enable(struct ffs_function *func)
1592 struct ffs_data *ffs = func->ffs;
1593 struct ffs_ep *ep = func->eps;
1594 struct ffs_epfile *epfile = ffs->epfiles;
1595 unsigned count = ffs->eps_count;
1596 unsigned long flags;
1599 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1601 struct usb_endpoint_descriptor *ds;
1604 if (ffs->gadget->speed == USB_SPEED_SUPER)
1606 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1611 /* fall-back to lower speed if desc missing for current speed */
1613 ds = ep->descs[desc_idx];
1614 } while (!ds && --desc_idx >= 0);
1621 ep->ep->driver_data = ep;
1623 ret = usb_ep_enable(ep->ep);
1626 epfile->in = usb_endpoint_dir_in(ds);
1627 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1632 wake_up(&epfile->wait);
1637 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1643 /* Parsing and building descriptors and strings *****************************/
1646 * This validates if data pointed by data is a valid USB descriptor as
1647 * well as record how many interfaces, endpoints and strings are
1648 * required by given configuration. Returns address after the
1649 * descriptor or NULL if data is invalid.
1652 enum ffs_entity_type {
1653 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1656 enum ffs_os_desc_type {
1657 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1660 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1662 struct usb_descriptor_header *desc,
1665 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1666 struct usb_os_desc_header *h, void *data,
1667 unsigned len, void *priv);
1669 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1670 ffs_entity_callback entity,
1673 struct usb_descriptor_header *_ds = (void *)data;
1679 /* At least two bytes are required: length and type */
1681 pr_vdebug("descriptor too short\n");
1685 /* If we have at least as many bytes as the descriptor takes? */
1686 length = _ds->bLength;
1688 pr_vdebug("descriptor longer then available data\n");
1692 #define __entity_check_INTERFACE(val) 1
1693 #define __entity_check_STRING(val) (val)
1694 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1695 #define __entity(type, val) do { \
1696 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1697 if (unlikely(!__entity_check_ ##type(val))) { \
1698 pr_vdebug("invalid entity's value\n"); \
1701 ret = entity(FFS_ ##type, &val, _ds, priv); \
1702 if (unlikely(ret < 0)) { \
1703 pr_debug("entity " #type "(%02x); ret = %d\n", \
1709 /* Parse descriptor depending on type. */
1710 switch (_ds->bDescriptorType) {
1714 case USB_DT_DEVICE_QUALIFIER:
1715 /* function can't have any of those */
1716 pr_vdebug("descriptor reserved for gadget: %d\n",
1717 _ds->bDescriptorType);
1720 case USB_DT_INTERFACE: {
1721 struct usb_interface_descriptor *ds = (void *)_ds;
1722 pr_vdebug("interface descriptor\n");
1723 if (length != sizeof *ds)
1726 __entity(INTERFACE, ds->bInterfaceNumber);
1728 __entity(STRING, ds->iInterface);
1732 case USB_DT_ENDPOINT: {
1733 struct usb_endpoint_descriptor *ds = (void *)_ds;
1734 pr_vdebug("endpoint descriptor\n");
1735 if (length != USB_DT_ENDPOINT_SIZE &&
1736 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1738 __entity(ENDPOINT, ds->bEndpointAddress);
1743 pr_vdebug("hid descriptor\n");
1744 if (length != sizeof(struct hid_descriptor))
1749 if (length != sizeof(struct usb_otg_descriptor))
1753 case USB_DT_INTERFACE_ASSOCIATION: {
1754 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1755 pr_vdebug("interface association descriptor\n");
1756 if (length != sizeof *ds)
1759 __entity(STRING, ds->iFunction);
1763 case USB_DT_SS_ENDPOINT_COMP:
1764 pr_vdebug("EP SS companion descriptor\n");
1765 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1769 case USB_DT_OTHER_SPEED_CONFIG:
1770 case USB_DT_INTERFACE_POWER:
1772 case USB_DT_SECURITY:
1773 case USB_DT_CS_RADIO_CONTROL:
1775 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1779 /* We should never be here */
1780 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1784 pr_vdebug("invalid length: %d (descriptor %d)\n",
1785 _ds->bLength, _ds->bDescriptorType);
1790 #undef __entity_check_DESCRIPTOR
1791 #undef __entity_check_INTERFACE
1792 #undef __entity_check_STRING
1793 #undef __entity_check_ENDPOINT
1798 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1799 ffs_entity_callback entity, void *priv)
1801 const unsigned _len = len;
1802 unsigned long num = 0;
1812 /* Record "descriptor" entity */
1813 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1814 if (unlikely(ret < 0)) {
1815 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1823 ret = ffs_do_single_desc(data, len, entity, priv);
1824 if (unlikely(ret < 0)) {
1825 pr_debug("%s returns %d\n", __func__, ret);
1835 static int __ffs_data_do_entity(enum ffs_entity_type type,
1836 u8 *valuep, struct usb_descriptor_header *desc,
1839 struct ffs_desc_helper *helper = priv;
1840 struct usb_endpoint_descriptor *d;
1845 case FFS_DESCRIPTOR:
1850 * Interfaces are indexed from zero so if we
1851 * encountered interface "n" then there are at least
1854 if (*valuep >= helper->interfaces_count)
1855 helper->interfaces_count = *valuep + 1;
1860 * Strings are indexed from 1 (0 is magic ;) reserved
1861 * for languages list or some such)
1863 if (*valuep > helper->ffs->strings_count)
1864 helper->ffs->strings_count = *valuep;
1869 helper->eps_count++;
1870 if (helper->eps_count >= 15)
1872 /* Check if descriptors for any speed were already parsed */
1873 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
1874 helper->ffs->eps_addrmap[helper->eps_count] =
1875 d->bEndpointAddress;
1876 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
1877 d->bEndpointAddress)
1885 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1886 struct usb_os_desc_header *desc)
1888 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1889 u16 w_index = le16_to_cpu(desc->wIndex);
1891 if (bcd_version != 1) {
1892 pr_vdebug("unsupported os descriptors version: %d",
1898 *next_type = FFS_OS_DESC_EXT_COMPAT;
1901 *next_type = FFS_OS_DESC_EXT_PROP;
1904 pr_vdebug("unsupported os descriptor type: %d", w_index);
1908 return sizeof(*desc);
1912 * Process all extended compatibility/extended property descriptors
1913 * of a feature descriptor
1915 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1916 enum ffs_os_desc_type type,
1918 ffs_os_desc_callback entity,
1920 struct usb_os_desc_header *h)
1923 const unsigned _len = len;
1927 /* loop over all ext compat/ext prop descriptors */
1928 while (feature_count--) {
1929 ret = entity(type, h, data, len, priv);
1930 if (unlikely(ret < 0)) {
1931 pr_debug("bad OS descriptor, type: %d\n", type);
1940 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1941 static int __must_check ffs_do_os_descs(unsigned count,
1942 char *data, unsigned len,
1943 ffs_os_desc_callback entity, void *priv)
1945 const unsigned _len = len;
1946 unsigned long num = 0;
1950 for (num = 0; num < count; ++num) {
1952 enum ffs_os_desc_type type;
1954 struct usb_os_desc_header *desc = (void *)data;
1956 if (len < sizeof(*desc))
1960 * Record "descriptor" entity.
1961 * Process dwLength, bcdVersion, wIndex, get b/wCount.
1962 * Move the data pointer to the beginning of extended
1963 * compatibilities proper or extended properties proper
1964 * portions of the data
1966 if (le32_to_cpu(desc->dwLength) > len)
1969 ret = __ffs_do_os_desc_header(&type, desc);
1970 if (unlikely(ret < 0)) {
1971 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
1976 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
1978 feature_count = le16_to_cpu(desc->wCount);
1979 if (type == FFS_OS_DESC_EXT_COMPAT &&
1980 (feature_count > 255 || desc->Reserved))
1986 * Process all function/property descriptors
1987 * of this Feature Descriptor
1989 ret = ffs_do_single_os_desc(data, len, type,
1990 feature_count, entity, priv, desc);
1991 if (unlikely(ret < 0)) {
1992 pr_debug("%s returns %d\n", __func__, ret);
2003 * Validate contents of the buffer from userspace related to OS descriptors.
2005 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2006 struct usb_os_desc_header *h, void *data,
2007 unsigned len, void *priv)
2009 struct ffs_data *ffs = priv;
2015 case FFS_OS_DESC_EXT_COMPAT: {
2016 struct usb_ext_compat_desc *d = data;
2019 if (len < sizeof(*d) ||
2020 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2023 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2024 if (d->Reserved2[i])
2027 length = sizeof(struct usb_ext_compat_desc);
2030 case FFS_OS_DESC_EXT_PROP: {
2031 struct usb_ext_prop_desc *d = data;
2035 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2037 length = le32_to_cpu(d->dwSize);
2038 type = le32_to_cpu(d->dwPropertyDataType);
2039 if (type < USB_EXT_PROP_UNICODE ||
2040 type > USB_EXT_PROP_UNICODE_MULTI) {
2041 pr_vdebug("unsupported os descriptor property type: %d",
2045 pnl = le16_to_cpu(d->wPropertyNameLength);
2046 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2047 if (length != 14 + pnl + pdl) {
2048 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2049 length, pnl, pdl, type);
2052 ++ffs->ms_os_descs_ext_prop_count;
2053 /* property name reported to the host as "WCHAR"s */
2054 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2055 ffs->ms_os_descs_ext_prop_data_len += pdl;
2059 pr_vdebug("unknown descriptor: %d\n", type);
2065 static int __ffs_data_got_descs(struct ffs_data *ffs,
2066 char *const _data, size_t len)
2068 char *data = _data, *raw_descs;
2069 unsigned os_descs_count = 0, counts[3], flags;
2070 int ret = -EINVAL, i;
2071 struct ffs_desc_helper helper;
2075 if (get_unaligned_le32(data + 4) != len)
2078 switch (get_unaligned_le32(data)) {
2079 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2080 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2084 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2085 flags = get_unaligned_le32(data + 8);
2086 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2087 FUNCTIONFS_HAS_HS_DESC |
2088 FUNCTIONFS_HAS_SS_DESC |
2089 FUNCTIONFS_HAS_MS_OS_DESC)) {
2100 /* Read fs_count, hs_count and ss_count (if present) */
2101 for (i = 0; i < 3; ++i) {
2102 if (!(flags & (1 << i))) {
2104 } else if (len < 4) {
2107 counts[i] = get_unaligned_le32(data);
2112 if (flags & (1 << i)) {
2113 os_descs_count = get_unaligned_le32(data);
2118 /* Read descriptors */
2121 for (i = 0; i < 3; ++i) {
2124 helper.interfaces_count = 0;
2125 helper.eps_count = 0;
2126 ret = ffs_do_descs(counts[i], data, len,
2127 __ffs_data_do_entity, &helper);
2130 if (!ffs->eps_count && !ffs->interfaces_count) {
2131 ffs->eps_count = helper.eps_count;
2132 ffs->interfaces_count = helper.interfaces_count;
2134 if (ffs->eps_count != helper.eps_count) {
2138 if (ffs->interfaces_count != helper.interfaces_count) {
2146 if (os_descs_count) {
2147 ret = ffs_do_os_descs(os_descs_count, data, len,
2148 __ffs_data_do_os_desc, ffs);
2155 if (raw_descs == data || len) {
2160 ffs->raw_descs_data = _data;
2161 ffs->raw_descs = raw_descs;
2162 ffs->raw_descs_length = data - raw_descs;
2163 ffs->fs_descs_count = counts[0];
2164 ffs->hs_descs_count = counts[1];
2165 ffs->ss_descs_count = counts[2];
2166 ffs->ms_os_descs_count = os_descs_count;
2175 static int __ffs_data_got_strings(struct ffs_data *ffs,
2176 char *const _data, size_t len)
2178 u32 str_count, needed_count, lang_count;
2179 struct usb_gadget_strings **stringtabs, *t;
2180 struct usb_string *strings, *s;
2181 const char *data = _data;
2185 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2186 get_unaligned_le32(data + 4) != len))
2188 str_count = get_unaligned_le32(data + 8);
2189 lang_count = get_unaligned_le32(data + 12);
2191 /* if one is zero the other must be zero */
2192 if (unlikely(!str_count != !lang_count))
2195 /* Do we have at least as many strings as descriptors need? */
2196 needed_count = ffs->strings_count;
2197 if (unlikely(str_count < needed_count))
2201 * If we don't need any strings just return and free all
2204 if (!needed_count) {
2209 /* Allocate everything in one chunk so there's less maintenance. */
2213 vla_item(d, struct usb_gadget_strings *, stringtabs,
2215 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2216 vla_item(d, struct usb_string, strings,
2217 lang_count*(needed_count+1));
2219 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2221 if (unlikely(!vlabuf)) {
2226 /* Initialize the VLA pointers */
2227 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2228 t = vla_ptr(vlabuf, d, stringtab);
2231 *stringtabs++ = t++;
2235 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2236 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2237 t = vla_ptr(vlabuf, d, stringtab);
2238 s = vla_ptr(vlabuf, d, strings);
2242 /* For each language */
2246 do { /* lang_count > 0 so we can use do-while */
2247 unsigned needed = needed_count;
2249 if (unlikely(len < 3))
2251 t->language = get_unaligned_le16(data);
2258 /* For each string */
2259 do { /* str_count > 0 so we can use do-while */
2260 size_t length = strnlen(data, len);
2262 if (unlikely(length == len))
2266 * User may provide more strings then we need,
2267 * if that's the case we simply ignore the
2270 if (likely(needed)) {
2272 * s->id will be set while adding
2273 * function to configuration so for
2274 * now just leave garbage here.
2283 } while (--str_count);
2285 s->id = 0; /* terminator */
2289 } while (--lang_count);
2291 /* Some garbage left? */
2296 ffs->stringtabs = stringtabs;
2297 ffs->raw_strings = _data;
2309 /* Events handling and management *******************************************/
2311 static void __ffs_event_add(struct ffs_data *ffs,
2312 enum usb_functionfs_event_type type)
2314 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2318 * Abort any unhandled setup
2320 * We do not need to worry about some cmpxchg() changing value
2321 * of ffs->setup_state without holding the lock because when
2322 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2323 * the source does nothing.
2325 if (ffs->setup_state == FFS_SETUP_PENDING)
2326 ffs->setup_state = FFS_SETUP_CANCELLED;
2329 case FUNCTIONFS_RESUME:
2330 rem_type2 = FUNCTIONFS_SUSPEND;
2332 case FUNCTIONFS_SUSPEND:
2333 case FUNCTIONFS_SETUP:
2335 /* Discard all similar events */
2338 case FUNCTIONFS_BIND:
2339 case FUNCTIONFS_UNBIND:
2340 case FUNCTIONFS_DISABLE:
2341 case FUNCTIONFS_ENABLE:
2342 /* Discard everything other then power management. */
2343 rem_type1 = FUNCTIONFS_SUSPEND;
2344 rem_type2 = FUNCTIONFS_RESUME;
2353 u8 *ev = ffs->ev.types, *out = ev;
2354 unsigned n = ffs->ev.count;
2355 for (; n; --n, ++ev)
2356 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2359 pr_vdebug("purging event %d\n", *ev);
2360 ffs->ev.count = out - ffs->ev.types;
2363 pr_vdebug("adding event %d\n", type);
2364 ffs->ev.types[ffs->ev.count++] = type;
2365 wake_up_locked(&ffs->ev.waitq);
2368 static void ffs_event_add(struct ffs_data *ffs,
2369 enum usb_functionfs_event_type type)
2371 unsigned long flags;
2372 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2373 __ffs_event_add(ffs, type);
2374 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2377 /* Bind/unbind USB function hooks *******************************************/
2379 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2383 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2384 if (ffs->eps_addrmap[i] == endpoint_address)
2389 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2390 struct usb_descriptor_header *desc,
2393 struct usb_endpoint_descriptor *ds = (void *)desc;
2394 struct ffs_function *func = priv;
2395 struct ffs_ep *ffs_ep;
2396 unsigned ep_desc_id, idx;
2397 static const char *speed_names[] = { "full", "high", "super" };
2399 if (type != FFS_DESCRIPTOR)
2403 * If ss_descriptors is not NULL, we are reading super speed
2404 * descriptors; if hs_descriptors is not NULL, we are reading high
2405 * speed descriptors; otherwise, we are reading full speed
2408 if (func->function.ss_descriptors) {
2410 func->function.ss_descriptors[(long)valuep] = desc;
2411 } else if (func->function.hs_descriptors) {
2413 func->function.hs_descriptors[(long)valuep] = desc;
2416 func->function.fs_descriptors[(long)valuep] = desc;
2419 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2422 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2426 ffs_ep = func->eps + idx;
2428 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2429 pr_err("two %sspeed descriptors for EP %d\n",
2430 speed_names[ep_desc_id],
2431 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2434 ffs_ep->descs[ep_desc_id] = ds;
2436 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2438 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2439 if (!ds->wMaxPacketSize)
2440 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2442 struct usb_request *req;
2445 pr_vdebug("autoconfig\n");
2446 ep = usb_ep_autoconfig(func->gadget, ds);
2449 ep->driver_data = func->eps + idx;
2451 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2457 func->eps_revmap[ds->bEndpointAddress &
2458 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2460 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2465 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2466 struct usb_descriptor_header *desc,
2469 struct ffs_function *func = priv;
2475 case FFS_DESCRIPTOR:
2476 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2481 if (func->interfaces_nums[idx] < 0) {
2482 int id = usb_interface_id(func->conf, &func->function);
2483 if (unlikely(id < 0))
2485 func->interfaces_nums[idx] = id;
2487 newValue = func->interfaces_nums[idx];
2491 /* String' IDs are allocated when fsf_data is bound to cdev */
2492 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2497 * USB_DT_ENDPOINT are handled in
2498 * __ffs_func_bind_do_descs().
2500 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2503 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2504 if (unlikely(!func->eps[idx].ep))
2508 struct usb_endpoint_descriptor **descs;
2509 descs = func->eps[idx].descs;
2510 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2515 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2520 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2521 struct usb_os_desc_header *h, void *data,
2522 unsigned len, void *priv)
2524 struct ffs_function *func = priv;
2528 case FFS_OS_DESC_EXT_COMPAT: {
2529 struct usb_ext_compat_desc *desc = data;
2530 struct usb_os_desc_table *t;
2532 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2533 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2534 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2535 ARRAY_SIZE(desc->CompatibleID) +
2536 ARRAY_SIZE(desc->SubCompatibleID));
2537 length = sizeof(*desc);
2540 case FFS_OS_DESC_EXT_PROP: {
2541 struct usb_ext_prop_desc *desc = data;
2542 struct usb_os_desc_table *t;
2543 struct usb_os_desc_ext_prop *ext_prop;
2544 char *ext_prop_name;
2545 char *ext_prop_data;
2547 t = &func->function.os_desc_table[h->interface];
2548 t->if_id = func->interfaces_nums[h->interface];
2550 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2551 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2553 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2554 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2555 ext_prop->data_len = le32_to_cpu(*(u32 *)
2556 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2557 length = ext_prop->name_len + ext_prop->data_len + 14;
2559 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2560 func->ffs->ms_os_descs_ext_prop_name_avail +=
2563 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2564 func->ffs->ms_os_descs_ext_prop_data_avail +=
2566 memcpy(ext_prop_data,
2567 usb_ext_prop_data_ptr(data, ext_prop->name_len),
2568 ext_prop->data_len);
2569 /* unicode data reported to the host as "WCHAR"s */
2570 switch (ext_prop->type) {
2571 case USB_EXT_PROP_UNICODE:
2572 case USB_EXT_PROP_UNICODE_ENV:
2573 case USB_EXT_PROP_UNICODE_LINK:
2574 case USB_EXT_PROP_UNICODE_MULTI:
2575 ext_prop->data_len *= 2;
2578 ext_prop->data = ext_prop_data;
2580 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2581 ext_prop->name_len);
2582 /* property name reported to the host as "WCHAR"s */
2583 ext_prop->name_len *= 2;
2584 ext_prop->name = ext_prop_name;
2586 t->os_desc->ext_prop_len +=
2587 ext_prop->name_len + ext_prop->data_len + 14;
2588 ++t->os_desc->ext_prop_count;
2589 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2593 pr_vdebug("unknown descriptor: %d\n", type);
2599 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2600 struct usb_configuration *c)
2602 struct ffs_function *func = ffs_func_from_usb(f);
2603 struct f_fs_opts *ffs_opts =
2604 container_of(f->fi, struct f_fs_opts, func_inst);
2610 * Legacy gadget triggers binding in functionfs_ready_callback,
2611 * which already uses locking; taking the same lock here would
2614 * Configfs-enabled gadgets however do need ffs_dev_lock.
2616 if (!ffs_opts->no_configfs)
2618 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2619 func->ffs = ffs_opts->dev->ffs_data;
2620 if (!ffs_opts->no_configfs)
2623 return ERR_PTR(ret);
2626 func->gadget = c->cdev->gadget;
2628 ffs_data_get(func->ffs);
2631 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2632 * configurations are bound in sequence with list_for_each_entry,
2633 * in each configuration its functions are bound in sequence
2634 * with list_for_each_entry, so we assume no race condition
2635 * with regard to ffs_opts->bound access
2637 if (!ffs_opts->refcnt) {
2638 ret = functionfs_bind(func->ffs, c->cdev);
2640 return ERR_PTR(ret);
2643 func->function.strings = func->ffs->stringtabs;
2648 static int _ffs_func_bind(struct usb_configuration *c,
2649 struct usb_function *f)
2651 struct ffs_function *func = ffs_func_from_usb(f);
2652 struct ffs_data *ffs = func->ffs;
2654 const int full = !!func->ffs->fs_descs_count;
2655 const int high = gadget_is_dualspeed(func->gadget) &&
2656 func->ffs->hs_descs_count;
2657 const int super = gadget_is_superspeed(func->gadget) &&
2658 func->ffs->ss_descs_count;
2660 int fs_len, hs_len, ss_len, ret, i;
2662 /* Make it a single chunk, less management later on */
2664 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2665 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2666 full ? ffs->fs_descs_count + 1 : 0);
2667 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2668 high ? ffs->hs_descs_count + 1 : 0);
2669 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2670 super ? ffs->ss_descs_count + 1 : 0);
2671 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2672 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2673 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2674 vla_item_with_sz(d, char[16], ext_compat,
2675 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2676 vla_item_with_sz(d, struct usb_os_desc, os_desc,
2677 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2678 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2679 ffs->ms_os_descs_ext_prop_count);
2680 vla_item_with_sz(d, char, ext_prop_name,
2681 ffs->ms_os_descs_ext_prop_name_len);
2682 vla_item_with_sz(d, char, ext_prop_data,
2683 ffs->ms_os_descs_ext_prop_data_len);
2684 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2689 /* Has descriptors only for speeds gadget does not support */
2690 if (unlikely(!(full | high | super)))
2693 /* Allocate a single chunk, less management later on */
2694 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2695 if (unlikely(!vlabuf))
2698 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2699 ffs->ms_os_descs_ext_prop_name_avail =
2700 vla_ptr(vlabuf, d, ext_prop_name);
2701 ffs->ms_os_descs_ext_prop_data_avail =
2702 vla_ptr(vlabuf, d, ext_prop_data);
2704 /* Copy descriptors */
2705 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2706 ffs->raw_descs_length);
2708 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2709 for (ret = ffs->eps_count; ret; --ret) {
2712 ptr = vla_ptr(vlabuf, d, eps);
2717 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2719 func->eps = vla_ptr(vlabuf, d, eps);
2720 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2723 * Go through all the endpoint descriptors and allocate
2724 * endpoints first, so that later we can rewrite the endpoint
2725 * numbers without worrying that it may be described later on.
2728 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2729 fs_len = ffs_do_descs(ffs->fs_descs_count,
2730 vla_ptr(vlabuf, d, raw_descs),
2732 __ffs_func_bind_do_descs, func);
2733 if (unlikely(fs_len < 0)) {
2742 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2743 hs_len = ffs_do_descs(ffs->hs_descs_count,
2744 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2745 d_raw_descs__sz - fs_len,
2746 __ffs_func_bind_do_descs, func);
2747 if (unlikely(hs_len < 0)) {
2755 if (likely(super)) {
2756 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2757 ss_len = ffs_do_descs(ffs->ss_descs_count,
2758 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2759 d_raw_descs__sz - fs_len - hs_len,
2760 __ffs_func_bind_do_descs, func);
2761 if (unlikely(ss_len < 0)) {
2770 * Now handle interface numbers allocation and interface and
2771 * endpoint numbers rewriting. We can do that in one go
2774 ret = ffs_do_descs(ffs->fs_descs_count +
2775 (high ? ffs->hs_descs_count : 0) +
2776 (super ? ffs->ss_descs_count : 0),
2777 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2778 __ffs_func_bind_do_nums, func);
2779 if (unlikely(ret < 0))
2782 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2783 if (c->cdev->use_os_string)
2784 for (i = 0; i < ffs->interfaces_count; ++i) {
2785 struct usb_os_desc *desc;
2787 desc = func->function.os_desc_table[i].os_desc =
2788 vla_ptr(vlabuf, d, os_desc) +
2789 i * sizeof(struct usb_os_desc);
2790 desc->ext_compat_id =
2791 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2792 INIT_LIST_HEAD(&desc->ext_prop);
2794 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2795 vla_ptr(vlabuf, d, raw_descs) +
2796 fs_len + hs_len + ss_len,
2797 d_raw_descs__sz - fs_len - hs_len - ss_len,
2798 __ffs_func_bind_do_os_desc, func);
2799 if (unlikely(ret < 0))
2801 func->function.os_desc_n =
2802 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2804 /* And we're done */
2805 ffs_event_add(ffs, FUNCTIONFS_BIND);
2809 /* XXX Do we need to release all claimed endpoints here? */
2813 static int ffs_func_bind(struct usb_configuration *c,
2814 struct usb_function *f)
2816 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2818 if (IS_ERR(ffs_opts))
2819 return PTR_ERR(ffs_opts);
2821 return _ffs_func_bind(c, f);
2825 /* Other USB function hooks *************************************************/
2827 static int ffs_func_set_alt(struct usb_function *f,
2828 unsigned interface, unsigned alt)
2830 struct ffs_function *func = ffs_func_from_usb(f);
2831 struct ffs_data *ffs = func->ffs;
2834 if (alt != (unsigned)-1) {
2835 intf = ffs_func_revmap_intf(func, interface);
2836 if (unlikely(intf < 0))
2841 ffs_func_eps_disable(ffs->func);
2843 if (ffs->state != FFS_ACTIVE)
2846 if (alt == (unsigned)-1) {
2848 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2853 ret = ffs_func_eps_enable(func);
2854 if (likely(ret >= 0))
2855 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2859 static void ffs_func_disable(struct usb_function *f)
2861 ffs_func_set_alt(f, 0, (unsigned)-1);
2864 static int ffs_func_setup(struct usb_function *f,
2865 const struct usb_ctrlrequest *creq)
2867 struct ffs_function *func = ffs_func_from_usb(f);
2868 struct ffs_data *ffs = func->ffs;
2869 unsigned long flags;
2874 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2875 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2876 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2877 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2878 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2881 * Most requests directed to interface go through here
2882 * (notable exceptions are set/get interface) so we need to
2883 * handle them. All other either handled by composite or
2884 * passed to usb_configuration->setup() (if one is set). No
2885 * matter, we will handle requests directed to endpoint here
2886 * as well (as it's straightforward) but what to do with any
2889 if (ffs->state != FFS_ACTIVE)
2892 switch (creq->bRequestType & USB_RECIP_MASK) {
2893 case USB_RECIP_INTERFACE:
2894 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2895 if (unlikely(ret < 0))
2899 case USB_RECIP_ENDPOINT:
2900 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2901 if (unlikely(ret < 0))
2909 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2910 ffs->ev.setup = *creq;
2911 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2912 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2913 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2918 static void ffs_func_suspend(struct usb_function *f)
2921 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2924 static void ffs_func_resume(struct usb_function *f)
2927 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2931 /* Endpoint and interface numbers reverse mapping ***************************/
2933 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2935 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2936 return num ? num : -EDOM;
2939 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2941 short *nums = func->interfaces_nums;
2942 unsigned count = func->ffs->interfaces_count;
2944 for (; count; --count, ++nums) {
2945 if (*nums >= 0 && *nums == intf)
2946 return nums - func->interfaces_nums;
2953 /* Devices management *******************************************************/
2955 static LIST_HEAD(ffs_devices);
2957 static struct ffs_dev *_ffs_do_find_dev(const char *name)
2959 struct ffs_dev *dev;
2961 list_for_each_entry(dev, &ffs_devices, entry) {
2962 if (!dev->name || !name)
2964 if (strcmp(dev->name, name) == 0)
2972 * ffs_lock must be taken by the caller of this function
2974 static struct ffs_dev *_ffs_get_single_dev(void)
2976 struct ffs_dev *dev;
2978 if (list_is_singular(&ffs_devices)) {
2979 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
2988 * ffs_lock must be taken by the caller of this function
2990 static struct ffs_dev *_ffs_find_dev(const char *name)
2992 struct ffs_dev *dev;
2994 dev = _ffs_get_single_dev();
2998 return _ffs_do_find_dev(name);
3001 /* Configfs support *********************************************************/
3003 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3005 return container_of(to_config_group(item), struct f_fs_opts,
3009 static void ffs_attr_release(struct config_item *item)
3011 struct f_fs_opts *opts = to_ffs_opts(item);
3013 usb_put_function_instance(&opts->func_inst);
3016 static struct configfs_item_operations ffs_item_ops = {
3017 .release = ffs_attr_release,
3020 static struct config_item_type ffs_func_type = {
3021 .ct_item_ops = &ffs_item_ops,
3022 .ct_owner = THIS_MODULE,
3026 /* Function registration interface ******************************************/
3028 static void ffs_free_inst(struct usb_function_instance *f)
3030 struct f_fs_opts *opts;
3032 opts = to_f_fs_opts(f);
3034 _ffs_free_dev(opts->dev);
3039 #define MAX_INST_NAME_LEN 40
3041 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3043 struct f_fs_opts *opts;
3048 name_len = strlen(name) + 1;
3049 if (name_len > MAX_INST_NAME_LEN)
3050 return -ENAMETOOLONG;
3052 ptr = kstrndup(name, name_len, GFP_KERNEL);
3056 opts = to_f_fs_opts(fi);
3061 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3062 ret = _ffs_name_dev(opts->dev, ptr);
3068 opts->dev->name_allocated = true;
3077 static struct usb_function_instance *ffs_alloc_inst(void)
3079 struct f_fs_opts *opts;
3080 struct ffs_dev *dev;
3082 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3084 return ERR_PTR(-ENOMEM);
3086 opts->func_inst.set_inst_name = ffs_set_inst_name;
3087 opts->func_inst.free_func_inst = ffs_free_inst;
3089 dev = _ffs_alloc_dev();
3093 return ERR_CAST(dev);
3098 config_group_init_type_name(&opts->func_inst.group, "",
3100 return &opts->func_inst;
3103 static void ffs_free(struct usb_function *f)
3105 kfree(ffs_func_from_usb(f));
3108 static void ffs_func_unbind(struct usb_configuration *c,
3109 struct usb_function *f)
3111 struct ffs_function *func = ffs_func_from_usb(f);
3112 struct ffs_data *ffs = func->ffs;
3113 struct f_fs_opts *opts =
3114 container_of(f->fi, struct f_fs_opts, func_inst);
3115 struct ffs_ep *ep = func->eps;
3116 unsigned count = ffs->eps_count;
3117 unsigned long flags;
3120 if (ffs->func == func) {
3121 ffs_func_eps_disable(func);
3125 if (!--opts->refcnt)
3126 functionfs_unbind(ffs);
3128 /* cleanup after autoconfig */
3129 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3131 if (ep->ep && ep->req)
3132 usb_ep_free_request(ep->ep, ep->req);
3136 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3140 * eps, descriptors and interfaces_nums are allocated in the
3141 * same chunk so only one free is required.
3143 func->function.fs_descriptors = NULL;
3144 func->function.hs_descriptors = NULL;
3145 func->function.ss_descriptors = NULL;
3146 func->interfaces_nums = NULL;
3148 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3151 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3153 struct ffs_function *func;
3157 func = kzalloc(sizeof(*func), GFP_KERNEL);
3158 if (unlikely(!func))
3159 return ERR_PTR(-ENOMEM);
3161 func->function.name = "Function FS Gadget";
3163 func->function.bind = ffs_func_bind;
3164 func->function.unbind = ffs_func_unbind;
3165 func->function.set_alt = ffs_func_set_alt;
3166 func->function.disable = ffs_func_disable;
3167 func->function.setup = ffs_func_setup;
3168 func->function.suspend = ffs_func_suspend;
3169 func->function.resume = ffs_func_resume;
3170 func->function.free_func = ffs_free;
3172 return &func->function;
3176 * ffs_lock must be taken by the caller of this function
3178 static struct ffs_dev *_ffs_alloc_dev(void)
3180 struct ffs_dev *dev;
3183 if (_ffs_get_single_dev())
3184 return ERR_PTR(-EBUSY);
3186 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3188 return ERR_PTR(-ENOMEM);
3190 if (list_empty(&ffs_devices)) {
3191 ret = functionfs_init();
3194 return ERR_PTR(ret);
3198 list_add(&dev->entry, &ffs_devices);
3204 * ffs_lock must be taken by the caller of this function
3205 * The caller is responsible for "name" being available whenever f_fs needs it
3207 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3209 struct ffs_dev *existing;
3211 existing = _ffs_do_find_dev(name);
3221 * The caller is responsible for "name" being available whenever f_fs needs it
3223 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3228 ret = _ffs_name_dev(dev, name);
3233 EXPORT_SYMBOL_GPL(ffs_name_dev);
3235 int ffs_single_dev(struct ffs_dev *dev)
3242 if (!list_is_singular(&ffs_devices))
3250 EXPORT_SYMBOL_GPL(ffs_single_dev);
3253 * ffs_lock must be taken by the caller of this function
3255 static void _ffs_free_dev(struct ffs_dev *dev)
3257 list_del(&dev->entry);
3258 if (dev->name_allocated)
3261 if (list_empty(&ffs_devices))
3262 functionfs_cleanup();
3265 static void *ffs_acquire_dev(const char *dev_name)
3267 struct ffs_dev *ffs_dev;
3272 ffs_dev = _ffs_find_dev(dev_name);
3274 ffs_dev = ERR_PTR(-ENOENT);
3275 else if (ffs_dev->mounted)
3276 ffs_dev = ERR_PTR(-EBUSY);
3277 else if (ffs_dev->ffs_acquire_dev_callback &&
3278 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3279 ffs_dev = ERR_PTR(-ENOENT);
3281 ffs_dev->mounted = true;
3287 static void ffs_release_dev(struct ffs_data *ffs_data)
3289 struct ffs_dev *ffs_dev;
3294 ffs_dev = ffs_data->private_data;
3296 ffs_dev->mounted = false;
3298 if (ffs_dev->ffs_release_dev_callback)
3299 ffs_dev->ffs_release_dev_callback(ffs_dev);
3305 static int ffs_ready(struct ffs_data *ffs)
3307 struct ffs_dev *ffs_obj;
3313 ffs_obj = ffs->private_data;
3318 if (WARN_ON(ffs_obj->desc_ready)) {
3323 ffs_obj->desc_ready = true;
3324 ffs_obj->ffs_data = ffs;
3326 if (ffs_obj->ffs_ready_callback)
3327 ret = ffs_obj->ffs_ready_callback(ffs);
3334 static void ffs_closed(struct ffs_data *ffs)
3336 struct ffs_dev *ffs_obj;
3341 ffs_obj = ffs->private_data;
3345 ffs_obj->desc_ready = false;
3347 if (ffs_obj->ffs_closed_callback)
3348 ffs_obj->ffs_closed_callback(ffs);
3350 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
3351 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
3354 unregister_gadget_item(ffs_obj->opts->
3355 func_inst.group.cg_item.ci_parent->ci_parent);
3360 /* Misc helper functions ****************************************************/
3362 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3365 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3366 : mutex_lock_interruptible(mutex);
3369 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3376 data = kmalloc(len, GFP_KERNEL);
3377 if (unlikely(!data))
3378 return ERR_PTR(-ENOMEM);
3380 if (unlikely(__copy_from_user(data, buf, len))) {
3382 return ERR_PTR(-EFAULT);
3385 pr_vdebug("Buffer from user space:\n");
3386 ffs_dump_mem("", data, len);
3391 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3392 MODULE_LICENSE("GPL");
3393 MODULE_AUTHOR("Michal Nazarewicz");