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 <linux/uio.h>
27 #include <linux/ipc_logging.h>
28 #include <asm/unaligned.h>
30 #include <linux/usb/composite.h>
31 #include <linux/usb/functionfs.h>
33 #include <linux/aio.h>
34 #include <linux/mmu_context.h>
35 #include <linux/poll.h>
36 #include <linux/eventfd.h>
40 #include "u_os_desc.h"
43 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
45 #define NUM_PAGES 10 /* # of pages for ipc logging */
47 static void *ffs_ipc_log;
48 #define ffs_log(fmt, ...) do { \
50 ipc_log_string(ffs_ipc_log, "%s: " fmt, __func__, \
52 pr_debug("%s: " fmt, __func__, ##__VA_ARGS__); \
55 /* Reference counter handling */
56 static void ffs_data_get(struct ffs_data *ffs);
57 static void ffs_data_put(struct ffs_data *ffs);
58 /* Creates new ffs_data object. */
59 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
61 /* Opened counter handling. */
62 static void ffs_data_opened(struct ffs_data *ffs);
63 static void ffs_data_closed(struct ffs_data *ffs);
65 /* Called with ffs->mutex held; take over ownership of data. */
66 static int __must_check
67 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
68 static int __must_check
69 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
71 static LIST_HEAD(inst_list);
73 /* ffs instance status */
74 #define INST_NAME_SIZE 16
76 struct ffs_inst_status {
77 char inst_name[INST_NAME_SIZE];
78 struct list_head list;
79 struct mutex ffs_lock;
81 struct f_fs_opts *opts;
82 struct ffs_data *ffs_data;
85 /* Free instance structures */
86 static void ffs_inst_clean(struct f_fs_opts *opts,
87 const char *inst_name);
88 static void ffs_inst_clean_delay(const char *inst_name);
89 static int ffs_inst_exist_check(const char *inst_name);
90 static struct ffs_inst_status *name_to_inst_status(
91 const char *inst_name, bool create_inst);
93 /* The function structure ***************************************************/
96 static bool first_read_done;
99 struct usb_configuration *conf;
100 struct usb_gadget *gadget;
101 struct ffs_data *ffs;
105 short *interfaces_nums;
107 struct usb_function function;
111 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
113 return container_of(f, struct ffs_function, function);
117 static inline enum ffs_setup_state
118 ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
120 return (enum ffs_setup_state)
121 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
125 static void ffs_func_eps_disable(struct ffs_function *func);
126 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
128 static int ffs_func_bind(struct usb_configuration *,
129 struct usb_function *);
130 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
131 static void ffs_func_disable(struct usb_function *);
132 static int ffs_func_setup(struct usb_function *,
133 const struct usb_ctrlrequest *);
134 static void ffs_func_suspend(struct usb_function *);
135 static void ffs_func_resume(struct usb_function *);
138 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
139 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
142 /* The endpoints structures *************************************************/
145 struct usb_ep *ep; /* P: ffs->eps_lock */
146 struct usb_request *req; /* P: epfile->mutex */
148 /* [0]: full speed, [1]: high speed, [2]: super speed */
149 struct usb_endpoint_descriptor *descs[3];
153 int status; /* P: epfile->mutex */
158 /* Protects ep->ep and ep->req. */
160 wait_queue_head_t wait;
163 struct ffs_data *ffs;
164 struct ffs_ep *ep; /* P: ffs->eps_lock */
166 struct dentry *dentry;
170 unsigned char in; /* P: ffs->eps_lock */
171 unsigned char isoc; /* P: ffs->eps_lock */
177 /* ffs_io_data structure ***************************************************/
184 struct iov_iter data;
188 struct mm_struct *mm;
189 struct work_struct work;
192 struct usb_request *req;
194 struct ffs_data *ffs;
197 struct ffs_desc_helper {
198 struct ffs_data *ffs;
199 unsigned interfaces_count;
203 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
204 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
206 static struct dentry *
207 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
208 const struct file_operations *fops);
210 /* Devices management *******************************************************/
212 DEFINE_MUTEX(ffs_lock);
213 EXPORT_SYMBOL_GPL(ffs_lock);
215 static struct ffs_dev *_ffs_find_dev(const char *name);
216 static struct ffs_dev *_ffs_alloc_dev(void);
217 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
218 static void _ffs_free_dev(struct ffs_dev *dev);
219 static void *ffs_acquire_dev(const char *dev_name);
220 static void ffs_release_dev(struct ffs_data *ffs_data);
221 static int ffs_ready(struct ffs_data *ffs);
222 static void ffs_closed(struct ffs_data *ffs);
224 /* Misc helper functions ****************************************************/
226 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
227 __attribute__((warn_unused_result, nonnull));
228 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
229 __attribute__((warn_unused_result, nonnull));
232 /* Control file aka ep0 *****************************************************/
234 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
236 struct ffs_data *ffs = req->context;
238 complete_all(&ffs->ep0req_completion);
241 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
243 struct usb_request *req = ffs->ep0req;
246 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
248 spin_unlock_irq(&ffs->ev.waitq.lock);
250 ffs_log("enter: state %d setup_state %d flags %lu", ffs->state,
251 ffs->setup_state, ffs->flags);
257 * UDC layer requires to provide a buffer even for ZLP, but should
258 * not use it at all. Let's provide some poisoned pointer to catch
259 * possible bug in the driver.
261 if (req->buf == NULL)
262 req->buf = (void *)0xDEADBABE;
264 reinit_completion(&ffs->ep0req_completion);
266 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
267 if (unlikely(ret < 0))
270 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
272 usb_ep_dequeue(ffs->gadget->ep0, req);
276 ffs->setup_state = FFS_NO_SETUP;
278 ffs_log("exit: state %d setup_state %d flags %lu", ffs->state,
279 ffs->setup_state, ffs->flags);
281 return req->status ? req->status : req->actual;
284 static int __ffs_ep0_stall(struct ffs_data *ffs)
286 ffs_log("state %d setup_state %d flags %lu can_stall %d", ffs->state,
287 ffs->setup_state, ffs->flags, ffs->ev.can_stall);
289 if (ffs->ev.can_stall) {
290 pr_vdebug("ep0 stall\n");
291 usb_ep_set_halt(ffs->gadget->ep0);
292 ffs->setup_state = FFS_NO_SETUP;
295 pr_debug("bogus ep0 stall!\n");
300 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
301 size_t len, loff_t *ptr)
303 struct ffs_data *ffs = file->private_data;
309 ffs_log("enter:len %zu state %d setup_state %d flags %lu", len,
310 ffs->state, ffs->setup_state, ffs->flags);
312 ret = ffs_inst_exist_check(ffs->dev_name);
316 /* Fast check if setup was canceled */
317 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
321 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
322 if (unlikely(ret < 0))
326 switch (ffs->state) {
327 case FFS_READ_DESCRIPTORS:
328 case FFS_READ_STRINGS:
330 if (unlikely(len < 16)) {
335 data = ffs_prepare_buffer(buf, len);
342 if (ffs->state == FFS_READ_DESCRIPTORS) {
343 pr_info("read descriptors\n");
344 ret = __ffs_data_got_descs(ffs, data, len);
345 if (unlikely(ret < 0))
348 ffs->state = FFS_READ_STRINGS;
351 pr_info("read strings\n");
352 ret = __ffs_data_got_strings(ffs, data, len);
353 if (unlikely(ret < 0))
356 ret = ffs_epfiles_create(ffs);
358 ffs->state = FFS_CLOSING;
362 ffs->state = FFS_ACTIVE;
363 mutex_unlock(&ffs->mutex);
365 ret = ffs_ready(ffs);
366 if (unlikely(ret < 0)) {
367 ffs->state = FFS_CLOSING;
378 * We're called from user space, we can use _irq
379 * rather then _irqsave
381 spin_lock_irq(&ffs->ev.waitq.lock);
382 switch (ffs_setup_state_clear_cancelled(ffs)) {
383 case FFS_SETUP_CANCELLED:
391 case FFS_SETUP_PENDING:
395 /* FFS_SETUP_PENDING */
396 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
397 spin_unlock_irq(&ffs->ev.waitq.lock);
398 ret = __ffs_ep0_stall(ffs);
402 /* FFS_SETUP_PENDING and not stall */
403 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
405 spin_unlock_irq(&ffs->ev.waitq.lock);
407 data = ffs_prepare_buffer(buf, len);
413 spin_lock_irq(&ffs->ev.waitq.lock);
416 * We are guaranteed to be still in FFS_ACTIVE state
417 * but the state of setup could have changed from
418 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
419 * to check for that. If that happened we copied data
420 * from user space in vain but it's unlikely.
422 * For sure we are not in FFS_NO_SETUP since this is
423 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
424 * transition can be performed and it's protected by
427 if (ffs_setup_state_clear_cancelled(ffs) ==
428 FFS_SETUP_CANCELLED) {
431 spin_unlock_irq(&ffs->ev.waitq.lock);
433 /* unlocks spinlock */
434 ret = __ffs_ep0_queue_wait(ffs, data, len);
444 ffs_log("exit:ret %zu state %d setup_state %d flags %lu", ret,
445 ffs->state, ffs->setup_state, ffs->flags);
447 mutex_unlock(&ffs->mutex);
451 /* Called with ffs->ev.waitq.lock and ffs->mutex held, both released on exit. */
452 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
456 * n cannot be bigger than ffs->ev.count, which cannot be bigger than
457 * size of ffs->ev.types array (which is four) so that's how much space
460 struct usb_functionfs_event events[ARRAY_SIZE(ffs->ev.types)];
461 const size_t size = n * sizeof *events;
464 memset(events, 0, size);
467 events[i].type = ffs->ev.types[i];
468 if (events[i].type == FUNCTIONFS_SETUP) {
469 events[i].u.setup = ffs->ev.setup;
470 ffs->setup_state = FFS_SETUP_PENDING;
476 memmove(ffs->ev.types, ffs->ev.types + n,
477 ffs->ev.count * sizeof *ffs->ev.types);
479 spin_unlock_irq(&ffs->ev.waitq.lock);
481 ffs_log("state %d setup_state %d flags %lu #evt %zu", ffs->state,
482 ffs->setup_state, ffs->flags, n);
484 mutex_unlock(&ffs->mutex);
486 return unlikely(copy_to_user(buf, events, size)) ? -EFAULT : size;
489 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
490 size_t len, loff_t *ptr)
492 struct ffs_data *ffs = file->private_data;
499 ffs_log("enter:len %zu state %d setup_state %d flags %lu", len,
500 ffs->state, ffs->setup_state, ffs->flags);
502 ret = ffs_inst_exist_check(ffs->dev_name);
506 /* Fast check if setup was canceled */
507 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
511 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
512 if (unlikely(ret < 0))
516 if (ffs->state != FFS_ACTIVE) {
522 * We're called from user space, we can use _irq rather then
525 spin_lock_irq(&ffs->ev.waitq.lock);
527 switch (ffs_setup_state_clear_cancelled(ffs)) {
528 case FFS_SETUP_CANCELLED:
533 n = len / sizeof(struct usb_functionfs_event);
539 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
544 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
550 return __ffs_ep0_read_events(ffs, buf,
551 min(n, (size_t)ffs->ev.count));
553 case FFS_SETUP_PENDING:
554 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
555 spin_unlock_irq(&ffs->ev.waitq.lock);
556 ret = __ffs_ep0_stall(ffs);
560 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
562 spin_unlock_irq(&ffs->ev.waitq.lock);
565 data = kmalloc(len, GFP_KERNEL);
566 if (unlikely(!data)) {
572 spin_lock_irq(&ffs->ev.waitq.lock);
574 /* See ffs_ep0_write() */
575 if (ffs_setup_state_clear_cancelled(ffs) ==
576 FFS_SETUP_CANCELLED) {
581 /* unlocks spinlock */
582 ret = __ffs_ep0_queue_wait(ffs, data, len);
583 if (likely(ret > 0) && unlikely(copy_to_user(buf, data, len)))
592 spin_unlock_irq(&ffs->ev.waitq.lock);
594 ffs_log("exit:ret %d state %d setup_state %d flags %lu", ret,
595 ffs->state, ffs->setup_state, ffs->flags);
597 mutex_unlock(&ffs->mutex);
603 static int ffs_ep0_open(struct inode *inode, struct file *file)
605 struct ffs_data *ffs = inode->i_private;
610 ffs_log("state %d setup_state %d flags %lu opened %d", ffs->state,
611 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
613 ret = ffs_inst_exist_check(ffs->dev_name);
617 if (unlikely(ffs->state == FFS_CLOSING))
620 smp_mb__before_atomic();
621 if (atomic_read(&ffs->opened))
624 file->private_data = ffs;
625 ffs_data_opened(ffs);
630 static int ffs_ep0_release(struct inode *inode, struct file *file)
632 struct ffs_data *ffs = file->private_data;
636 ffs_log("state %d setup_state %d flags %lu opened %d", ffs->state,
637 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
639 ffs_data_closed(ffs);
644 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
646 struct ffs_data *ffs = file->private_data;
647 struct usb_gadget *gadget = ffs->gadget;
652 ffs_log("state %d setup_state %d flags %lu opened %d", ffs->state,
653 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
655 ret = ffs_inst_exist_check(ffs->dev_name);
659 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
660 struct ffs_function *func = ffs->func;
661 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
662 } else if (gadget && gadget->ops->ioctl) {
663 ret = gadget->ops->ioctl(gadget, code, value);
671 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
673 struct ffs_data *ffs = file->private_data;
674 unsigned int mask = POLLWRNORM;
677 ffs_log("enter:state %d setup_state %d flags %lu opened %d", ffs->state,
678 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
680 ret = ffs_inst_exist_check(ffs->dev_name);
684 poll_wait(file, &ffs->ev.waitq, wait);
686 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
687 if (unlikely(ret < 0))
690 switch (ffs->state) {
691 case FFS_READ_DESCRIPTORS:
692 case FFS_READ_STRINGS:
697 switch (ffs->setup_state) {
703 case FFS_SETUP_PENDING:
704 case FFS_SETUP_CANCELLED:
705 mask |= (POLLIN | POLLOUT);
710 case FFS_DEACTIVATED:
714 ffs_log("exit: mask %u", mask);
716 mutex_unlock(&ffs->mutex);
721 static const struct file_operations ffs_ep0_operations = {
724 .open = ffs_ep0_open,
725 .write = ffs_ep0_write,
726 .read = ffs_ep0_read,
727 .release = ffs_ep0_release,
728 .unlocked_ioctl = ffs_ep0_ioctl,
729 .poll = ffs_ep0_poll,
733 /* "Normal" endpoints operations ********************************************/
735 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
737 struct ffs_ep *ep = _ep->driver_data;
740 /* req may be freed during unbind */
741 if (ep && ep->req && likely(req->context)) {
742 struct ffs_ep *ep = _ep->driver_data;
743 ep->status = req->status ? req->status : req->actual;
744 /* Set is_busy false to indicate completion of last request */
746 ffs_log("ep status %d for req %pK", ep->status, req);
747 complete(req->context);
751 static void ffs_user_copy_worker(struct work_struct *work)
753 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
755 int ret = io_data->req->status ? io_data->req->status :
756 io_data->req->actual;
757 bool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD;
759 ffs_log("enter: ret %d", ret);
761 if (io_data->read && ret > 0) {
762 mm_segment_t oldfs = get_fs();
766 ret = copy_to_iter(io_data->buf, ret, &io_data->data);
767 if (ret != io_data->req->actual && iov_iter_count(&io_data->data))
769 unuse_mm(io_data->mm);
773 io_data->kiocb->ki_complete(io_data->kiocb, ret, ret);
775 if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd)
776 eventfd_signal(io_data->ffs->ffs_eventfd, 1);
778 usb_ep_free_request(io_data->ep, io_data->req);
781 kfree(io_data->to_free);
788 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
789 struct usb_request *req)
791 struct ffs_io_data *io_data = req->context;
797 INIT_WORK(&io_data->work, ffs_user_copy_worker);
798 schedule_work(&io_data->work);
803 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
805 struct ffs_epfile *epfile = file->private_data;
807 struct ffs_data *ffs = epfile->ffs;
809 ssize_t ret, data_len = -EINVAL;
812 ffs_log("enter: epfile name %s epfile err %d (%s)", epfile->name,
813 atomic_read(&epfile->error), io_data->read ? "READ" : "WRITE");
815 ret = ffs_inst_exist_check(epfile->ffs->dev_name);
819 smp_mb__before_atomic();
821 if (atomic_read(&epfile->error))
824 /* Are we still active? */
825 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
830 /* Wait for endpoint to be enabled */
833 if (file->f_flags & O_NONBLOCK) {
838 /* Don't wait on write if device is offline */
839 if (!io_data->read) {
845 * If ep is disabled, this fails all current IOs
846 * and wait for next epfile open to happen.
848 smp_mb__before_atomic();
849 if (!atomic_read(&epfile->error)) {
850 ret = wait_event_interruptible(epfile->wait,
863 halt = (!io_data->read == !epfile->in);
864 if (halt && epfile->isoc) {
869 /* Allocate & copy */
872 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
873 * before the waiting completes, so do not assign to 'gadget' earlier
875 struct usb_gadget *gadget = epfile->ffs->gadget;
878 spin_lock_irq(&epfile->ffs->eps_lock);
879 /* In the meantime, endpoint got disabled or changed. */
880 if (epfile->ep != ep) {
881 spin_unlock_irq(&epfile->ffs->eps_lock);
884 data_len = iov_iter_count(&io_data->data);
886 * Controller may require buffer size to be aligned to
887 * maxpacketsize of an out endpoint.
890 data_len = usb_ep_align_maybe(gadget, ep->ep, data_len);
891 spin_unlock_irq(&epfile->ffs->eps_lock);
893 data = kmalloc(data_len, GFP_KERNEL);
896 if (!io_data->read) {
897 copied = copy_from_iter(data, data_len, &io_data->data);
898 if (copied != data_len) {
905 /* We will be using request */
906 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
910 spin_lock_irq(&epfile->ffs->eps_lock);
912 if (epfile->ep != ep) {
913 /* In the meantime, endpoint got disabled or changed. */
915 spin_unlock_irq(&epfile->ffs->eps_lock);
918 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
919 usb_ep_set_halt(ep->ep);
920 spin_unlock_irq(&epfile->ffs->eps_lock);
923 /* Fire the request */
924 struct usb_request *req;
927 * Sanity Check: even though data_len can't be used
928 * uninitialized at the time I write this comment, some
929 * compilers complain about this situation.
930 * In order to keep the code clean from warnings, data_len is
931 * being initialized to -EINVAL during its declaration, which
932 * means we can't rely on compiler anymore to warn no future
933 * changes won't result in data_len being used uninitialized.
934 * For such reason, we're adding this redundant sanity check
937 if (unlikely(data_len == -EINVAL)) {
938 WARN(1, "%s: data_len == -EINVAL\n", __func__);
944 req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC);
949 req->length = data_len;
952 io_data->ep = ep->ep;
954 io_data->ffs = epfile->ffs;
956 req->context = io_data;
957 req->complete = ffs_epfile_async_io_complete;
959 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
961 usb_ep_free_request(ep->ep, req);
966 spin_unlock_irq(&epfile->ffs->eps_lock);
968 struct completion *done;
972 req->length = data_len;
975 req->complete = ffs_epfile_io_complete;
978 reinit_completion(&epfile->ffs->epout_completion);
979 done = &epfile->ffs->epout_completion;
981 reinit_completion(&epfile->ffs->epin_completion);
982 done = &epfile->ffs->epin_completion;
987 * Don't queue another read request if previous is
990 if (!(io_data->read && ep->is_busy)) {
991 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
995 spin_unlock_irq(&epfile->ffs->eps_lock);
997 if (unlikely(ret < 0)) {
1000 wait_for_completion_interruptible(done))) {
1001 spin_lock_irq(&epfile->ffs->eps_lock);
1003 * While we were acquiring lock endpoint got
1004 * disabled (disconnect) or changed
1005 * (composition switch) ?
1007 if (epfile->ep == ep)
1008 usb_ep_dequeue(ep->ep, req);
1009 spin_unlock_irq(&epfile->ffs->eps_lock);
1013 * XXX We may end up silently droping data
1014 * here. Since data_len (i.e. req->length) may
1015 * be bigger than len (after being rounded up
1016 * to maxpacketsize), we may end up with more
1017 * data then user space has space for.
1019 spin_lock_irq(&epfile->ffs->eps_lock);
1021 * While we were acquiring lock endpoint got
1022 * disabled (disconnect) or changed
1023 * (composition switch) ?
1025 if (epfile->ep == ep) {
1028 first_read_done = true;
1033 /* do wait again if func eps are not enabled */
1034 if (io_data->read && !first_read_done
1036 unsigned short count = ffs->eps_count;
1038 pr_debug("%s: waiting for the online state\n",
1044 spin_unlock_irq(&epfile->ffs->eps_lock);
1045 mutex_unlock(&epfile->mutex);
1046 epfile = ffs->epfiles;
1048 atomic_set(&epfile->error, 0);
1051 epfile = file->private_data;
1055 spin_unlock_irq(&epfile->ffs->eps_lock);
1056 if (io_data->read && ret > 0) {
1058 if (ret > data_len) {
1060 pr_err("More data(%zd) received than intended length(%zu)\n",
1064 ret = copy_to_iter(data, ret, &io_data->data);
1065 pr_debug("copied (%zd) bytes to user space\n", ret);
1067 pr_err("Fail to copy to user\n");
1077 mutex_unlock(&epfile->mutex);
1079 ffs_log("exit:ret %zu", ret);
1084 spin_unlock_irq(&epfile->ffs->eps_lock);
1085 mutex_unlock(&epfile->mutex);
1089 ffs_log("exit: ret %zu", ret);
1095 ffs_epfile_open(struct inode *inode, struct file *file)
1097 struct ffs_epfile *epfile = inode->i_private;
1102 ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1103 epfile->ffs->setup_state, epfile->ffs->flags);
1105 ret = ffs_inst_exist_check(epfile->ffs->dev_name);
1109 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1112 smp_mb__before_atomic();
1113 if (atomic_read(&epfile->opened)) {
1114 pr_err("%s(): ep(%s) is already opened.\n",
1115 __func__, epfile->name);
1119 smp_mb__before_atomic();
1120 atomic_set(&epfile->opened, 1);
1121 file->private_data = epfile;
1122 ffs_data_opened(epfile->ffs);
1124 smp_mb__before_atomic();
1125 atomic_set(&epfile->error, 0);
1126 first_read_done = false;
1128 ffs_log("exit:state %d setup_state %d flag %lu", epfile->ffs->state,
1129 epfile->ffs->setup_state, epfile->ffs->flags);
1134 static int ffs_aio_cancel(struct kiocb *kiocb)
1136 struct ffs_io_data *io_data = kiocb->private;
1137 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
1142 ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1143 epfile->ffs->setup_state, epfile->ffs->flags);
1145 spin_lock_irq(&epfile->ffs->eps_lock);
1147 if (likely(io_data && io_data->ep && io_data->req))
1148 value = usb_ep_dequeue(io_data->ep, io_data->req);
1152 spin_unlock_irq(&epfile->ffs->eps_lock);
1154 ffs_log("exit: value %d", value);
1159 static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
1161 struct ffs_io_data io_data, *p = &io_data;
1168 if (!is_sync_kiocb(kiocb)) {
1169 p = kmalloc(sizeof(io_data), GFP_KERNEL);
1180 p->mm = current->mm;
1185 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1187 res = ffs_epfile_io(kiocb->ki_filp, p);
1188 if (res == -EIOCBQUEUED)
1200 static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
1202 struct ffs_io_data io_data, *p = &io_data;
1209 if (!is_sync_kiocb(kiocb)) {
1210 p = kmalloc(sizeof(io_data), GFP_KERNEL);
1221 p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
1230 p->mm = current->mm;
1235 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1237 res = ffs_epfile_io(kiocb->ki_filp, p);
1238 if (res == -EIOCBQUEUED)
1254 ffs_epfile_release(struct inode *inode, struct file *file)
1256 struct ffs_epfile *epfile = inode->i_private;
1260 ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1261 epfile->ffs->setup_state, epfile->ffs->flags);
1263 smp_mb__before_atomic();
1264 atomic_set(&epfile->opened, 0);
1265 atomic_set(&epfile->error, 1);
1266 ffs_data_closed(epfile->ffs);
1267 file->private_data = NULL;
1274 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1275 unsigned long value)
1277 struct ffs_epfile *epfile = file->private_data;
1282 ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1283 epfile->ffs->setup_state, epfile->ffs->flags);
1285 ret = ffs_inst_exist_check(epfile->ffs->dev_name);
1289 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1292 spin_lock_irq(&epfile->ffs->eps_lock);
1293 if (likely(epfile->ep)) {
1295 case FUNCTIONFS_FIFO_STATUS:
1296 ret = usb_ep_fifo_status(epfile->ep->ep);
1298 case FUNCTIONFS_FIFO_FLUSH:
1299 usb_ep_fifo_flush(epfile->ep->ep);
1302 case FUNCTIONFS_CLEAR_HALT:
1303 ret = usb_ep_clear_halt(epfile->ep->ep);
1305 case FUNCTIONFS_ENDPOINT_REVMAP:
1306 ret = epfile->ep->num;
1308 case FUNCTIONFS_ENDPOINT_DESC:
1311 struct usb_endpoint_descriptor *desc;
1313 switch (epfile->ffs->gadget->speed) {
1314 case USB_SPEED_SUPER:
1317 case USB_SPEED_HIGH:
1323 desc = epfile->ep->descs[desc_idx];
1325 spin_unlock_irq(&epfile->ffs->eps_lock);
1326 ret = copy_to_user((void *)value, desc, sizeof(*desc));
1337 spin_unlock_irq(&epfile->ffs->eps_lock);
1339 ffs_log("exit:ret %d", ret);
1344 static const struct file_operations ffs_epfile_operations = {
1345 .llseek = no_llseek,
1347 .open = ffs_epfile_open,
1348 .write_iter = ffs_epfile_write_iter,
1349 .read_iter = ffs_epfile_read_iter,
1350 .release = ffs_epfile_release,
1351 .unlocked_ioctl = ffs_epfile_ioctl,
1355 /* File system and super block operations ***********************************/
1358 * Mounting the file system creates a controller file, used first for
1359 * function configuration then later for event monitoring.
1362 static struct inode *__must_check
1363 ffs_sb_make_inode(struct super_block *sb, void *data,
1364 const struct file_operations *fops,
1365 const struct inode_operations *iops,
1366 struct ffs_file_perms *perms)
1368 struct inode *inode;
1374 inode = new_inode(sb);
1376 if (likely(inode)) {
1377 struct timespec current_time = CURRENT_TIME;
1379 inode->i_ino = get_next_ino();
1380 inode->i_mode = perms->mode;
1381 inode->i_uid = perms->uid;
1382 inode->i_gid = perms->gid;
1383 inode->i_atime = current_time;
1384 inode->i_mtime = current_time;
1385 inode->i_ctime = current_time;
1386 inode->i_private = data;
1388 inode->i_fop = fops;
1398 /* Create "regular" file */
1399 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1400 const char *name, void *data,
1401 const struct file_operations *fops)
1403 struct ffs_data *ffs = sb->s_fs_info;
1404 struct dentry *dentry;
1405 struct inode *inode;
1411 dentry = d_alloc_name(sb->s_root, name);
1412 if (unlikely(!dentry))
1415 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1416 if (unlikely(!inode)) {
1421 d_add(dentry, inode);
1429 static const struct super_operations ffs_sb_operations = {
1430 .statfs = simple_statfs,
1431 .drop_inode = generic_delete_inode,
1434 struct ffs_sb_fill_data {
1435 struct ffs_file_perms perms;
1437 const char *dev_name;
1439 struct ffs_data *ffs_data;
1442 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1444 struct ffs_sb_fill_data *data = _data;
1445 struct inode *inode;
1446 struct ffs_data *ffs = data->ffs_data;
1453 data->ffs_data = NULL;
1454 sb->s_fs_info = ffs;
1455 sb->s_blocksize = PAGE_CACHE_SIZE;
1456 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1457 sb->s_magic = FUNCTIONFS_MAGIC;
1458 sb->s_op = &ffs_sb_operations;
1459 sb->s_time_gran = 1;
1462 data->perms.mode = data->root_mode;
1463 inode = ffs_sb_make_inode(sb, NULL,
1464 &simple_dir_operations,
1465 &simple_dir_inode_operations,
1467 sb->s_root = d_make_root(inode);
1468 if (unlikely(!sb->s_root))
1472 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1473 &ffs_ep0_operations)))
1481 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1487 if (!opts || !*opts)
1491 unsigned long value;
1495 comma = strchr(opts, ',');
1500 eq = strchr(opts, '=');
1501 if (unlikely(!eq)) {
1502 pr_err("'=' missing in %s\n", opts);
1508 if (kstrtoul(eq + 1, 0, &value)) {
1509 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1513 /* Interpret option */
1514 switch (eq - opts) {
1516 if (!memcmp(opts, "no_disconnect", 13))
1517 data->no_disconnect = !!value;
1522 if (!memcmp(opts, "rmode", 5))
1523 data->root_mode = (value & 0555) | S_IFDIR;
1524 else if (!memcmp(opts, "fmode", 5))
1525 data->perms.mode = (value & 0666) | S_IFREG;
1531 if (!memcmp(opts, "mode", 4)) {
1532 data->root_mode = (value & 0555) | S_IFDIR;
1533 data->perms.mode = (value & 0666) | S_IFREG;
1540 if (!memcmp(opts, "uid", 3)) {
1541 data->perms.uid = make_kuid(current_user_ns(), value);
1542 if (!uid_valid(data->perms.uid)) {
1543 pr_err("%s: unmapped value: %lu\n", opts, value);
1546 } else if (!memcmp(opts, "gid", 3)) {
1547 data->perms.gid = make_kgid(current_user_ns(), value);
1548 if (!gid_valid(data->perms.gid)) {
1549 pr_err("%s: unmapped value: %lu\n", opts, value);
1559 pr_err("%s: invalid option\n", opts);
1563 /* Next iteration */
1574 /* "mount -t functionfs dev_name /dev/function" ends up here */
1576 static struct dentry *
1577 ffs_fs_mount(struct file_system_type *t, int flags,
1578 const char *dev_name, void *opts)
1580 struct ffs_sb_fill_data data = {
1582 .mode = S_IFREG | 0600,
1583 .uid = GLOBAL_ROOT_UID,
1584 .gid = GLOBAL_ROOT_GID,
1586 .root_mode = S_IFDIR | 0500,
1587 .no_disconnect = false,
1592 struct ffs_data *ffs;
1593 struct ffs_inst_status *inst_status;
1599 ret = ffs_fs_parse_opts(&data, opts);
1600 if (unlikely(ret < 0))
1601 return ERR_PTR(ret);
1603 ffs = ffs_data_new();
1605 return ERR_PTR(-ENOMEM);
1606 ffs->file_perms = data.perms;
1607 ffs->no_disconnect = data.no_disconnect;
1609 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1610 if (unlikely(!ffs->dev_name)) {
1612 return ERR_PTR(-ENOMEM);
1615 ffs_dev = ffs_acquire_dev(dev_name);
1616 if (IS_ERR(ffs_dev)) {
1618 return ERR_CAST(ffs_dev);
1620 ffs->private_data = ffs_dev;
1621 data.ffs_data = ffs;
1623 inst_status = name_to_inst_status(ffs->dev_name, false);
1624 if (IS_ERR(inst_status)) {
1625 ffs_log("failed to find instance (%s)\n",
1627 return ERR_PTR(-EINVAL);
1630 /* Store ffs to global status structure */
1632 inst_status->ffs_data = ffs;
1635 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1636 if (IS_ERR(rv) && data.ffs_data) {
1637 ffs_release_dev(data.ffs_data);
1638 ffs_data_put(data.ffs_data);
1647 ffs_fs_kill_sb(struct super_block *sb)
1653 kill_litter_super(sb);
1654 if (sb->s_fs_info) {
1655 ffs_release_dev(sb->s_fs_info);
1656 ffs_data_closed(sb->s_fs_info);
1662 static struct file_system_type ffs_fs_type = {
1663 .owner = THIS_MODULE,
1664 .name = "functionfs",
1665 .mount = ffs_fs_mount,
1666 .kill_sb = ffs_fs_kill_sb,
1668 MODULE_ALIAS_FS("functionfs");
1671 /* Driver's main init/cleanup functions *************************************/
1673 static int functionfs_init(void)
1679 ret = register_filesystem(&ffs_fs_type);
1681 pr_info("file system registered\n");
1683 pr_err("failed registering file system (%d)\n", ret);
1688 static void functionfs_cleanup(void)
1692 pr_info("unloading\n");
1693 unregister_filesystem(&ffs_fs_type);
1696 /* ffs_data and ffs_function construction and destruction code **************/
1698 static void ffs_data_clear(struct ffs_data *ffs);
1699 static void ffs_data_reset(struct ffs_data *ffs);
1701 static void ffs_data_get(struct ffs_data *ffs)
1707 smp_mb__before_atomic();
1708 atomic_inc(&ffs->ref);
1713 static void ffs_data_opened(struct ffs_data *ffs)
1717 ffs_log("enter: state %d setup_state %d flag %lu opened %d", ffs->state,
1718 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
1720 smp_mb__before_atomic();
1721 atomic_inc(&ffs->ref);
1722 if (atomic_add_return(1, &ffs->opened) == 1 &&
1723 ffs->state == FFS_DEACTIVATED) {
1724 ffs->state = FFS_CLOSING;
1725 ffs_data_reset(ffs);
1728 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1729 ffs->setup_state, ffs->flags);
1732 static void ffs_data_put(struct ffs_data *ffs)
1734 struct ffs_inst_status *inst_status;
1735 const char *dev_name;
1741 smp_mb__before_atomic();
1742 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1743 pr_info("%s(): freeing\n", __func__);
1744 /* Clear ffs from global structure */
1745 inst_status = name_to_inst_status(ffs->dev_name, false);
1746 if (!IS_ERR(inst_status)) {
1748 inst_status->ffs_data = NULL;
1751 ffs_data_clear(ffs);
1752 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1753 waitqueue_active(&ffs->ep0req_completion.wait));
1754 dev_name = ffs->dev_name;
1756 ffs_inst_clean_delay(dev_name);
1763 static void ffs_data_closed(struct ffs_data *ffs)
1767 ffs_log("enter: state %d setup_state %d flag %lu opened %d", ffs->state,
1768 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
1770 smp_mb__before_atomic();
1771 if (atomic_dec_and_test(&ffs->opened)) {
1772 if (ffs->no_disconnect) {
1773 ffs->state = FFS_DEACTIVATED;
1775 ffs_epfiles_destroy(ffs->epfiles,
1777 ffs->epfiles = NULL;
1779 if (ffs->setup_state == FFS_SETUP_PENDING)
1780 __ffs_ep0_stall(ffs);
1782 ffs->state = FFS_CLOSING;
1783 ffs_data_reset(ffs);
1787 smp_mb__before_atomic();
1788 if (atomic_read(&ffs->opened) < 0) {
1789 ffs->state = FFS_CLOSING;
1790 ffs_data_reset(ffs);
1793 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1794 ffs->setup_state, ffs->flags);
1799 static struct ffs_data *ffs_data_new(void)
1801 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1809 atomic_set(&ffs->ref, 1);
1810 atomic_set(&ffs->opened, 0);
1811 ffs->state = FFS_READ_DESCRIPTORS;
1812 mutex_init(&ffs->mutex);
1813 spin_lock_init(&ffs->eps_lock);
1814 init_waitqueue_head(&ffs->ev.waitq);
1815 init_completion(&ffs->ep0req_completion);
1816 init_completion(&ffs->epout_completion);
1817 init_completion(&ffs->epin_completion);
1819 /* XXX REVISIT need to update it in some places, or do we? */
1820 ffs->ev.can_stall = 1;
1827 static void ffs_data_clear(struct ffs_data *ffs)
1831 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1832 ffs->setup_state, ffs->flags);
1834 pr_debug("%s: ffs->gadget= %pK, ffs->flags= %lu\n",
1835 __func__, ffs->gadget, ffs->flags);
1839 pr_err("%s: ffs:%pK ffs->gadget= %pK, ffs->flags= %lu\n",
1840 __func__, ffs, ffs->gadget, ffs->flags);
1841 BUG_ON(ffs->gadget);
1844 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1846 if (ffs->ffs_eventfd)
1847 eventfd_ctx_put(ffs->ffs_eventfd);
1849 kfree(ffs->raw_descs_data);
1850 kfree(ffs->raw_strings);
1851 kfree(ffs->stringtabs);
1853 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1854 ffs->setup_state, ffs->flags);
1857 static void ffs_data_reset(struct ffs_data *ffs)
1861 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1862 ffs->setup_state, ffs->flags);
1864 ffs_data_clear(ffs);
1866 ffs->epfiles = NULL;
1867 ffs->raw_descs_data = NULL;
1868 ffs->raw_descs = NULL;
1869 ffs->raw_strings = NULL;
1870 ffs->stringtabs = NULL;
1872 ffs->raw_descs_length = 0;
1873 ffs->fs_descs_count = 0;
1874 ffs->hs_descs_count = 0;
1875 ffs->ss_descs_count = 0;
1877 ffs->strings_count = 0;
1878 ffs->interfaces_count = 0;
1883 ffs->state = FFS_READ_DESCRIPTORS;
1884 ffs->setup_state = FFS_NO_SETUP;
1887 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1888 ffs->setup_state, ffs->flags);
1892 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1894 struct usb_gadget_strings **lang;
1899 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1900 ffs->setup_state, ffs->flags);
1902 if (WARN_ON(ffs->state != FFS_ACTIVE
1903 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1906 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1907 if (unlikely(first_id < 0))
1910 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1911 if (unlikely(!ffs->ep0req))
1913 ffs->ep0req->complete = ffs_ep0_complete;
1914 ffs->ep0req->context = ffs;
1916 lang = ffs->stringtabs;
1918 for (; *lang; ++lang) {
1919 struct usb_string *str = (*lang)->strings;
1921 for (; str->s; ++id, ++str)
1926 ffs->gadget = cdev->gadget;
1928 ffs_log("exit: state %d setup_state %d flag %lu gadget %pK\n",
1929 ffs->state, ffs->setup_state, ffs->flags, ffs->gadget);
1935 static void functionfs_unbind(struct ffs_data *ffs)
1939 if (!WARN_ON(!ffs->gadget)) {
1940 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1943 clear_bit(FFS_FL_BOUND, &ffs->flags);
1944 ffs_log("state %d setup_state %d flag %lu gadget %pK\n",
1945 ffs->state, ffs->setup_state, ffs->flags, ffs->gadget);
1950 static int ffs_epfiles_create(struct ffs_data *ffs)
1952 struct ffs_epfile *epfile, *epfiles;
1957 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1958 ffs->setup_state, ffs->flags);
1960 count = ffs->eps_count;
1961 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1966 for (i = 1; i <= count; ++i, ++epfile) {
1968 mutex_init(&epfile->mutex);
1969 init_waitqueue_head(&epfile->wait);
1970 atomic_set(&epfile->opened, 0);
1971 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1972 sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
1974 sprintf(epfile->name, "ep%u", i);
1975 epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
1977 &ffs_epfile_operations);
1978 if (unlikely(!epfile->dentry)) {
1979 ffs_epfiles_destroy(epfiles, i - 1);
1984 ffs->epfiles = epfiles;
1986 ffs_log("exit: eps_count %u state %d setup_state %d flag %lu",
1987 count, ffs->state, ffs->setup_state, ffs->flags);
1992 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1994 struct ffs_epfile *epfile = epfiles;
1998 ffs_log("enter: count %u", count);
2000 for (; count; --count, ++epfile) {
2001 BUG_ON(mutex_is_locked(&epfile->mutex) ||
2002 waitqueue_active(&epfile->wait));
2003 if (epfile->dentry) {
2004 d_delete(epfile->dentry);
2005 dput(epfile->dentry);
2006 epfile->dentry = NULL;
2015 static void ffs_func_eps_disable(struct ffs_function *func)
2017 struct ffs_ep *ep = func->eps;
2018 struct ffs_epfile *epfile = func->ffs->epfiles;
2019 unsigned count = func->ffs->eps_count;
2020 unsigned long flags;
2022 ffs_log("enter: state %d setup_state %d flag %lu", func->ffs->state,
2023 func->ffs->setup_state, func->ffs->flags);
2025 spin_lock_irqsave(&func->ffs->eps_lock, flags);
2028 smp_mb__before_atomic();
2030 atomic_set(&epfile->error, 1);
2032 /* pending requests get nuked */
2034 usb_ep_disable(ep->ep);
2038 atomic_set(&epfile->error, 1);
2043 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2048 static int ffs_func_eps_enable(struct ffs_function *func)
2050 struct ffs_data *ffs = func->ffs;
2051 struct ffs_ep *ep = func->eps;
2052 struct ffs_epfile *epfile = ffs->epfiles;
2053 unsigned count = ffs->eps_count;
2054 unsigned long flags;
2057 ffs_log("enter: state %d setup_state %d flag %lu", func->ffs->state,
2058 func->ffs->setup_state, func->ffs->flags);
2060 spin_lock_irqsave(&func->ffs->eps_lock, flags);
2062 struct usb_endpoint_descriptor *ds;
2065 if (ffs->gadget->speed == USB_SPEED_SUPER)
2067 else if (ffs->gadget->speed == USB_SPEED_HIGH)
2072 /* fall-back to lower speed if desc missing for current speed */
2074 ds = ep->descs[desc_idx];
2075 } while (!ds && --desc_idx >= 0);
2082 ep->ep->driver_data = ep;
2085 ret = config_ep_by_speed(func->gadget, &func->function, ep->ep);
2087 pr_err("%s(): config_ep_by_speed(%d) err for %s\n",
2088 __func__, ret, ep->ep->name);
2093 * userspace setting maxburst > 1 results more fifo
2094 * allocation than without maxburst. Change maxburst to 1
2095 * only to allocate fifo size of max packet size.
2097 ep->ep->maxburst = 1;
2098 ret = usb_ep_enable(ep->ep);
2101 epfile->in = usb_endpoint_dir_in(ds);
2102 epfile->isoc = usb_endpoint_xfer_isoc(ds);
2103 ffs_log("usb_ep_enable %s", ep->ep->name);
2108 wake_up(&epfile->wait);
2113 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2115 ffs_log("exit: ret %d", ret);
2121 /* Parsing and building descriptors and strings *****************************/
2124 * This validates if data pointed by data is a valid USB descriptor as
2125 * well as record how many interfaces, endpoints and strings are
2126 * required by given configuration. Returns address after the
2127 * descriptor or NULL if data is invalid.
2130 enum ffs_entity_type {
2131 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
2134 enum ffs_os_desc_type {
2135 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
2138 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
2140 struct usb_descriptor_header *desc,
2143 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
2144 struct usb_os_desc_header *h, void *data,
2145 unsigned len, void *priv);
2147 static int __must_check ffs_do_single_desc(char *data, unsigned len,
2148 ffs_entity_callback entity,
2151 struct usb_descriptor_header *_ds = (void *)data;
2157 ffs_log("enter: len %u", len);
2159 /* At least two bytes are required: length and type */
2161 pr_vdebug("descriptor too short\n");
2165 /* If we have at least as many bytes as the descriptor takes? */
2166 length = _ds->bLength;
2168 pr_vdebug("descriptor longer then available data\n");
2172 #define __entity_check_INTERFACE(val) 1
2173 #define __entity_check_STRING(val) (val)
2174 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
2175 #define __entity(type, val) do { \
2176 pr_vdebug("entity " #type "(%02x)\n", (val)); \
2177 if (unlikely(!__entity_check_ ##type(val))) { \
2178 pr_vdebug("invalid entity's value\n"); \
2181 ret = entity(FFS_ ##type, &val, _ds, priv); \
2182 if (unlikely(ret < 0)) { \
2183 pr_debug("entity " #type "(%02x); ret = %d\n", \
2189 /* Parse descriptor depending on type. */
2190 switch (_ds->bDescriptorType) {
2194 case USB_DT_DEVICE_QUALIFIER:
2195 /* function can't have any of those */
2196 pr_vdebug("descriptor reserved for gadget: %d\n",
2197 _ds->bDescriptorType);
2200 case USB_DT_INTERFACE: {
2201 struct usb_interface_descriptor *ds = (void *)_ds;
2202 pr_vdebug("interface descriptor\n");
2203 if (length != sizeof *ds)
2206 __entity(INTERFACE, ds->bInterfaceNumber);
2208 __entity(STRING, ds->iInterface);
2212 case USB_DT_ENDPOINT: {
2213 struct usb_endpoint_descriptor *ds = (void *)_ds;
2214 pr_vdebug("endpoint descriptor\n");
2215 if (length != USB_DT_ENDPOINT_SIZE &&
2216 length != USB_DT_ENDPOINT_AUDIO_SIZE)
2218 __entity(ENDPOINT, ds->bEndpointAddress);
2223 pr_vdebug("hid descriptor\n");
2224 if (length != sizeof(struct hid_descriptor))
2229 if (length != sizeof(struct usb_otg_descriptor))
2233 case USB_DT_INTERFACE_ASSOCIATION: {
2234 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
2235 pr_vdebug("interface association descriptor\n");
2236 if (length != sizeof *ds)
2239 __entity(STRING, ds->iFunction);
2243 case USB_DT_SS_ENDPOINT_COMP:
2244 pr_vdebug("EP SS companion descriptor\n");
2245 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
2249 case USB_DT_OTHER_SPEED_CONFIG:
2250 case USB_DT_INTERFACE_POWER:
2252 case USB_DT_SECURITY:
2253 case USB_DT_CS_RADIO_CONTROL:
2255 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
2259 /* We should never be here */
2260 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
2264 pr_vdebug("invalid length: %d (descriptor %d)\n",
2265 _ds->bLength, _ds->bDescriptorType);
2270 #undef __entity_check_DESCRIPTOR
2271 #undef __entity_check_INTERFACE
2272 #undef __entity_check_STRING
2273 #undef __entity_check_ENDPOINT
2275 ffs_log("exit: desc type %d length %d", _ds->bDescriptorType, length);
2280 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
2281 ffs_entity_callback entity, void *priv)
2283 const unsigned _len = len;
2284 unsigned long num = 0;
2288 ffs_log("enter: len %u", len);
2296 /* Record "descriptor" entity */
2297 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
2298 if (unlikely(ret < 0)) {
2299 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
2307 ret = ffs_do_single_desc(data, len, entity, priv);
2308 if (unlikely(ret < 0)) {
2309 pr_debug("%s returns %d\n", __func__, ret);
2318 ffs_log("exit: len %u", len);
2321 static int __ffs_data_do_entity(enum ffs_entity_type type,
2322 u8 *valuep, struct usb_descriptor_header *desc,
2325 struct ffs_desc_helper *helper = priv;
2326 struct usb_endpoint_descriptor *d;
2330 ffs_log("enter: type %u", type);
2333 case FFS_DESCRIPTOR:
2338 * Interfaces are indexed from zero so if we
2339 * encountered interface "n" then there are at least
2342 if (*valuep >= helper->interfaces_count)
2343 helper->interfaces_count = *valuep + 1;
2348 * Strings are indexed from 1 (0 is magic ;) reserved
2349 * for languages list or some such)
2351 if (*valuep > helper->ffs->strings_count)
2352 helper->ffs->strings_count = *valuep;
2357 helper->eps_count++;
2358 if (helper->eps_count >= 15)
2360 /* Check if descriptors for any speed were already parsed */
2361 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
2362 helper->ffs->eps_addrmap[helper->eps_count] =
2363 d->bEndpointAddress;
2364 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
2365 d->bEndpointAddress)
2375 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
2376 struct usb_os_desc_header *desc)
2378 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
2379 u16 w_index = le16_to_cpu(desc->wIndex);
2383 if (bcd_version != 1) {
2384 pr_vdebug("unsupported os descriptors version: %d",
2390 *next_type = FFS_OS_DESC_EXT_COMPAT;
2393 *next_type = FFS_OS_DESC_EXT_PROP;
2396 pr_vdebug("unsupported os descriptor type: %d", w_index);
2400 ffs_log("exit: size of desc %zu", sizeof(*desc));
2402 return sizeof(*desc);
2406 * Process all extended compatibility/extended property descriptors
2407 * of a feature descriptor
2409 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
2410 enum ffs_os_desc_type type,
2412 ffs_os_desc_callback entity,
2414 struct usb_os_desc_header *h)
2417 const unsigned _len = len;
2421 ffs_log("enter: len %u os desc type %d", len, type);
2423 /* loop over all ext compat/ext prop descriptors */
2424 while (feature_count--) {
2425 ret = entity(type, h, data, len, priv);
2426 if (unlikely(ret < 0)) {
2427 pr_debug("bad OS descriptor, type: %d\n", type);
2439 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
2440 static int __must_check ffs_do_os_descs(unsigned count,
2441 char *data, unsigned len,
2442 ffs_os_desc_callback entity, void *priv)
2444 const unsigned _len = len;
2445 unsigned long num = 0;
2449 ffs_log("enter: len %u", len);
2451 for (num = 0; num < count; ++num) {
2453 enum ffs_os_desc_type type;
2455 struct usb_os_desc_header *desc = (void *)data;
2457 if (len < sizeof(*desc))
2461 * Record "descriptor" entity.
2462 * Process dwLength, bcdVersion, wIndex, get b/wCount.
2463 * Move the data pointer to the beginning of extended
2464 * compatibilities proper or extended properties proper
2465 * portions of the data
2467 if (le32_to_cpu(desc->dwLength) > len)
2470 ret = __ffs_do_os_desc_header(&type, desc);
2471 if (unlikely(ret < 0)) {
2472 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
2477 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2479 feature_count = le16_to_cpu(desc->wCount);
2480 if (type == FFS_OS_DESC_EXT_COMPAT &&
2481 (feature_count > 255 || desc->Reserved))
2487 * Process all function/property descriptors
2488 * of this Feature Descriptor
2490 ret = ffs_do_single_os_desc(data, len, type,
2491 feature_count, entity, priv, desc);
2492 if (unlikely(ret < 0)) {
2493 pr_debug("%s returns %d\n", __func__, ret);
2507 * Validate contents of the buffer from userspace related to OS descriptors.
2509 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2510 struct usb_os_desc_header *h, void *data,
2511 unsigned len, void *priv)
2513 struct ffs_data *ffs = priv;
2518 ffs_log("enter: len %u", len);
2521 case FFS_OS_DESC_EXT_COMPAT: {
2522 struct usb_ext_compat_desc *d = data;
2525 if (len < sizeof(*d) ||
2526 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2527 d->Reserved1 != 1) {
2528 pr_err("%s(): Invalid os_desct_ext_compat\n",
2532 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2533 if (d->Reserved2[i]) {
2534 pr_err("%s(): Invalid Reserved2 of ext_compat\n",
2539 length = sizeof(struct usb_ext_compat_desc);
2542 case FFS_OS_DESC_EXT_PROP: {
2543 struct usb_ext_prop_desc *d = data;
2547 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2549 length = le32_to_cpu(d->dwSize);
2552 type = le32_to_cpu(d->dwPropertyDataType);
2553 if (type < USB_EXT_PROP_UNICODE ||
2554 type > USB_EXT_PROP_UNICODE_MULTI) {
2555 pr_vdebug("unsupported os descriptor property type: %d",
2559 pnl = le16_to_cpu(d->wPropertyNameLength);
2560 if (length < 14 + pnl) {
2561 pr_vdebug("invalid os descriptor length: %d pnl:%d (descriptor %d)\n",
2565 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2566 if (length != 14 + pnl + pdl) {
2567 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2568 length, pnl, pdl, type);
2571 ++ffs->ms_os_descs_ext_prop_count;
2572 /* property name reported to the host as "WCHAR"s */
2573 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2574 ffs->ms_os_descs_ext_prop_data_len += pdl;
2578 pr_vdebug("unknown descriptor: %d\n", type);
2587 static int __ffs_data_got_descs(struct ffs_data *ffs,
2588 char *const _data, size_t len)
2590 char *data = _data, *raw_descs;
2591 unsigned os_descs_count = 0, counts[3], flags;
2592 int ret = -EINVAL, i;
2593 struct ffs_desc_helper helper;
2597 ffs_log("enter: len %zu", len);
2599 if (get_unaligned_le32(data + 4) != len)
2602 switch (get_unaligned_le32(data)) {
2603 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2604 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2608 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2609 flags = get_unaligned_le32(data + 8);
2610 ffs->user_flags = flags;
2611 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2612 FUNCTIONFS_HAS_HS_DESC |
2613 FUNCTIONFS_HAS_SS_DESC |
2614 FUNCTIONFS_HAS_MS_OS_DESC |
2615 FUNCTIONFS_VIRTUAL_ADDR |
2616 FUNCTIONFS_EVENTFD)) {
2627 if (flags & FUNCTIONFS_EVENTFD) {
2631 eventfd_ctx_fdget((int)get_unaligned_le32(data));
2632 if (IS_ERR(ffs->ffs_eventfd)) {
2633 ret = PTR_ERR(ffs->ffs_eventfd);
2634 ffs->ffs_eventfd = NULL;
2641 /* Read fs_count, hs_count and ss_count (if present) */
2642 for (i = 0; i < 3; ++i) {
2643 if (!(flags & (1 << i))) {
2645 } else if (len < 4) {
2648 counts[i] = get_unaligned_le32(data);
2653 if (flags & (1 << i)) {
2657 os_descs_count = get_unaligned_le32(data);
2662 /* Read descriptors */
2665 for (i = 0; i < 3; ++i) {
2668 helper.interfaces_count = 0;
2669 helper.eps_count = 0;
2670 ret = ffs_do_descs(counts[i], data, len,
2671 __ffs_data_do_entity, &helper);
2674 if (!ffs->eps_count && !ffs->interfaces_count) {
2675 ffs->eps_count = helper.eps_count;
2676 ffs->interfaces_count = helper.interfaces_count;
2678 if (ffs->eps_count != helper.eps_count) {
2682 if (ffs->interfaces_count != helper.interfaces_count) {
2690 if (os_descs_count) {
2691 ret = ffs_do_os_descs(os_descs_count, data, len,
2692 __ffs_data_do_os_desc, ffs);
2699 if (raw_descs == data || len) {
2704 ffs->raw_descs_data = _data;
2705 ffs->raw_descs = raw_descs;
2706 ffs->raw_descs_length = data - raw_descs;
2707 ffs->fs_descs_count = counts[0];
2708 ffs->hs_descs_count = counts[1];
2709 ffs->ss_descs_count = counts[2];
2710 ffs->ms_os_descs_count = os_descs_count;
2718 ffs_log("exit: ret %d", ret);
2722 static int __ffs_data_got_strings(struct ffs_data *ffs,
2723 char *const _data, size_t len)
2725 u32 str_count, needed_count, lang_count;
2726 struct usb_gadget_strings **stringtabs, *t;
2727 struct usb_string *strings, *s;
2728 const char *data = _data;
2732 ffs_log("enter: len %zu", len);
2734 if (unlikely(len < 16 ||
2735 get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2736 get_unaligned_le32(data + 4) != len))
2738 str_count = get_unaligned_le32(data + 8);
2739 lang_count = get_unaligned_le32(data + 12);
2741 /* if one is zero the other must be zero */
2742 if (unlikely(!str_count != !lang_count))
2745 /* Do we have at least as many strings as descriptors need? */
2746 needed_count = ffs->strings_count;
2747 if (unlikely(str_count < needed_count))
2751 * If we don't need any strings just return and free all
2754 if (!needed_count) {
2759 /* Allocate everything in one chunk so there's less maintenance. */
2763 vla_item(d, struct usb_gadget_strings *, stringtabs,
2765 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2766 vla_item(d, struct usb_string, strings,
2767 lang_count*(needed_count+1));
2769 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2771 if (unlikely(!vlabuf)) {
2776 /* Initialize the VLA pointers */
2777 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2778 t = vla_ptr(vlabuf, d, stringtab);
2781 *stringtabs++ = t++;
2785 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2786 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2787 t = vla_ptr(vlabuf, d, stringtab);
2788 s = vla_ptr(vlabuf, d, strings);
2792 /* For each language */
2796 do { /* lang_count > 0 so we can use do-while */
2797 unsigned needed = needed_count;
2799 if (unlikely(len < 3))
2801 t->language = get_unaligned_le16(data);
2808 /* For each string */
2809 do { /* str_count > 0 so we can use do-while */
2810 size_t length = strnlen(data, len);
2812 if (unlikely(length == len))
2816 * User may provide more strings then we need,
2817 * if that's the case we simply ignore the
2820 if (likely(needed)) {
2822 * s->id will be set while adding
2823 * function to configuration so for
2824 * now just leave garbage here.
2833 } while (--str_count);
2835 s->id = 0; /* terminator */
2839 } while (--lang_count);
2841 /* Some garbage left? */
2846 ffs->stringtabs = stringtabs;
2847 ffs->raw_strings = _data;
2856 ffs_log("exit: -EINVAL");
2861 /* Events handling and management *******************************************/
2863 static void __ffs_event_add(struct ffs_data *ffs,
2864 enum usb_functionfs_event_type type)
2866 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2869 ffs_log("enter: type %d state %d setup_state %d flag %lu", type,
2870 ffs->state, ffs->setup_state, ffs->flags);
2873 * Abort any unhandled setup
2875 * We do not need to worry about some cmpxchg() changing value
2876 * of ffs->setup_state without holding the lock because when
2877 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2878 * the source does nothing.
2880 if (ffs->setup_state == FFS_SETUP_PENDING)
2881 ffs->setup_state = FFS_SETUP_CANCELLED;
2884 * Logic of this function guarantees that there are at most four pending
2885 * evens on ffs->ev.types queue. This is important because the queue
2886 * has space for four elements only and __ffs_ep0_read_events function
2887 * depends on that limit as well. If more event types are added, those
2888 * limits have to be revisited or guaranteed to still hold.
2891 case FUNCTIONFS_RESUME:
2892 rem_type2 = FUNCTIONFS_SUSPEND;
2894 case FUNCTIONFS_SUSPEND:
2895 case FUNCTIONFS_SETUP:
2897 /* Discard all similar events */
2900 case FUNCTIONFS_BIND:
2901 case FUNCTIONFS_UNBIND:
2902 case FUNCTIONFS_DISABLE:
2903 case FUNCTIONFS_ENABLE:
2904 /* Discard everything other then power management. */
2905 rem_type1 = FUNCTIONFS_SUSPEND;
2906 rem_type2 = FUNCTIONFS_RESUME;
2911 WARN(1, "%d: unknown event, this should not happen\n", type);
2916 u8 *ev = ffs->ev.types, *out = ev;
2917 unsigned n = ffs->ev.count;
2918 for (; n; --n, ++ev)
2919 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2922 pr_vdebug("purging event %d\n", *ev);
2923 ffs->ev.count = out - ffs->ev.types;
2926 pr_vdebug("adding event %d\n", type);
2927 ffs->ev.types[ffs->ev.count++] = type;
2928 wake_up_locked(&ffs->ev.waitq);
2929 if (ffs->ffs_eventfd)
2930 eventfd_signal(ffs->ffs_eventfd, 1);
2932 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
2933 ffs->setup_state, ffs->flags);
2936 static void ffs_event_add(struct ffs_data *ffs,
2937 enum usb_functionfs_event_type type)
2939 unsigned long flags;
2940 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2941 __ffs_event_add(ffs, type);
2942 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2945 /* Bind/unbind USB function hooks *******************************************/
2947 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2951 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2952 if (ffs->eps_addrmap[i] == endpoint_address)
2957 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2958 struct usb_descriptor_header *desc,
2961 struct usb_endpoint_descriptor *ds = (void *)desc;
2962 struct ffs_function *func = priv;
2963 struct ffs_ep *ffs_ep;
2964 unsigned ep_desc_id;
2966 static const char *speed_names[] = { "full", "high", "super" };
2970 if (type != FFS_DESCRIPTOR)
2974 * If ss_descriptors is not NULL, we are reading super speed
2975 * descriptors; if hs_descriptors is not NULL, we are reading high
2976 * speed descriptors; otherwise, we are reading full speed
2979 if (func->function.ss_descriptors) {
2981 func->function.ss_descriptors[(long)valuep] = desc;
2982 } else if (func->function.hs_descriptors) {
2984 func->function.hs_descriptors[(long)valuep] = desc;
2987 func->function.fs_descriptors[(long)valuep] = desc;
2990 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2993 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2997 ffs_ep = func->eps + idx;
2999 if (unlikely(ffs_ep->descs[ep_desc_id])) {
3000 pr_err("two %sspeed descriptors for EP %d\n",
3001 speed_names[ep_desc_id],
3002 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
3005 ffs_ep->descs[ep_desc_id] = ds;
3007 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
3009 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
3010 if (!ds->wMaxPacketSize)
3011 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
3013 struct usb_request *req;
3015 u8 bEndpointAddress;
3018 * We back up bEndpointAddress because autoconfig overwrites
3019 * it with physical endpoint address.
3021 bEndpointAddress = ds->bEndpointAddress;
3022 pr_vdebug("autoconfig\n");
3023 ep = usb_ep_autoconfig(func->gadget, ds);
3026 ep->driver_data = func->eps + idx;
3028 req = usb_ep_alloc_request(ep, GFP_KERNEL);
3034 func->eps_revmap[ds->bEndpointAddress &
3035 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
3037 * If we use virtual address mapping, we restore
3038 * original bEndpointAddress value.
3040 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3041 ds->bEndpointAddress = bEndpointAddress;
3043 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
3050 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
3051 struct usb_descriptor_header *desc,
3054 struct ffs_function *func = priv;
3058 ffs_log("enter: type %d", type);
3062 case FFS_DESCRIPTOR:
3063 /* Handled in previous pass by __ffs_func_bind_do_descs() */
3068 if (func->interfaces_nums[idx] < 0) {
3069 int id = usb_interface_id(func->conf, &func->function);
3070 if (unlikely(id < 0))
3072 func->interfaces_nums[idx] = id;
3074 newValue = func->interfaces_nums[idx];
3078 /* String' IDs are allocated when fsf_data is bound to cdev */
3079 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
3084 * USB_DT_ENDPOINT are handled in
3085 * __ffs_func_bind_do_descs().
3087 if (desc->bDescriptorType == USB_DT_ENDPOINT)
3090 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
3091 if (unlikely(!func->eps[idx].ep))
3095 struct usb_endpoint_descriptor **descs;
3096 descs = func->eps[idx].descs;
3097 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
3102 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
3105 ffs_log("exit: newValue %d", newValue);
3110 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
3111 struct usb_os_desc_header *h, void *data,
3112 unsigned len, void *priv)
3114 struct ffs_function *func = priv;
3117 ffs_log("enter: type %d", type);
3120 case FFS_OS_DESC_EXT_COMPAT: {
3121 struct usb_ext_compat_desc *desc = data;
3122 struct usb_os_desc_table *t;
3124 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
3125 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
3126 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
3127 ARRAY_SIZE(desc->CompatibleID) +
3128 ARRAY_SIZE(desc->SubCompatibleID));
3129 length = sizeof(*desc);
3132 case FFS_OS_DESC_EXT_PROP: {
3133 struct usb_ext_prop_desc *desc = data;
3134 struct usb_os_desc_table *t;
3135 struct usb_os_desc_ext_prop *ext_prop;
3136 char *ext_prop_name;
3137 char *ext_prop_data;
3139 t = &func->function.os_desc_table[h->interface];
3140 t->if_id = func->interfaces_nums[h->interface];
3142 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
3143 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
3145 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
3146 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
3147 ext_prop->data_len = le32_to_cpu(*(u32 *)
3148 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
3149 length = ext_prop->name_len + ext_prop->data_len + 14;
3151 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
3152 func->ffs->ms_os_descs_ext_prop_name_avail +=
3155 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
3156 func->ffs->ms_os_descs_ext_prop_data_avail +=
3158 memcpy(ext_prop_data,
3159 usb_ext_prop_data_ptr(data, ext_prop->name_len),
3160 ext_prop->data_len);
3161 /* unicode data reported to the host as "WCHAR"s */
3162 switch (ext_prop->type) {
3163 case USB_EXT_PROP_UNICODE:
3164 case USB_EXT_PROP_UNICODE_ENV:
3165 case USB_EXT_PROP_UNICODE_LINK:
3166 case USB_EXT_PROP_UNICODE_MULTI:
3167 ext_prop->data_len *= 2;
3170 ext_prop->data = ext_prop_data;
3172 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
3173 ext_prop->name_len);
3174 /* property name reported to the host as "WCHAR"s */
3175 ext_prop->name_len *= 2;
3176 ext_prop->name = ext_prop_name;
3178 t->os_desc->ext_prop_len +=
3179 ext_prop->name_len + ext_prop->data_len + 14;
3180 ++t->os_desc->ext_prop_count;
3181 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
3185 pr_vdebug("unknown descriptor: %d\n", type);
3193 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
3194 struct usb_configuration *c)
3196 struct ffs_function *func = ffs_func_from_usb(f);
3197 struct f_fs_opts *ffs_opts =
3198 container_of(f->fi, struct f_fs_opts, func_inst);
3206 * Legacy gadget triggers binding in functionfs_ready_callback,
3207 * which already uses locking; taking the same lock here would
3210 * Configfs-enabled gadgets however do need ffs_dev_lock.
3212 if (!ffs_opts->no_configfs)
3214 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
3215 func->ffs = ffs_opts->dev->ffs_data;
3216 if (!ffs_opts->no_configfs)
3219 return ERR_PTR(ret);
3222 func->gadget = c->cdev->gadget;
3225 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
3226 * configurations are bound in sequence with list_for_each_entry,
3227 * in each configuration its functions are bound in sequence
3228 * with list_for_each_entry, so we assume no race condition
3229 * with regard to ffs_opts->bound access
3231 if (!ffs_opts->refcnt) {
3232 ret = functionfs_bind(func->ffs, c->cdev);
3234 return ERR_PTR(ret);
3237 func->function.strings = func->ffs->stringtabs;
3244 static int _ffs_func_bind(struct usb_configuration *c,
3245 struct usb_function *f)
3247 struct ffs_function *func = ffs_func_from_usb(f);
3248 struct ffs_data *ffs = func->ffs;
3250 const int full = !!func->ffs->fs_descs_count;
3251 const int high = !!func->ffs->hs_descs_count;
3252 const int super = !!func->ffs->ss_descs_count;
3254 int fs_len, hs_len, ss_len, ret, i;
3255 struct ffs_ep *eps_ptr;
3257 /* Make it a single chunk, less management later on */
3259 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
3260 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
3261 full ? ffs->fs_descs_count + 1 : 0);
3262 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
3263 high ? ffs->hs_descs_count + 1 : 0);
3264 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
3265 super ? ffs->ss_descs_count + 1 : 0);
3266 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
3267 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
3268 c->cdev->use_os_string ? ffs->interfaces_count : 0);
3269 vla_item_with_sz(d, char[16], ext_compat,
3270 c->cdev->use_os_string ? ffs->interfaces_count : 0);
3271 vla_item_with_sz(d, struct usb_os_desc, os_desc,
3272 c->cdev->use_os_string ? ffs->interfaces_count : 0);
3273 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
3274 ffs->ms_os_descs_ext_prop_count);
3275 vla_item_with_sz(d, char, ext_prop_name,
3276 ffs->ms_os_descs_ext_prop_name_len);
3277 vla_item_with_sz(d, char, ext_prop_data,
3278 ffs->ms_os_descs_ext_prop_data_len);
3279 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
3284 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
3285 ffs->setup_state, ffs->flags);
3287 /* Has descriptors only for speeds gadget does not support */
3288 if (unlikely(!(full | high | super)))
3291 /* Allocate a single chunk, less management later on */
3292 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
3293 if (unlikely(!vlabuf))
3296 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
3297 ffs->ms_os_descs_ext_prop_name_avail =
3298 vla_ptr(vlabuf, d, ext_prop_name);
3299 ffs->ms_os_descs_ext_prop_data_avail =
3300 vla_ptr(vlabuf, d, ext_prop_data);
3302 /* Copy descriptors */
3303 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
3304 ffs->raw_descs_length);
3306 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
3307 eps_ptr = vla_ptr(vlabuf, d, eps);
3308 for (i = 0; i < ffs->eps_count; i++)
3309 eps_ptr[i].num = -1;
3312 * d_eps == vlabuf, func->eps used to kfree vlabuf later
3314 func->eps = vla_ptr(vlabuf, d, eps);
3315 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
3318 * Go through all the endpoint descriptors and allocate
3319 * endpoints first, so that later we can rewrite the endpoint
3320 * numbers without worrying that it may be described later on.
3323 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
3324 fs_len = ffs_do_descs(ffs->fs_descs_count,
3325 vla_ptr(vlabuf, d, raw_descs),
3327 __ffs_func_bind_do_descs, func);
3328 if (unlikely(fs_len < 0)) {
3337 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
3338 hs_len = ffs_do_descs(ffs->hs_descs_count,
3339 vla_ptr(vlabuf, d, raw_descs) + fs_len,
3340 d_raw_descs__sz - fs_len,
3341 __ffs_func_bind_do_descs, func);
3342 if (unlikely(hs_len < 0)) {
3350 if (likely(super)) {
3351 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
3352 ss_len = ffs_do_descs(ffs->ss_descs_count,
3353 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
3354 d_raw_descs__sz - fs_len - hs_len,
3355 __ffs_func_bind_do_descs, func);
3356 if (unlikely(ss_len < 0)) {
3365 * Now handle interface numbers allocation and interface and
3366 * endpoint numbers rewriting. We can do that in one go
3369 ret = ffs_do_descs(ffs->fs_descs_count +
3370 (high ? ffs->hs_descs_count : 0) +
3371 (super ? ffs->ss_descs_count : 0),
3372 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
3373 __ffs_func_bind_do_nums, func);
3374 if (unlikely(ret < 0))
3377 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
3378 if (c->cdev->use_os_string) {
3379 for (i = 0; i < ffs->interfaces_count; ++i) {
3380 struct usb_os_desc *desc;
3382 desc = func->function.os_desc_table[i].os_desc =
3383 vla_ptr(vlabuf, d, os_desc) +
3384 i * sizeof(struct usb_os_desc);
3385 desc->ext_compat_id =
3386 vla_ptr(vlabuf, d, ext_compat) + i * 16;
3387 INIT_LIST_HEAD(&desc->ext_prop);
3389 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
3390 vla_ptr(vlabuf, d, raw_descs) +
3391 fs_len + hs_len + ss_len,
3392 d_raw_descs__sz - fs_len - hs_len -
3394 __ffs_func_bind_do_os_desc, func);
3395 if (unlikely(ret < 0))
3398 func->function.os_desc_n =
3399 c->cdev->use_os_string ? ffs->interfaces_count : 0;
3401 /* And we're done */
3402 ffs_event_add(ffs, FUNCTIONFS_BIND);
3404 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
3405 ffs->setup_state, ffs->flags);
3410 /* XXX Do we need to release all claimed endpoints here? */
3411 ffs_log("exit: ret %d", ret);
3415 static int ffs_func_bind(struct usb_configuration *c,
3416 struct usb_function *f)
3418 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
3419 struct ffs_function *func = ffs_func_from_usb(f);
3424 if (IS_ERR(ffs_opts))
3425 return PTR_ERR(ffs_opts);
3427 ret = _ffs_func_bind(c, f);
3428 if (ret && !--ffs_opts->refcnt)
3429 functionfs_unbind(func->ffs);
3431 ffs_log("exit: ret %d", ret);
3437 /* Other USB function hooks *************************************************/
3439 static void ffs_reset_work(struct work_struct *work)
3441 struct ffs_data *ffs = container_of(work,
3442 struct ffs_data, reset_work);
3446 ffs_data_reset(ffs);
3451 static int ffs_func_set_alt(struct usb_function *f,
3452 unsigned interface, unsigned alt)
3454 struct ffs_function *func = ffs_func_from_usb(f);
3455 struct ffs_data *ffs = func->ffs;
3460 if (alt != (unsigned)-1) {
3461 intf = ffs_func_revmap_intf(func, interface);
3462 if (unlikely(intf < 0))
3467 ffs_func_eps_disable(ffs->func);
3469 /* matching put to allow LPM on disconnect */
3470 usb_gadget_autopm_put_async(ffs->gadget);
3473 if (ffs->state == FFS_DEACTIVATED) {
3474 ffs->state = FFS_CLOSING;
3475 INIT_WORK(&ffs->reset_work, ffs_reset_work);
3476 schedule_work(&ffs->reset_work);
3480 if (ffs->state != FFS_ACTIVE)
3483 if (alt == (unsigned)-1) {
3485 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
3490 ret = ffs_func_eps_enable(func);
3491 if (likely(ret >= 0)) {
3492 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
3493 /* Disable USB LPM later on bus_suspend */
3494 usb_gadget_autopm_get_async(ffs->gadget);
3497 ffs_log("exit: ret %d", ret);
3502 static void ffs_func_disable(struct usb_function *f)
3506 ffs_func_set_alt(f, 0, (unsigned)-1);
3511 static int ffs_func_setup(struct usb_function *f,
3512 const struct usb_ctrlrequest *creq)
3514 struct ffs_function *func = ffs_func_from_usb(f);
3515 struct ffs_data *ffs = func->ffs;
3516 unsigned long flags;
3523 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
3524 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
3525 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
3526 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
3527 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
3530 * Most requests directed to interface go through here
3531 * (notable exceptions are set/get interface) so we need to
3532 * handle them. All other either handled by composite or
3533 * passed to usb_configuration->setup() (if one is set). No
3534 * matter, we will handle requests directed to endpoint here
3535 * as well (as it's straightforward) but what to do with any
3538 if (ffs->state != FFS_ACTIVE)
3541 switch (creq->bRequestType & USB_RECIP_MASK) {
3542 case USB_RECIP_INTERFACE:
3543 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
3544 if (unlikely(ret < 0))
3548 case USB_RECIP_ENDPOINT:
3549 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
3550 if (unlikely(ret < 0))
3552 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3553 ret = func->ffs->eps_addrmap[ret];
3560 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
3561 ffs->ev.setup = *creq;
3562 ffs->ev.setup.wIndex = cpu_to_le16(ret);
3563 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
3564 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
3568 return USB_GADGET_DELAYED_STATUS;
3571 static void ffs_func_suspend(struct usb_function *f)
3577 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
3582 static void ffs_func_resume(struct usb_function *f)
3588 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
3594 /* Endpoint and interface numbers reverse mapping ***************************/
3596 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
3598 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
3599 return num ? num : -EDOM;
3602 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
3604 short *nums = func->interfaces_nums;
3605 unsigned count = func->ffs->interfaces_count;
3609 for (; count; --count, ++nums) {
3610 if (*nums >= 0 && *nums == intf)
3611 return nums - func->interfaces_nums;
3620 /* Devices management *******************************************************/
3622 static LIST_HEAD(ffs_devices);
3624 static struct ffs_dev *_ffs_do_find_dev(const char *name)
3626 struct ffs_dev *dev;
3630 list_for_each_entry(dev, &ffs_devices, entry) {
3631 if (!dev->name || !name)
3633 if (strcmp(dev->name, name) == 0)
3643 * ffs_lock must be taken by the caller of this function
3645 static struct ffs_dev *_ffs_get_single_dev(void)
3647 struct ffs_dev *dev;
3651 if (list_is_singular(&ffs_devices)) {
3652 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3663 * ffs_lock must be taken by the caller of this function
3665 static struct ffs_dev *_ffs_find_dev(const char *name)
3667 struct ffs_dev *dev;
3671 dev = _ffs_get_single_dev();
3675 dev = _ffs_do_find_dev(name);
3682 /* Configfs support *********************************************************/
3684 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3686 return container_of(to_config_group(item), struct f_fs_opts,
3690 static void ffs_attr_release(struct config_item *item)
3692 struct f_fs_opts *opts = to_ffs_opts(item);
3694 usb_put_function_instance(&opts->func_inst);
3697 static struct configfs_item_operations ffs_item_ops = {
3698 .release = ffs_attr_release,
3701 static struct config_item_type ffs_func_type = {
3702 .ct_item_ops = &ffs_item_ops,
3703 .ct_owner = THIS_MODULE,
3707 /* Function registration interface ******************************************/
3709 static struct ffs_inst_status *name_to_inst_status(
3710 const char *inst_name, bool create_inst)
3712 struct ffs_inst_status *inst_status;
3714 list_for_each_entry(inst_status, &inst_list, list) {
3715 if (!strncasecmp(inst_status->inst_name,
3716 inst_name, strlen(inst_name)))
3721 return ERR_PTR(-ENODEV);
3723 inst_status = kzalloc(sizeof(struct ffs_inst_status),
3726 return ERR_PTR(-ENOMEM);
3728 mutex_init(&inst_status->ffs_lock);
3729 snprintf(inst_status->inst_name, INST_NAME_SIZE, inst_name);
3730 list_add_tail(&inst_status->list, &inst_list);
3735 static int ffs_inst_exist_check(const char *inst_name)
3737 struct ffs_inst_status *inst_status;
3739 inst_status = name_to_inst_status(inst_name, false);
3740 if (IS_ERR(inst_status)) {
3742 "%s: failed to find instance (%s)\n",
3743 __func__, inst_name);
3747 mutex_lock(&inst_status->ffs_lock);
3749 if (unlikely(inst_status->inst_exist == false)) {
3750 mutex_unlock(&inst_status->ffs_lock);
3752 "%s: f_fs instance (%s) has been freed already.\n",
3753 __func__, inst_name);
3757 mutex_unlock(&inst_status->ffs_lock);
3762 static void ffs_inst_clean(struct f_fs_opts *opts,
3763 const char *inst_name)
3765 struct ffs_inst_status *inst_status;
3767 inst_status = name_to_inst_status(inst_name, false);
3768 if (IS_ERR(inst_status)) {
3770 "%s: failed to find instance (%s)\n",
3771 __func__, inst_name);
3775 inst_status->opts = NULL;
3778 _ffs_free_dev(opts->dev);
3783 static void ffs_inst_clean_delay(const char *inst_name)
3785 struct ffs_inst_status *inst_status;
3787 inst_status = name_to_inst_status(inst_name, false);
3788 if (IS_ERR(inst_status)) {
3790 "%s: failed to find (%s) instance\n",
3791 __func__, inst_name);
3795 mutex_lock(&inst_status->ffs_lock);
3797 if (unlikely(inst_status->inst_exist == false)) {
3798 if (inst_status->opts) {
3799 ffs_inst_clean(inst_status->opts, inst_name);
3800 pr_err_ratelimited("%s: Delayed free memory\n",
3803 mutex_unlock(&inst_status->ffs_lock);
3807 mutex_unlock(&inst_status->ffs_lock);
3810 static void ffs_free_inst(struct usb_function_instance *f)
3812 struct f_fs_opts *opts;
3813 struct ffs_inst_status *inst_status;
3815 opts = to_f_fs_opts(f);
3817 inst_status = name_to_inst_status(opts->dev->name, false);
3818 if (IS_ERR(inst_status)) {
3819 ffs_log("failed to find (%s) instance\n",
3824 mutex_lock(&inst_status->ffs_lock);
3825 if (opts->dev->ffs_data
3826 && atomic_read(&opts->dev->ffs_data->opened)) {
3827 inst_status->inst_exist = false;
3828 mutex_unlock(&inst_status->ffs_lock);
3829 ffs_log("Dev is open, free mem when dev (%s) close\n",
3834 ffs_inst_clean(opts, opts->dev->name);
3835 inst_status->inst_exist = false;
3836 mutex_unlock(&inst_status->ffs_lock);
3839 #define MAX_INST_NAME_LEN 40
3841 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3843 struct f_fs_opts *opts, *opts_prev;
3844 struct ffs_data *ffs_data_tmp;
3848 struct ffs_inst_status *inst_status;
3850 name_len = strlen(name) + 1;
3851 if (name_len > MAX_INST_NAME_LEN)
3852 return -ENAMETOOLONG;
3854 ptr = kstrndup(name, name_len, GFP_KERNEL);
3858 inst_status = name_to_inst_status(ptr, true);
3859 if (IS_ERR(inst_status)) {
3860 ffs_log("failed to create status struct for (%s) instance\n",
3865 mutex_lock(&inst_status->ffs_lock);
3866 opts_prev = inst_status->opts;
3868 mutex_unlock(&inst_status->ffs_lock);
3869 ffs_log("instance (%s): prev inst do not freed yet\n",
3870 inst_status->inst_name);
3873 mutex_unlock(&inst_status->ffs_lock);
3875 opts = to_f_fs_opts(fi);
3880 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3881 ret = _ffs_name_dev(opts->dev, ptr);
3887 opts->dev->name_allocated = true;
3890 * If ffs instance is freed and created once, new allocated
3891 * opts->dev need to initialize opts->dev->ffs_data, and
3892 * ffs_private_data also need to update new allocated opts->dev
3895 ffs_data_tmp = inst_status->ffs_data;
3897 opts->dev->ffs_data = ffs_data_tmp;
3899 if (opts->dev->ffs_data)
3900 opts->dev->ffs_data->private_data = opts->dev;
3906 mutex_lock(&inst_status->ffs_lock);
3907 inst_status->inst_exist = true;
3908 inst_status->opts = opts;
3909 mutex_unlock(&inst_status->ffs_lock);
3914 static struct usb_function_instance *ffs_alloc_inst(void)
3916 struct f_fs_opts *opts;
3917 struct ffs_dev *dev;
3919 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3921 return ERR_PTR(-ENOMEM);
3923 opts->func_inst.set_inst_name = ffs_set_inst_name;
3924 opts->func_inst.free_func_inst = ffs_free_inst;
3926 dev = _ffs_alloc_dev();
3930 return ERR_CAST(dev);
3935 config_group_init_type_name(&opts->func_inst.group, "",
3937 return &opts->func_inst;
3940 static void ffs_free(struct usb_function *f)
3942 kfree(ffs_func_from_usb(f));
3945 static void ffs_func_unbind(struct usb_configuration *c,
3946 struct usb_function *f)
3948 struct ffs_function *func = ffs_func_from_usb(f);
3949 struct ffs_data *ffs = func->ffs;
3950 struct f_fs_opts *opts =
3951 container_of(f->fi, struct f_fs_opts, func_inst);
3952 struct ffs_ep *ep = func->eps;
3953 unsigned count = ffs->eps_count;
3954 unsigned long flags;
3958 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
3959 ffs->setup_state, ffs->flags);
3961 if (ffs->func == func) {
3962 ffs_func_eps_disable(func);
3966 if (!--opts->refcnt)
3967 functionfs_unbind(ffs);
3969 /* cleanup after autoconfig */
3970 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3972 if (ep->ep && ep->req)
3973 usb_ep_free_request(ep->ep, ep->req);
3978 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3982 * eps, descriptors and interfaces_nums are allocated in the
3983 * same chunk so only one free is required.
3985 func->function.fs_descriptors = NULL;
3986 func->function.hs_descriptors = NULL;
3987 func->function.ss_descriptors = NULL;
3988 func->interfaces_nums = NULL;
3990 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3992 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
3993 ffs->setup_state, ffs->flags);
3996 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3998 struct ffs_function *func;
4002 func = kzalloc(sizeof(*func), GFP_KERNEL);
4003 if (unlikely(!func))
4004 return ERR_PTR(-ENOMEM);
4006 func->function.name = "Function FS Gadget";
4008 func->function.bind = ffs_func_bind;
4009 func->function.unbind = ffs_func_unbind;
4010 func->function.set_alt = ffs_func_set_alt;
4011 func->function.disable = ffs_func_disable;
4012 func->function.setup = ffs_func_setup;
4013 func->function.suspend = ffs_func_suspend;
4014 func->function.resume = ffs_func_resume;
4015 func->function.free_func = ffs_free;
4017 return &func->function;
4021 * ffs_lock must be taken by the caller of this function
4023 static struct ffs_dev *_ffs_alloc_dev(void)
4025 struct ffs_dev *dev;
4028 if (_ffs_get_single_dev())
4029 return ERR_PTR(-EBUSY);
4031 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
4033 return ERR_PTR(-ENOMEM);
4035 if (list_empty(&ffs_devices)) {
4036 ret = functionfs_init();
4039 return ERR_PTR(ret);
4043 list_add(&dev->entry, &ffs_devices);
4049 * ffs_lock must be taken by the caller of this function
4050 * The caller is responsible for "name" being available whenever f_fs needs it
4052 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
4054 struct ffs_dev *existing;
4058 existing = _ffs_do_find_dev(name);
4070 * The caller is responsible for "name" being available whenever f_fs needs it
4072 int ffs_name_dev(struct ffs_dev *dev, const char *name)
4079 ret = _ffs_name_dev(dev, name);
4086 EXPORT_SYMBOL_GPL(ffs_name_dev);
4088 int ffs_single_dev(struct ffs_dev *dev)
4097 if (!list_is_singular(&ffs_devices))
4108 EXPORT_SYMBOL_GPL(ffs_single_dev);
4111 * ffs_lock must be taken by the caller of this function
4113 static void _ffs_free_dev(struct ffs_dev *dev)
4118 list_del(&dev->entry);
4119 if (dev->name_allocated)
4122 if (list_empty(&ffs_devices))
4123 functionfs_cleanup();
4128 static void *ffs_acquire_dev(const char *dev_name)
4130 struct ffs_dev *ffs_dev;
4138 ffs_dev = _ffs_find_dev(dev_name);
4140 ffs_dev = ERR_PTR(-ENOENT);
4141 else if (ffs_dev->mounted)
4142 ffs_dev = ERR_PTR(-EBUSY);
4143 else if (ffs_dev->ffs_acquire_dev_callback &&
4144 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
4145 ffs_dev = ERR_PTR(-ENOENT);
4147 ffs_dev->mounted = true;
4156 static void ffs_release_dev(struct ffs_data *ffs_data)
4158 struct ffs_dev *ffs_dev;
4166 ffs_dev = ffs_data->private_data;
4168 ffs_dev->mounted = false;
4170 if (ffs_dev->ffs_release_dev_callback)
4171 ffs_dev->ffs_release_dev_callback(ffs_dev);
4179 static int ffs_ready(struct ffs_data *ffs)
4181 struct ffs_dev *ffs_obj;
4190 ffs_obj = ffs->private_data;
4195 if (WARN_ON(ffs_obj->desc_ready)) {
4200 ffs_obj->desc_ready = true;
4201 ffs_obj->ffs_data = ffs;
4203 if (ffs_obj->ffs_ready_callback) {
4204 ret = ffs_obj->ffs_ready_callback(ffs);
4209 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
4218 static void ffs_closed(struct ffs_data *ffs)
4220 struct ffs_dev *ffs_obj;
4221 struct f_fs_opts *opts;
4229 ffs_obj = ffs->private_data;
4235 ffs_obj->desc_ready = false;
4237 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags) &&
4238 ffs_obj->ffs_closed_callback)
4239 ffs_obj->ffs_closed_callback(ffs);
4241 if (ffs_obj->opts) {
4242 opts = ffs_obj->opts;
4248 smp_mb__before_atomic();
4249 if (opts->no_configfs || !opts->func_inst.group.cg_item.ci_parent
4250 || !atomic_read(&opts->func_inst.group.cg_item.ci_kref.refcount)) {
4257 if (test_bit(FFS_FL_BOUND, &ffs->flags)) {
4258 unregister_gadget_item(opts->
4259 func_inst.group.cg_item.ci_parent->ci_parent);
4260 ffs_log("unreg gadget done");
4266 /* Misc helper functions ****************************************************/
4268 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
4271 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
4272 : mutex_lock_interruptible(mutex);
4275 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
4282 data = kmalloc(len, GFP_KERNEL);
4283 if (unlikely(!data))
4284 return ERR_PTR(-ENOMEM);
4286 if (unlikely(copy_from_user(data, buf, len))) {
4288 return ERR_PTR(-EFAULT);
4291 pr_vdebug("Buffer from user space:\n");
4292 ffs_dump_mem("", data, len);
4297 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
4299 static int ffs_init(void)
4301 ffs_ipc_log = ipc_log_context_create(NUM_PAGES, "f_fs", 0);
4302 if (IS_ERR_OR_NULL(ffs_ipc_log))
4307 module_init(ffs_init);
4309 static void __exit ffs_exit(void)
4311 struct ffs_inst_status *inst_status, *inst_status_tmp = NULL;
4313 list_for_each_entry(inst_status, &inst_list, list) {
4314 if (inst_status_tmp) {
4315 list_del(&inst_status_tmp->list);
4316 kfree(inst_status_tmp);
4318 inst_status_tmp = inst_status;
4320 if (inst_status_tmp) {
4321 list_del(&inst_status_tmp->list);
4322 kfree(inst_status_tmp);
4326 ipc_log_context_destroy(ffs_ipc_log);
4330 module_exit(ffs_exit);
4332 MODULE_LICENSE("GPL");
4333 MODULE_AUTHOR("Michal Nazarewicz");