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>
39 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
41 /* Reference counter handling */
42 static void ffs_data_get(struct ffs_data *ffs);
43 static void ffs_data_put(struct ffs_data *ffs);
44 /* Creates new ffs_data object. */
45 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
47 /* Opened counter handling. */
48 static void ffs_data_opened(struct ffs_data *ffs);
49 static void ffs_data_closed(struct ffs_data *ffs);
51 /* Called with ffs->mutex held; take over ownership of data. */
52 static int __must_check
53 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
54 static int __must_check
55 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
58 /* The function structure ***************************************************/
63 struct usb_configuration *conf;
64 struct usb_gadget *gadget;
69 short *interfaces_nums;
71 struct usb_function function;
75 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
77 return container_of(f, struct ffs_function, function);
81 static inline enum ffs_setup_state
82 ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
84 return (enum ffs_setup_state)
85 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
89 static void ffs_func_eps_disable(struct ffs_function *func);
90 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
92 static int ffs_func_bind(struct usb_configuration *,
93 struct usb_function *);
94 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
95 static void ffs_func_disable(struct usb_function *);
96 static int ffs_func_setup(struct usb_function *,
97 const struct usb_ctrlrequest *);
98 static void ffs_func_suspend(struct usb_function *);
99 static void ffs_func_resume(struct usb_function *);
102 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
103 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
106 /* The endpoints structures *************************************************/
109 struct usb_ep *ep; /* P: ffs->eps_lock */
110 struct usb_request *req; /* P: epfile->mutex */
112 /* [0]: full speed, [1]: high speed, [2]: super speed */
113 struct usb_endpoint_descriptor *descs[3];
117 int status; /* P: epfile->mutex */
121 /* Protects ep->ep and ep->req. */
123 wait_queue_head_t wait;
125 struct ffs_data *ffs;
126 struct ffs_ep *ep; /* P: ffs->eps_lock */
128 struct dentry *dentry;
132 unsigned char in; /* P: ffs->eps_lock */
133 unsigned char isoc; /* P: ffs->eps_lock */
138 /* ffs_io_data structure ***************************************************/
145 const struct iovec *iovec;
146 unsigned long nr_segs;
150 struct mm_struct *mm;
151 struct work_struct work;
154 struct usb_request *req;
157 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
158 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
160 static struct inode *__must_check
161 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
162 const struct file_operations *fops,
163 struct dentry **dentry_p);
165 /* Devices management *******************************************************/
167 DEFINE_MUTEX(ffs_lock);
168 EXPORT_SYMBOL_GPL(ffs_lock);
170 static struct ffs_dev *_ffs_find_dev(const char *name);
171 static struct ffs_dev *_ffs_alloc_dev(void);
172 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
173 static void _ffs_free_dev(struct ffs_dev *dev);
174 static void *ffs_acquire_dev(const char *dev_name);
175 static void ffs_release_dev(struct ffs_data *ffs_data);
176 static int ffs_ready(struct ffs_data *ffs);
177 static void ffs_closed(struct ffs_data *ffs);
179 /* Misc helper functions ****************************************************/
181 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
182 __attribute__((warn_unused_result, nonnull));
183 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
184 __attribute__((warn_unused_result, nonnull));
187 /* Control file aka ep0 *****************************************************/
189 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
191 struct ffs_data *ffs = req->context;
193 complete_all(&ffs->ep0req_completion);
196 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
198 struct usb_request *req = ffs->ep0req;
201 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
203 spin_unlock_irq(&ffs->ev.waitq.lock);
209 * UDC layer requires to provide a buffer even for ZLP, but should
210 * not use it at all. Let's provide some poisoned pointer to catch
211 * possible bug in the driver.
213 if (req->buf == NULL)
214 req->buf = (void *)0xDEADBABE;
216 reinit_completion(&ffs->ep0req_completion);
218 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
219 if (unlikely(ret < 0))
222 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
224 usb_ep_dequeue(ffs->gadget->ep0, req);
228 ffs->setup_state = FFS_NO_SETUP;
229 return req->status ? req->status : req->actual;
232 static int __ffs_ep0_stall(struct ffs_data *ffs)
234 if (ffs->ev.can_stall) {
235 pr_vdebug("ep0 stall\n");
236 usb_ep_set_halt(ffs->gadget->ep0);
237 ffs->setup_state = FFS_NO_SETUP;
240 pr_debug("bogus ep0 stall!\n");
245 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
246 size_t len, loff_t *ptr)
248 struct ffs_data *ffs = file->private_data;
254 /* Fast check if setup was canceled */
255 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
259 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
260 if (unlikely(ret < 0))
264 switch (ffs->state) {
265 case FFS_READ_DESCRIPTORS:
266 case FFS_READ_STRINGS:
268 if (unlikely(len < 16)) {
273 data = ffs_prepare_buffer(buf, len);
280 if (ffs->state == FFS_READ_DESCRIPTORS) {
281 pr_info("read descriptors\n");
282 ret = __ffs_data_got_descs(ffs, data, len);
283 if (unlikely(ret < 0))
286 ffs->state = FFS_READ_STRINGS;
289 pr_info("read strings\n");
290 ret = __ffs_data_got_strings(ffs, data, len);
291 if (unlikely(ret < 0))
294 ret = ffs_epfiles_create(ffs);
296 ffs->state = FFS_CLOSING;
300 ffs->state = FFS_ACTIVE;
301 mutex_unlock(&ffs->mutex);
303 ret = ffs_ready(ffs);
304 if (unlikely(ret < 0)) {
305 ffs->state = FFS_CLOSING;
309 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
317 * We're called from user space, we can use _irq
318 * rather then _irqsave
320 spin_lock_irq(&ffs->ev.waitq.lock);
321 switch (ffs_setup_state_clear_cancelled(ffs)) {
322 case FFS_SETUP_CANCELLED:
330 case FFS_SETUP_PENDING:
334 /* FFS_SETUP_PENDING */
335 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
336 spin_unlock_irq(&ffs->ev.waitq.lock);
337 ret = __ffs_ep0_stall(ffs);
341 /* FFS_SETUP_PENDING and not stall */
342 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
344 spin_unlock_irq(&ffs->ev.waitq.lock);
346 data = ffs_prepare_buffer(buf, len);
352 spin_lock_irq(&ffs->ev.waitq.lock);
355 * We are guaranteed to be still in FFS_ACTIVE state
356 * but the state of setup could have changed from
357 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
358 * to check for that. If that happened we copied data
359 * from user space in vain but it's unlikely.
361 * For sure we are not in FFS_NO_SETUP since this is
362 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
363 * transition can be performed and it's protected by
366 if (ffs_setup_state_clear_cancelled(ffs) ==
367 FFS_SETUP_CANCELLED) {
370 spin_unlock_irq(&ffs->ev.waitq.lock);
372 /* unlocks spinlock */
373 ret = __ffs_ep0_queue_wait(ffs, data, len);
383 mutex_unlock(&ffs->mutex);
387 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
391 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
394 struct usb_functionfs_event events[n];
397 memset(events, 0, sizeof events);
400 events[i].type = ffs->ev.types[i];
401 if (events[i].type == FUNCTIONFS_SETUP) {
402 events[i].u.setup = ffs->ev.setup;
403 ffs->setup_state = FFS_SETUP_PENDING;
407 if (n < ffs->ev.count) {
409 memmove(ffs->ev.types, ffs->ev.types + n,
410 ffs->ev.count * sizeof *ffs->ev.types);
415 spin_unlock_irq(&ffs->ev.waitq.lock);
416 mutex_unlock(&ffs->mutex);
418 return unlikely(__copy_to_user(buf, events, sizeof events))
419 ? -EFAULT : sizeof events;
422 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
423 size_t len, loff_t *ptr)
425 struct ffs_data *ffs = file->private_data;
432 /* Fast check if setup was canceled */
433 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
437 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
438 if (unlikely(ret < 0))
442 if (ffs->state != FFS_ACTIVE) {
448 * We're called from user space, we can use _irq rather then
451 spin_lock_irq(&ffs->ev.waitq.lock);
453 switch (ffs_setup_state_clear_cancelled(ffs)) {
454 case FFS_SETUP_CANCELLED:
459 n = len / sizeof(struct usb_functionfs_event);
465 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
470 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
476 return __ffs_ep0_read_events(ffs, buf,
477 min(n, (size_t)ffs->ev.count));
479 case FFS_SETUP_PENDING:
480 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
481 spin_unlock_irq(&ffs->ev.waitq.lock);
482 ret = __ffs_ep0_stall(ffs);
486 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
488 spin_unlock_irq(&ffs->ev.waitq.lock);
491 data = kmalloc(len, GFP_KERNEL);
492 if (unlikely(!data)) {
498 spin_lock_irq(&ffs->ev.waitq.lock);
500 /* See ffs_ep0_write() */
501 if (ffs_setup_state_clear_cancelled(ffs) ==
502 FFS_SETUP_CANCELLED) {
507 /* unlocks spinlock */
508 ret = __ffs_ep0_queue_wait(ffs, data, len);
509 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
518 spin_unlock_irq(&ffs->ev.waitq.lock);
520 mutex_unlock(&ffs->mutex);
525 static int ffs_ep0_open(struct inode *inode, struct file *file)
527 struct ffs_data *ffs = inode->i_private;
531 if (unlikely(ffs->state == FFS_CLOSING))
534 file->private_data = ffs;
535 ffs_data_opened(ffs);
540 static int ffs_ep0_release(struct inode *inode, struct file *file)
542 struct ffs_data *ffs = file->private_data;
546 ffs_data_closed(ffs);
551 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
553 struct ffs_data *ffs = file->private_data;
554 struct usb_gadget *gadget = ffs->gadget;
559 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
560 struct ffs_function *func = ffs->func;
561 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
562 } else if (gadget && gadget->ops->ioctl) {
563 ret = gadget->ops->ioctl(gadget, code, value);
571 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
573 struct ffs_data *ffs = file->private_data;
574 unsigned int mask = POLLWRNORM;
577 poll_wait(file, &ffs->ev.waitq, wait);
579 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
580 if (unlikely(ret < 0))
583 switch (ffs->state) {
584 case FFS_READ_DESCRIPTORS:
585 case FFS_READ_STRINGS:
590 switch (ffs->setup_state) {
596 case FFS_SETUP_PENDING:
597 case FFS_SETUP_CANCELLED:
598 mask |= (POLLIN | POLLOUT);
605 mutex_unlock(&ffs->mutex);
610 static const struct file_operations ffs_ep0_operations = {
613 .open = ffs_ep0_open,
614 .write = ffs_ep0_write,
615 .read = ffs_ep0_read,
616 .release = ffs_ep0_release,
617 .unlocked_ioctl = ffs_ep0_ioctl,
618 .poll = ffs_ep0_poll,
622 /* "Normal" endpoints operations ********************************************/
624 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
627 if (likely(req->context)) {
628 struct ffs_ep *ep = _ep->driver_data;
629 ep->status = req->status ? req->status : req->actual;
630 complete(req->context);
634 static void ffs_user_copy_worker(struct work_struct *work)
636 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
638 int ret = io_data->req->status ? io_data->req->status :
639 io_data->req->actual;
641 if (io_data->read && ret > 0) {
645 for (i = 0; i < io_data->nr_segs; i++) {
646 if (unlikely(copy_to_user(io_data->iovec[i].iov_base,
648 io_data->iovec[i].iov_len))) {
652 pos += io_data->iovec[i].iov_len;
654 unuse_mm(io_data->mm);
657 aio_complete(io_data->kiocb, ret, ret);
659 usb_ep_free_request(io_data->ep, io_data->req);
661 io_data->kiocb->private = NULL;
663 kfree(io_data->iovec);
668 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
669 struct usb_request *req)
671 struct ffs_io_data *io_data = req->context;
675 INIT_WORK(&io_data->work, ffs_user_copy_worker);
676 schedule_work(&io_data->work);
679 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
681 struct ffs_epfile *epfile = file->private_data;
684 ssize_t ret, data_len;
687 /* Are we still active? */
688 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
693 /* Wait for endpoint to be enabled */
696 if (file->f_flags & O_NONBLOCK) {
701 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
709 halt = (!io_data->read == !epfile->in);
710 if (halt && epfile->isoc) {
715 /* Allocate & copy */
718 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
719 * before the waiting completes, so do not assign to 'gadget' earlier
721 struct usb_gadget *gadget = epfile->ffs->gadget;
723 spin_lock_irq(&epfile->ffs->eps_lock);
724 /* In the meantime, endpoint got disabled or changed. */
725 if (epfile->ep != ep) {
726 spin_unlock_irq(&epfile->ffs->eps_lock);
730 * Controller may require buffer size to be aligned to
731 * maxpacketsize of an out endpoint.
733 data_len = io_data->read ?
734 usb_ep_align_maybe(gadget, ep->ep, io_data->len) :
736 spin_unlock_irq(&epfile->ffs->eps_lock);
738 data = kmalloc(data_len, GFP_KERNEL);
741 if (io_data->aio && !io_data->read) {
744 for (i = 0; i < io_data->nr_segs; i++) {
745 if (unlikely(copy_from_user(&data[pos],
746 io_data->iovec[i].iov_base,
747 io_data->iovec[i].iov_len))) {
751 pos += io_data->iovec[i].iov_len;
754 if (!io_data->read &&
755 unlikely(__copy_from_user(data, io_data->buf,
763 /* We will be using request */
764 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
768 spin_lock_irq(&epfile->ffs->eps_lock);
770 if (epfile->ep != ep) {
771 /* In the meantime, endpoint got disabled or changed. */
773 spin_unlock_irq(&epfile->ffs->eps_lock);
776 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
777 usb_ep_set_halt(ep->ep);
778 spin_unlock_irq(&epfile->ffs->eps_lock);
781 /* Fire the request */
782 struct usb_request *req;
785 req = usb_ep_alloc_request(ep->ep, GFP_KERNEL);
790 req->length = io_data->len;
793 io_data->ep = ep->ep;
796 req->context = io_data;
797 req->complete = ffs_epfile_async_io_complete;
799 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
801 usb_ep_free_request(ep->ep, req);
806 spin_unlock_irq(&epfile->ffs->eps_lock);
808 DECLARE_COMPLETION_ONSTACK(done);
812 req->length = io_data->len;
814 req->context = &done;
815 req->complete = ffs_epfile_io_complete;
817 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
819 spin_unlock_irq(&epfile->ffs->eps_lock);
821 if (unlikely(ret < 0)) {
824 wait_for_completion_interruptible(&done))) {
826 usb_ep_dequeue(ep->ep, req);
829 * XXX We may end up silently droping data
830 * here. Since data_len (i.e. req->length) may
831 * be bigger than len (after being rounded up
832 * to maxpacketsize), we may end up with more
833 * data then user space has space for.
836 if (io_data->read && ret > 0) {
837 ret = min_t(size_t, ret, io_data->len);
839 if (unlikely(copy_to_user(io_data->buf,
848 mutex_unlock(&epfile->mutex);
852 spin_unlock_irq(&epfile->ffs->eps_lock);
853 mutex_unlock(&epfile->mutex);
860 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
863 struct ffs_io_data io_data;
868 io_data.read = false;
869 io_data.buf = (char * __user)buf;
872 return ffs_epfile_io(file, &io_data);
876 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
878 struct ffs_io_data io_data;
887 return ffs_epfile_io(file, &io_data);
891 ffs_epfile_open(struct inode *inode, struct file *file)
893 struct ffs_epfile *epfile = inode->i_private;
897 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
900 file->private_data = epfile;
901 ffs_data_opened(epfile->ffs);
906 static int ffs_aio_cancel(struct kiocb *kiocb)
908 struct ffs_io_data *io_data = kiocb->private;
909 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
914 spin_lock_irq(&epfile->ffs->eps_lock);
916 if (likely(io_data && io_data->ep && io_data->req))
917 value = usb_ep_dequeue(io_data->ep, io_data->req);
921 spin_unlock_irq(&epfile->ffs->eps_lock);
926 static ssize_t ffs_epfile_aio_write(struct kiocb *kiocb,
927 const struct iovec *iovec,
928 unsigned long nr_segs, loff_t loff)
930 struct ffs_io_data *io_data;
934 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
935 if (unlikely(!io_data))
939 io_data->read = false;
940 io_data->kiocb = kiocb;
941 io_data->iovec = iovec;
942 io_data->nr_segs = nr_segs;
943 io_data->len = kiocb->ki_nbytes;
944 io_data->mm = current->mm;
946 kiocb->private = io_data;
948 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
950 return ffs_epfile_io(kiocb->ki_filp, io_data);
953 static ssize_t ffs_epfile_aio_read(struct kiocb *kiocb,
954 const struct iovec *iovec,
955 unsigned long nr_segs, loff_t loff)
957 struct ffs_io_data *io_data;
958 struct iovec *iovec_copy;
962 iovec_copy = kmalloc_array(nr_segs, sizeof(*iovec_copy), GFP_KERNEL);
963 if (unlikely(!iovec_copy))
966 memcpy(iovec_copy, iovec, sizeof(struct iovec)*nr_segs);
968 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
969 if (unlikely(!io_data)) {
975 io_data->read = true;
976 io_data->kiocb = kiocb;
977 io_data->iovec = iovec_copy;
978 io_data->nr_segs = nr_segs;
979 io_data->len = kiocb->ki_nbytes;
980 io_data->mm = current->mm;
982 kiocb->private = io_data;
984 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
986 return ffs_epfile_io(kiocb->ki_filp, io_data);
990 ffs_epfile_release(struct inode *inode, struct file *file)
992 struct ffs_epfile *epfile = inode->i_private;
996 ffs_data_closed(epfile->ffs);
1001 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1002 unsigned long value)
1004 struct ffs_epfile *epfile = file->private_data;
1009 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1012 spin_lock_irq(&epfile->ffs->eps_lock);
1013 if (likely(epfile->ep)) {
1015 case FUNCTIONFS_FIFO_STATUS:
1016 ret = usb_ep_fifo_status(epfile->ep->ep);
1018 case FUNCTIONFS_FIFO_FLUSH:
1019 usb_ep_fifo_flush(epfile->ep->ep);
1022 case FUNCTIONFS_CLEAR_HALT:
1023 ret = usb_ep_clear_halt(epfile->ep->ep);
1025 case FUNCTIONFS_ENDPOINT_REVMAP:
1026 ret = epfile->ep->num;
1034 spin_unlock_irq(&epfile->ffs->eps_lock);
1039 static const struct file_operations ffs_epfile_operations = {
1040 .llseek = no_llseek,
1042 .open = ffs_epfile_open,
1043 .write = ffs_epfile_write,
1044 .read = ffs_epfile_read,
1045 .aio_write = ffs_epfile_aio_write,
1046 .aio_read = ffs_epfile_aio_read,
1047 .release = ffs_epfile_release,
1048 .unlocked_ioctl = ffs_epfile_ioctl,
1052 /* File system and super block operations ***********************************/
1055 * Mounting the file system creates a controller file, used first for
1056 * function configuration then later for event monitoring.
1059 static struct inode *__must_check
1060 ffs_sb_make_inode(struct super_block *sb, void *data,
1061 const struct file_operations *fops,
1062 const struct inode_operations *iops,
1063 struct ffs_file_perms *perms)
1065 struct inode *inode;
1069 inode = new_inode(sb);
1071 if (likely(inode)) {
1072 struct timespec current_time = CURRENT_TIME;
1074 inode->i_ino = get_next_ino();
1075 inode->i_mode = perms->mode;
1076 inode->i_uid = perms->uid;
1077 inode->i_gid = perms->gid;
1078 inode->i_atime = current_time;
1079 inode->i_mtime = current_time;
1080 inode->i_ctime = current_time;
1081 inode->i_private = data;
1083 inode->i_fop = fops;
1091 /* Create "regular" file */
1092 static struct inode *ffs_sb_create_file(struct super_block *sb,
1093 const char *name, void *data,
1094 const struct file_operations *fops,
1095 struct dentry **dentry_p)
1097 struct ffs_data *ffs = sb->s_fs_info;
1098 struct dentry *dentry;
1099 struct inode *inode;
1103 dentry = d_alloc_name(sb->s_root, name);
1104 if (unlikely(!dentry))
1107 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1108 if (unlikely(!inode)) {
1113 d_add(dentry, inode);
1121 static const struct super_operations ffs_sb_operations = {
1122 .statfs = simple_statfs,
1123 .drop_inode = generic_delete_inode,
1126 struct ffs_sb_fill_data {
1127 struct ffs_file_perms perms;
1129 const char *dev_name;
1130 struct ffs_data *ffs_data;
1133 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1135 struct ffs_sb_fill_data *data = _data;
1136 struct inode *inode;
1137 struct ffs_data *ffs = data->ffs_data;
1142 data->ffs_data = NULL;
1143 sb->s_fs_info = ffs;
1144 sb->s_blocksize = PAGE_CACHE_SIZE;
1145 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1146 sb->s_magic = FUNCTIONFS_MAGIC;
1147 sb->s_op = &ffs_sb_operations;
1148 sb->s_time_gran = 1;
1151 data->perms.mode = data->root_mode;
1152 inode = ffs_sb_make_inode(sb, NULL,
1153 &simple_dir_operations,
1154 &simple_dir_inode_operations,
1156 sb->s_root = d_make_root(inode);
1157 if (unlikely(!sb->s_root))
1161 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1162 &ffs_ep0_operations, NULL)))
1168 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1172 if (!opts || !*opts)
1176 unsigned long value;
1180 comma = strchr(opts, ',');
1185 eq = strchr(opts, '=');
1186 if (unlikely(!eq)) {
1187 pr_err("'=' missing in %s\n", opts);
1193 if (kstrtoul(eq + 1, 0, &value)) {
1194 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1198 /* Interpret option */
1199 switch (eq - opts) {
1201 if (!memcmp(opts, "rmode", 5))
1202 data->root_mode = (value & 0555) | S_IFDIR;
1203 else if (!memcmp(opts, "fmode", 5))
1204 data->perms.mode = (value & 0666) | S_IFREG;
1210 if (!memcmp(opts, "mode", 4)) {
1211 data->root_mode = (value & 0555) | S_IFDIR;
1212 data->perms.mode = (value & 0666) | S_IFREG;
1219 if (!memcmp(opts, "uid", 3)) {
1220 data->perms.uid = make_kuid(current_user_ns(), value);
1221 if (!uid_valid(data->perms.uid)) {
1222 pr_err("%s: unmapped value: %lu\n", opts, value);
1225 } else if (!memcmp(opts, "gid", 3)) {
1226 data->perms.gid = make_kgid(current_user_ns(), value);
1227 if (!gid_valid(data->perms.gid)) {
1228 pr_err("%s: unmapped value: %lu\n", opts, value);
1238 pr_err("%s: invalid option\n", opts);
1242 /* Next iteration */
1251 /* "mount -t functionfs dev_name /dev/function" ends up here */
1253 static struct dentry *
1254 ffs_fs_mount(struct file_system_type *t, int flags,
1255 const char *dev_name, void *opts)
1257 struct ffs_sb_fill_data data = {
1259 .mode = S_IFREG | 0600,
1260 .uid = GLOBAL_ROOT_UID,
1261 .gid = GLOBAL_ROOT_GID,
1263 .root_mode = S_IFDIR | 0500,
1268 struct ffs_data *ffs;
1272 ret = ffs_fs_parse_opts(&data, opts);
1273 if (unlikely(ret < 0))
1274 return ERR_PTR(ret);
1276 ffs = ffs_data_new();
1278 return ERR_PTR(-ENOMEM);
1279 ffs->file_perms = data.perms;
1281 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1282 if (unlikely(!ffs->dev_name)) {
1284 return ERR_PTR(-ENOMEM);
1287 ffs_dev = ffs_acquire_dev(dev_name);
1288 if (IS_ERR(ffs_dev)) {
1290 return ERR_CAST(ffs_dev);
1292 ffs->private_data = ffs_dev;
1293 data.ffs_data = ffs;
1295 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1296 if (IS_ERR(rv) && data.ffs_data) {
1297 ffs_release_dev(data.ffs_data);
1298 ffs_data_put(data.ffs_data);
1304 ffs_fs_kill_sb(struct super_block *sb)
1308 kill_litter_super(sb);
1309 if (sb->s_fs_info) {
1310 ffs_release_dev(sb->s_fs_info);
1311 ffs_data_put(sb->s_fs_info);
1315 static struct file_system_type ffs_fs_type = {
1316 .owner = THIS_MODULE,
1317 .name = "functionfs",
1318 .mount = ffs_fs_mount,
1319 .kill_sb = ffs_fs_kill_sb,
1321 MODULE_ALIAS_FS("functionfs");
1324 /* Driver's main init/cleanup functions *************************************/
1326 static int functionfs_init(void)
1332 ret = register_filesystem(&ffs_fs_type);
1334 pr_info("file system registered\n");
1336 pr_err("failed registering file system (%d)\n", ret);
1341 static void functionfs_cleanup(void)
1345 pr_info("unloading\n");
1346 unregister_filesystem(&ffs_fs_type);
1350 /* ffs_data and ffs_function construction and destruction code **************/
1352 static void ffs_data_clear(struct ffs_data *ffs);
1353 static void ffs_data_reset(struct ffs_data *ffs);
1355 static void ffs_data_get(struct ffs_data *ffs)
1359 atomic_inc(&ffs->ref);
1362 static void ffs_data_opened(struct ffs_data *ffs)
1366 atomic_inc(&ffs->ref);
1367 atomic_inc(&ffs->opened);
1370 static void ffs_data_put(struct ffs_data *ffs)
1374 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1375 pr_info("%s(): freeing\n", __func__);
1376 ffs_data_clear(ffs);
1377 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1378 waitqueue_active(&ffs->ep0req_completion.wait));
1379 kfree(ffs->dev_name);
1384 static void ffs_data_closed(struct ffs_data *ffs)
1388 if (atomic_dec_and_test(&ffs->opened)) {
1389 ffs->state = FFS_CLOSING;
1390 ffs_data_reset(ffs);
1396 static struct ffs_data *ffs_data_new(void)
1398 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1404 atomic_set(&ffs->ref, 1);
1405 atomic_set(&ffs->opened, 0);
1406 ffs->state = FFS_READ_DESCRIPTORS;
1407 mutex_init(&ffs->mutex);
1408 spin_lock_init(&ffs->eps_lock);
1409 init_waitqueue_head(&ffs->ev.waitq);
1410 init_completion(&ffs->ep0req_completion);
1412 /* XXX REVISIT need to update it in some places, or do we? */
1413 ffs->ev.can_stall = 1;
1418 static void ffs_data_clear(struct ffs_data *ffs)
1422 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1425 BUG_ON(ffs->gadget);
1428 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1430 kfree(ffs->raw_descs_data);
1431 kfree(ffs->raw_strings);
1432 kfree(ffs->stringtabs);
1435 static void ffs_data_reset(struct ffs_data *ffs)
1439 ffs_data_clear(ffs);
1441 ffs->epfiles = NULL;
1442 ffs->raw_descs_data = NULL;
1443 ffs->raw_descs = NULL;
1444 ffs->raw_strings = NULL;
1445 ffs->stringtabs = NULL;
1447 ffs->raw_descs_length = 0;
1448 ffs->fs_descs_count = 0;
1449 ffs->hs_descs_count = 0;
1450 ffs->ss_descs_count = 0;
1452 ffs->strings_count = 0;
1453 ffs->interfaces_count = 0;
1458 ffs->state = FFS_READ_DESCRIPTORS;
1459 ffs->setup_state = FFS_NO_SETUP;
1464 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1466 struct usb_gadget_strings **lang;
1471 if (WARN_ON(ffs->state != FFS_ACTIVE
1472 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1475 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1476 if (unlikely(first_id < 0))
1479 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1480 if (unlikely(!ffs->ep0req))
1482 ffs->ep0req->complete = ffs_ep0_complete;
1483 ffs->ep0req->context = ffs;
1485 lang = ffs->stringtabs;
1486 for (lang = ffs->stringtabs; *lang; ++lang) {
1487 struct usb_string *str = (*lang)->strings;
1489 for (; str->s; ++id, ++str)
1493 ffs->gadget = cdev->gadget;
1498 static void functionfs_unbind(struct ffs_data *ffs)
1502 if (!WARN_ON(!ffs->gadget)) {
1503 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1506 clear_bit(FFS_FL_BOUND, &ffs->flags);
1511 static int ffs_epfiles_create(struct ffs_data *ffs)
1513 struct ffs_epfile *epfile, *epfiles;
1518 count = ffs->eps_count;
1519 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1524 for (i = 1; i <= count; ++i, ++epfile) {
1526 mutex_init(&epfile->mutex);
1527 init_waitqueue_head(&epfile->wait);
1528 sprintf(epfiles->name, "ep%u", i);
1529 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1530 &ffs_epfile_operations,
1531 &epfile->dentry))) {
1532 ffs_epfiles_destroy(epfiles, i - 1);
1537 ffs->epfiles = epfiles;
1541 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1543 struct ffs_epfile *epfile = epfiles;
1547 for (; count; --count, ++epfile) {
1548 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1549 waitqueue_active(&epfile->wait));
1550 if (epfile->dentry) {
1551 d_delete(epfile->dentry);
1552 dput(epfile->dentry);
1553 epfile->dentry = NULL;
1561 static void ffs_func_eps_disable(struct ffs_function *func)
1563 struct ffs_ep *ep = func->eps;
1564 struct ffs_epfile *epfile = func->ffs->epfiles;
1565 unsigned count = func->ffs->eps_count;
1566 unsigned long flags;
1568 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1570 /* pending requests get nuked */
1572 usb_ep_disable(ep->ep);
1578 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1581 static int ffs_func_eps_enable(struct ffs_function *func)
1583 struct ffs_data *ffs = func->ffs;
1584 struct ffs_ep *ep = func->eps;
1585 struct ffs_epfile *epfile = ffs->epfiles;
1586 unsigned count = ffs->eps_count;
1587 unsigned long flags;
1590 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1592 struct usb_endpoint_descriptor *ds;
1595 if (ffs->gadget->speed == USB_SPEED_SUPER)
1597 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1602 /* fall-back to lower speed if desc missing for current speed */
1604 ds = ep->descs[desc_idx];
1605 } while (!ds && --desc_idx >= 0);
1612 ep->ep->driver_data = ep;
1614 ret = usb_ep_enable(ep->ep);
1617 epfile->in = usb_endpoint_dir_in(ds);
1618 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1623 wake_up(&epfile->wait);
1628 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1634 /* Parsing and building descriptors and strings *****************************/
1637 * This validates if data pointed by data is a valid USB descriptor as
1638 * well as record how many interfaces, endpoints and strings are
1639 * required by given configuration. Returns address after the
1640 * descriptor or NULL if data is invalid.
1643 enum ffs_entity_type {
1644 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1647 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1649 struct usb_descriptor_header *desc,
1652 static int __must_check ffs_do_desc(char *data, unsigned len,
1653 ffs_entity_callback entity, void *priv)
1655 struct usb_descriptor_header *_ds = (void *)data;
1661 /* At least two bytes are required: length and type */
1663 pr_vdebug("descriptor too short\n");
1667 /* If we have at least as many bytes as the descriptor takes? */
1668 length = _ds->bLength;
1670 pr_vdebug("descriptor longer then available data\n");
1674 #define __entity_check_INTERFACE(val) 1
1675 #define __entity_check_STRING(val) (val)
1676 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1677 #define __entity(type, val) do { \
1678 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1679 if (unlikely(!__entity_check_ ##type(val))) { \
1680 pr_vdebug("invalid entity's value\n"); \
1683 ret = entity(FFS_ ##type, &val, _ds, priv); \
1684 if (unlikely(ret < 0)) { \
1685 pr_debug("entity " #type "(%02x); ret = %d\n", \
1691 /* Parse descriptor depending on type. */
1692 switch (_ds->bDescriptorType) {
1696 case USB_DT_DEVICE_QUALIFIER:
1697 /* function can't have any of those */
1698 pr_vdebug("descriptor reserved for gadget: %d\n",
1699 _ds->bDescriptorType);
1702 case USB_DT_INTERFACE: {
1703 struct usb_interface_descriptor *ds = (void *)_ds;
1704 pr_vdebug("interface descriptor\n");
1705 if (length != sizeof *ds)
1708 __entity(INTERFACE, ds->bInterfaceNumber);
1710 __entity(STRING, ds->iInterface);
1714 case USB_DT_ENDPOINT: {
1715 struct usb_endpoint_descriptor *ds = (void *)_ds;
1716 pr_vdebug("endpoint descriptor\n");
1717 if (length != USB_DT_ENDPOINT_SIZE &&
1718 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1720 __entity(ENDPOINT, ds->bEndpointAddress);
1725 pr_vdebug("hid descriptor\n");
1726 if (length != sizeof(struct hid_descriptor))
1731 if (length != sizeof(struct usb_otg_descriptor))
1735 case USB_DT_INTERFACE_ASSOCIATION: {
1736 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1737 pr_vdebug("interface association descriptor\n");
1738 if (length != sizeof *ds)
1741 __entity(STRING, ds->iFunction);
1745 case USB_DT_SS_ENDPOINT_COMP:
1746 pr_vdebug("EP SS companion descriptor\n");
1747 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1751 case USB_DT_OTHER_SPEED_CONFIG:
1752 case USB_DT_INTERFACE_POWER:
1754 case USB_DT_SECURITY:
1755 case USB_DT_CS_RADIO_CONTROL:
1757 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1761 /* We should never be here */
1762 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1766 pr_vdebug("invalid length: %d (descriptor %d)\n",
1767 _ds->bLength, _ds->bDescriptorType);
1772 #undef __entity_check_DESCRIPTOR
1773 #undef __entity_check_INTERFACE
1774 #undef __entity_check_STRING
1775 #undef __entity_check_ENDPOINT
1780 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1781 ffs_entity_callback entity, void *priv)
1783 const unsigned _len = len;
1784 unsigned long num = 0;
1794 /* Record "descriptor" entity */
1795 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1796 if (unlikely(ret < 0)) {
1797 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1805 ret = ffs_do_desc(data, len, entity, priv);
1806 if (unlikely(ret < 0)) {
1807 pr_debug("%s returns %d\n", __func__, ret);
1817 static int __ffs_data_do_entity(enum ffs_entity_type type,
1818 u8 *valuep, struct usb_descriptor_header *desc,
1821 struct ffs_data *ffs = priv;
1826 case FFS_DESCRIPTOR:
1831 * Interfaces are indexed from zero so if we
1832 * encountered interface "n" then there are at least
1835 if (*valuep >= ffs->interfaces_count)
1836 ffs->interfaces_count = *valuep + 1;
1841 * Strings are indexed from 1 (0 is magic ;) reserved
1842 * for languages list or some such)
1844 if (*valuep > ffs->strings_count)
1845 ffs->strings_count = *valuep;
1849 /* Endpoints are indexed from 1 as well. */
1850 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1851 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1858 static int __ffs_data_got_descs(struct ffs_data *ffs,
1859 char *const _data, size_t len)
1861 char *data = _data, *raw_descs;
1862 unsigned counts[3], flags;
1863 int ret = -EINVAL, i;
1867 if (get_unaligned_le32(data + 4) != len)
1870 switch (get_unaligned_le32(data)) {
1871 case FUNCTIONFS_DESCRIPTORS_MAGIC:
1872 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
1876 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
1877 flags = get_unaligned_le32(data + 8);
1878 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
1879 FUNCTIONFS_HAS_HS_DESC |
1880 FUNCTIONFS_HAS_SS_DESC)) {
1891 /* Read fs_count, hs_count and ss_count (if present) */
1892 for (i = 0; i < 3; ++i) {
1893 if (!(flags & (1 << i))) {
1895 } else if (len < 4) {
1898 counts[i] = get_unaligned_le32(data);
1904 /* Read descriptors */
1906 for (i = 0; i < 3; ++i) {
1909 ret = ffs_do_descs(counts[i], data, len,
1910 __ffs_data_do_entity, ffs);
1917 if (raw_descs == data || len) {
1922 ffs->raw_descs_data = _data;
1923 ffs->raw_descs = raw_descs;
1924 ffs->raw_descs_length = data - raw_descs;
1925 ffs->fs_descs_count = counts[0];
1926 ffs->hs_descs_count = counts[1];
1927 ffs->ss_descs_count = counts[2];
1936 static int __ffs_data_got_strings(struct ffs_data *ffs,
1937 char *const _data, size_t len)
1939 u32 str_count, needed_count, lang_count;
1940 struct usb_gadget_strings **stringtabs, *t;
1941 struct usb_string *strings, *s;
1942 const char *data = _data;
1946 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1947 get_unaligned_le32(data + 4) != len))
1949 str_count = get_unaligned_le32(data + 8);
1950 lang_count = get_unaligned_le32(data + 12);
1952 /* if one is zero the other must be zero */
1953 if (unlikely(!str_count != !lang_count))
1956 /* Do we have at least as many strings as descriptors need? */
1957 needed_count = ffs->strings_count;
1958 if (unlikely(str_count < needed_count))
1962 * If we don't need any strings just return and free all
1965 if (!needed_count) {
1970 /* Allocate everything in one chunk so there's less maintenance. */
1974 vla_item(d, struct usb_gadget_strings *, stringtabs,
1976 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
1977 vla_item(d, struct usb_string, strings,
1978 lang_count*(needed_count+1));
1980 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
1982 if (unlikely(!vlabuf)) {
1987 /* Initialize the VLA pointers */
1988 stringtabs = vla_ptr(vlabuf, d, stringtabs);
1989 t = vla_ptr(vlabuf, d, stringtab);
1992 *stringtabs++ = t++;
1996 /* stringtabs = vlabuf = d_stringtabs for later kfree */
1997 stringtabs = vla_ptr(vlabuf, d, stringtabs);
1998 t = vla_ptr(vlabuf, d, stringtab);
1999 s = vla_ptr(vlabuf, d, strings);
2003 /* For each language */
2007 do { /* lang_count > 0 so we can use do-while */
2008 unsigned needed = needed_count;
2010 if (unlikely(len < 3))
2012 t->language = get_unaligned_le16(data);
2019 /* For each string */
2020 do { /* str_count > 0 so we can use do-while */
2021 size_t length = strnlen(data, len);
2023 if (unlikely(length == len))
2027 * User may provide more strings then we need,
2028 * if that's the case we simply ignore the
2031 if (likely(needed)) {
2033 * s->id will be set while adding
2034 * function to configuration so for
2035 * now just leave garbage here.
2044 } while (--str_count);
2046 s->id = 0; /* terminator */
2050 } while (--lang_count);
2052 /* Some garbage left? */
2057 ffs->stringtabs = stringtabs;
2058 ffs->raw_strings = _data;
2070 /* Events handling and management *******************************************/
2072 static void __ffs_event_add(struct ffs_data *ffs,
2073 enum usb_functionfs_event_type type)
2075 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2079 * Abort any unhandled setup
2081 * We do not need to worry about some cmpxchg() changing value
2082 * of ffs->setup_state without holding the lock because when
2083 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2084 * the source does nothing.
2086 if (ffs->setup_state == FFS_SETUP_PENDING)
2087 ffs->setup_state = FFS_SETUP_CANCELLED;
2090 case FUNCTIONFS_RESUME:
2091 rem_type2 = FUNCTIONFS_SUSPEND;
2093 case FUNCTIONFS_SUSPEND:
2094 case FUNCTIONFS_SETUP:
2096 /* Discard all similar events */
2099 case FUNCTIONFS_BIND:
2100 case FUNCTIONFS_UNBIND:
2101 case FUNCTIONFS_DISABLE:
2102 case FUNCTIONFS_ENABLE:
2103 /* Discard everything other then power management. */
2104 rem_type1 = FUNCTIONFS_SUSPEND;
2105 rem_type2 = FUNCTIONFS_RESUME;
2114 u8 *ev = ffs->ev.types, *out = ev;
2115 unsigned n = ffs->ev.count;
2116 for (; n; --n, ++ev)
2117 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2120 pr_vdebug("purging event %d\n", *ev);
2121 ffs->ev.count = out - ffs->ev.types;
2124 pr_vdebug("adding event %d\n", type);
2125 ffs->ev.types[ffs->ev.count++] = type;
2126 wake_up_locked(&ffs->ev.waitq);
2129 static void ffs_event_add(struct ffs_data *ffs,
2130 enum usb_functionfs_event_type type)
2132 unsigned long flags;
2133 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2134 __ffs_event_add(ffs, type);
2135 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2139 /* Bind/unbind USB function hooks *******************************************/
2141 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2142 struct usb_descriptor_header *desc,
2145 struct usb_endpoint_descriptor *ds = (void *)desc;
2146 struct ffs_function *func = priv;
2147 struct ffs_ep *ffs_ep;
2148 unsigned ep_desc_id, idx;
2149 static const char *speed_names[] = { "full", "high", "super" };
2151 if (type != FFS_DESCRIPTOR)
2155 * If ss_descriptors is not NULL, we are reading super speed
2156 * descriptors; if hs_descriptors is not NULL, we are reading high
2157 * speed descriptors; otherwise, we are reading full speed
2160 if (func->function.ss_descriptors) {
2162 func->function.ss_descriptors[(long)valuep] = desc;
2163 } else if (func->function.hs_descriptors) {
2165 func->function.hs_descriptors[(long)valuep] = desc;
2168 func->function.fs_descriptors[(long)valuep] = desc;
2171 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2174 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2175 ffs_ep = func->eps + idx;
2177 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2178 pr_err("two %sspeed descriptors for EP %d\n",
2179 speed_names[ep_desc_id],
2180 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2183 ffs_ep->descs[ep_desc_id] = ds;
2185 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2187 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2188 if (!ds->wMaxPacketSize)
2189 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2191 struct usb_request *req;
2194 pr_vdebug("autoconfig\n");
2195 ep = usb_ep_autoconfig(func->gadget, ds);
2198 ep->driver_data = func->eps + idx;
2200 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2206 func->eps_revmap[ds->bEndpointAddress &
2207 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2209 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2214 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2215 struct usb_descriptor_header *desc,
2218 struct ffs_function *func = priv;
2224 case FFS_DESCRIPTOR:
2225 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2230 if (func->interfaces_nums[idx] < 0) {
2231 int id = usb_interface_id(func->conf, &func->function);
2232 if (unlikely(id < 0))
2234 func->interfaces_nums[idx] = id;
2236 newValue = func->interfaces_nums[idx];
2240 /* String' IDs are allocated when fsf_data is bound to cdev */
2241 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2246 * USB_DT_ENDPOINT are handled in
2247 * __ffs_func_bind_do_descs().
2249 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2252 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2253 if (unlikely(!func->eps[idx].ep))
2257 struct usb_endpoint_descriptor **descs;
2258 descs = func->eps[idx].descs;
2259 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2264 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2269 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2270 struct usb_configuration *c)
2272 struct ffs_function *func = ffs_func_from_usb(f);
2273 struct f_fs_opts *ffs_opts =
2274 container_of(f->fi, struct f_fs_opts, func_inst);
2280 * Legacy gadget triggers binding in functionfs_ready_callback,
2281 * which already uses locking; taking the same lock here would
2284 * Configfs-enabled gadgets however do need ffs_dev_lock.
2286 if (!ffs_opts->no_configfs)
2288 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2289 func->ffs = ffs_opts->dev->ffs_data;
2290 if (!ffs_opts->no_configfs)
2293 return ERR_PTR(ret);
2296 func->gadget = c->cdev->gadget;
2298 ffs_data_get(func->ffs);
2301 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2302 * configurations are bound in sequence with list_for_each_entry,
2303 * in each configuration its functions are bound in sequence
2304 * with list_for_each_entry, so we assume no race condition
2305 * with regard to ffs_opts->bound access
2307 if (!ffs_opts->refcnt) {
2308 ret = functionfs_bind(func->ffs, c->cdev);
2310 return ERR_PTR(ret);
2313 func->function.strings = func->ffs->stringtabs;
2318 static int _ffs_func_bind(struct usb_configuration *c,
2319 struct usb_function *f)
2321 struct ffs_function *func = ffs_func_from_usb(f);
2322 struct ffs_data *ffs = func->ffs;
2324 const int full = !!func->ffs->fs_descs_count;
2325 const int high = gadget_is_dualspeed(func->gadget) &&
2326 func->ffs->hs_descs_count;
2327 const int super = gadget_is_superspeed(func->gadget) &&
2328 func->ffs->ss_descs_count;
2330 int fs_len, hs_len, ret;
2332 /* Make it a single chunk, less management later on */
2334 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2335 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2336 full ? ffs->fs_descs_count + 1 : 0);
2337 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2338 high ? ffs->hs_descs_count + 1 : 0);
2339 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2340 super ? ffs->ss_descs_count + 1 : 0);
2341 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2342 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2347 /* Has descriptors only for speeds gadget does not support */
2348 if (unlikely(!(full | high | super)))
2351 /* Allocate a single chunk, less management later on */
2352 vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2353 if (unlikely(!vlabuf))
2357 memset(vla_ptr(vlabuf, d, eps), 0, d_eps__sz);
2358 /* Copy descriptors */
2359 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2360 ffs->raw_descs_length);
2362 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2363 for (ret = ffs->eps_count; ret; --ret) {
2366 ptr = vla_ptr(vlabuf, d, eps);
2371 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2373 func->eps = vla_ptr(vlabuf, d, eps);
2374 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2377 * Go through all the endpoint descriptors and allocate
2378 * endpoints first, so that later we can rewrite the endpoint
2379 * numbers without worrying that it may be described later on.
2382 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2383 fs_len = ffs_do_descs(ffs->fs_descs_count,
2384 vla_ptr(vlabuf, d, raw_descs),
2386 __ffs_func_bind_do_descs, func);
2387 if (unlikely(fs_len < 0)) {
2396 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2397 hs_len = ffs_do_descs(ffs->hs_descs_count,
2398 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2399 d_raw_descs__sz - fs_len,
2400 __ffs_func_bind_do_descs, func);
2401 if (unlikely(hs_len < 0)) {
2409 if (likely(super)) {
2410 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2411 ret = ffs_do_descs(ffs->ss_descs_count,
2412 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2413 d_raw_descs__sz - fs_len - hs_len,
2414 __ffs_func_bind_do_descs, func);
2415 if (unlikely(ret < 0))
2420 * Now handle interface numbers allocation and interface and
2421 * endpoint numbers rewriting. We can do that in one go
2424 ret = ffs_do_descs(ffs->fs_descs_count +
2425 (high ? ffs->hs_descs_count : 0) +
2426 (super ? ffs->ss_descs_count : 0),
2427 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2428 __ffs_func_bind_do_nums, func);
2429 if (unlikely(ret < 0))
2432 /* And we're done */
2433 ffs_event_add(ffs, FUNCTIONFS_BIND);
2437 /* XXX Do we need to release all claimed endpoints here? */
2441 static int ffs_func_bind(struct usb_configuration *c,
2442 struct usb_function *f)
2444 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2446 if (IS_ERR(ffs_opts))
2447 return PTR_ERR(ffs_opts);
2449 return _ffs_func_bind(c, f);
2453 /* Other USB function hooks *************************************************/
2455 static int ffs_func_set_alt(struct usb_function *f,
2456 unsigned interface, unsigned alt)
2458 struct ffs_function *func = ffs_func_from_usb(f);
2459 struct ffs_data *ffs = func->ffs;
2462 if (alt != (unsigned)-1) {
2463 intf = ffs_func_revmap_intf(func, interface);
2464 if (unlikely(intf < 0))
2469 ffs_func_eps_disable(ffs->func);
2471 if (ffs->state != FFS_ACTIVE)
2474 if (alt == (unsigned)-1) {
2476 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2481 ret = ffs_func_eps_enable(func);
2482 if (likely(ret >= 0))
2483 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2487 static void ffs_func_disable(struct usb_function *f)
2489 ffs_func_set_alt(f, 0, (unsigned)-1);
2492 static int ffs_func_setup(struct usb_function *f,
2493 const struct usb_ctrlrequest *creq)
2495 struct ffs_function *func = ffs_func_from_usb(f);
2496 struct ffs_data *ffs = func->ffs;
2497 unsigned long flags;
2502 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2503 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2504 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2505 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2506 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2509 * Most requests directed to interface go through here
2510 * (notable exceptions are set/get interface) so we need to
2511 * handle them. All other either handled by composite or
2512 * passed to usb_configuration->setup() (if one is set). No
2513 * matter, we will handle requests directed to endpoint here
2514 * as well (as it's straightforward) but what to do with any
2517 if (ffs->state != FFS_ACTIVE)
2520 switch (creq->bRequestType & USB_RECIP_MASK) {
2521 case USB_RECIP_INTERFACE:
2522 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2523 if (unlikely(ret < 0))
2527 case USB_RECIP_ENDPOINT:
2528 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2529 if (unlikely(ret < 0))
2537 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2538 ffs->ev.setup = *creq;
2539 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2540 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2541 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2546 static void ffs_func_suspend(struct usb_function *f)
2549 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2552 static void ffs_func_resume(struct usb_function *f)
2555 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2559 /* Endpoint and interface numbers reverse mapping ***************************/
2561 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2563 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2564 return num ? num : -EDOM;
2567 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2569 short *nums = func->interfaces_nums;
2570 unsigned count = func->ffs->interfaces_count;
2572 for (; count; --count, ++nums) {
2573 if (*nums >= 0 && *nums == intf)
2574 return nums - func->interfaces_nums;
2581 /* Devices management *******************************************************/
2583 static LIST_HEAD(ffs_devices);
2585 static struct ffs_dev *_ffs_do_find_dev(const char *name)
2587 struct ffs_dev *dev;
2589 list_for_each_entry(dev, &ffs_devices, entry) {
2590 if (!dev->name || !name)
2592 if (strcmp(dev->name, name) == 0)
2600 * ffs_lock must be taken by the caller of this function
2602 static struct ffs_dev *_ffs_get_single_dev(void)
2604 struct ffs_dev *dev;
2606 if (list_is_singular(&ffs_devices)) {
2607 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
2616 * ffs_lock must be taken by the caller of this function
2618 static struct ffs_dev *_ffs_find_dev(const char *name)
2620 struct ffs_dev *dev;
2622 dev = _ffs_get_single_dev();
2626 return _ffs_do_find_dev(name);
2629 /* Configfs support *********************************************************/
2631 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
2633 return container_of(to_config_group(item), struct f_fs_opts,
2637 static void ffs_attr_release(struct config_item *item)
2639 struct f_fs_opts *opts = to_ffs_opts(item);
2641 usb_put_function_instance(&opts->func_inst);
2644 static struct configfs_item_operations ffs_item_ops = {
2645 .release = ffs_attr_release,
2648 static struct config_item_type ffs_func_type = {
2649 .ct_item_ops = &ffs_item_ops,
2650 .ct_owner = THIS_MODULE,
2654 /* Function registration interface ******************************************/
2656 static void ffs_free_inst(struct usb_function_instance *f)
2658 struct f_fs_opts *opts;
2660 opts = to_f_fs_opts(f);
2662 _ffs_free_dev(opts->dev);
2667 #define MAX_INST_NAME_LEN 40
2669 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
2671 struct f_fs_opts *opts;
2676 name_len = strlen(name) + 1;
2677 if (name_len > MAX_INST_NAME_LEN)
2678 return -ENAMETOOLONG;
2680 ptr = kstrndup(name, name_len, GFP_KERNEL);
2684 opts = to_f_fs_opts(fi);
2689 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
2690 ret = _ffs_name_dev(opts->dev, ptr);
2696 opts->dev->name_allocated = true;
2705 static struct usb_function_instance *ffs_alloc_inst(void)
2707 struct f_fs_opts *opts;
2708 struct ffs_dev *dev;
2710 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2712 return ERR_PTR(-ENOMEM);
2714 opts->func_inst.set_inst_name = ffs_set_inst_name;
2715 opts->func_inst.free_func_inst = ffs_free_inst;
2717 dev = _ffs_alloc_dev();
2721 return ERR_CAST(dev);
2726 config_group_init_type_name(&opts->func_inst.group, "",
2728 return &opts->func_inst;
2731 static void ffs_free(struct usb_function *f)
2733 kfree(ffs_func_from_usb(f));
2736 static void ffs_func_unbind(struct usb_configuration *c,
2737 struct usb_function *f)
2739 struct ffs_function *func = ffs_func_from_usb(f);
2740 struct ffs_data *ffs = func->ffs;
2741 struct f_fs_opts *opts =
2742 container_of(f->fi, struct f_fs_opts, func_inst);
2743 struct ffs_ep *ep = func->eps;
2744 unsigned count = ffs->eps_count;
2745 unsigned long flags;
2748 if (ffs->func == func) {
2749 ffs_func_eps_disable(func);
2753 if (!--opts->refcnt)
2754 functionfs_unbind(ffs);
2756 /* cleanup after autoconfig */
2757 spin_lock_irqsave(&func->ffs->eps_lock, flags);
2759 if (ep->ep && ep->req)
2760 usb_ep_free_request(ep->ep, ep->req);
2764 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2768 * eps, descriptors and interfaces_nums are allocated in the
2769 * same chunk so only one free is required.
2771 func->function.fs_descriptors = NULL;
2772 func->function.hs_descriptors = NULL;
2773 func->function.ss_descriptors = NULL;
2774 func->interfaces_nums = NULL;
2776 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2779 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
2781 struct ffs_function *func;
2785 func = kzalloc(sizeof(*func), GFP_KERNEL);
2786 if (unlikely(!func))
2787 return ERR_PTR(-ENOMEM);
2789 func->function.name = "Function FS Gadget";
2791 func->function.bind = ffs_func_bind;
2792 func->function.unbind = ffs_func_unbind;
2793 func->function.set_alt = ffs_func_set_alt;
2794 func->function.disable = ffs_func_disable;
2795 func->function.setup = ffs_func_setup;
2796 func->function.suspend = ffs_func_suspend;
2797 func->function.resume = ffs_func_resume;
2798 func->function.free_func = ffs_free;
2800 return &func->function;
2804 * ffs_lock must be taken by the caller of this function
2806 static struct ffs_dev *_ffs_alloc_dev(void)
2808 struct ffs_dev *dev;
2811 if (_ffs_get_single_dev())
2812 return ERR_PTR(-EBUSY);
2814 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2816 return ERR_PTR(-ENOMEM);
2818 if (list_empty(&ffs_devices)) {
2819 ret = functionfs_init();
2822 return ERR_PTR(ret);
2826 list_add(&dev->entry, &ffs_devices);
2832 * ffs_lock must be taken by the caller of this function
2833 * The caller is responsible for "name" being available whenever f_fs needs it
2835 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
2837 struct ffs_dev *existing;
2839 existing = _ffs_do_find_dev(name);
2849 * The caller is responsible for "name" being available whenever f_fs needs it
2851 int ffs_name_dev(struct ffs_dev *dev, const char *name)
2856 ret = _ffs_name_dev(dev, name);
2861 EXPORT_SYMBOL_GPL(ffs_name_dev);
2863 int ffs_single_dev(struct ffs_dev *dev)
2870 if (!list_is_singular(&ffs_devices))
2878 EXPORT_SYMBOL_GPL(ffs_single_dev);
2881 * ffs_lock must be taken by the caller of this function
2883 static void _ffs_free_dev(struct ffs_dev *dev)
2885 list_del(&dev->entry);
2886 if (dev->name_allocated)
2889 if (list_empty(&ffs_devices))
2890 functionfs_cleanup();
2893 static void *ffs_acquire_dev(const char *dev_name)
2895 struct ffs_dev *ffs_dev;
2900 ffs_dev = _ffs_find_dev(dev_name);
2902 ffs_dev = ERR_PTR(-ENODEV);
2903 else if (ffs_dev->mounted)
2904 ffs_dev = ERR_PTR(-EBUSY);
2905 else if (ffs_dev->ffs_acquire_dev_callback &&
2906 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
2907 ffs_dev = ERR_PTR(-ENODEV);
2909 ffs_dev->mounted = true;
2915 static void ffs_release_dev(struct ffs_data *ffs_data)
2917 struct ffs_dev *ffs_dev;
2922 ffs_dev = ffs_data->private_data;
2924 ffs_dev->mounted = false;
2926 if (ffs_dev->ffs_release_dev_callback)
2927 ffs_dev->ffs_release_dev_callback(ffs_dev);
2933 static int ffs_ready(struct ffs_data *ffs)
2935 struct ffs_dev *ffs_obj;
2941 ffs_obj = ffs->private_data;
2946 if (WARN_ON(ffs_obj->desc_ready)) {
2951 ffs_obj->desc_ready = true;
2952 ffs_obj->ffs_data = ffs;
2954 if (ffs_obj->ffs_ready_callback)
2955 ret = ffs_obj->ffs_ready_callback(ffs);
2962 static void ffs_closed(struct ffs_data *ffs)
2964 struct ffs_dev *ffs_obj;
2969 ffs_obj = ffs->private_data;
2973 ffs_obj->desc_ready = false;
2975 if (ffs_obj->ffs_closed_callback)
2976 ffs_obj->ffs_closed_callback(ffs);
2978 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
2979 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
2982 unregister_gadget_item(ffs_obj->opts->
2983 func_inst.group.cg_item.ci_parent->ci_parent);
2988 /* Misc helper functions ****************************************************/
2990 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2993 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2994 : mutex_lock_interruptible(mutex);
2997 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3004 data = kmalloc(len, GFP_KERNEL);
3005 if (unlikely(!data))
3006 return ERR_PTR(-ENOMEM);
3008 if (unlikely(__copy_from_user(data, buf, len))) {
3010 return ERR_PTR(-EFAULT);
3013 pr_vdebug("Buffer from user space:\n");
3014 ffs_dump_mem("", data, len);
3019 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3020 MODULE_LICENSE("GPL");
3021 MODULE_AUTHOR("Michal Nazarewicz");