2 * f_fs.c -- user mode file system API for USB composite function controllers
4 * Copyright (C) 2010 Samsung Electronics
7 * Based on inode.c (GadgetFS) which was:
8 * Copyright (C) 2003-2004 David Brownell
9 * Copyright (C) 2003 Agilent Technologies
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
19 /* #define VERBOSE_DEBUG */
21 #include <linux/blkdev.h>
22 #include <linux/pagemap.h>
23 #include <linux/export.h>
24 #include <linux/hid.h>
25 #include <linux/module.h>
26 #include <asm/unaligned.h>
28 #include <linux/usb/composite.h>
29 #include <linux/usb/functionfs.h>
31 #include <linux/aio.h>
32 #include <linux/mmu_context.h>
33 #include <linux/poll.h>
37 #include "u_os_desc.h"
40 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
42 /* Reference counter handling */
43 static void ffs_data_get(struct ffs_data *ffs);
44 static void ffs_data_put(struct ffs_data *ffs);
45 /* Creates new ffs_data object. */
46 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
48 /* Opened counter handling. */
49 static void ffs_data_opened(struct ffs_data *ffs);
50 static void ffs_data_closed(struct ffs_data *ffs);
52 /* Called with ffs->mutex held; take over ownership of data. */
53 static int __must_check
54 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
55 static int __must_check
56 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
59 /* The function structure ***************************************************/
64 struct usb_configuration *conf;
65 struct usb_gadget *gadget;
70 short *interfaces_nums;
72 struct usb_function function;
76 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
78 return container_of(f, struct ffs_function, function);
82 static inline enum ffs_setup_state
83 ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
85 return (enum ffs_setup_state)
86 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
90 static void ffs_func_eps_disable(struct ffs_function *func);
91 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
93 static int ffs_func_bind(struct usb_configuration *,
94 struct usb_function *);
95 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
96 static void ffs_func_disable(struct usb_function *);
97 static int ffs_func_setup(struct usb_function *,
98 const struct usb_ctrlrequest *);
99 static void ffs_func_suspend(struct usb_function *);
100 static void ffs_func_resume(struct usb_function *);
103 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
104 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
107 /* The endpoints structures *************************************************/
110 struct usb_ep *ep; /* P: ffs->eps_lock */
111 struct usb_request *req; /* P: epfile->mutex */
113 /* [0]: full speed, [1]: high speed, [2]: super speed */
114 struct usb_endpoint_descriptor *descs[3];
118 int status; /* P: epfile->mutex */
122 /* Protects ep->ep and ep->req. */
124 wait_queue_head_t wait;
126 struct ffs_data *ffs;
127 struct ffs_ep *ep; /* P: ffs->eps_lock */
129 struct dentry *dentry;
133 unsigned char in; /* P: ffs->eps_lock */
134 unsigned char isoc; /* P: ffs->eps_lock */
139 /* ffs_io_data structure ***************************************************/
146 const struct iovec *iovec;
147 unsigned long nr_segs;
151 struct mm_struct *mm;
152 struct work_struct work;
155 struct usb_request *req;
158 struct ffs_desc_helper {
159 struct ffs_data *ffs;
160 unsigned interfaces_count;
164 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
165 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
167 static struct dentry *
168 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
169 const struct file_operations *fops);
171 /* Devices management *******************************************************/
173 DEFINE_MUTEX(ffs_lock);
174 EXPORT_SYMBOL_GPL(ffs_lock);
176 static struct ffs_dev *_ffs_find_dev(const char *name);
177 static struct ffs_dev *_ffs_alloc_dev(void);
178 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
179 static void _ffs_free_dev(struct ffs_dev *dev);
180 static void *ffs_acquire_dev(const char *dev_name);
181 static void ffs_release_dev(struct ffs_data *ffs_data);
182 static int ffs_ready(struct ffs_data *ffs);
183 static void ffs_closed(struct ffs_data *ffs);
185 /* Misc helper functions ****************************************************/
187 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
188 __attribute__((warn_unused_result, nonnull));
189 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
190 __attribute__((warn_unused_result, nonnull));
193 /* Control file aka ep0 *****************************************************/
195 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
197 struct ffs_data *ffs = req->context;
199 complete_all(&ffs->ep0req_completion);
202 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
204 struct usb_request *req = ffs->ep0req;
207 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
209 spin_unlock_irq(&ffs->ev.waitq.lock);
215 * UDC layer requires to provide a buffer even for ZLP, but should
216 * not use it at all. Let's provide some poisoned pointer to catch
217 * possible bug in the driver.
219 if (req->buf == NULL)
220 req->buf = (void *)0xDEADBABE;
222 reinit_completion(&ffs->ep0req_completion);
224 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
225 if (unlikely(ret < 0))
228 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
230 usb_ep_dequeue(ffs->gadget->ep0, req);
234 ffs->setup_state = FFS_NO_SETUP;
235 return req->status ? req->status : req->actual;
238 static int __ffs_ep0_stall(struct ffs_data *ffs)
240 if (ffs->ev.can_stall) {
241 pr_vdebug("ep0 stall\n");
242 usb_ep_set_halt(ffs->gadget->ep0);
243 ffs->setup_state = FFS_NO_SETUP;
246 pr_debug("bogus ep0 stall!\n");
251 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
252 size_t len, loff_t *ptr)
254 struct ffs_data *ffs = file->private_data;
260 /* Fast check if setup was canceled */
261 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
265 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
266 if (unlikely(ret < 0))
270 switch (ffs->state) {
271 case FFS_READ_DESCRIPTORS:
272 case FFS_READ_STRINGS:
274 if (unlikely(len < 16)) {
279 data = ffs_prepare_buffer(buf, len);
286 if (ffs->state == FFS_READ_DESCRIPTORS) {
287 pr_info("read descriptors\n");
288 ret = __ffs_data_got_descs(ffs, data, len);
289 if (unlikely(ret < 0))
292 ffs->state = FFS_READ_STRINGS;
295 pr_info("read strings\n");
296 ret = __ffs_data_got_strings(ffs, data, len);
297 if (unlikely(ret < 0))
300 ret = ffs_epfiles_create(ffs);
302 ffs->state = FFS_CLOSING;
306 ffs->state = FFS_ACTIVE;
307 mutex_unlock(&ffs->mutex);
309 ret = ffs_ready(ffs);
310 if (unlikely(ret < 0)) {
311 ffs->state = FFS_CLOSING;
315 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
323 * We're called from user space, we can use _irq
324 * rather then _irqsave
326 spin_lock_irq(&ffs->ev.waitq.lock);
327 switch (ffs_setup_state_clear_cancelled(ffs)) {
328 case FFS_SETUP_CANCELLED:
336 case FFS_SETUP_PENDING:
340 /* FFS_SETUP_PENDING */
341 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
342 spin_unlock_irq(&ffs->ev.waitq.lock);
343 ret = __ffs_ep0_stall(ffs);
347 /* FFS_SETUP_PENDING and not stall */
348 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
350 spin_unlock_irq(&ffs->ev.waitq.lock);
352 data = ffs_prepare_buffer(buf, len);
358 spin_lock_irq(&ffs->ev.waitq.lock);
361 * We are guaranteed to be still in FFS_ACTIVE state
362 * but the state of setup could have changed from
363 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
364 * to check for that. If that happened we copied data
365 * from user space in vain but it's unlikely.
367 * For sure we are not in FFS_NO_SETUP since this is
368 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
369 * transition can be performed and it's protected by
372 if (ffs_setup_state_clear_cancelled(ffs) ==
373 FFS_SETUP_CANCELLED) {
376 spin_unlock_irq(&ffs->ev.waitq.lock);
378 /* unlocks spinlock */
379 ret = __ffs_ep0_queue_wait(ffs, data, len);
389 mutex_unlock(&ffs->mutex);
393 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
397 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
400 struct usb_functionfs_event events[n];
403 memset(events, 0, sizeof events);
406 events[i].type = ffs->ev.types[i];
407 if (events[i].type == FUNCTIONFS_SETUP) {
408 events[i].u.setup = ffs->ev.setup;
409 ffs->setup_state = FFS_SETUP_PENDING;
413 if (n < ffs->ev.count) {
415 memmove(ffs->ev.types, ffs->ev.types + n,
416 ffs->ev.count * sizeof *ffs->ev.types);
421 spin_unlock_irq(&ffs->ev.waitq.lock);
422 mutex_unlock(&ffs->mutex);
424 return unlikely(__copy_to_user(buf, events, sizeof events))
425 ? -EFAULT : sizeof events;
428 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
429 size_t len, loff_t *ptr)
431 struct ffs_data *ffs = file->private_data;
438 /* Fast check if setup was canceled */
439 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
443 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
444 if (unlikely(ret < 0))
448 if (ffs->state != FFS_ACTIVE) {
454 * We're called from user space, we can use _irq rather then
457 spin_lock_irq(&ffs->ev.waitq.lock);
459 switch (ffs_setup_state_clear_cancelled(ffs)) {
460 case FFS_SETUP_CANCELLED:
465 n = len / sizeof(struct usb_functionfs_event);
471 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
476 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
482 return __ffs_ep0_read_events(ffs, buf,
483 min(n, (size_t)ffs->ev.count));
485 case FFS_SETUP_PENDING:
486 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
487 spin_unlock_irq(&ffs->ev.waitq.lock);
488 ret = __ffs_ep0_stall(ffs);
492 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
494 spin_unlock_irq(&ffs->ev.waitq.lock);
497 data = kmalloc(len, GFP_KERNEL);
498 if (unlikely(!data)) {
504 spin_lock_irq(&ffs->ev.waitq.lock);
506 /* See ffs_ep0_write() */
507 if (ffs_setup_state_clear_cancelled(ffs) ==
508 FFS_SETUP_CANCELLED) {
513 /* unlocks spinlock */
514 ret = __ffs_ep0_queue_wait(ffs, data, len);
515 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
524 spin_unlock_irq(&ffs->ev.waitq.lock);
526 mutex_unlock(&ffs->mutex);
531 static int ffs_ep0_open(struct inode *inode, struct file *file)
533 struct ffs_data *ffs = inode->i_private;
537 if (unlikely(ffs->state == FFS_CLOSING))
540 file->private_data = ffs;
541 ffs_data_opened(ffs);
546 static int ffs_ep0_release(struct inode *inode, struct file *file)
548 struct ffs_data *ffs = file->private_data;
552 ffs_data_closed(ffs);
557 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
559 struct ffs_data *ffs = file->private_data;
560 struct usb_gadget *gadget = ffs->gadget;
565 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
566 struct ffs_function *func = ffs->func;
567 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
568 } else if (gadget && gadget->ops->ioctl) {
569 ret = gadget->ops->ioctl(gadget, code, value);
577 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
579 struct ffs_data *ffs = file->private_data;
580 unsigned int mask = POLLWRNORM;
583 poll_wait(file, &ffs->ev.waitq, wait);
585 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
586 if (unlikely(ret < 0))
589 switch (ffs->state) {
590 case FFS_READ_DESCRIPTORS:
591 case FFS_READ_STRINGS:
596 switch (ffs->setup_state) {
602 case FFS_SETUP_PENDING:
603 case FFS_SETUP_CANCELLED:
604 mask |= (POLLIN | POLLOUT);
611 mutex_unlock(&ffs->mutex);
616 static const struct file_operations ffs_ep0_operations = {
619 .open = ffs_ep0_open,
620 .write = ffs_ep0_write,
621 .read = ffs_ep0_read,
622 .release = ffs_ep0_release,
623 .unlocked_ioctl = ffs_ep0_ioctl,
624 .poll = ffs_ep0_poll,
628 /* "Normal" endpoints operations ********************************************/
630 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
633 if (likely(req->context)) {
634 struct ffs_ep *ep = _ep->driver_data;
635 ep->status = req->status ? req->status : req->actual;
636 complete(req->context);
640 static void ffs_user_copy_worker(struct work_struct *work)
642 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
644 int ret = io_data->req->status ? io_data->req->status :
645 io_data->req->actual;
647 if (io_data->read && ret > 0) {
651 for (i = 0; i < io_data->nr_segs; i++) {
652 if (unlikely(copy_to_user(io_data->iovec[i].iov_base,
654 io_data->iovec[i].iov_len))) {
658 pos += io_data->iovec[i].iov_len;
660 unuse_mm(io_data->mm);
663 aio_complete(io_data->kiocb, ret, ret);
665 usb_ep_free_request(io_data->ep, io_data->req);
667 io_data->kiocb->private = NULL;
669 kfree(io_data->iovec);
674 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
675 struct usb_request *req)
677 struct ffs_io_data *io_data = req->context;
681 INIT_WORK(&io_data->work, ffs_user_copy_worker);
682 schedule_work(&io_data->work);
685 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
687 struct ffs_epfile *epfile = file->private_data;
690 ssize_t ret, data_len;
693 /* Are we still active? */
694 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
699 /* Wait for endpoint to be enabled */
702 if (file->f_flags & O_NONBLOCK) {
707 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
715 halt = (!io_data->read == !epfile->in);
716 if (halt && epfile->isoc) {
721 /* Allocate & copy */
724 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
725 * before the waiting completes, so do not assign to 'gadget' earlier
727 struct usb_gadget *gadget = epfile->ffs->gadget;
729 spin_lock_irq(&epfile->ffs->eps_lock);
730 /* In the meantime, endpoint got disabled or changed. */
731 if (epfile->ep != ep) {
732 spin_unlock_irq(&epfile->ffs->eps_lock);
736 * Controller may require buffer size to be aligned to
737 * maxpacketsize of an out endpoint.
739 data_len = io_data->read ?
740 usb_ep_align_maybe(gadget, ep->ep, io_data->len) :
742 spin_unlock_irq(&epfile->ffs->eps_lock);
744 data = kmalloc(data_len, GFP_KERNEL);
747 if (io_data->aio && !io_data->read) {
750 for (i = 0; i < io_data->nr_segs; i++) {
751 if (unlikely(copy_from_user(&data[pos],
752 io_data->iovec[i].iov_base,
753 io_data->iovec[i].iov_len))) {
757 pos += io_data->iovec[i].iov_len;
760 if (!io_data->read &&
761 unlikely(__copy_from_user(data, io_data->buf,
769 /* We will be using request */
770 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
774 spin_lock_irq(&epfile->ffs->eps_lock);
776 if (epfile->ep != ep) {
777 /* In the meantime, endpoint got disabled or changed. */
779 spin_unlock_irq(&epfile->ffs->eps_lock);
782 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
783 usb_ep_set_halt(ep->ep);
784 spin_unlock_irq(&epfile->ffs->eps_lock);
787 /* Fire the request */
788 struct usb_request *req;
791 req = usb_ep_alloc_request(ep->ep, GFP_KERNEL);
796 req->length = io_data->len;
799 io_data->ep = ep->ep;
802 req->context = io_data;
803 req->complete = ffs_epfile_async_io_complete;
805 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
807 usb_ep_free_request(ep->ep, req);
812 spin_unlock_irq(&epfile->ffs->eps_lock);
814 DECLARE_COMPLETION_ONSTACK(done);
818 req->length = io_data->len;
820 req->context = &done;
821 req->complete = ffs_epfile_io_complete;
823 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
825 spin_unlock_irq(&epfile->ffs->eps_lock);
827 if (unlikely(ret < 0)) {
830 wait_for_completion_interruptible(&done))) {
832 usb_ep_dequeue(ep->ep, req);
835 * XXX We may end up silently droping data
836 * here. Since data_len (i.e. req->length) may
837 * be bigger than len (after being rounded up
838 * to maxpacketsize), we may end up with more
839 * data then user space has space for.
842 if (io_data->read && ret > 0) {
843 ret = min_t(size_t, ret, io_data->len);
845 if (unlikely(copy_to_user(io_data->buf,
854 mutex_unlock(&epfile->mutex);
858 spin_unlock_irq(&epfile->ffs->eps_lock);
859 mutex_unlock(&epfile->mutex);
866 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
869 struct ffs_io_data io_data;
874 io_data.read = false;
875 io_data.buf = (char * __user)buf;
878 return ffs_epfile_io(file, &io_data);
882 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
884 struct ffs_io_data io_data;
893 return ffs_epfile_io(file, &io_data);
897 ffs_epfile_open(struct inode *inode, struct file *file)
899 struct ffs_epfile *epfile = inode->i_private;
903 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
906 file->private_data = epfile;
907 ffs_data_opened(epfile->ffs);
912 static int ffs_aio_cancel(struct kiocb *kiocb)
914 struct ffs_io_data *io_data = kiocb->private;
915 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
920 spin_lock_irq(&epfile->ffs->eps_lock);
922 if (likely(io_data && io_data->ep && io_data->req))
923 value = usb_ep_dequeue(io_data->ep, io_data->req);
927 spin_unlock_irq(&epfile->ffs->eps_lock);
932 static ssize_t ffs_epfile_aio_write(struct kiocb *kiocb,
933 const struct iovec *iovec,
934 unsigned long nr_segs, loff_t loff)
936 struct ffs_io_data *io_data;
940 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
941 if (unlikely(!io_data))
945 io_data->read = false;
946 io_data->kiocb = kiocb;
947 io_data->iovec = iovec;
948 io_data->nr_segs = nr_segs;
949 io_data->len = kiocb->ki_nbytes;
950 io_data->mm = current->mm;
952 kiocb->private = io_data;
954 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
956 return ffs_epfile_io(kiocb->ki_filp, io_data);
959 static ssize_t ffs_epfile_aio_read(struct kiocb *kiocb,
960 const struct iovec *iovec,
961 unsigned long nr_segs, loff_t loff)
963 struct ffs_io_data *io_data;
964 struct iovec *iovec_copy;
968 iovec_copy = kmalloc_array(nr_segs, sizeof(*iovec_copy), GFP_KERNEL);
969 if (unlikely(!iovec_copy))
972 memcpy(iovec_copy, iovec, sizeof(struct iovec)*nr_segs);
974 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
975 if (unlikely(!io_data)) {
981 io_data->read = true;
982 io_data->kiocb = kiocb;
983 io_data->iovec = iovec_copy;
984 io_data->nr_segs = nr_segs;
985 io_data->len = kiocb->ki_nbytes;
986 io_data->mm = current->mm;
988 kiocb->private = io_data;
990 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
992 return ffs_epfile_io(kiocb->ki_filp, io_data);
996 ffs_epfile_release(struct inode *inode, struct file *file)
998 struct ffs_epfile *epfile = inode->i_private;
1002 ffs_data_closed(epfile->ffs);
1007 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1008 unsigned long value)
1010 struct ffs_epfile *epfile = file->private_data;
1015 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1018 spin_lock_irq(&epfile->ffs->eps_lock);
1019 if (likely(epfile->ep)) {
1021 case FUNCTIONFS_FIFO_STATUS:
1022 ret = usb_ep_fifo_status(epfile->ep->ep);
1024 case FUNCTIONFS_FIFO_FLUSH:
1025 usb_ep_fifo_flush(epfile->ep->ep);
1028 case FUNCTIONFS_CLEAR_HALT:
1029 ret = usb_ep_clear_halt(epfile->ep->ep);
1031 case FUNCTIONFS_ENDPOINT_REVMAP:
1032 ret = epfile->ep->num;
1034 case FUNCTIONFS_ENDPOINT_DESC:
1037 struct usb_endpoint_descriptor *desc;
1039 switch (epfile->ffs->gadget->speed) {
1040 case USB_SPEED_SUPER:
1043 case USB_SPEED_HIGH:
1049 desc = epfile->ep->descs[desc_idx];
1051 spin_unlock_irq(&epfile->ffs->eps_lock);
1052 ret = copy_to_user((void *)value, desc, sizeof(*desc));
1063 spin_unlock_irq(&epfile->ffs->eps_lock);
1068 static const struct file_operations ffs_epfile_operations = {
1069 .llseek = no_llseek,
1071 .open = ffs_epfile_open,
1072 .write = ffs_epfile_write,
1073 .read = ffs_epfile_read,
1074 .aio_write = ffs_epfile_aio_write,
1075 .aio_read = ffs_epfile_aio_read,
1076 .release = ffs_epfile_release,
1077 .unlocked_ioctl = ffs_epfile_ioctl,
1081 /* File system and super block operations ***********************************/
1084 * Mounting the file system creates a controller file, used first for
1085 * function configuration then later for event monitoring.
1088 static struct inode *__must_check
1089 ffs_sb_make_inode(struct super_block *sb, void *data,
1090 const struct file_operations *fops,
1091 const struct inode_operations *iops,
1092 struct ffs_file_perms *perms)
1094 struct inode *inode;
1098 inode = new_inode(sb);
1100 if (likely(inode)) {
1101 struct timespec current_time = CURRENT_TIME;
1103 inode->i_ino = get_next_ino();
1104 inode->i_mode = perms->mode;
1105 inode->i_uid = perms->uid;
1106 inode->i_gid = perms->gid;
1107 inode->i_atime = current_time;
1108 inode->i_mtime = current_time;
1109 inode->i_ctime = current_time;
1110 inode->i_private = data;
1112 inode->i_fop = fops;
1120 /* Create "regular" file */
1121 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1122 const char *name, void *data,
1123 const struct file_operations *fops)
1125 struct ffs_data *ffs = sb->s_fs_info;
1126 struct dentry *dentry;
1127 struct inode *inode;
1131 dentry = d_alloc_name(sb->s_root, name);
1132 if (unlikely(!dentry))
1135 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1136 if (unlikely(!inode)) {
1141 d_add(dentry, inode);
1146 static const struct super_operations ffs_sb_operations = {
1147 .statfs = simple_statfs,
1148 .drop_inode = generic_delete_inode,
1151 struct ffs_sb_fill_data {
1152 struct ffs_file_perms perms;
1154 const char *dev_name;
1155 struct ffs_data *ffs_data;
1158 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1160 struct ffs_sb_fill_data *data = _data;
1161 struct inode *inode;
1162 struct ffs_data *ffs = data->ffs_data;
1167 data->ffs_data = NULL;
1168 sb->s_fs_info = ffs;
1169 sb->s_blocksize = PAGE_CACHE_SIZE;
1170 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1171 sb->s_magic = FUNCTIONFS_MAGIC;
1172 sb->s_op = &ffs_sb_operations;
1173 sb->s_time_gran = 1;
1176 data->perms.mode = data->root_mode;
1177 inode = ffs_sb_make_inode(sb, NULL,
1178 &simple_dir_operations,
1179 &simple_dir_inode_operations,
1181 sb->s_root = d_make_root(inode);
1182 if (unlikely(!sb->s_root))
1186 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1187 &ffs_ep0_operations)))
1193 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1197 if (!opts || !*opts)
1201 unsigned long value;
1205 comma = strchr(opts, ',');
1210 eq = strchr(opts, '=');
1211 if (unlikely(!eq)) {
1212 pr_err("'=' missing in %s\n", opts);
1218 if (kstrtoul(eq + 1, 0, &value)) {
1219 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1223 /* Interpret option */
1224 switch (eq - opts) {
1226 if (!memcmp(opts, "rmode", 5))
1227 data->root_mode = (value & 0555) | S_IFDIR;
1228 else if (!memcmp(opts, "fmode", 5))
1229 data->perms.mode = (value & 0666) | S_IFREG;
1235 if (!memcmp(opts, "mode", 4)) {
1236 data->root_mode = (value & 0555) | S_IFDIR;
1237 data->perms.mode = (value & 0666) | S_IFREG;
1244 if (!memcmp(opts, "uid", 3)) {
1245 data->perms.uid = make_kuid(current_user_ns(), value);
1246 if (!uid_valid(data->perms.uid)) {
1247 pr_err("%s: unmapped value: %lu\n", opts, value);
1250 } else if (!memcmp(opts, "gid", 3)) {
1251 data->perms.gid = make_kgid(current_user_ns(), value);
1252 if (!gid_valid(data->perms.gid)) {
1253 pr_err("%s: unmapped value: %lu\n", opts, value);
1263 pr_err("%s: invalid option\n", opts);
1267 /* Next iteration */
1276 /* "mount -t functionfs dev_name /dev/function" ends up here */
1278 static struct dentry *
1279 ffs_fs_mount(struct file_system_type *t, int flags,
1280 const char *dev_name, void *opts)
1282 struct ffs_sb_fill_data data = {
1284 .mode = S_IFREG | 0600,
1285 .uid = GLOBAL_ROOT_UID,
1286 .gid = GLOBAL_ROOT_GID,
1288 .root_mode = S_IFDIR | 0500,
1293 struct ffs_data *ffs;
1297 ret = ffs_fs_parse_opts(&data, opts);
1298 if (unlikely(ret < 0))
1299 return ERR_PTR(ret);
1301 ffs = ffs_data_new();
1303 return ERR_PTR(-ENOMEM);
1304 ffs->file_perms = data.perms;
1306 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1307 if (unlikely(!ffs->dev_name)) {
1309 return ERR_PTR(-ENOMEM);
1312 ffs_dev = ffs_acquire_dev(dev_name);
1313 if (IS_ERR(ffs_dev)) {
1315 return ERR_CAST(ffs_dev);
1317 ffs->private_data = ffs_dev;
1318 data.ffs_data = ffs;
1320 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1321 if (IS_ERR(rv) && data.ffs_data) {
1322 ffs_release_dev(data.ffs_data);
1323 ffs_data_put(data.ffs_data);
1329 ffs_fs_kill_sb(struct super_block *sb)
1333 kill_litter_super(sb);
1334 if (sb->s_fs_info) {
1335 ffs_release_dev(sb->s_fs_info);
1336 ffs_data_put(sb->s_fs_info);
1340 static struct file_system_type ffs_fs_type = {
1341 .owner = THIS_MODULE,
1342 .name = "functionfs",
1343 .mount = ffs_fs_mount,
1344 .kill_sb = ffs_fs_kill_sb,
1346 MODULE_ALIAS_FS("functionfs");
1349 /* Driver's main init/cleanup functions *************************************/
1351 static int functionfs_init(void)
1357 ret = register_filesystem(&ffs_fs_type);
1359 pr_info("file system registered\n");
1361 pr_err("failed registering file system (%d)\n", ret);
1366 static void functionfs_cleanup(void)
1370 pr_info("unloading\n");
1371 unregister_filesystem(&ffs_fs_type);
1375 /* ffs_data and ffs_function construction and destruction code **************/
1377 static void ffs_data_clear(struct ffs_data *ffs);
1378 static void ffs_data_reset(struct ffs_data *ffs);
1380 static void ffs_data_get(struct ffs_data *ffs)
1384 atomic_inc(&ffs->ref);
1387 static void ffs_data_opened(struct ffs_data *ffs)
1391 atomic_inc(&ffs->ref);
1392 atomic_inc(&ffs->opened);
1395 static void ffs_data_put(struct ffs_data *ffs)
1399 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1400 pr_info("%s(): freeing\n", __func__);
1401 ffs_data_clear(ffs);
1402 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1403 waitqueue_active(&ffs->ep0req_completion.wait));
1404 kfree(ffs->dev_name);
1409 static void ffs_data_closed(struct ffs_data *ffs)
1413 if (atomic_dec_and_test(&ffs->opened)) {
1414 ffs->state = FFS_CLOSING;
1415 ffs_data_reset(ffs);
1421 static struct ffs_data *ffs_data_new(void)
1423 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1429 atomic_set(&ffs->ref, 1);
1430 atomic_set(&ffs->opened, 0);
1431 ffs->state = FFS_READ_DESCRIPTORS;
1432 mutex_init(&ffs->mutex);
1433 spin_lock_init(&ffs->eps_lock);
1434 init_waitqueue_head(&ffs->ev.waitq);
1435 init_completion(&ffs->ep0req_completion);
1437 /* XXX REVISIT need to update it in some places, or do we? */
1438 ffs->ev.can_stall = 1;
1443 static void ffs_data_clear(struct ffs_data *ffs)
1447 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1450 BUG_ON(ffs->gadget);
1453 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1455 kfree(ffs->raw_descs_data);
1456 kfree(ffs->raw_strings);
1457 kfree(ffs->stringtabs);
1460 static void ffs_data_reset(struct ffs_data *ffs)
1464 ffs_data_clear(ffs);
1466 ffs->epfiles = NULL;
1467 ffs->raw_descs_data = NULL;
1468 ffs->raw_descs = NULL;
1469 ffs->raw_strings = NULL;
1470 ffs->stringtabs = NULL;
1472 ffs->raw_descs_length = 0;
1473 ffs->fs_descs_count = 0;
1474 ffs->hs_descs_count = 0;
1475 ffs->ss_descs_count = 0;
1477 ffs->strings_count = 0;
1478 ffs->interfaces_count = 0;
1483 ffs->state = FFS_READ_DESCRIPTORS;
1484 ffs->setup_state = FFS_NO_SETUP;
1489 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1491 struct usb_gadget_strings **lang;
1496 if (WARN_ON(ffs->state != FFS_ACTIVE
1497 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1500 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1501 if (unlikely(first_id < 0))
1504 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1505 if (unlikely(!ffs->ep0req))
1507 ffs->ep0req->complete = ffs_ep0_complete;
1508 ffs->ep0req->context = ffs;
1510 lang = ffs->stringtabs;
1512 for (; *lang; ++lang) {
1513 struct usb_string *str = (*lang)->strings;
1515 for (; str->s; ++id, ++str)
1520 ffs->gadget = cdev->gadget;
1525 static void functionfs_unbind(struct ffs_data *ffs)
1529 if (!WARN_ON(!ffs->gadget)) {
1530 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1533 clear_bit(FFS_FL_BOUND, &ffs->flags);
1538 static int ffs_epfiles_create(struct ffs_data *ffs)
1540 struct ffs_epfile *epfile, *epfiles;
1545 count = ffs->eps_count;
1546 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1551 for (i = 1; i <= count; ++i, ++epfile) {
1553 mutex_init(&epfile->mutex);
1554 init_waitqueue_head(&epfile->wait);
1555 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1556 sprintf(epfiles->name, "ep%02x", ffs->eps_addrmap[i]);
1558 sprintf(epfiles->name, "ep%u", i);
1559 epfile->dentry = ffs_sb_create_file(ffs->sb, epfiles->name,
1561 &ffs_epfile_operations);
1562 if (unlikely(!epfile->dentry)) {
1563 ffs_epfiles_destroy(epfiles, i - 1);
1568 ffs->epfiles = epfiles;
1572 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1574 struct ffs_epfile *epfile = epfiles;
1578 for (; count; --count, ++epfile) {
1579 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1580 waitqueue_active(&epfile->wait));
1581 if (epfile->dentry) {
1582 d_delete(epfile->dentry);
1583 dput(epfile->dentry);
1584 epfile->dentry = NULL;
1592 static void ffs_func_eps_disable(struct ffs_function *func)
1594 struct ffs_ep *ep = func->eps;
1595 struct ffs_epfile *epfile = func->ffs->epfiles;
1596 unsigned count = func->ffs->eps_count;
1597 unsigned long flags;
1599 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1601 /* pending requests get nuked */
1603 usb_ep_disable(ep->ep);
1609 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1612 static int ffs_func_eps_enable(struct ffs_function *func)
1614 struct ffs_data *ffs = func->ffs;
1615 struct ffs_ep *ep = func->eps;
1616 struct ffs_epfile *epfile = ffs->epfiles;
1617 unsigned count = ffs->eps_count;
1618 unsigned long flags;
1621 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1623 struct usb_endpoint_descriptor *ds;
1626 if (ffs->gadget->speed == USB_SPEED_SUPER)
1628 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1633 /* fall-back to lower speed if desc missing for current speed */
1635 ds = ep->descs[desc_idx];
1636 } while (!ds && --desc_idx >= 0);
1643 ep->ep->driver_data = ep;
1645 ret = usb_ep_enable(ep->ep);
1648 epfile->in = usb_endpoint_dir_in(ds);
1649 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1654 wake_up(&epfile->wait);
1659 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1665 /* Parsing and building descriptors and strings *****************************/
1668 * This validates if data pointed by data is a valid USB descriptor as
1669 * well as record how many interfaces, endpoints and strings are
1670 * required by given configuration. Returns address after the
1671 * descriptor or NULL if data is invalid.
1674 enum ffs_entity_type {
1675 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1678 enum ffs_os_desc_type {
1679 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1682 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1684 struct usb_descriptor_header *desc,
1687 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1688 struct usb_os_desc_header *h, void *data,
1689 unsigned len, void *priv);
1691 static int __must_check ffs_do_single_desc(char *data, unsigned len,
1692 ffs_entity_callback entity,
1695 struct usb_descriptor_header *_ds = (void *)data;
1701 /* At least two bytes are required: length and type */
1703 pr_vdebug("descriptor too short\n");
1707 /* If we have at least as many bytes as the descriptor takes? */
1708 length = _ds->bLength;
1710 pr_vdebug("descriptor longer then available data\n");
1714 #define __entity_check_INTERFACE(val) 1
1715 #define __entity_check_STRING(val) (val)
1716 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1717 #define __entity(type, val) do { \
1718 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1719 if (unlikely(!__entity_check_ ##type(val))) { \
1720 pr_vdebug("invalid entity's value\n"); \
1723 ret = entity(FFS_ ##type, &val, _ds, priv); \
1724 if (unlikely(ret < 0)) { \
1725 pr_debug("entity " #type "(%02x); ret = %d\n", \
1731 /* Parse descriptor depending on type. */
1732 switch (_ds->bDescriptorType) {
1736 case USB_DT_DEVICE_QUALIFIER:
1737 /* function can't have any of those */
1738 pr_vdebug("descriptor reserved for gadget: %d\n",
1739 _ds->bDescriptorType);
1742 case USB_DT_INTERFACE: {
1743 struct usb_interface_descriptor *ds = (void *)_ds;
1744 pr_vdebug("interface descriptor\n");
1745 if (length != sizeof *ds)
1748 __entity(INTERFACE, ds->bInterfaceNumber);
1750 __entity(STRING, ds->iInterface);
1754 case USB_DT_ENDPOINT: {
1755 struct usb_endpoint_descriptor *ds = (void *)_ds;
1756 pr_vdebug("endpoint descriptor\n");
1757 if (length != USB_DT_ENDPOINT_SIZE &&
1758 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1760 __entity(ENDPOINT, ds->bEndpointAddress);
1765 pr_vdebug("hid descriptor\n");
1766 if (length != sizeof(struct hid_descriptor))
1771 if (length != sizeof(struct usb_otg_descriptor))
1775 case USB_DT_INTERFACE_ASSOCIATION: {
1776 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1777 pr_vdebug("interface association descriptor\n");
1778 if (length != sizeof *ds)
1781 __entity(STRING, ds->iFunction);
1785 case USB_DT_SS_ENDPOINT_COMP:
1786 pr_vdebug("EP SS companion descriptor\n");
1787 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1791 case USB_DT_OTHER_SPEED_CONFIG:
1792 case USB_DT_INTERFACE_POWER:
1794 case USB_DT_SECURITY:
1795 case USB_DT_CS_RADIO_CONTROL:
1797 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1801 /* We should never be here */
1802 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1806 pr_vdebug("invalid length: %d (descriptor %d)\n",
1807 _ds->bLength, _ds->bDescriptorType);
1812 #undef __entity_check_DESCRIPTOR
1813 #undef __entity_check_INTERFACE
1814 #undef __entity_check_STRING
1815 #undef __entity_check_ENDPOINT
1820 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1821 ffs_entity_callback entity, void *priv)
1823 const unsigned _len = len;
1824 unsigned long num = 0;
1834 /* Record "descriptor" entity */
1835 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1836 if (unlikely(ret < 0)) {
1837 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1845 ret = ffs_do_single_desc(data, len, entity, priv);
1846 if (unlikely(ret < 0)) {
1847 pr_debug("%s returns %d\n", __func__, ret);
1857 static int __ffs_data_do_entity(enum ffs_entity_type type,
1858 u8 *valuep, struct usb_descriptor_header *desc,
1861 struct ffs_desc_helper *helper = priv;
1862 struct usb_endpoint_descriptor *d;
1867 case FFS_DESCRIPTOR:
1872 * Interfaces are indexed from zero so if we
1873 * encountered interface "n" then there are at least
1876 if (*valuep >= helper->interfaces_count)
1877 helper->interfaces_count = *valuep + 1;
1882 * Strings are indexed from 1 (0 is magic ;) reserved
1883 * for languages list or some such)
1885 if (*valuep > helper->ffs->strings_count)
1886 helper->ffs->strings_count = *valuep;
1891 helper->eps_count++;
1892 if (helper->eps_count >= 15)
1894 /* Check if descriptors for any speed were already parsed */
1895 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
1896 helper->ffs->eps_addrmap[helper->eps_count] =
1897 d->bEndpointAddress;
1898 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
1899 d->bEndpointAddress)
1907 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1908 struct usb_os_desc_header *desc)
1910 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1911 u16 w_index = le16_to_cpu(desc->wIndex);
1913 if (bcd_version != 1) {
1914 pr_vdebug("unsupported os descriptors version: %d",
1920 *next_type = FFS_OS_DESC_EXT_COMPAT;
1923 *next_type = FFS_OS_DESC_EXT_PROP;
1926 pr_vdebug("unsupported os descriptor type: %d", w_index);
1930 return sizeof(*desc);
1934 * Process all extended compatibility/extended property descriptors
1935 * of a feature descriptor
1937 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1938 enum ffs_os_desc_type type,
1940 ffs_os_desc_callback entity,
1942 struct usb_os_desc_header *h)
1945 const unsigned _len = len;
1949 /* loop over all ext compat/ext prop descriptors */
1950 while (feature_count--) {
1951 ret = entity(type, h, data, len, priv);
1952 if (unlikely(ret < 0)) {
1953 pr_debug("bad OS descriptor, type: %d\n", type);
1962 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1963 static int __must_check ffs_do_os_descs(unsigned count,
1964 char *data, unsigned len,
1965 ffs_os_desc_callback entity, void *priv)
1967 const unsigned _len = len;
1968 unsigned long num = 0;
1972 for (num = 0; num < count; ++num) {
1974 enum ffs_os_desc_type type;
1976 struct usb_os_desc_header *desc = (void *)data;
1978 if (len < sizeof(*desc))
1982 * Record "descriptor" entity.
1983 * Process dwLength, bcdVersion, wIndex, get b/wCount.
1984 * Move the data pointer to the beginning of extended
1985 * compatibilities proper or extended properties proper
1986 * portions of the data
1988 if (le32_to_cpu(desc->dwLength) > len)
1991 ret = __ffs_do_os_desc_header(&type, desc);
1992 if (unlikely(ret < 0)) {
1993 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
1998 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2000 feature_count = le16_to_cpu(desc->wCount);
2001 if (type == FFS_OS_DESC_EXT_COMPAT &&
2002 (feature_count > 255 || desc->Reserved))
2008 * Process all function/property descriptors
2009 * of this Feature Descriptor
2011 ret = ffs_do_single_os_desc(data, len, type,
2012 feature_count, entity, priv, desc);
2013 if (unlikely(ret < 0)) {
2014 pr_debug("%s returns %d\n", __func__, ret);
2025 * Validate contents of the buffer from userspace related to OS descriptors.
2027 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2028 struct usb_os_desc_header *h, void *data,
2029 unsigned len, void *priv)
2031 struct ffs_data *ffs = priv;
2037 case FFS_OS_DESC_EXT_COMPAT: {
2038 struct usb_ext_compat_desc *d = data;
2041 if (len < sizeof(*d) ||
2042 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2045 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2046 if (d->Reserved2[i])
2049 length = sizeof(struct usb_ext_compat_desc);
2052 case FFS_OS_DESC_EXT_PROP: {
2053 struct usb_ext_prop_desc *d = data;
2057 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2059 length = le32_to_cpu(d->dwSize);
2060 type = le32_to_cpu(d->dwPropertyDataType);
2061 if (type < USB_EXT_PROP_UNICODE ||
2062 type > USB_EXT_PROP_UNICODE_MULTI) {
2063 pr_vdebug("unsupported os descriptor property type: %d",
2067 pnl = le16_to_cpu(d->wPropertyNameLength);
2068 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2069 if (length != 14 + pnl + pdl) {
2070 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2071 length, pnl, pdl, type);
2074 ++ffs->ms_os_descs_ext_prop_count;
2075 /* property name reported to the host as "WCHAR"s */
2076 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2077 ffs->ms_os_descs_ext_prop_data_len += pdl;
2081 pr_vdebug("unknown descriptor: %d\n", type);
2087 static int __ffs_data_got_descs(struct ffs_data *ffs,
2088 char *const _data, size_t len)
2090 char *data = _data, *raw_descs;
2091 unsigned os_descs_count = 0, counts[3], flags;
2092 int ret = -EINVAL, i;
2093 struct ffs_desc_helper helper;
2097 if (get_unaligned_le32(data + 4) != len)
2100 switch (get_unaligned_le32(data)) {
2101 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2102 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2106 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2107 flags = get_unaligned_le32(data + 8);
2108 ffs->user_flags = flags;
2109 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2110 FUNCTIONFS_HAS_HS_DESC |
2111 FUNCTIONFS_HAS_SS_DESC |
2112 FUNCTIONFS_HAS_MS_OS_DESC |
2113 FUNCTIONFS_VIRTUAL_ADDR)) {
2124 /* Read fs_count, hs_count and ss_count (if present) */
2125 for (i = 0; i < 3; ++i) {
2126 if (!(flags & (1 << i))) {
2128 } else if (len < 4) {
2131 counts[i] = get_unaligned_le32(data);
2136 if (flags & (1 << i)) {
2137 os_descs_count = get_unaligned_le32(data);
2142 /* Read descriptors */
2145 for (i = 0; i < 3; ++i) {
2148 helper.interfaces_count = 0;
2149 helper.eps_count = 0;
2150 ret = ffs_do_descs(counts[i], data, len,
2151 __ffs_data_do_entity, &helper);
2154 if (!ffs->eps_count && !ffs->interfaces_count) {
2155 ffs->eps_count = helper.eps_count;
2156 ffs->interfaces_count = helper.interfaces_count;
2158 if (ffs->eps_count != helper.eps_count) {
2162 if (ffs->interfaces_count != helper.interfaces_count) {
2170 if (os_descs_count) {
2171 ret = ffs_do_os_descs(os_descs_count, data, len,
2172 __ffs_data_do_os_desc, ffs);
2179 if (raw_descs == data || len) {
2184 ffs->raw_descs_data = _data;
2185 ffs->raw_descs = raw_descs;
2186 ffs->raw_descs_length = data - raw_descs;
2187 ffs->fs_descs_count = counts[0];
2188 ffs->hs_descs_count = counts[1];
2189 ffs->ss_descs_count = counts[2];
2190 ffs->ms_os_descs_count = os_descs_count;
2199 static int __ffs_data_got_strings(struct ffs_data *ffs,
2200 char *const _data, size_t len)
2202 u32 str_count, needed_count, lang_count;
2203 struct usb_gadget_strings **stringtabs, *t;
2204 struct usb_string *strings, *s;
2205 const char *data = _data;
2209 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2210 get_unaligned_le32(data + 4) != len))
2212 str_count = get_unaligned_le32(data + 8);
2213 lang_count = get_unaligned_le32(data + 12);
2215 /* if one is zero the other must be zero */
2216 if (unlikely(!str_count != !lang_count))
2219 /* Do we have at least as many strings as descriptors need? */
2220 needed_count = ffs->strings_count;
2221 if (unlikely(str_count < needed_count))
2225 * If we don't need any strings just return and free all
2228 if (!needed_count) {
2233 /* Allocate everything in one chunk so there's less maintenance. */
2237 vla_item(d, struct usb_gadget_strings *, stringtabs,
2239 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2240 vla_item(d, struct usb_string, strings,
2241 lang_count*(needed_count+1));
2243 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2245 if (unlikely(!vlabuf)) {
2250 /* Initialize the VLA pointers */
2251 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2252 t = vla_ptr(vlabuf, d, stringtab);
2255 *stringtabs++ = t++;
2259 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2260 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2261 t = vla_ptr(vlabuf, d, stringtab);
2262 s = vla_ptr(vlabuf, d, strings);
2266 /* For each language */
2270 do { /* lang_count > 0 so we can use do-while */
2271 unsigned needed = needed_count;
2273 if (unlikely(len < 3))
2275 t->language = get_unaligned_le16(data);
2282 /* For each string */
2283 do { /* str_count > 0 so we can use do-while */
2284 size_t length = strnlen(data, len);
2286 if (unlikely(length == len))
2290 * User may provide more strings then we need,
2291 * if that's the case we simply ignore the
2294 if (likely(needed)) {
2296 * s->id will be set while adding
2297 * function to configuration so for
2298 * now just leave garbage here.
2307 } while (--str_count);
2309 s->id = 0; /* terminator */
2313 } while (--lang_count);
2315 /* Some garbage left? */
2320 ffs->stringtabs = stringtabs;
2321 ffs->raw_strings = _data;
2333 /* Events handling and management *******************************************/
2335 static void __ffs_event_add(struct ffs_data *ffs,
2336 enum usb_functionfs_event_type type)
2338 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2342 * Abort any unhandled setup
2344 * We do not need to worry about some cmpxchg() changing value
2345 * of ffs->setup_state without holding the lock because when
2346 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2347 * the source does nothing.
2349 if (ffs->setup_state == FFS_SETUP_PENDING)
2350 ffs->setup_state = FFS_SETUP_CANCELLED;
2353 case FUNCTIONFS_RESUME:
2354 rem_type2 = FUNCTIONFS_SUSPEND;
2356 case FUNCTIONFS_SUSPEND:
2357 case FUNCTIONFS_SETUP:
2359 /* Discard all similar events */
2362 case FUNCTIONFS_BIND:
2363 case FUNCTIONFS_UNBIND:
2364 case FUNCTIONFS_DISABLE:
2365 case FUNCTIONFS_ENABLE:
2366 /* Discard everything other then power management. */
2367 rem_type1 = FUNCTIONFS_SUSPEND;
2368 rem_type2 = FUNCTIONFS_RESUME;
2373 WARN(1, "%d: unknown event, this should not happen\n", type);
2378 u8 *ev = ffs->ev.types, *out = ev;
2379 unsigned n = ffs->ev.count;
2380 for (; n; --n, ++ev)
2381 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2384 pr_vdebug("purging event %d\n", *ev);
2385 ffs->ev.count = out - ffs->ev.types;
2388 pr_vdebug("adding event %d\n", type);
2389 ffs->ev.types[ffs->ev.count++] = type;
2390 wake_up_locked(&ffs->ev.waitq);
2393 static void ffs_event_add(struct ffs_data *ffs,
2394 enum usb_functionfs_event_type type)
2396 unsigned long flags;
2397 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2398 __ffs_event_add(ffs, type);
2399 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2402 /* Bind/unbind USB function hooks *******************************************/
2404 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2408 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2409 if (ffs->eps_addrmap[i] == endpoint_address)
2414 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2415 struct usb_descriptor_header *desc,
2418 struct usb_endpoint_descriptor *ds = (void *)desc;
2419 struct ffs_function *func = priv;
2420 struct ffs_ep *ffs_ep;
2421 unsigned ep_desc_id;
2423 static const char *speed_names[] = { "full", "high", "super" };
2425 if (type != FFS_DESCRIPTOR)
2429 * If ss_descriptors is not NULL, we are reading super speed
2430 * descriptors; if hs_descriptors is not NULL, we are reading high
2431 * speed descriptors; otherwise, we are reading full speed
2434 if (func->function.ss_descriptors) {
2436 func->function.ss_descriptors[(long)valuep] = desc;
2437 } else if (func->function.hs_descriptors) {
2439 func->function.hs_descriptors[(long)valuep] = desc;
2442 func->function.fs_descriptors[(long)valuep] = desc;
2445 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2448 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2452 ffs_ep = func->eps + idx;
2454 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2455 pr_err("two %sspeed descriptors for EP %d\n",
2456 speed_names[ep_desc_id],
2457 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2460 ffs_ep->descs[ep_desc_id] = ds;
2462 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2464 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2465 if (!ds->wMaxPacketSize)
2466 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2468 struct usb_request *req;
2470 u8 bEndpointAddress;
2473 * We back up bEndpointAddress because autoconfig overwrites
2474 * it with physical endpoint address.
2476 bEndpointAddress = ds->bEndpointAddress;
2477 pr_vdebug("autoconfig\n");
2478 ep = usb_ep_autoconfig(func->gadget, ds);
2481 ep->driver_data = func->eps + idx;
2483 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2489 func->eps_revmap[ds->bEndpointAddress &
2490 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2492 * If we use virtual address mapping, we restore
2493 * original bEndpointAddress value.
2495 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2496 ds->bEndpointAddress = bEndpointAddress;
2498 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2503 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2504 struct usb_descriptor_header *desc,
2507 struct ffs_function *func = priv;
2513 case FFS_DESCRIPTOR:
2514 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2519 if (func->interfaces_nums[idx] < 0) {
2520 int id = usb_interface_id(func->conf, &func->function);
2521 if (unlikely(id < 0))
2523 func->interfaces_nums[idx] = id;
2525 newValue = func->interfaces_nums[idx];
2529 /* String' IDs are allocated when fsf_data is bound to cdev */
2530 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2535 * USB_DT_ENDPOINT are handled in
2536 * __ffs_func_bind_do_descs().
2538 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2541 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2542 if (unlikely(!func->eps[idx].ep))
2546 struct usb_endpoint_descriptor **descs;
2547 descs = func->eps[idx].descs;
2548 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2553 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2558 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2559 struct usb_os_desc_header *h, void *data,
2560 unsigned len, void *priv)
2562 struct ffs_function *func = priv;
2566 case FFS_OS_DESC_EXT_COMPAT: {
2567 struct usb_ext_compat_desc *desc = data;
2568 struct usb_os_desc_table *t;
2570 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2571 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2572 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2573 ARRAY_SIZE(desc->CompatibleID) +
2574 ARRAY_SIZE(desc->SubCompatibleID));
2575 length = sizeof(*desc);
2578 case FFS_OS_DESC_EXT_PROP: {
2579 struct usb_ext_prop_desc *desc = data;
2580 struct usb_os_desc_table *t;
2581 struct usb_os_desc_ext_prop *ext_prop;
2582 char *ext_prop_name;
2583 char *ext_prop_data;
2585 t = &func->function.os_desc_table[h->interface];
2586 t->if_id = func->interfaces_nums[h->interface];
2588 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2589 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2591 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2592 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2593 ext_prop->data_len = le32_to_cpu(*(u32 *)
2594 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2595 length = ext_prop->name_len + ext_prop->data_len + 14;
2597 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2598 func->ffs->ms_os_descs_ext_prop_name_avail +=
2601 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2602 func->ffs->ms_os_descs_ext_prop_data_avail +=
2604 memcpy(ext_prop_data,
2605 usb_ext_prop_data_ptr(data, ext_prop->name_len),
2606 ext_prop->data_len);
2607 /* unicode data reported to the host as "WCHAR"s */
2608 switch (ext_prop->type) {
2609 case USB_EXT_PROP_UNICODE:
2610 case USB_EXT_PROP_UNICODE_ENV:
2611 case USB_EXT_PROP_UNICODE_LINK:
2612 case USB_EXT_PROP_UNICODE_MULTI:
2613 ext_prop->data_len *= 2;
2616 ext_prop->data = ext_prop_data;
2618 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2619 ext_prop->name_len);
2620 /* property name reported to the host as "WCHAR"s */
2621 ext_prop->name_len *= 2;
2622 ext_prop->name = ext_prop_name;
2624 t->os_desc->ext_prop_len +=
2625 ext_prop->name_len + ext_prop->data_len + 14;
2626 ++t->os_desc->ext_prop_count;
2627 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2631 pr_vdebug("unknown descriptor: %d\n", type);
2637 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2638 struct usb_configuration *c)
2640 struct ffs_function *func = ffs_func_from_usb(f);
2641 struct f_fs_opts *ffs_opts =
2642 container_of(f->fi, struct f_fs_opts, func_inst);
2648 * Legacy gadget triggers binding in functionfs_ready_callback,
2649 * which already uses locking; taking the same lock here would
2652 * Configfs-enabled gadgets however do need ffs_dev_lock.
2654 if (!ffs_opts->no_configfs)
2656 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2657 func->ffs = ffs_opts->dev->ffs_data;
2658 if (!ffs_opts->no_configfs)
2661 return ERR_PTR(ret);
2664 func->gadget = c->cdev->gadget;
2666 ffs_data_get(func->ffs);
2669 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2670 * configurations are bound in sequence with list_for_each_entry,
2671 * in each configuration its functions are bound in sequence
2672 * with list_for_each_entry, so we assume no race condition
2673 * with regard to ffs_opts->bound access
2675 if (!ffs_opts->refcnt) {
2676 ret = functionfs_bind(func->ffs, c->cdev);
2678 return ERR_PTR(ret);
2681 func->function.strings = func->ffs->stringtabs;
2686 static int _ffs_func_bind(struct usb_configuration *c,
2687 struct usb_function *f)
2689 struct ffs_function *func = ffs_func_from_usb(f);
2690 struct ffs_data *ffs = func->ffs;
2692 const int full = !!func->ffs->fs_descs_count;
2693 const int high = gadget_is_dualspeed(func->gadget) &&
2694 func->ffs->hs_descs_count;
2695 const int super = gadget_is_superspeed(func->gadget) &&
2696 func->ffs->ss_descs_count;
2698 int fs_len, hs_len, ss_len, ret, i;
2700 /* Make it a single chunk, less management later on */
2702 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2703 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2704 full ? ffs->fs_descs_count + 1 : 0);
2705 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2706 high ? ffs->hs_descs_count + 1 : 0);
2707 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2708 super ? ffs->ss_descs_count + 1 : 0);
2709 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2710 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2711 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2712 vla_item_with_sz(d, char[16], ext_compat,
2713 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2714 vla_item_with_sz(d, struct usb_os_desc, os_desc,
2715 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2716 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2717 ffs->ms_os_descs_ext_prop_count);
2718 vla_item_with_sz(d, char, ext_prop_name,
2719 ffs->ms_os_descs_ext_prop_name_len);
2720 vla_item_with_sz(d, char, ext_prop_data,
2721 ffs->ms_os_descs_ext_prop_data_len);
2722 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2727 /* Has descriptors only for speeds gadget does not support */
2728 if (unlikely(!(full | high | super)))
2731 /* Allocate a single chunk, less management later on */
2732 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2733 if (unlikely(!vlabuf))
2736 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2737 ffs->ms_os_descs_ext_prop_name_avail =
2738 vla_ptr(vlabuf, d, ext_prop_name);
2739 ffs->ms_os_descs_ext_prop_data_avail =
2740 vla_ptr(vlabuf, d, ext_prop_data);
2742 /* Copy descriptors */
2743 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2744 ffs->raw_descs_length);
2746 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2747 for (ret = ffs->eps_count; ret; --ret) {
2750 ptr = vla_ptr(vlabuf, d, eps);
2755 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2757 func->eps = vla_ptr(vlabuf, d, eps);
2758 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2761 * Go through all the endpoint descriptors and allocate
2762 * endpoints first, so that later we can rewrite the endpoint
2763 * numbers without worrying that it may be described later on.
2766 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2767 fs_len = ffs_do_descs(ffs->fs_descs_count,
2768 vla_ptr(vlabuf, d, raw_descs),
2770 __ffs_func_bind_do_descs, func);
2771 if (unlikely(fs_len < 0)) {
2780 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2781 hs_len = ffs_do_descs(ffs->hs_descs_count,
2782 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2783 d_raw_descs__sz - fs_len,
2784 __ffs_func_bind_do_descs, func);
2785 if (unlikely(hs_len < 0)) {
2793 if (likely(super)) {
2794 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2795 ss_len = ffs_do_descs(ffs->ss_descs_count,
2796 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2797 d_raw_descs__sz - fs_len - hs_len,
2798 __ffs_func_bind_do_descs, func);
2799 if (unlikely(ss_len < 0)) {
2808 * Now handle interface numbers allocation and interface and
2809 * endpoint numbers rewriting. We can do that in one go
2812 ret = ffs_do_descs(ffs->fs_descs_count +
2813 (high ? ffs->hs_descs_count : 0) +
2814 (super ? ffs->ss_descs_count : 0),
2815 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2816 __ffs_func_bind_do_nums, func);
2817 if (unlikely(ret < 0))
2820 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2821 if (c->cdev->use_os_string)
2822 for (i = 0; i < ffs->interfaces_count; ++i) {
2823 struct usb_os_desc *desc;
2825 desc = func->function.os_desc_table[i].os_desc =
2826 vla_ptr(vlabuf, d, os_desc) +
2827 i * sizeof(struct usb_os_desc);
2828 desc->ext_compat_id =
2829 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2830 INIT_LIST_HEAD(&desc->ext_prop);
2832 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2833 vla_ptr(vlabuf, d, raw_descs) +
2834 fs_len + hs_len + ss_len,
2835 d_raw_descs__sz - fs_len - hs_len - ss_len,
2836 __ffs_func_bind_do_os_desc, func);
2837 if (unlikely(ret < 0))
2839 func->function.os_desc_n =
2840 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2842 /* And we're done */
2843 ffs_event_add(ffs, FUNCTIONFS_BIND);
2847 /* XXX Do we need to release all claimed endpoints here? */
2851 static int ffs_func_bind(struct usb_configuration *c,
2852 struct usb_function *f)
2854 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2856 if (IS_ERR(ffs_opts))
2857 return PTR_ERR(ffs_opts);
2859 return _ffs_func_bind(c, f);
2863 /* Other USB function hooks *************************************************/
2865 static int ffs_func_set_alt(struct usb_function *f,
2866 unsigned interface, unsigned alt)
2868 struct ffs_function *func = ffs_func_from_usb(f);
2869 struct ffs_data *ffs = func->ffs;
2872 if (alt != (unsigned)-1) {
2873 intf = ffs_func_revmap_intf(func, interface);
2874 if (unlikely(intf < 0))
2879 ffs_func_eps_disable(ffs->func);
2881 if (ffs->state != FFS_ACTIVE)
2884 if (alt == (unsigned)-1) {
2886 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2891 ret = ffs_func_eps_enable(func);
2892 if (likely(ret >= 0))
2893 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2897 static void ffs_func_disable(struct usb_function *f)
2899 ffs_func_set_alt(f, 0, (unsigned)-1);
2902 static int ffs_func_setup(struct usb_function *f,
2903 const struct usb_ctrlrequest *creq)
2905 struct ffs_function *func = ffs_func_from_usb(f);
2906 struct ffs_data *ffs = func->ffs;
2907 unsigned long flags;
2912 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2913 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2914 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2915 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2916 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2919 * Most requests directed to interface go through here
2920 * (notable exceptions are set/get interface) so we need to
2921 * handle them. All other either handled by composite or
2922 * passed to usb_configuration->setup() (if one is set). No
2923 * matter, we will handle requests directed to endpoint here
2924 * as well (as it's straightforward) but what to do with any
2927 if (ffs->state != FFS_ACTIVE)
2930 switch (creq->bRequestType & USB_RECIP_MASK) {
2931 case USB_RECIP_INTERFACE:
2932 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2933 if (unlikely(ret < 0))
2937 case USB_RECIP_ENDPOINT:
2938 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2939 if (unlikely(ret < 0))
2941 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2942 ret = func->ffs->eps_addrmap[ret];
2949 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2950 ffs->ev.setup = *creq;
2951 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2952 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2953 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2958 static void ffs_func_suspend(struct usb_function *f)
2961 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2964 static void ffs_func_resume(struct usb_function *f)
2967 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2971 /* Endpoint and interface numbers reverse mapping ***************************/
2973 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2975 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2976 return num ? num : -EDOM;
2979 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2981 short *nums = func->interfaces_nums;
2982 unsigned count = func->ffs->interfaces_count;
2984 for (; count; --count, ++nums) {
2985 if (*nums >= 0 && *nums == intf)
2986 return nums - func->interfaces_nums;
2993 /* Devices management *******************************************************/
2995 static LIST_HEAD(ffs_devices);
2997 static struct ffs_dev *_ffs_do_find_dev(const char *name)
2999 struct ffs_dev *dev;
3001 list_for_each_entry(dev, &ffs_devices, entry) {
3002 if (!dev->name || !name)
3004 if (strcmp(dev->name, name) == 0)
3012 * ffs_lock must be taken by the caller of this function
3014 static struct ffs_dev *_ffs_get_single_dev(void)
3016 struct ffs_dev *dev;
3018 if (list_is_singular(&ffs_devices)) {
3019 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3028 * ffs_lock must be taken by the caller of this function
3030 static struct ffs_dev *_ffs_find_dev(const char *name)
3032 struct ffs_dev *dev;
3034 dev = _ffs_get_single_dev();
3038 return _ffs_do_find_dev(name);
3041 /* Configfs support *********************************************************/
3043 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3045 return container_of(to_config_group(item), struct f_fs_opts,
3049 static void ffs_attr_release(struct config_item *item)
3051 struct f_fs_opts *opts = to_ffs_opts(item);
3053 usb_put_function_instance(&opts->func_inst);
3056 static struct configfs_item_operations ffs_item_ops = {
3057 .release = ffs_attr_release,
3060 static struct config_item_type ffs_func_type = {
3061 .ct_item_ops = &ffs_item_ops,
3062 .ct_owner = THIS_MODULE,
3066 /* Function registration interface ******************************************/
3068 static void ffs_free_inst(struct usb_function_instance *f)
3070 struct f_fs_opts *opts;
3072 opts = to_f_fs_opts(f);
3074 _ffs_free_dev(opts->dev);
3079 #define MAX_INST_NAME_LEN 40
3081 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3083 struct f_fs_opts *opts;
3088 name_len = strlen(name) + 1;
3089 if (name_len > MAX_INST_NAME_LEN)
3090 return -ENAMETOOLONG;
3092 ptr = kstrndup(name, name_len, GFP_KERNEL);
3096 opts = to_f_fs_opts(fi);
3101 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3102 ret = _ffs_name_dev(opts->dev, ptr);
3108 opts->dev->name_allocated = true;
3117 static struct usb_function_instance *ffs_alloc_inst(void)
3119 struct f_fs_opts *opts;
3120 struct ffs_dev *dev;
3122 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3124 return ERR_PTR(-ENOMEM);
3126 opts->func_inst.set_inst_name = ffs_set_inst_name;
3127 opts->func_inst.free_func_inst = ffs_free_inst;
3129 dev = _ffs_alloc_dev();
3133 return ERR_CAST(dev);
3138 config_group_init_type_name(&opts->func_inst.group, "",
3140 return &opts->func_inst;
3143 static void ffs_free(struct usb_function *f)
3145 kfree(ffs_func_from_usb(f));
3148 static void ffs_func_unbind(struct usb_configuration *c,
3149 struct usb_function *f)
3151 struct ffs_function *func = ffs_func_from_usb(f);
3152 struct ffs_data *ffs = func->ffs;
3153 struct f_fs_opts *opts =
3154 container_of(f->fi, struct f_fs_opts, func_inst);
3155 struct ffs_ep *ep = func->eps;
3156 unsigned count = ffs->eps_count;
3157 unsigned long flags;
3160 if (ffs->func == func) {
3161 ffs_func_eps_disable(func);
3165 if (!--opts->refcnt)
3166 functionfs_unbind(ffs);
3168 /* cleanup after autoconfig */
3169 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3171 if (ep->ep && ep->req)
3172 usb_ep_free_request(ep->ep, ep->req);
3176 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3180 * eps, descriptors and interfaces_nums are allocated in the
3181 * same chunk so only one free is required.
3183 func->function.fs_descriptors = NULL;
3184 func->function.hs_descriptors = NULL;
3185 func->function.ss_descriptors = NULL;
3186 func->interfaces_nums = NULL;
3188 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3191 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3193 struct ffs_function *func;
3197 func = kzalloc(sizeof(*func), GFP_KERNEL);
3198 if (unlikely(!func))
3199 return ERR_PTR(-ENOMEM);
3201 func->function.name = "Function FS Gadget";
3203 func->function.bind = ffs_func_bind;
3204 func->function.unbind = ffs_func_unbind;
3205 func->function.set_alt = ffs_func_set_alt;
3206 func->function.disable = ffs_func_disable;
3207 func->function.setup = ffs_func_setup;
3208 func->function.suspend = ffs_func_suspend;
3209 func->function.resume = ffs_func_resume;
3210 func->function.free_func = ffs_free;
3212 return &func->function;
3216 * ffs_lock must be taken by the caller of this function
3218 static struct ffs_dev *_ffs_alloc_dev(void)
3220 struct ffs_dev *dev;
3223 if (_ffs_get_single_dev())
3224 return ERR_PTR(-EBUSY);
3226 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3228 return ERR_PTR(-ENOMEM);
3230 if (list_empty(&ffs_devices)) {
3231 ret = functionfs_init();
3234 return ERR_PTR(ret);
3238 list_add(&dev->entry, &ffs_devices);
3244 * ffs_lock must be taken by the caller of this function
3245 * The caller is responsible for "name" being available whenever f_fs needs it
3247 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3249 struct ffs_dev *existing;
3251 existing = _ffs_do_find_dev(name);
3261 * The caller is responsible for "name" being available whenever f_fs needs it
3263 int ffs_name_dev(struct ffs_dev *dev, const char *name)
3268 ret = _ffs_name_dev(dev, name);
3273 EXPORT_SYMBOL_GPL(ffs_name_dev);
3275 int ffs_single_dev(struct ffs_dev *dev)
3282 if (!list_is_singular(&ffs_devices))
3290 EXPORT_SYMBOL_GPL(ffs_single_dev);
3293 * ffs_lock must be taken by the caller of this function
3295 static void _ffs_free_dev(struct ffs_dev *dev)
3297 list_del(&dev->entry);
3298 if (dev->name_allocated)
3301 if (list_empty(&ffs_devices))
3302 functionfs_cleanup();
3305 static void *ffs_acquire_dev(const char *dev_name)
3307 struct ffs_dev *ffs_dev;
3312 ffs_dev = _ffs_find_dev(dev_name);
3314 ffs_dev = ERR_PTR(-ENOENT);
3315 else if (ffs_dev->mounted)
3316 ffs_dev = ERR_PTR(-EBUSY);
3317 else if (ffs_dev->ffs_acquire_dev_callback &&
3318 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3319 ffs_dev = ERR_PTR(-ENOENT);
3321 ffs_dev->mounted = true;
3327 static void ffs_release_dev(struct ffs_data *ffs_data)
3329 struct ffs_dev *ffs_dev;
3334 ffs_dev = ffs_data->private_data;
3336 ffs_dev->mounted = false;
3338 if (ffs_dev->ffs_release_dev_callback)
3339 ffs_dev->ffs_release_dev_callback(ffs_dev);
3345 static int ffs_ready(struct ffs_data *ffs)
3347 struct ffs_dev *ffs_obj;
3353 ffs_obj = ffs->private_data;
3358 if (WARN_ON(ffs_obj->desc_ready)) {
3363 ffs_obj->desc_ready = true;
3364 ffs_obj->ffs_data = ffs;
3366 if (ffs_obj->ffs_ready_callback)
3367 ret = ffs_obj->ffs_ready_callback(ffs);
3374 static void ffs_closed(struct ffs_data *ffs)
3376 struct ffs_dev *ffs_obj;
3381 ffs_obj = ffs->private_data;
3385 ffs_obj->desc_ready = false;
3387 if (ffs_obj->ffs_closed_callback)
3388 ffs_obj->ffs_closed_callback(ffs);
3390 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
3391 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
3394 unregister_gadget_item(ffs_obj->opts->
3395 func_inst.group.cg_item.ci_parent->ci_parent);
3400 /* Misc helper functions ****************************************************/
3402 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3405 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3406 : mutex_lock_interruptible(mutex);
3409 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3416 data = kmalloc(len, GFP_KERNEL);
3417 if (unlikely(!data))
3418 return ERR_PTR(-ENOMEM);
3420 if (unlikely(__copy_from_user(data, buf, len))) {
3422 return ERR_PTR(-EFAULT);
3425 pr_vdebug("Buffer from user space:\n");
3426 ffs_dump_mem("", data, len);
3431 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3432 MODULE_LICENSE("GPL");
3433 MODULE_AUTHOR("Michal Nazarewicz");