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;
1035 case FUNCTIONFS_ENDPOINT_DESC:
1038 struct usb_endpoint_descriptor *desc;
1040 switch (epfile->ffs->gadget->speed) {
1041 case USB_SPEED_SUPER:
1044 case USB_SPEED_HIGH:
1050 desc = epfile->ep->descs[desc_idx];
1052 spin_unlock_irq(&epfile->ffs->eps_lock);
1053 ret = copy_to_user((void *)value, desc, sizeof(*desc));
1064 spin_unlock_irq(&epfile->ffs->eps_lock);
1069 static const struct file_operations ffs_epfile_operations = {
1070 .llseek = no_llseek,
1072 .open = ffs_epfile_open,
1073 .write = ffs_epfile_write,
1074 .read = ffs_epfile_read,
1075 .aio_write = ffs_epfile_aio_write,
1076 .aio_read = ffs_epfile_aio_read,
1077 .release = ffs_epfile_release,
1078 .unlocked_ioctl = ffs_epfile_ioctl,
1082 /* File system and super block operations ***********************************/
1085 * Mounting the file system creates a controller file, used first for
1086 * function configuration then later for event monitoring.
1089 static struct inode *__must_check
1090 ffs_sb_make_inode(struct super_block *sb, void *data,
1091 const struct file_operations *fops,
1092 const struct inode_operations *iops,
1093 struct ffs_file_perms *perms)
1095 struct inode *inode;
1099 inode = new_inode(sb);
1101 if (likely(inode)) {
1102 struct timespec current_time = CURRENT_TIME;
1104 inode->i_ino = get_next_ino();
1105 inode->i_mode = perms->mode;
1106 inode->i_uid = perms->uid;
1107 inode->i_gid = perms->gid;
1108 inode->i_atime = current_time;
1109 inode->i_mtime = current_time;
1110 inode->i_ctime = current_time;
1111 inode->i_private = data;
1113 inode->i_fop = fops;
1121 /* Create "regular" file */
1122 static struct inode *ffs_sb_create_file(struct super_block *sb,
1123 const char *name, void *data,
1124 const struct file_operations *fops,
1125 struct dentry **dentry_p)
1127 struct ffs_data *ffs = sb->s_fs_info;
1128 struct dentry *dentry;
1129 struct inode *inode;
1133 dentry = d_alloc_name(sb->s_root, name);
1134 if (unlikely(!dentry))
1137 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1138 if (unlikely(!inode)) {
1143 d_add(dentry, inode);
1151 static const struct super_operations ffs_sb_operations = {
1152 .statfs = simple_statfs,
1153 .drop_inode = generic_delete_inode,
1156 struct ffs_sb_fill_data {
1157 struct ffs_file_perms perms;
1159 const char *dev_name;
1160 struct ffs_data *ffs_data;
1163 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1165 struct ffs_sb_fill_data *data = _data;
1166 struct inode *inode;
1167 struct ffs_data *ffs = data->ffs_data;
1172 data->ffs_data = NULL;
1173 sb->s_fs_info = ffs;
1174 sb->s_blocksize = PAGE_CACHE_SIZE;
1175 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1176 sb->s_magic = FUNCTIONFS_MAGIC;
1177 sb->s_op = &ffs_sb_operations;
1178 sb->s_time_gran = 1;
1181 data->perms.mode = data->root_mode;
1182 inode = ffs_sb_make_inode(sb, NULL,
1183 &simple_dir_operations,
1184 &simple_dir_inode_operations,
1186 sb->s_root = d_make_root(inode);
1187 if (unlikely(!sb->s_root))
1191 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1192 &ffs_ep0_operations, NULL)))
1198 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1202 if (!opts || !*opts)
1206 unsigned long value;
1210 comma = strchr(opts, ',');
1215 eq = strchr(opts, '=');
1216 if (unlikely(!eq)) {
1217 pr_err("'=' missing in %s\n", opts);
1223 if (kstrtoul(eq + 1, 0, &value)) {
1224 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1228 /* Interpret option */
1229 switch (eq - opts) {
1231 if (!memcmp(opts, "rmode", 5))
1232 data->root_mode = (value & 0555) | S_IFDIR;
1233 else if (!memcmp(opts, "fmode", 5))
1234 data->perms.mode = (value & 0666) | S_IFREG;
1240 if (!memcmp(opts, "mode", 4)) {
1241 data->root_mode = (value & 0555) | S_IFDIR;
1242 data->perms.mode = (value & 0666) | S_IFREG;
1249 if (!memcmp(opts, "uid", 3)) {
1250 data->perms.uid = make_kuid(current_user_ns(), value);
1251 if (!uid_valid(data->perms.uid)) {
1252 pr_err("%s: unmapped value: %lu\n", opts, value);
1255 } else if (!memcmp(opts, "gid", 3)) {
1256 data->perms.gid = make_kgid(current_user_ns(), value);
1257 if (!gid_valid(data->perms.gid)) {
1258 pr_err("%s: unmapped value: %lu\n", opts, value);
1268 pr_err("%s: invalid option\n", opts);
1272 /* Next iteration */
1281 /* "mount -t functionfs dev_name /dev/function" ends up here */
1283 static struct dentry *
1284 ffs_fs_mount(struct file_system_type *t, int flags,
1285 const char *dev_name, void *opts)
1287 struct ffs_sb_fill_data data = {
1289 .mode = S_IFREG | 0600,
1290 .uid = GLOBAL_ROOT_UID,
1291 .gid = GLOBAL_ROOT_GID,
1293 .root_mode = S_IFDIR | 0500,
1298 struct ffs_data *ffs;
1302 ret = ffs_fs_parse_opts(&data, opts);
1303 if (unlikely(ret < 0))
1304 return ERR_PTR(ret);
1306 ffs = ffs_data_new();
1308 return ERR_PTR(-ENOMEM);
1309 ffs->file_perms = data.perms;
1311 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1312 if (unlikely(!ffs->dev_name)) {
1314 return ERR_PTR(-ENOMEM);
1317 ffs_dev = ffs_acquire_dev(dev_name);
1318 if (IS_ERR(ffs_dev)) {
1320 return ERR_CAST(ffs_dev);
1322 ffs->private_data = ffs_dev;
1323 data.ffs_data = ffs;
1325 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1326 if (IS_ERR(rv) && data.ffs_data) {
1327 ffs_release_dev(data.ffs_data);
1328 ffs_data_put(data.ffs_data);
1334 ffs_fs_kill_sb(struct super_block *sb)
1338 kill_litter_super(sb);
1339 if (sb->s_fs_info) {
1340 ffs_release_dev(sb->s_fs_info);
1341 ffs_data_put(sb->s_fs_info);
1345 static struct file_system_type ffs_fs_type = {
1346 .owner = THIS_MODULE,
1347 .name = "functionfs",
1348 .mount = ffs_fs_mount,
1349 .kill_sb = ffs_fs_kill_sb,
1351 MODULE_ALIAS_FS("functionfs");
1354 /* Driver's main init/cleanup functions *************************************/
1356 static int functionfs_init(void)
1362 ret = register_filesystem(&ffs_fs_type);
1364 pr_info("file system registered\n");
1366 pr_err("failed registering file system (%d)\n", ret);
1371 static void functionfs_cleanup(void)
1375 pr_info("unloading\n");
1376 unregister_filesystem(&ffs_fs_type);
1380 /* ffs_data and ffs_function construction and destruction code **************/
1382 static void ffs_data_clear(struct ffs_data *ffs);
1383 static void ffs_data_reset(struct ffs_data *ffs);
1385 static void ffs_data_get(struct ffs_data *ffs)
1389 atomic_inc(&ffs->ref);
1392 static void ffs_data_opened(struct ffs_data *ffs)
1396 atomic_inc(&ffs->ref);
1397 atomic_inc(&ffs->opened);
1400 static void ffs_data_put(struct ffs_data *ffs)
1404 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1405 pr_info("%s(): freeing\n", __func__);
1406 ffs_data_clear(ffs);
1407 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1408 waitqueue_active(&ffs->ep0req_completion.wait));
1409 kfree(ffs->dev_name);
1414 static void ffs_data_closed(struct ffs_data *ffs)
1418 if (atomic_dec_and_test(&ffs->opened)) {
1419 ffs->state = FFS_CLOSING;
1420 ffs_data_reset(ffs);
1426 static struct ffs_data *ffs_data_new(void)
1428 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1434 atomic_set(&ffs->ref, 1);
1435 atomic_set(&ffs->opened, 0);
1436 ffs->state = FFS_READ_DESCRIPTORS;
1437 mutex_init(&ffs->mutex);
1438 spin_lock_init(&ffs->eps_lock);
1439 init_waitqueue_head(&ffs->ev.waitq);
1440 init_completion(&ffs->ep0req_completion);
1442 /* XXX REVISIT need to update it in some places, or do we? */
1443 ffs->ev.can_stall = 1;
1448 static void ffs_data_clear(struct ffs_data *ffs)
1452 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1455 BUG_ON(ffs->gadget);
1458 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1460 kfree(ffs->raw_descs_data);
1461 kfree(ffs->raw_strings);
1462 kfree(ffs->stringtabs);
1465 static void ffs_data_reset(struct ffs_data *ffs)
1469 ffs_data_clear(ffs);
1471 ffs->epfiles = NULL;
1472 ffs->raw_descs_data = NULL;
1473 ffs->raw_descs = NULL;
1474 ffs->raw_strings = NULL;
1475 ffs->stringtabs = NULL;
1477 ffs->raw_descs_length = 0;
1478 ffs->fs_descs_count = 0;
1479 ffs->hs_descs_count = 0;
1480 ffs->ss_descs_count = 0;
1482 ffs->strings_count = 0;
1483 ffs->interfaces_count = 0;
1488 ffs->state = FFS_READ_DESCRIPTORS;
1489 ffs->setup_state = FFS_NO_SETUP;
1494 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1496 struct usb_gadget_strings **lang;
1501 if (WARN_ON(ffs->state != FFS_ACTIVE
1502 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1505 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1506 if (unlikely(first_id < 0))
1509 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1510 if (unlikely(!ffs->ep0req))
1512 ffs->ep0req->complete = ffs_ep0_complete;
1513 ffs->ep0req->context = ffs;
1515 lang = ffs->stringtabs;
1517 for (; *lang; ++lang) {
1518 struct usb_string *str = (*lang)->strings;
1520 for (; str->s; ++id, ++str)
1525 ffs->gadget = cdev->gadget;
1530 static void functionfs_unbind(struct ffs_data *ffs)
1534 if (!WARN_ON(!ffs->gadget)) {
1535 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1538 clear_bit(FFS_FL_BOUND, &ffs->flags);
1543 static int ffs_epfiles_create(struct ffs_data *ffs)
1545 struct ffs_epfile *epfile, *epfiles;
1550 count = ffs->eps_count;
1551 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1556 for (i = 1; i <= count; ++i, ++epfile) {
1558 mutex_init(&epfile->mutex);
1559 init_waitqueue_head(&epfile->wait);
1560 sprintf(epfiles->name, "ep%u", i);
1561 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1562 &ffs_epfile_operations,
1563 &epfile->dentry))) {
1564 ffs_epfiles_destroy(epfiles, i - 1);
1569 ffs->epfiles = epfiles;
1573 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1575 struct ffs_epfile *epfile = epfiles;
1579 for (; count; --count, ++epfile) {
1580 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1581 waitqueue_active(&epfile->wait));
1582 if (epfile->dentry) {
1583 d_delete(epfile->dentry);
1584 dput(epfile->dentry);
1585 epfile->dentry = NULL;
1593 static void ffs_func_eps_disable(struct ffs_function *func)
1595 struct ffs_ep *ep = func->eps;
1596 struct ffs_epfile *epfile = func->ffs->epfiles;
1597 unsigned count = func->ffs->eps_count;
1598 unsigned long flags;
1600 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1602 /* pending requests get nuked */
1604 usb_ep_disable(ep->ep);
1610 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1613 static int ffs_func_eps_enable(struct ffs_function *func)
1615 struct ffs_data *ffs = func->ffs;
1616 struct ffs_ep *ep = func->eps;
1617 struct ffs_epfile *epfile = ffs->epfiles;
1618 unsigned count = ffs->eps_count;
1619 unsigned long flags;
1622 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1624 struct usb_endpoint_descriptor *ds;
1627 if (ffs->gadget->speed == USB_SPEED_SUPER)
1629 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1634 /* fall-back to lower speed if desc missing for current speed */
1636 ds = ep->descs[desc_idx];
1637 } while (!ds && --desc_idx >= 0);
1644 ep->ep->driver_data = ep;
1646 ret = usb_ep_enable(ep->ep);
1649 epfile->in = usb_endpoint_dir_in(ds);
1650 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1655 wake_up(&epfile->wait);
1660 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1666 /* Parsing and building descriptors and strings *****************************/
1669 * This validates if data pointed by data is a valid USB descriptor as
1670 * well as record how many interfaces, endpoints and strings are
1671 * required by given configuration. Returns address after the
1672 * descriptor or NULL if data is invalid.
1675 enum ffs_entity_type {
1676 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1679 enum ffs_os_desc_type {
1680 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1683 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1685 struct usb_descriptor_header *desc,
1688 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1689 struct usb_os_desc_header *h, void *data,
1690 unsigned len, void *priv);
1692 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1693 ffs_entity_callback entity,
1696 struct usb_descriptor_header *_ds = (void *)data;
1702 /* At least two bytes are required: length and type */
1704 pr_vdebug("descriptor too short\n");
1708 /* If we have at least as many bytes as the descriptor takes? */
1709 length = _ds->bLength;
1711 pr_vdebug("descriptor longer then available data\n");
1715 #define __entity_check_INTERFACE(val) 1
1716 #define __entity_check_STRING(val) (val)
1717 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1718 #define __entity(type, val) do { \
1719 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1720 if (unlikely(!__entity_check_ ##type(val))) { \
1721 pr_vdebug("invalid entity's value\n"); \
1724 ret = entity(FFS_ ##type, &val, _ds, priv); \
1725 if (unlikely(ret < 0)) { \
1726 pr_debug("entity " #type "(%02x); ret = %d\n", \
1732 /* Parse descriptor depending on type. */
1733 switch (_ds->bDescriptorType) {
1737 case USB_DT_DEVICE_QUALIFIER:
1738 /* function can't have any of those */
1739 pr_vdebug("descriptor reserved for gadget: %d\n",
1740 _ds->bDescriptorType);
1743 case USB_DT_INTERFACE: {
1744 struct usb_interface_descriptor *ds = (void *)_ds;
1745 pr_vdebug("interface descriptor\n");
1746 if (length != sizeof *ds)
1749 __entity(INTERFACE, ds->bInterfaceNumber);
1751 __entity(STRING, ds->iInterface);
1755 case USB_DT_ENDPOINT: {
1756 struct usb_endpoint_descriptor *ds = (void *)_ds;
1757 pr_vdebug("endpoint descriptor\n");
1758 if (length != USB_DT_ENDPOINT_SIZE &&
1759 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1761 __entity(ENDPOINT, ds->bEndpointAddress);
1766 pr_vdebug("hid descriptor\n");
1767 if (length != sizeof(struct hid_descriptor))
1772 if (length != sizeof(struct usb_otg_descriptor))
1776 case USB_DT_INTERFACE_ASSOCIATION: {
1777 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1778 pr_vdebug("interface association descriptor\n");
1779 if (length != sizeof *ds)
1782 __entity(STRING, ds->iFunction);
1786 case USB_DT_SS_ENDPOINT_COMP:
1787 pr_vdebug("EP SS companion descriptor\n");
1788 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1792 case USB_DT_OTHER_SPEED_CONFIG:
1793 case USB_DT_INTERFACE_POWER:
1795 case USB_DT_SECURITY:
1796 case USB_DT_CS_RADIO_CONTROL:
1798 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1802 /* We should never be here */
1803 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1807 pr_vdebug("invalid length: %d (descriptor %d)\n",
1808 _ds->bLength, _ds->bDescriptorType);
1813 #undef __entity_check_DESCRIPTOR
1814 #undef __entity_check_INTERFACE
1815 #undef __entity_check_STRING
1816 #undef __entity_check_ENDPOINT
1821 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1822 ffs_entity_callback entity, void *priv)
1824 const unsigned _len = len;
1825 unsigned long num = 0;
1835 /* Record "descriptor" entity */
1836 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1837 if (unlikely(ret < 0)) {
1838 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1846 ret = ffs_do_single_desc(data, len, entity, priv);
1847 if (unlikely(ret < 0)) {
1848 pr_debug("%s returns %d\n", __func__, ret);
1858 static int __ffs_data_do_entity(enum ffs_entity_type type,
1859 u8 *valuep, struct usb_descriptor_header *desc,
1862 struct ffs_desc_helper *helper = priv;
1863 struct usb_endpoint_descriptor *d;
1868 case FFS_DESCRIPTOR:
1873 * Interfaces are indexed from zero so if we
1874 * encountered interface "n" then there are at least
1877 if (*valuep >= helper->interfaces_count)
1878 helper->interfaces_count = *valuep + 1;
1883 * Strings are indexed from 1 (0 is magic ;) reserved
1884 * for languages list or some such)
1886 if (*valuep > helper->ffs->strings_count)
1887 helper->ffs->strings_count = *valuep;
1892 helper->eps_count++;
1893 if (helper->eps_count >= 15)
1895 /* Check if descriptors for any speed were already parsed */
1896 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
1897 helper->ffs->eps_addrmap[helper->eps_count] =
1898 d->bEndpointAddress;
1899 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
1900 d->bEndpointAddress)
1908 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1909 struct usb_os_desc_header *desc)
1911 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1912 u16 w_index = le16_to_cpu(desc->wIndex);
1914 if (bcd_version != 1) {
1915 pr_vdebug("unsupported os descriptors version: %d",
1921 *next_type = FFS_OS_DESC_EXT_COMPAT;
1924 *next_type = FFS_OS_DESC_EXT_PROP;
1927 pr_vdebug("unsupported os descriptor type: %d", w_index);
1931 return sizeof(*desc);
1935 * Process all extended compatibility/extended property descriptors
1936 * of a feature descriptor
1938 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1939 enum ffs_os_desc_type type,
1941 ffs_os_desc_callback entity,
1943 struct usb_os_desc_header *h)
1946 const unsigned _len = len;
1950 /* loop over all ext compat/ext prop descriptors */
1951 while (feature_count--) {
1952 ret = entity(type, h, data, len, priv);
1953 if (unlikely(ret < 0)) {
1954 pr_debug("bad OS descriptor, type: %d\n", type);
1963 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1964 static int __must_check ffs_do_os_descs(unsigned count,
1965 char *data, unsigned len,
1966 ffs_os_desc_callback entity, void *priv)
1968 const unsigned _len = len;
1969 unsigned long num = 0;
1973 for (num = 0; num < count; ++num) {
1975 enum ffs_os_desc_type type;
1977 struct usb_os_desc_header *desc = (void *)data;
1979 if (len < sizeof(*desc))
1983 * Record "descriptor" entity.
1984 * Process dwLength, bcdVersion, wIndex, get b/wCount.
1985 * Move the data pointer to the beginning of extended
1986 * compatibilities proper or extended properties proper
1987 * portions of the data
1989 if (le32_to_cpu(desc->dwLength) > len)
1992 ret = __ffs_do_os_desc_header(&type, desc);
1993 if (unlikely(ret < 0)) {
1994 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
1999 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2001 feature_count = le16_to_cpu(desc->wCount);
2002 if (type == FFS_OS_DESC_EXT_COMPAT &&
2003 (feature_count > 255 || desc->Reserved))
2009 * Process all function/property descriptors
2010 * of this Feature Descriptor
2012 ret = ffs_do_single_os_desc(data, len, type,
2013 feature_count, entity, priv, desc);
2014 if (unlikely(ret < 0)) {
2015 pr_debug("%s returns %d\n", __func__, ret);
2026 * Validate contents of the buffer from userspace related to OS descriptors.
2028 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2029 struct usb_os_desc_header *h, void *data,
2030 unsigned len, void *priv)
2032 struct ffs_data *ffs = priv;
2038 case FFS_OS_DESC_EXT_COMPAT: {
2039 struct usb_ext_compat_desc *d = data;
2042 if (len < sizeof(*d) ||
2043 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2046 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2047 if (d->Reserved2[i])
2050 length = sizeof(struct usb_ext_compat_desc);
2053 case FFS_OS_DESC_EXT_PROP: {
2054 struct usb_ext_prop_desc *d = data;
2058 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2060 length = le32_to_cpu(d->dwSize);
2061 type = le32_to_cpu(d->dwPropertyDataType);
2062 if (type < USB_EXT_PROP_UNICODE ||
2063 type > USB_EXT_PROP_UNICODE_MULTI) {
2064 pr_vdebug("unsupported os descriptor property type: %d",
2068 pnl = le16_to_cpu(d->wPropertyNameLength);
2069 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2070 if (length != 14 + pnl + pdl) {
2071 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2072 length, pnl, pdl, type);
2075 ++ffs->ms_os_descs_ext_prop_count;
2076 /* property name reported to the host as "WCHAR"s */
2077 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2078 ffs->ms_os_descs_ext_prop_data_len += pdl;
2082 pr_vdebug("unknown descriptor: %d\n", type);
2088 static int __ffs_data_got_descs(struct ffs_data *ffs,
2089 char *const _data, size_t len)
2091 char *data = _data, *raw_descs;
2092 unsigned os_descs_count = 0, counts[3], flags;
2093 int ret = -EINVAL, i;
2094 struct ffs_desc_helper helper;
2098 if (get_unaligned_le32(data + 4) != len)
2101 switch (get_unaligned_le32(data)) {
2102 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2103 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2107 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2108 flags = get_unaligned_le32(data + 8);
2109 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2110 FUNCTIONFS_HAS_HS_DESC |
2111 FUNCTIONFS_HAS_SS_DESC |
2112 FUNCTIONFS_HAS_MS_OS_DESC)) {
2123 /* Read fs_count, hs_count and ss_count (if present) */
2124 for (i = 0; i < 3; ++i) {
2125 if (!(flags & (1 << i))) {
2127 } else if (len < 4) {
2130 counts[i] = get_unaligned_le32(data);
2135 if (flags & (1 << i)) {
2136 os_descs_count = get_unaligned_le32(data);
2141 /* Read descriptors */
2144 for (i = 0; i < 3; ++i) {
2147 helper.interfaces_count = 0;
2148 helper.eps_count = 0;
2149 ret = ffs_do_descs(counts[i], data, len,
2150 __ffs_data_do_entity, &helper);
2153 if (!ffs->eps_count && !ffs->interfaces_count) {
2154 ffs->eps_count = helper.eps_count;
2155 ffs->interfaces_count = helper.interfaces_count;
2157 if (ffs->eps_count != helper.eps_count) {
2161 if (ffs->interfaces_count != helper.interfaces_count) {
2169 if (os_descs_count) {
2170 ret = ffs_do_os_descs(os_descs_count, data, len,
2171 __ffs_data_do_os_desc, ffs);
2178 if (raw_descs == data || len) {
2183 ffs->raw_descs_data = _data;
2184 ffs->raw_descs = raw_descs;
2185 ffs->raw_descs_length = data - raw_descs;
2186 ffs->fs_descs_count = counts[0];
2187 ffs->hs_descs_count = counts[1];
2188 ffs->ss_descs_count = counts[2];
2189 ffs->ms_os_descs_count = os_descs_count;
2198 static int __ffs_data_got_strings(struct ffs_data *ffs,
2199 char *const _data, size_t len)
2201 u32 str_count, needed_count, lang_count;
2202 struct usb_gadget_strings **stringtabs, *t;
2203 struct usb_string *strings, *s;
2204 const char *data = _data;
2208 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2209 get_unaligned_le32(data + 4) != len))
2211 str_count = get_unaligned_le32(data + 8);
2212 lang_count = get_unaligned_le32(data + 12);
2214 /* if one is zero the other must be zero */
2215 if (unlikely(!str_count != !lang_count))
2218 /* Do we have at least as many strings as descriptors need? */
2219 needed_count = ffs->strings_count;
2220 if (unlikely(str_count < needed_count))
2224 * If we don't need any strings just return and free all
2227 if (!needed_count) {
2232 /* Allocate everything in one chunk so there's less maintenance. */
2236 vla_item(d, struct usb_gadget_strings *, stringtabs,
2238 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2239 vla_item(d, struct usb_string, strings,
2240 lang_count*(needed_count+1));
2242 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2244 if (unlikely(!vlabuf)) {
2249 /* Initialize the VLA pointers */
2250 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2251 t = vla_ptr(vlabuf, d, stringtab);
2254 *stringtabs++ = t++;
2258 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2259 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2260 t = vla_ptr(vlabuf, d, stringtab);
2261 s = vla_ptr(vlabuf, d, strings);
2265 /* For each language */
2269 do { /* lang_count > 0 so we can use do-while */
2270 unsigned needed = needed_count;
2272 if (unlikely(len < 3))
2274 t->language = get_unaligned_le16(data);
2281 /* For each string */
2282 do { /* str_count > 0 so we can use do-while */
2283 size_t length = strnlen(data, len);
2285 if (unlikely(length == len))
2289 * User may provide more strings then we need,
2290 * if that's the case we simply ignore the
2293 if (likely(needed)) {
2295 * s->id will be set while adding
2296 * function to configuration so for
2297 * now just leave garbage here.
2306 } while (--str_count);
2308 s->id = 0; /* terminator */
2312 } while (--lang_count);
2314 /* Some garbage left? */
2319 ffs->stringtabs = stringtabs;
2320 ffs->raw_strings = _data;
2332 /* Events handling and management *******************************************/
2334 static void __ffs_event_add(struct ffs_data *ffs,
2335 enum usb_functionfs_event_type type)
2337 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2341 * Abort any unhandled setup
2343 * We do not need to worry about some cmpxchg() changing value
2344 * of ffs->setup_state without holding the lock because when
2345 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2346 * the source does nothing.
2348 if (ffs->setup_state == FFS_SETUP_PENDING)
2349 ffs->setup_state = FFS_SETUP_CANCELLED;
2352 case FUNCTIONFS_RESUME:
2353 rem_type2 = FUNCTIONFS_SUSPEND;
2355 case FUNCTIONFS_SUSPEND:
2356 case FUNCTIONFS_SETUP:
2358 /* Discard all similar events */
2361 case FUNCTIONFS_BIND:
2362 case FUNCTIONFS_UNBIND:
2363 case FUNCTIONFS_DISABLE:
2364 case FUNCTIONFS_ENABLE:
2365 /* Discard everything other then power management. */
2366 rem_type1 = FUNCTIONFS_SUSPEND;
2367 rem_type2 = FUNCTIONFS_RESUME;
2372 WARN(1, "%d: unknown event, this should not happen\n", type);
2377 u8 *ev = ffs->ev.types, *out = ev;
2378 unsigned n = ffs->ev.count;
2379 for (; n; --n, ++ev)
2380 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2383 pr_vdebug("purging event %d\n", *ev);
2384 ffs->ev.count = out - ffs->ev.types;
2387 pr_vdebug("adding event %d\n", type);
2388 ffs->ev.types[ffs->ev.count++] = type;
2389 wake_up_locked(&ffs->ev.waitq);
2392 static void ffs_event_add(struct ffs_data *ffs,
2393 enum usb_functionfs_event_type type)
2395 unsigned long flags;
2396 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2397 __ffs_event_add(ffs, type);
2398 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2401 /* Bind/unbind USB function hooks *******************************************/
2403 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2407 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2408 if (ffs->eps_addrmap[i] == endpoint_address)
2413 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2414 struct usb_descriptor_header *desc,
2417 struct usb_endpoint_descriptor *ds = (void *)desc;
2418 struct ffs_function *func = priv;
2419 struct ffs_ep *ffs_ep;
2420 unsigned ep_desc_id;
2422 static const char *speed_names[] = { "full", "high", "super" };
2424 if (type != FFS_DESCRIPTOR)
2428 * If ss_descriptors is not NULL, we are reading super speed
2429 * descriptors; if hs_descriptors is not NULL, we are reading high
2430 * speed descriptors; otherwise, we are reading full speed
2433 if (func->function.ss_descriptors) {
2435 func->function.ss_descriptors[(long)valuep] = desc;
2436 } else if (func->function.hs_descriptors) {
2438 func->function.hs_descriptors[(long)valuep] = desc;
2441 func->function.fs_descriptors[(long)valuep] = desc;
2444 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2447 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2451 ffs_ep = func->eps + idx;
2453 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2454 pr_err("two %sspeed descriptors for EP %d\n",
2455 speed_names[ep_desc_id],
2456 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2459 ffs_ep->descs[ep_desc_id] = ds;
2461 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2463 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2464 if (!ds->wMaxPacketSize)
2465 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2467 struct usb_request *req;
2470 pr_vdebug("autoconfig\n");
2471 ep = usb_ep_autoconfig(func->gadget, ds);
2474 ep->driver_data = func->eps + idx;
2476 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2482 func->eps_revmap[ds->bEndpointAddress &
2483 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2485 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2490 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2491 struct usb_descriptor_header *desc,
2494 struct ffs_function *func = priv;
2500 case FFS_DESCRIPTOR:
2501 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2506 if (func->interfaces_nums[idx] < 0) {
2507 int id = usb_interface_id(func->conf, &func->function);
2508 if (unlikely(id < 0))
2510 func->interfaces_nums[idx] = id;
2512 newValue = func->interfaces_nums[idx];
2516 /* String' IDs are allocated when fsf_data is bound to cdev */
2517 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2522 * USB_DT_ENDPOINT are handled in
2523 * __ffs_func_bind_do_descs().
2525 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2528 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2529 if (unlikely(!func->eps[idx].ep))
2533 struct usb_endpoint_descriptor **descs;
2534 descs = func->eps[idx].descs;
2535 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2540 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2545 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2546 struct usb_os_desc_header *h, void *data,
2547 unsigned len, void *priv)
2549 struct ffs_function *func = priv;
2553 case FFS_OS_DESC_EXT_COMPAT: {
2554 struct usb_ext_compat_desc *desc = data;
2555 struct usb_os_desc_table *t;
2557 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2558 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2559 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2560 ARRAY_SIZE(desc->CompatibleID) +
2561 ARRAY_SIZE(desc->SubCompatibleID));
2562 length = sizeof(*desc);
2565 case FFS_OS_DESC_EXT_PROP: {
2566 struct usb_ext_prop_desc *desc = data;
2567 struct usb_os_desc_table *t;
2568 struct usb_os_desc_ext_prop *ext_prop;
2569 char *ext_prop_name;
2570 char *ext_prop_data;
2572 t = &func->function.os_desc_table[h->interface];
2573 t->if_id = func->interfaces_nums[h->interface];
2575 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2576 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2578 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2579 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2580 ext_prop->data_len = le32_to_cpu(*(u32 *)
2581 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2582 length = ext_prop->name_len + ext_prop->data_len + 14;
2584 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2585 func->ffs->ms_os_descs_ext_prop_name_avail +=
2588 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2589 func->ffs->ms_os_descs_ext_prop_data_avail +=
2591 memcpy(ext_prop_data,
2592 usb_ext_prop_data_ptr(data, ext_prop->name_len),
2593 ext_prop->data_len);
2594 /* unicode data reported to the host as "WCHAR"s */
2595 switch (ext_prop->type) {
2596 case USB_EXT_PROP_UNICODE:
2597 case USB_EXT_PROP_UNICODE_ENV:
2598 case USB_EXT_PROP_UNICODE_LINK:
2599 case USB_EXT_PROP_UNICODE_MULTI:
2600 ext_prop->data_len *= 2;
2603 ext_prop->data = ext_prop_data;
2605 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2606 ext_prop->name_len);
2607 /* property name reported to the host as "WCHAR"s */
2608 ext_prop->name_len *= 2;
2609 ext_prop->name = ext_prop_name;
2611 t->os_desc->ext_prop_len +=
2612 ext_prop->name_len + ext_prop->data_len + 14;
2613 ++t->os_desc->ext_prop_count;
2614 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2618 pr_vdebug("unknown descriptor: %d\n", type);
2624 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2625 struct usb_configuration *c)
2627 struct ffs_function *func = ffs_func_from_usb(f);
2628 struct f_fs_opts *ffs_opts =
2629 container_of(f->fi, struct f_fs_opts, func_inst);
2635 * Legacy gadget triggers binding in functionfs_ready_callback,
2636 * which already uses locking; taking the same lock here would
2639 * Configfs-enabled gadgets however do need ffs_dev_lock.
2641 if (!ffs_opts->no_configfs)
2643 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2644 func->ffs = ffs_opts->dev->ffs_data;
2645 if (!ffs_opts->no_configfs)
2648 return ERR_PTR(ret);
2651 func->gadget = c->cdev->gadget;
2653 ffs_data_get(func->ffs);
2656 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2657 * configurations are bound in sequence with list_for_each_entry,
2658 * in each configuration its functions are bound in sequence
2659 * with list_for_each_entry, so we assume no race condition
2660 * with regard to ffs_opts->bound access
2662 if (!ffs_opts->refcnt) {
2663 ret = functionfs_bind(func->ffs, c->cdev);
2665 return ERR_PTR(ret);
2668 func->function.strings = func->ffs->stringtabs;
2673 static int _ffs_func_bind(struct usb_configuration *c,
2674 struct usb_function *f)
2676 struct ffs_function *func = ffs_func_from_usb(f);
2677 struct ffs_data *ffs = func->ffs;
2679 const int full = !!func->ffs->fs_descs_count;
2680 const int high = gadget_is_dualspeed(func->gadget) &&
2681 func->ffs->hs_descs_count;
2682 const int super = gadget_is_superspeed(func->gadget) &&
2683 func->ffs->ss_descs_count;
2685 int fs_len, hs_len, ss_len, ret, i;
2687 /* Make it a single chunk, less management later on */
2689 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2690 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2691 full ? ffs->fs_descs_count + 1 : 0);
2692 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2693 high ? ffs->hs_descs_count + 1 : 0);
2694 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2695 super ? ffs->ss_descs_count + 1 : 0);
2696 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2697 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2698 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2699 vla_item_with_sz(d, char[16], ext_compat,
2700 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2701 vla_item_with_sz(d, struct usb_os_desc, os_desc,
2702 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2703 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2704 ffs->ms_os_descs_ext_prop_count);
2705 vla_item_with_sz(d, char, ext_prop_name,
2706 ffs->ms_os_descs_ext_prop_name_len);
2707 vla_item_with_sz(d, char, ext_prop_data,
2708 ffs->ms_os_descs_ext_prop_data_len);
2709 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2714 /* Has descriptors only for speeds gadget does not support */
2715 if (unlikely(!(full | high | super)))
2718 /* Allocate a single chunk, less management later on */
2719 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2720 if (unlikely(!vlabuf))
2723 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2724 ffs->ms_os_descs_ext_prop_name_avail =
2725 vla_ptr(vlabuf, d, ext_prop_name);
2726 ffs->ms_os_descs_ext_prop_data_avail =
2727 vla_ptr(vlabuf, d, ext_prop_data);
2729 /* Copy descriptors */
2730 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2731 ffs->raw_descs_length);
2733 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2734 for (ret = ffs->eps_count; ret; --ret) {
2737 ptr = vla_ptr(vlabuf, d, eps);
2742 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2744 func->eps = vla_ptr(vlabuf, d, eps);
2745 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2748 * Go through all the endpoint descriptors and allocate
2749 * endpoints first, so that later we can rewrite the endpoint
2750 * numbers without worrying that it may be described later on.
2753 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2754 fs_len = ffs_do_descs(ffs->fs_descs_count,
2755 vla_ptr(vlabuf, d, raw_descs),
2757 __ffs_func_bind_do_descs, func);
2758 if (unlikely(fs_len < 0)) {
2767 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2768 hs_len = ffs_do_descs(ffs->hs_descs_count,
2769 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2770 d_raw_descs__sz - fs_len,
2771 __ffs_func_bind_do_descs, func);
2772 if (unlikely(hs_len < 0)) {
2780 if (likely(super)) {
2781 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2782 ss_len = ffs_do_descs(ffs->ss_descs_count,
2783 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2784 d_raw_descs__sz - fs_len - hs_len,
2785 __ffs_func_bind_do_descs, func);
2786 if (unlikely(ss_len < 0)) {
2795 * Now handle interface numbers allocation and interface and
2796 * endpoint numbers rewriting. We can do that in one go
2799 ret = ffs_do_descs(ffs->fs_descs_count +
2800 (high ? ffs->hs_descs_count : 0) +
2801 (super ? ffs->ss_descs_count : 0),
2802 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2803 __ffs_func_bind_do_nums, func);
2804 if (unlikely(ret < 0))
2807 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2808 if (c->cdev->use_os_string)
2809 for (i = 0; i < ffs->interfaces_count; ++i) {
2810 struct usb_os_desc *desc;
2812 desc = func->function.os_desc_table[i].os_desc =
2813 vla_ptr(vlabuf, d, os_desc) +
2814 i * sizeof(struct usb_os_desc);
2815 desc->ext_compat_id =
2816 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2817 INIT_LIST_HEAD(&desc->ext_prop);
2819 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2820 vla_ptr(vlabuf, d, raw_descs) +
2821 fs_len + hs_len + ss_len,
2822 d_raw_descs__sz - fs_len - hs_len - ss_len,
2823 __ffs_func_bind_do_os_desc, func);
2824 if (unlikely(ret < 0))
2826 func->function.os_desc_n =
2827 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2829 /* And we're done */
2830 ffs_event_add(ffs, FUNCTIONFS_BIND);
2834 /* XXX Do we need to release all claimed endpoints here? */
2838 static int ffs_func_bind(struct usb_configuration *c,
2839 struct usb_function *f)
2841 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2843 if (IS_ERR(ffs_opts))
2844 return PTR_ERR(ffs_opts);
2846 return _ffs_func_bind(c, f);
2850 /* Other USB function hooks *************************************************/
2852 static int ffs_func_set_alt(struct usb_function *f,
2853 unsigned interface, unsigned alt)
2855 struct ffs_function *func = ffs_func_from_usb(f);
2856 struct ffs_data *ffs = func->ffs;
2859 if (alt != (unsigned)-1) {
2860 intf = ffs_func_revmap_intf(func, interface);
2861 if (unlikely(intf < 0))
2866 ffs_func_eps_disable(ffs->func);
2868 if (ffs->state != FFS_ACTIVE)
2871 if (alt == (unsigned)-1) {
2873 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2878 ret = ffs_func_eps_enable(func);
2879 if (likely(ret >= 0))
2880 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2884 static void ffs_func_disable(struct usb_function *f)
2886 ffs_func_set_alt(f, 0, (unsigned)-1);
2889 static int ffs_func_setup(struct usb_function *f,
2890 const struct usb_ctrlrequest *creq)
2892 struct ffs_function *func = ffs_func_from_usb(f);
2893 struct ffs_data *ffs = func->ffs;
2894 unsigned long flags;
2899 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2900 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2901 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2902 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2903 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2906 * Most requests directed to interface go through here
2907 * (notable exceptions are set/get interface) so we need to
2908 * handle them. All other either handled by composite or
2909 * passed to usb_configuration->setup() (if one is set). No
2910 * matter, we will handle requests directed to endpoint here
2911 * as well (as it's straightforward) but what to do with any
2914 if (ffs->state != FFS_ACTIVE)
2917 switch (creq->bRequestType & USB_RECIP_MASK) {
2918 case USB_RECIP_INTERFACE:
2919 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2920 if (unlikely(ret < 0))
2924 case USB_RECIP_ENDPOINT:
2925 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2926 if (unlikely(ret < 0))
2934 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2935 ffs->ev.setup = *creq;
2936 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2937 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2938 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2943 static void ffs_func_suspend(struct usb_function *f)
2946 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2949 static void ffs_func_resume(struct usb_function *f)
2952 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2956 /* Endpoint and interface numbers reverse mapping ***************************/
2958 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2960 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2961 return num ? num : -EDOM;
2964 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2966 short *nums = func->interfaces_nums;
2967 unsigned count = func->ffs->interfaces_count;
2969 for (; count; --count, ++nums) {
2970 if (*nums >= 0 && *nums == intf)
2971 return nums - func->interfaces_nums;
2978 /* Devices management *******************************************************/
2980 static LIST_HEAD(ffs_devices);
2982 static struct ffs_dev *_ffs_do_find_dev(const char *name)
2984 struct ffs_dev *dev;
2986 list_for_each_entry(dev, &ffs_devices, entry) {
2987 if (!dev->name || !name)
2989 if (strcmp(dev->name, name) == 0)
2997 * ffs_lock must be taken by the caller of this function
2999 static struct ffs_dev *_ffs_get_single_dev(void)
3001 struct ffs_dev *dev;
3003 if (list_is_singular(&ffs_devices)) {
3004 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3013 * ffs_lock must be taken by the caller of this function
3015 static struct ffs_dev *_ffs_find_dev(const char *name)
3017 struct ffs_dev *dev;
3019 dev = _ffs_get_single_dev();
3023 return _ffs_do_find_dev(name);
3026 /* Configfs support *********************************************************/
3028 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3030 return container_of(to_config_group(item), struct f_fs_opts,
3034 static void ffs_attr_release(struct config_item *item)
3036 struct f_fs_opts *opts = to_ffs_opts(item);
3038 usb_put_function_instance(&opts->func_inst);
3041 static struct configfs_item_operations ffs_item_ops = {
3042 .release = ffs_attr_release,
3045 static struct config_item_type ffs_func_type = {
3046 .ct_item_ops = &ffs_item_ops,
3047 .ct_owner = THIS_MODULE,
3051 /* Function registration interface ******************************************/
3053 static void ffs_free_inst(struct usb_function_instance *f)
3055 struct f_fs_opts *opts;
3057 opts = to_f_fs_opts(f);
3059 _ffs_free_dev(opts->dev);
3064 #define MAX_INST_NAME_LEN 40
3066 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3068 struct f_fs_opts *opts;
3073 name_len = strlen(name) + 1;
3074 if (name_len > MAX_INST_NAME_LEN)
3075 return -ENAMETOOLONG;
3077 ptr = kstrndup(name, name_len, GFP_KERNEL);
3081 opts = to_f_fs_opts(fi);
3086 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3087 ret = _ffs_name_dev(opts->dev, ptr);
3093 opts->dev->name_allocated = true;
3102 static struct usb_function_instance *ffs_alloc_inst(void)
3104 struct f_fs_opts *opts;
3105 struct ffs_dev *dev;
3107 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3109 return ERR_PTR(-ENOMEM);
3111 opts->func_inst.set_inst_name = ffs_set_inst_name;
3112 opts->func_inst.free_func_inst = ffs_free_inst;
3114 dev = _ffs_alloc_dev();
3118 return ERR_CAST(dev);
3123 config_group_init_type_name(&opts->func_inst.group, "",
3125 return &opts->func_inst;
3128 static void ffs_free(struct usb_function *f)
3130 kfree(ffs_func_from_usb(f));
3133 static void ffs_func_unbind(struct usb_configuration *c,
3134 struct usb_function *f)
3136 struct ffs_function *func = ffs_func_from_usb(f);
3137 struct ffs_data *ffs = func->ffs;
3138 struct f_fs_opts *opts =
3139 container_of(f->fi, struct f_fs_opts, func_inst);
3140 struct ffs_ep *ep = func->eps;
3141 unsigned count = ffs->eps_count;
3142 unsigned long flags;
3145 if (ffs->func == func) {
3146 ffs_func_eps_disable(func);
3150 if (!--opts->refcnt)
3151 functionfs_unbind(ffs);
3153 /* cleanup after autoconfig */
3154 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3156 if (ep->ep && ep->req)
3157 usb_ep_free_request(ep->ep, ep->req);
3161 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3165 * eps, descriptors and interfaces_nums are allocated in the
3166 * same chunk so only one free is required.
3168 func->function.fs_descriptors = NULL;
3169 func->function.hs_descriptors = NULL;
3170 func->function.ss_descriptors = NULL;
3171 func->interfaces_nums = NULL;
3173 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3176 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3178 struct ffs_function *func;
3182 func = kzalloc(sizeof(*func), GFP_KERNEL);
3183 if (unlikely(!func))
3184 return ERR_PTR(-ENOMEM);
3186 func->function.name = "Function FS Gadget";
3188 func->function.bind = ffs_func_bind;
3189 func->function.unbind = ffs_func_unbind;
3190 func->function.set_alt = ffs_func_set_alt;
3191 func->function.disable = ffs_func_disable;
3192 func->function.setup = ffs_func_setup;
3193 func->function.suspend = ffs_func_suspend;
3194 func->function.resume = ffs_func_resume;
3195 func->function.free_func = ffs_free;
3197 return &func->function;
3201 * ffs_lock must be taken by the caller of this function
3203 static struct ffs_dev *_ffs_alloc_dev(void)
3205 struct ffs_dev *dev;
3208 if (_ffs_get_single_dev())
3209 return ERR_PTR(-EBUSY);
3211 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3213 return ERR_PTR(-ENOMEM);
3215 if (list_empty(&ffs_devices)) {
3216 ret = functionfs_init();
3219 return ERR_PTR(ret);
3223 list_add(&dev->entry, &ffs_devices);
3229 * ffs_lock must be taken by the caller of this function
3230 * The caller is responsible for "name" being available whenever f_fs needs it
3232 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3234 struct ffs_dev *existing;
3236 existing = _ffs_do_find_dev(name);
3246 * The caller is responsible for "name" being available whenever f_fs needs it
3248 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3253 ret = _ffs_name_dev(dev, name);
3258 EXPORT_SYMBOL_GPL(ffs_name_dev);
3260 int ffs_single_dev(struct ffs_dev *dev)
3267 if (!list_is_singular(&ffs_devices))
3275 EXPORT_SYMBOL_GPL(ffs_single_dev);
3278 * ffs_lock must be taken by the caller of this function
3280 static void _ffs_free_dev(struct ffs_dev *dev)
3282 list_del(&dev->entry);
3283 if (dev->name_allocated)
3286 if (list_empty(&ffs_devices))
3287 functionfs_cleanup();
3290 static void *ffs_acquire_dev(const char *dev_name)
3292 struct ffs_dev *ffs_dev;
3297 ffs_dev = _ffs_find_dev(dev_name);
3299 ffs_dev = ERR_PTR(-ENOENT);
3300 else if (ffs_dev->mounted)
3301 ffs_dev = ERR_PTR(-EBUSY);
3302 else if (ffs_dev->ffs_acquire_dev_callback &&
3303 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3304 ffs_dev = ERR_PTR(-ENOENT);
3306 ffs_dev->mounted = true;
3312 static void ffs_release_dev(struct ffs_data *ffs_data)
3314 struct ffs_dev *ffs_dev;
3319 ffs_dev = ffs_data->private_data;
3321 ffs_dev->mounted = false;
3323 if (ffs_dev->ffs_release_dev_callback)
3324 ffs_dev->ffs_release_dev_callback(ffs_dev);
3330 static int ffs_ready(struct ffs_data *ffs)
3332 struct ffs_dev *ffs_obj;
3338 ffs_obj = ffs->private_data;
3343 if (WARN_ON(ffs_obj->desc_ready)) {
3348 ffs_obj->desc_ready = true;
3349 ffs_obj->ffs_data = ffs;
3351 if (ffs_obj->ffs_ready_callback)
3352 ret = ffs_obj->ffs_ready_callback(ffs);
3359 static void ffs_closed(struct ffs_data *ffs)
3361 struct ffs_dev *ffs_obj;
3366 ffs_obj = ffs->private_data;
3370 ffs_obj->desc_ready = false;
3372 if (ffs_obj->ffs_closed_callback)
3373 ffs_obj->ffs_closed_callback(ffs);
3375 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
3376 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
3379 unregister_gadget_item(ffs_obj->opts->
3380 func_inst.group.cg_item.ci_parent->ci_parent);
3385 /* Misc helper functions ****************************************************/
3387 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3390 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3391 : mutex_lock_interruptible(mutex);
3394 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3401 data = kmalloc(len, GFP_KERNEL);
3402 if (unlikely(!data))
3403 return ERR_PTR(-ENOMEM);
3405 if (unlikely(__copy_from_user(data, buf, len))) {
3407 return ERR_PTR(-EFAULT);
3410 pr_vdebug("Buffer from user space:\n");
3411 ffs_dump_mem("", data, len);
3416 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3417 MODULE_LICENSE("GPL");
3418 MODULE_AUTHOR("Michal Nazarewicz");