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)) {
992 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
995 spin_unlock_irq(&epfile->ffs->eps_lock);
997 if (unlikely(ret < 0)) {
1000 } else if (unlikely(
1001 wait_for_completion_interruptible(done))) {
1002 spin_lock_irq(&epfile->ffs->eps_lock);
1004 * While we were acquiring lock endpoint got
1005 * disabled (disconnect) or changed
1006 * (composition switch) ?
1008 if (epfile->ep == ep)
1009 usb_ep_dequeue(ep->ep, req);
1010 spin_unlock_irq(&epfile->ffs->eps_lock);
1014 * XXX We may end up silently droping data
1015 * here. Since data_len (i.e. req->length) may
1016 * be bigger than len (after being rounded up
1017 * to maxpacketsize), we may end up with more
1018 * data then user space has space for.
1020 spin_lock_irq(&epfile->ffs->eps_lock);
1022 * While we were acquiring lock endpoint got
1023 * disabled (disconnect) or changed
1024 * (composition switch) ?
1026 if (epfile->ep == ep) {
1029 first_read_done = true;
1034 /* do wait again if func eps are not enabled */
1035 if (io_data->read && !first_read_done
1037 unsigned short count = ffs->eps_count;
1039 pr_debug("%s: waiting for the online state\n",
1045 spin_unlock_irq(&epfile->ffs->eps_lock);
1046 mutex_unlock(&epfile->mutex);
1047 epfile = ffs->epfiles;
1049 atomic_set(&epfile->error, 0);
1052 epfile = file->private_data;
1056 spin_unlock_irq(&epfile->ffs->eps_lock);
1057 if (io_data->read && ret > 0) {
1059 if (ret > data_len) {
1061 pr_err("More data(%zd) received than intended length(%zu)\n",
1065 ret = copy_to_iter(data, ret, &io_data->data);
1066 pr_debug("copied (%zd) bytes to user space\n", ret);
1068 pr_err("Fail to copy to user\n");
1078 mutex_unlock(&epfile->mutex);
1080 ffs_log("exit:ret %zu", ret);
1085 spin_unlock_irq(&epfile->ffs->eps_lock);
1086 mutex_unlock(&epfile->mutex);
1090 ffs_log("exit: ret %zu", ret);
1096 ffs_epfile_open(struct inode *inode, struct file *file)
1098 struct ffs_epfile *epfile = inode->i_private;
1103 ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1104 epfile->ffs->setup_state, epfile->ffs->flags);
1106 ret = ffs_inst_exist_check(epfile->ffs->dev_name);
1110 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1113 smp_mb__before_atomic();
1114 if (atomic_read(&epfile->opened)) {
1115 pr_err("%s(): ep(%s) is already opened.\n",
1116 __func__, epfile->name);
1120 smp_mb__before_atomic();
1121 atomic_set(&epfile->opened, 1);
1122 file->private_data = epfile;
1123 ffs_data_opened(epfile->ffs);
1125 smp_mb__before_atomic();
1126 atomic_set(&epfile->error, 0);
1127 first_read_done = false;
1129 ffs_log("exit:state %d setup_state %d flag %lu", epfile->ffs->state,
1130 epfile->ffs->setup_state, epfile->ffs->flags);
1135 static int ffs_aio_cancel(struct kiocb *kiocb)
1137 struct ffs_io_data *io_data = kiocb->private;
1138 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
1143 ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1144 epfile->ffs->setup_state, epfile->ffs->flags);
1146 spin_lock_irq(&epfile->ffs->eps_lock);
1148 if (likely(io_data && io_data->ep && io_data->req))
1149 value = usb_ep_dequeue(io_data->ep, io_data->req);
1153 spin_unlock_irq(&epfile->ffs->eps_lock);
1155 ffs_log("exit: value %d", value);
1160 static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
1162 struct ffs_io_data io_data, *p = &io_data;
1169 if (!is_sync_kiocb(kiocb)) {
1170 p = kmalloc(sizeof(io_data), GFP_KERNEL);
1181 p->mm = current->mm;
1186 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1188 res = ffs_epfile_io(kiocb->ki_filp, p);
1189 if (res == -EIOCBQUEUED)
1201 static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
1203 struct ffs_io_data io_data, *p = &io_data;
1210 if (!is_sync_kiocb(kiocb)) {
1211 p = kmalloc(sizeof(io_data), GFP_KERNEL);
1222 p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
1231 p->mm = current->mm;
1236 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1238 res = ffs_epfile_io(kiocb->ki_filp, p);
1239 if (res == -EIOCBQUEUED)
1255 ffs_epfile_release(struct inode *inode, struct file *file)
1257 struct ffs_epfile *epfile = inode->i_private;
1261 ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1262 epfile->ffs->setup_state, epfile->ffs->flags);
1264 smp_mb__before_atomic();
1265 atomic_set(&epfile->opened, 0);
1266 atomic_set(&epfile->error, 1);
1267 ffs_data_closed(epfile->ffs);
1268 file->private_data = NULL;
1275 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1276 unsigned long value)
1278 struct ffs_epfile *epfile = file->private_data;
1283 ffs_log("enter:state %d setup_state %d flag %lu", epfile->ffs->state,
1284 epfile->ffs->setup_state, epfile->ffs->flags);
1286 ret = ffs_inst_exist_check(epfile->ffs->dev_name);
1290 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1293 spin_lock_irq(&epfile->ffs->eps_lock);
1294 if (likely(epfile->ep)) {
1296 case FUNCTIONFS_FIFO_STATUS:
1297 ret = usb_ep_fifo_status(epfile->ep->ep);
1299 case FUNCTIONFS_FIFO_FLUSH:
1300 usb_ep_fifo_flush(epfile->ep->ep);
1303 case FUNCTIONFS_CLEAR_HALT:
1304 ret = usb_ep_clear_halt(epfile->ep->ep);
1306 case FUNCTIONFS_ENDPOINT_REVMAP:
1307 ret = epfile->ep->num;
1309 case FUNCTIONFS_ENDPOINT_DESC:
1312 struct usb_endpoint_descriptor *desc;
1314 switch (epfile->ffs->gadget->speed) {
1315 case USB_SPEED_SUPER:
1318 case USB_SPEED_HIGH:
1324 desc = epfile->ep->descs[desc_idx];
1326 spin_unlock_irq(&epfile->ffs->eps_lock);
1327 ret = copy_to_user((void *)value, desc, sizeof(*desc));
1338 spin_unlock_irq(&epfile->ffs->eps_lock);
1340 ffs_log("exit:ret %d", ret);
1345 static const struct file_operations ffs_epfile_operations = {
1346 .llseek = no_llseek,
1348 .open = ffs_epfile_open,
1349 .write_iter = ffs_epfile_write_iter,
1350 .read_iter = ffs_epfile_read_iter,
1351 .release = ffs_epfile_release,
1352 .unlocked_ioctl = ffs_epfile_ioctl,
1356 /* File system and super block operations ***********************************/
1359 * Mounting the file system creates a controller file, used first for
1360 * function configuration then later for event monitoring.
1363 static struct inode *__must_check
1364 ffs_sb_make_inode(struct super_block *sb, void *data,
1365 const struct file_operations *fops,
1366 const struct inode_operations *iops,
1367 struct ffs_file_perms *perms)
1369 struct inode *inode;
1375 inode = new_inode(sb);
1377 if (likely(inode)) {
1378 struct timespec current_time = CURRENT_TIME;
1380 inode->i_ino = get_next_ino();
1381 inode->i_mode = perms->mode;
1382 inode->i_uid = perms->uid;
1383 inode->i_gid = perms->gid;
1384 inode->i_atime = current_time;
1385 inode->i_mtime = current_time;
1386 inode->i_ctime = current_time;
1387 inode->i_private = data;
1389 inode->i_fop = fops;
1399 /* Create "regular" file */
1400 static struct dentry *ffs_sb_create_file(struct super_block *sb,
1401 const char *name, void *data,
1402 const struct file_operations *fops)
1404 struct ffs_data *ffs = sb->s_fs_info;
1405 struct dentry *dentry;
1406 struct inode *inode;
1412 dentry = d_alloc_name(sb->s_root, name);
1413 if (unlikely(!dentry))
1416 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1417 if (unlikely(!inode)) {
1422 d_add(dentry, inode);
1430 static const struct super_operations ffs_sb_operations = {
1431 .statfs = simple_statfs,
1432 .drop_inode = generic_delete_inode,
1435 struct ffs_sb_fill_data {
1436 struct ffs_file_perms perms;
1438 const char *dev_name;
1440 struct ffs_data *ffs_data;
1443 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1445 struct ffs_sb_fill_data *data = _data;
1446 struct inode *inode;
1447 struct ffs_data *ffs = data->ffs_data;
1454 data->ffs_data = NULL;
1455 sb->s_fs_info = ffs;
1456 sb->s_blocksize = PAGE_CACHE_SIZE;
1457 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1458 sb->s_magic = FUNCTIONFS_MAGIC;
1459 sb->s_op = &ffs_sb_operations;
1460 sb->s_time_gran = 1;
1463 data->perms.mode = data->root_mode;
1464 inode = ffs_sb_make_inode(sb, NULL,
1465 &simple_dir_operations,
1466 &simple_dir_inode_operations,
1468 sb->s_root = d_make_root(inode);
1469 if (unlikely(!sb->s_root))
1473 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1474 &ffs_ep0_operations)))
1482 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1488 if (!opts || !*opts)
1492 unsigned long value;
1496 comma = strchr(opts, ',');
1501 eq = strchr(opts, '=');
1502 if (unlikely(!eq)) {
1503 pr_err("'=' missing in %s\n", opts);
1509 if (kstrtoul(eq + 1, 0, &value)) {
1510 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1514 /* Interpret option */
1515 switch (eq - opts) {
1517 if (!memcmp(opts, "no_disconnect", 13))
1518 data->no_disconnect = !!value;
1523 if (!memcmp(opts, "rmode", 5))
1524 data->root_mode = (value & 0555) | S_IFDIR;
1525 else if (!memcmp(opts, "fmode", 5))
1526 data->perms.mode = (value & 0666) | S_IFREG;
1532 if (!memcmp(opts, "mode", 4)) {
1533 data->root_mode = (value & 0555) | S_IFDIR;
1534 data->perms.mode = (value & 0666) | S_IFREG;
1541 if (!memcmp(opts, "uid", 3)) {
1542 data->perms.uid = make_kuid(current_user_ns(), value);
1543 if (!uid_valid(data->perms.uid)) {
1544 pr_err("%s: unmapped value: %lu\n", opts, value);
1547 } else if (!memcmp(opts, "gid", 3)) {
1548 data->perms.gid = make_kgid(current_user_ns(), value);
1549 if (!gid_valid(data->perms.gid)) {
1550 pr_err("%s: unmapped value: %lu\n", opts, value);
1560 pr_err("%s: invalid option\n", opts);
1564 /* Next iteration */
1575 /* "mount -t functionfs dev_name /dev/function" ends up here */
1577 static struct dentry *
1578 ffs_fs_mount(struct file_system_type *t, int flags,
1579 const char *dev_name, void *opts)
1581 struct ffs_sb_fill_data data = {
1583 .mode = S_IFREG | 0600,
1584 .uid = GLOBAL_ROOT_UID,
1585 .gid = GLOBAL_ROOT_GID,
1587 .root_mode = S_IFDIR | 0500,
1588 .no_disconnect = false,
1593 struct ffs_data *ffs;
1594 struct ffs_inst_status *inst_status;
1600 ret = ffs_fs_parse_opts(&data, opts);
1601 if (unlikely(ret < 0))
1602 return ERR_PTR(ret);
1604 ffs = ffs_data_new();
1606 return ERR_PTR(-ENOMEM);
1607 ffs->file_perms = data.perms;
1608 ffs->no_disconnect = data.no_disconnect;
1610 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1611 if (unlikely(!ffs->dev_name)) {
1613 return ERR_PTR(-ENOMEM);
1616 ffs_dev = ffs_acquire_dev(dev_name);
1617 if (IS_ERR(ffs_dev)) {
1619 return ERR_CAST(ffs_dev);
1621 ffs->private_data = ffs_dev;
1622 data.ffs_data = ffs;
1624 inst_status = name_to_inst_status(ffs->dev_name, false);
1625 if (IS_ERR(inst_status)) {
1626 ffs_log("failed to find instance (%s)\n",
1628 return ERR_PTR(-EINVAL);
1631 /* Store ffs to global status structure */
1633 inst_status->ffs_data = ffs;
1636 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1637 if (IS_ERR(rv) && data.ffs_data) {
1638 ffs_release_dev(data.ffs_data);
1639 ffs_data_put(data.ffs_data);
1648 ffs_fs_kill_sb(struct super_block *sb)
1654 kill_litter_super(sb);
1655 if (sb->s_fs_info) {
1656 ffs_release_dev(sb->s_fs_info);
1657 ffs_data_closed(sb->s_fs_info);
1663 static struct file_system_type ffs_fs_type = {
1664 .owner = THIS_MODULE,
1665 .name = "functionfs",
1666 .mount = ffs_fs_mount,
1667 .kill_sb = ffs_fs_kill_sb,
1669 MODULE_ALIAS_FS("functionfs");
1672 /* Driver's main init/cleanup functions *************************************/
1674 static int functionfs_init(void)
1680 ret = register_filesystem(&ffs_fs_type);
1682 pr_info("file system registered\n");
1684 pr_err("failed registering file system (%d)\n", ret);
1689 static void functionfs_cleanup(void)
1693 pr_info("unloading\n");
1694 unregister_filesystem(&ffs_fs_type);
1697 /* ffs_data and ffs_function construction and destruction code **************/
1699 static void ffs_data_clear(struct ffs_data *ffs);
1700 static void ffs_data_reset(struct ffs_data *ffs);
1702 static void ffs_data_get(struct ffs_data *ffs)
1708 smp_mb__before_atomic();
1709 atomic_inc(&ffs->ref);
1714 static void ffs_data_opened(struct ffs_data *ffs)
1718 ffs_log("enter: state %d setup_state %d flag %lu opened %d", ffs->state,
1719 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
1721 smp_mb__before_atomic();
1722 atomic_inc(&ffs->ref);
1723 if (atomic_add_return(1, &ffs->opened) == 1 &&
1724 ffs->state == FFS_DEACTIVATED) {
1725 ffs->state = FFS_CLOSING;
1726 ffs_data_reset(ffs);
1729 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1730 ffs->setup_state, ffs->flags);
1733 static void ffs_data_put(struct ffs_data *ffs)
1735 struct ffs_inst_status *inst_status;
1736 const char *dev_name;
1742 smp_mb__before_atomic();
1743 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1744 pr_info("%s(): freeing\n", __func__);
1745 /* Clear ffs from global structure */
1746 inst_status = name_to_inst_status(ffs->dev_name, false);
1747 if (!IS_ERR(inst_status)) {
1749 inst_status->ffs_data = NULL;
1752 ffs_data_clear(ffs);
1753 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1754 waitqueue_active(&ffs->ep0req_completion.wait));
1755 dev_name = ffs->dev_name;
1757 ffs_inst_clean_delay(dev_name);
1764 static void ffs_data_closed(struct ffs_data *ffs)
1768 ffs_log("enter: state %d setup_state %d flag %lu opened %d", ffs->state,
1769 ffs->setup_state, ffs->flags, atomic_read(&ffs->opened));
1771 smp_mb__before_atomic();
1772 if (atomic_dec_and_test(&ffs->opened)) {
1773 if (ffs->no_disconnect) {
1774 ffs->state = FFS_DEACTIVATED;
1776 ffs_epfiles_destroy(ffs->epfiles,
1778 ffs->epfiles = NULL;
1780 if (ffs->setup_state == FFS_SETUP_PENDING)
1781 __ffs_ep0_stall(ffs);
1783 ffs->state = FFS_CLOSING;
1784 ffs_data_reset(ffs);
1788 smp_mb__before_atomic();
1789 if (atomic_read(&ffs->opened) < 0) {
1790 ffs->state = FFS_CLOSING;
1791 ffs_data_reset(ffs);
1794 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1795 ffs->setup_state, ffs->flags);
1800 static struct ffs_data *ffs_data_new(void)
1802 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1810 atomic_set(&ffs->ref, 1);
1811 atomic_set(&ffs->opened, 0);
1812 ffs->state = FFS_READ_DESCRIPTORS;
1813 mutex_init(&ffs->mutex);
1814 spin_lock_init(&ffs->eps_lock);
1815 init_waitqueue_head(&ffs->ev.waitq);
1816 init_completion(&ffs->ep0req_completion);
1817 init_completion(&ffs->epout_completion);
1818 init_completion(&ffs->epin_completion);
1820 /* XXX REVISIT need to update it in some places, or do we? */
1821 ffs->ev.can_stall = 1;
1828 static void ffs_data_clear(struct ffs_data *ffs)
1832 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1833 ffs->setup_state, ffs->flags);
1835 pr_debug("%s: ffs->gadget= %pK, ffs->flags= %lu\n",
1836 __func__, ffs->gadget, ffs->flags);
1840 pr_err("%s: ffs:%pK ffs->gadget= %pK, ffs->flags= %lu\n",
1841 __func__, ffs, ffs->gadget, ffs->flags);
1842 BUG_ON(ffs->gadget);
1845 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1847 if (ffs->ffs_eventfd)
1848 eventfd_ctx_put(ffs->ffs_eventfd);
1850 kfree(ffs->raw_descs_data);
1851 kfree(ffs->raw_strings);
1852 kfree(ffs->stringtabs);
1854 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1855 ffs->setup_state, ffs->flags);
1858 static void ffs_data_reset(struct ffs_data *ffs)
1862 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1863 ffs->setup_state, ffs->flags);
1865 ffs_data_clear(ffs);
1867 ffs->epfiles = NULL;
1868 ffs->raw_descs_data = NULL;
1869 ffs->raw_descs = NULL;
1870 ffs->raw_strings = NULL;
1871 ffs->stringtabs = NULL;
1873 ffs->raw_descs_length = 0;
1874 ffs->fs_descs_count = 0;
1875 ffs->hs_descs_count = 0;
1876 ffs->ss_descs_count = 0;
1878 ffs->strings_count = 0;
1879 ffs->interfaces_count = 0;
1884 ffs->state = FFS_READ_DESCRIPTORS;
1885 ffs->setup_state = FFS_NO_SETUP;
1888 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
1889 ffs->setup_state, ffs->flags);
1893 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1895 struct usb_gadget_strings **lang;
1900 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1901 ffs->setup_state, ffs->flags);
1903 if (WARN_ON(ffs->state != FFS_ACTIVE
1904 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1907 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1908 if (unlikely(first_id < 0))
1911 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1912 if (unlikely(!ffs->ep0req))
1914 ffs->ep0req->complete = ffs_ep0_complete;
1915 ffs->ep0req->context = ffs;
1917 lang = ffs->stringtabs;
1919 for (; *lang; ++lang) {
1920 struct usb_string *str = (*lang)->strings;
1922 for (; str->s; ++id, ++str)
1927 ffs->gadget = cdev->gadget;
1929 ffs_log("exit: state %d setup_state %d flag %lu gadget %pK\n",
1930 ffs->state, ffs->setup_state, ffs->flags, ffs->gadget);
1936 static void functionfs_unbind(struct ffs_data *ffs)
1940 if (!WARN_ON(!ffs->gadget)) {
1941 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1944 clear_bit(FFS_FL_BOUND, &ffs->flags);
1945 ffs_log("state %d setup_state %d flag %lu gadget %pK\n",
1946 ffs->state, ffs->setup_state, ffs->flags, ffs->gadget);
1951 static int ffs_epfiles_create(struct ffs_data *ffs)
1953 struct ffs_epfile *epfile, *epfiles;
1958 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
1959 ffs->setup_state, ffs->flags);
1961 count = ffs->eps_count;
1962 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1967 for (i = 1; i <= count; ++i, ++epfile) {
1969 mutex_init(&epfile->mutex);
1970 init_waitqueue_head(&epfile->wait);
1971 atomic_set(&epfile->opened, 0);
1972 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1973 sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
1975 sprintf(epfile->name, "ep%u", i);
1976 epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
1978 &ffs_epfile_operations);
1979 if (unlikely(!epfile->dentry)) {
1980 ffs_epfiles_destroy(epfiles, i - 1);
1985 ffs->epfiles = epfiles;
1987 ffs_log("exit: eps_count %u state %d setup_state %d flag %lu",
1988 count, ffs->state, ffs->setup_state, ffs->flags);
1993 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1995 struct ffs_epfile *epfile = epfiles;
1999 ffs_log("enter: count %u", count);
2001 for (; count; --count, ++epfile) {
2002 BUG_ON(mutex_is_locked(&epfile->mutex) ||
2003 waitqueue_active(&epfile->wait));
2004 if (epfile->dentry) {
2005 d_delete(epfile->dentry);
2006 dput(epfile->dentry);
2007 epfile->dentry = NULL;
2016 static void ffs_func_eps_disable(struct ffs_function *func)
2018 struct ffs_ep *ep = func->eps;
2019 struct ffs_epfile *epfile = func->ffs->epfiles;
2020 unsigned count = func->ffs->eps_count;
2021 unsigned long flags;
2023 ffs_log("enter: state %d setup_state %d flag %lu", func->ffs->state,
2024 func->ffs->setup_state, func->ffs->flags);
2026 spin_lock_irqsave(&func->ffs->eps_lock, flags);
2029 smp_mb__before_atomic();
2031 atomic_set(&epfile->error, 1);
2033 /* pending requests get nuked */
2035 usb_ep_disable(ep->ep);
2039 atomic_set(&epfile->error, 1);
2044 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2049 static int ffs_func_eps_enable(struct ffs_function *func)
2051 struct ffs_data *ffs = func->ffs;
2052 struct ffs_ep *ep = func->eps;
2053 struct ffs_epfile *epfile = ffs->epfiles;
2054 unsigned count = ffs->eps_count;
2055 unsigned long flags;
2058 ffs_log("enter: state %d setup_state %d flag %lu", func->ffs->state,
2059 func->ffs->setup_state, func->ffs->flags);
2061 spin_lock_irqsave(&func->ffs->eps_lock, flags);
2063 struct usb_endpoint_descriptor *ds;
2066 if (ffs->gadget->speed == USB_SPEED_SUPER)
2068 else if (ffs->gadget->speed == USB_SPEED_HIGH)
2073 /* fall-back to lower speed if desc missing for current speed */
2075 ds = ep->descs[desc_idx];
2076 } while (!ds && --desc_idx >= 0);
2083 ep->ep->driver_data = ep;
2086 ret = config_ep_by_speed(func->gadget, &func->function, ep->ep);
2088 pr_err("%s(): config_ep_by_speed(%d) err for %s\n",
2089 __func__, ret, ep->ep->name);
2094 * userspace setting maxburst > 1 results more fifo
2095 * allocation than without maxburst. Change maxburst to 1
2096 * only to allocate fifo size of max packet size.
2098 ep->ep->maxburst = 1;
2099 ret = usb_ep_enable(ep->ep);
2102 epfile->in = usb_endpoint_dir_in(ds);
2103 epfile->isoc = usb_endpoint_xfer_isoc(ds);
2104 ffs_log("usb_ep_enable %s", ep->ep->name);
2109 wake_up(&epfile->wait);
2114 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2116 ffs_log("exit: ret %d", ret);
2122 /* Parsing and building descriptors and strings *****************************/
2125 * This validates if data pointed by data is a valid USB descriptor as
2126 * well as record how many interfaces, endpoints and strings are
2127 * required by given configuration. Returns address after the
2128 * descriptor or NULL if data is invalid.
2131 enum ffs_entity_type {
2132 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
2135 enum ffs_os_desc_type {
2136 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
2139 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
2141 struct usb_descriptor_header *desc,
2144 typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
2145 struct usb_os_desc_header *h, void *data,
2146 unsigned len, void *priv);
2148 static int __must_check ffs_do_single_desc(char *data, unsigned len,
2149 ffs_entity_callback entity,
2152 struct usb_descriptor_header *_ds = (void *)data;
2158 ffs_log("enter: len %u", len);
2160 /* At least two bytes are required: length and type */
2162 pr_vdebug("descriptor too short\n");
2166 /* If we have at least as many bytes as the descriptor takes? */
2167 length = _ds->bLength;
2169 pr_vdebug("descriptor longer then available data\n");
2173 #define __entity_check_INTERFACE(val) 1
2174 #define __entity_check_STRING(val) (val)
2175 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
2176 #define __entity(type, val) do { \
2177 pr_vdebug("entity " #type "(%02x)\n", (val)); \
2178 if (unlikely(!__entity_check_ ##type(val))) { \
2179 pr_vdebug("invalid entity's value\n"); \
2182 ret = entity(FFS_ ##type, &val, _ds, priv); \
2183 if (unlikely(ret < 0)) { \
2184 pr_debug("entity " #type "(%02x); ret = %d\n", \
2190 /* Parse descriptor depending on type. */
2191 switch (_ds->bDescriptorType) {
2195 case USB_DT_DEVICE_QUALIFIER:
2196 /* function can't have any of those */
2197 pr_vdebug("descriptor reserved for gadget: %d\n",
2198 _ds->bDescriptorType);
2201 case USB_DT_INTERFACE: {
2202 struct usb_interface_descriptor *ds = (void *)_ds;
2203 pr_vdebug("interface descriptor\n");
2204 if (length != sizeof *ds)
2207 __entity(INTERFACE, ds->bInterfaceNumber);
2209 __entity(STRING, ds->iInterface);
2213 case USB_DT_ENDPOINT: {
2214 struct usb_endpoint_descriptor *ds = (void *)_ds;
2215 pr_vdebug("endpoint descriptor\n");
2216 if (length != USB_DT_ENDPOINT_SIZE &&
2217 length != USB_DT_ENDPOINT_AUDIO_SIZE)
2219 __entity(ENDPOINT, ds->bEndpointAddress);
2224 pr_vdebug("hid descriptor\n");
2225 if (length != sizeof(struct hid_descriptor))
2230 if (length != sizeof(struct usb_otg_descriptor))
2234 case USB_DT_INTERFACE_ASSOCIATION: {
2235 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
2236 pr_vdebug("interface association descriptor\n");
2237 if (length != sizeof *ds)
2240 __entity(STRING, ds->iFunction);
2244 case USB_DT_SS_ENDPOINT_COMP:
2245 pr_vdebug("EP SS companion descriptor\n");
2246 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
2250 case USB_DT_OTHER_SPEED_CONFIG:
2251 case USB_DT_INTERFACE_POWER:
2253 case USB_DT_SECURITY:
2254 case USB_DT_CS_RADIO_CONTROL:
2256 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
2260 /* We should never be here */
2261 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
2265 pr_vdebug("invalid length: %d (descriptor %d)\n",
2266 _ds->bLength, _ds->bDescriptorType);
2271 #undef __entity_check_DESCRIPTOR
2272 #undef __entity_check_INTERFACE
2273 #undef __entity_check_STRING
2274 #undef __entity_check_ENDPOINT
2276 ffs_log("exit: desc type %d length %d", _ds->bDescriptorType, length);
2281 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
2282 ffs_entity_callback entity, void *priv)
2284 const unsigned _len = len;
2285 unsigned long num = 0;
2289 ffs_log("enter: len %u", len);
2297 /* Record "descriptor" entity */
2298 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
2299 if (unlikely(ret < 0)) {
2300 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
2308 ret = ffs_do_single_desc(data, len, entity, priv);
2309 if (unlikely(ret < 0)) {
2310 pr_debug("%s returns %d\n", __func__, ret);
2319 ffs_log("exit: len %u", len);
2322 static int __ffs_data_do_entity(enum ffs_entity_type type,
2323 u8 *valuep, struct usb_descriptor_header *desc,
2326 struct ffs_desc_helper *helper = priv;
2327 struct usb_endpoint_descriptor *d;
2331 ffs_log("enter: type %u", type);
2334 case FFS_DESCRIPTOR:
2339 * Interfaces are indexed from zero so if we
2340 * encountered interface "n" then there are at least
2343 if (*valuep >= helper->interfaces_count)
2344 helper->interfaces_count = *valuep + 1;
2349 * Strings are indexed from 1 (0 is magic ;) reserved
2350 * for languages list or some such)
2352 if (*valuep > helper->ffs->strings_count)
2353 helper->ffs->strings_count = *valuep;
2358 helper->eps_count++;
2359 if (helper->eps_count >= 15)
2361 /* Check if descriptors for any speed were already parsed */
2362 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
2363 helper->ffs->eps_addrmap[helper->eps_count] =
2364 d->bEndpointAddress;
2365 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
2366 d->bEndpointAddress)
2376 static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
2377 struct usb_os_desc_header *desc)
2379 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
2380 u16 w_index = le16_to_cpu(desc->wIndex);
2384 if (bcd_version != 1) {
2385 pr_vdebug("unsupported os descriptors version: %d",
2391 *next_type = FFS_OS_DESC_EXT_COMPAT;
2394 *next_type = FFS_OS_DESC_EXT_PROP;
2397 pr_vdebug("unsupported os descriptor type: %d", w_index);
2401 ffs_log("exit: size of desc %zu", sizeof(*desc));
2403 return sizeof(*desc);
2407 * Process all extended compatibility/extended property descriptors
2408 * of a feature descriptor
2410 static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
2411 enum ffs_os_desc_type type,
2413 ffs_os_desc_callback entity,
2415 struct usb_os_desc_header *h)
2418 const unsigned _len = len;
2422 ffs_log("enter: len %u os desc type %d", len, type);
2424 /* loop over all ext compat/ext prop descriptors */
2425 while (feature_count--) {
2426 ret = entity(type, h, data, len, priv);
2427 if (unlikely(ret < 0)) {
2428 pr_debug("bad OS descriptor, type: %d\n", type);
2440 /* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
2441 static int __must_check ffs_do_os_descs(unsigned count,
2442 char *data, unsigned len,
2443 ffs_os_desc_callback entity, void *priv)
2445 const unsigned _len = len;
2446 unsigned long num = 0;
2450 ffs_log("enter: len %u", len);
2452 for (num = 0; num < count; ++num) {
2454 enum ffs_os_desc_type type;
2456 struct usb_os_desc_header *desc = (void *)data;
2458 if (len < sizeof(*desc))
2462 * Record "descriptor" entity.
2463 * Process dwLength, bcdVersion, wIndex, get b/wCount.
2464 * Move the data pointer to the beginning of extended
2465 * compatibilities proper or extended properties proper
2466 * portions of the data
2468 if (le32_to_cpu(desc->dwLength) > len)
2471 ret = __ffs_do_os_desc_header(&type, desc);
2472 if (unlikely(ret < 0)) {
2473 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
2478 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2480 feature_count = le16_to_cpu(desc->wCount);
2481 if (type == FFS_OS_DESC_EXT_COMPAT &&
2482 (feature_count > 255 || desc->Reserved))
2488 * Process all function/property descriptors
2489 * of this Feature Descriptor
2491 ret = ffs_do_single_os_desc(data, len, type,
2492 feature_count, entity, priv, desc);
2493 if (unlikely(ret < 0)) {
2494 pr_debug("%s returns %d\n", __func__, ret);
2508 * Validate contents of the buffer from userspace related to OS descriptors.
2510 static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2511 struct usb_os_desc_header *h, void *data,
2512 unsigned len, void *priv)
2514 struct ffs_data *ffs = priv;
2519 ffs_log("enter: len %u", len);
2522 case FFS_OS_DESC_EXT_COMPAT: {
2523 struct usb_ext_compat_desc *d = data;
2526 if (len < sizeof(*d) ||
2527 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2528 d->Reserved1 != 1) {
2529 pr_err("%s(): Invalid os_desct_ext_compat\n",
2533 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2534 if (d->Reserved2[i]) {
2535 pr_err("%s(): Invalid Reserved2 of ext_compat\n",
2540 length = sizeof(struct usb_ext_compat_desc);
2543 case FFS_OS_DESC_EXT_PROP: {
2544 struct usb_ext_prop_desc *d = data;
2548 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2550 length = le32_to_cpu(d->dwSize);
2553 type = le32_to_cpu(d->dwPropertyDataType);
2554 if (type < USB_EXT_PROP_UNICODE ||
2555 type > USB_EXT_PROP_UNICODE_MULTI) {
2556 pr_vdebug("unsupported os descriptor property type: %d",
2560 pnl = le16_to_cpu(d->wPropertyNameLength);
2561 if (length < 14 + pnl) {
2562 pr_vdebug("invalid os descriptor length: %d pnl:%d (descriptor %d)\n",
2566 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2567 if (length != 14 + pnl + pdl) {
2568 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2569 length, pnl, pdl, type);
2572 ++ffs->ms_os_descs_ext_prop_count;
2573 /* property name reported to the host as "WCHAR"s */
2574 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2575 ffs->ms_os_descs_ext_prop_data_len += pdl;
2579 pr_vdebug("unknown descriptor: %d\n", type);
2588 static int __ffs_data_got_descs(struct ffs_data *ffs,
2589 char *const _data, size_t len)
2591 char *data = _data, *raw_descs;
2592 unsigned os_descs_count = 0, counts[3], flags;
2593 int ret = -EINVAL, i;
2594 struct ffs_desc_helper helper;
2598 ffs_log("enter: len %zu", len);
2600 if (get_unaligned_le32(data + 4) != len)
2603 switch (get_unaligned_le32(data)) {
2604 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2605 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2609 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2610 flags = get_unaligned_le32(data + 8);
2611 ffs->user_flags = flags;
2612 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2613 FUNCTIONFS_HAS_HS_DESC |
2614 FUNCTIONFS_HAS_SS_DESC |
2615 FUNCTIONFS_HAS_MS_OS_DESC |
2616 FUNCTIONFS_VIRTUAL_ADDR |
2617 FUNCTIONFS_EVENTFD)) {
2628 if (flags & FUNCTIONFS_EVENTFD) {
2632 eventfd_ctx_fdget((int)get_unaligned_le32(data));
2633 if (IS_ERR(ffs->ffs_eventfd)) {
2634 ret = PTR_ERR(ffs->ffs_eventfd);
2635 ffs->ffs_eventfd = NULL;
2642 /* Read fs_count, hs_count and ss_count (if present) */
2643 for (i = 0; i < 3; ++i) {
2644 if (!(flags & (1 << i))) {
2646 } else if (len < 4) {
2649 counts[i] = get_unaligned_le32(data);
2654 if (flags & (1 << i)) {
2658 os_descs_count = get_unaligned_le32(data);
2663 /* Read descriptors */
2666 for (i = 0; i < 3; ++i) {
2669 helper.interfaces_count = 0;
2670 helper.eps_count = 0;
2671 ret = ffs_do_descs(counts[i], data, len,
2672 __ffs_data_do_entity, &helper);
2675 if (!ffs->eps_count && !ffs->interfaces_count) {
2676 ffs->eps_count = helper.eps_count;
2677 ffs->interfaces_count = helper.interfaces_count;
2679 if (ffs->eps_count != helper.eps_count) {
2683 if (ffs->interfaces_count != helper.interfaces_count) {
2691 if (os_descs_count) {
2692 ret = ffs_do_os_descs(os_descs_count, data, len,
2693 __ffs_data_do_os_desc, ffs);
2700 if (raw_descs == data || len) {
2705 ffs->raw_descs_data = _data;
2706 ffs->raw_descs = raw_descs;
2707 ffs->raw_descs_length = data - raw_descs;
2708 ffs->fs_descs_count = counts[0];
2709 ffs->hs_descs_count = counts[1];
2710 ffs->ss_descs_count = counts[2];
2711 ffs->ms_os_descs_count = os_descs_count;
2719 ffs_log("exit: ret %d", ret);
2723 static int __ffs_data_got_strings(struct ffs_data *ffs,
2724 char *const _data, size_t len)
2726 u32 str_count, needed_count, lang_count;
2727 struct usb_gadget_strings **stringtabs, *t;
2728 struct usb_string *strings, *s;
2729 const char *data = _data;
2733 ffs_log("enter: len %zu", len);
2735 if (unlikely(len < 16 ||
2736 get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2737 get_unaligned_le32(data + 4) != len))
2739 str_count = get_unaligned_le32(data + 8);
2740 lang_count = get_unaligned_le32(data + 12);
2742 /* if one is zero the other must be zero */
2743 if (unlikely(!str_count != !lang_count))
2746 /* Do we have at least as many strings as descriptors need? */
2747 needed_count = ffs->strings_count;
2748 if (unlikely(str_count < needed_count))
2752 * If we don't need any strings just return and free all
2755 if (!needed_count) {
2760 /* Allocate everything in one chunk so there's less maintenance. */
2764 vla_item(d, struct usb_gadget_strings *, stringtabs,
2766 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2767 vla_item(d, struct usb_string, strings,
2768 lang_count*(needed_count+1));
2770 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2772 if (unlikely(!vlabuf)) {
2777 /* Initialize the VLA pointers */
2778 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2779 t = vla_ptr(vlabuf, d, stringtab);
2782 *stringtabs++ = t++;
2786 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2787 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2788 t = vla_ptr(vlabuf, d, stringtab);
2789 s = vla_ptr(vlabuf, d, strings);
2793 /* For each language */
2797 do { /* lang_count > 0 so we can use do-while */
2798 unsigned needed = needed_count;
2800 if (unlikely(len < 3))
2802 t->language = get_unaligned_le16(data);
2809 /* For each string */
2810 do { /* str_count > 0 so we can use do-while */
2811 size_t length = strnlen(data, len);
2813 if (unlikely(length == len))
2817 * User may provide more strings then we need,
2818 * if that's the case we simply ignore the
2821 if (likely(needed)) {
2823 * s->id will be set while adding
2824 * function to configuration so for
2825 * now just leave garbage here.
2834 } while (--str_count);
2836 s->id = 0; /* terminator */
2840 } while (--lang_count);
2842 /* Some garbage left? */
2847 ffs->stringtabs = stringtabs;
2848 ffs->raw_strings = _data;
2857 ffs_log("exit: -EINVAL");
2862 /* Events handling and management *******************************************/
2864 static void __ffs_event_add(struct ffs_data *ffs,
2865 enum usb_functionfs_event_type type)
2867 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2870 ffs_log("enter: type %d state %d setup_state %d flag %lu", type,
2871 ffs->state, ffs->setup_state, ffs->flags);
2874 * Abort any unhandled setup
2876 * We do not need to worry about some cmpxchg() changing value
2877 * of ffs->setup_state without holding the lock because when
2878 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2879 * the source does nothing.
2881 if (ffs->setup_state == FFS_SETUP_PENDING)
2882 ffs->setup_state = FFS_SETUP_CANCELLED;
2885 * Logic of this function guarantees that there are at most four pending
2886 * evens on ffs->ev.types queue. This is important because the queue
2887 * has space for four elements only and __ffs_ep0_read_events function
2888 * depends on that limit as well. If more event types are added, those
2889 * limits have to be revisited or guaranteed to still hold.
2892 case FUNCTIONFS_RESUME:
2893 rem_type2 = FUNCTIONFS_SUSPEND;
2895 case FUNCTIONFS_SUSPEND:
2896 case FUNCTIONFS_SETUP:
2898 /* Discard all similar events */
2901 case FUNCTIONFS_BIND:
2902 case FUNCTIONFS_UNBIND:
2903 case FUNCTIONFS_DISABLE:
2904 case FUNCTIONFS_ENABLE:
2905 /* Discard everything other then power management. */
2906 rem_type1 = FUNCTIONFS_SUSPEND;
2907 rem_type2 = FUNCTIONFS_RESUME;
2912 WARN(1, "%d: unknown event, this should not happen\n", type);
2917 u8 *ev = ffs->ev.types, *out = ev;
2918 unsigned n = ffs->ev.count;
2919 for (; n; --n, ++ev)
2920 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2923 pr_vdebug("purging event %d\n", *ev);
2924 ffs->ev.count = out - ffs->ev.types;
2927 pr_vdebug("adding event %d\n", type);
2928 ffs->ev.types[ffs->ev.count++] = type;
2929 wake_up_locked(&ffs->ev.waitq);
2930 if (ffs->ffs_eventfd)
2931 eventfd_signal(ffs->ffs_eventfd, 1);
2933 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
2934 ffs->setup_state, ffs->flags);
2937 static void ffs_event_add(struct ffs_data *ffs,
2938 enum usb_functionfs_event_type type)
2940 unsigned long flags;
2941 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2942 __ffs_event_add(ffs, type);
2943 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2946 /* Bind/unbind USB function hooks *******************************************/
2948 static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2952 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2953 if (ffs->eps_addrmap[i] == endpoint_address)
2958 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2959 struct usb_descriptor_header *desc,
2962 struct usb_endpoint_descriptor *ds = (void *)desc;
2963 struct ffs_function *func = priv;
2964 struct ffs_ep *ffs_ep;
2965 unsigned ep_desc_id;
2967 static const char *speed_names[] = { "full", "high", "super" };
2971 if (type != FFS_DESCRIPTOR)
2975 * If ss_descriptors is not NULL, we are reading super speed
2976 * descriptors; if hs_descriptors is not NULL, we are reading high
2977 * speed descriptors; otherwise, we are reading full speed
2980 if (func->function.ss_descriptors) {
2982 func->function.ss_descriptors[(long)valuep] = desc;
2983 } else if (func->function.hs_descriptors) {
2985 func->function.hs_descriptors[(long)valuep] = desc;
2988 func->function.fs_descriptors[(long)valuep] = desc;
2991 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2994 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2998 ffs_ep = func->eps + idx;
3000 if (unlikely(ffs_ep->descs[ep_desc_id])) {
3001 pr_err("two %sspeed descriptors for EP %d\n",
3002 speed_names[ep_desc_id],
3003 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
3006 ffs_ep->descs[ep_desc_id] = ds;
3008 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
3010 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
3011 if (!ds->wMaxPacketSize)
3012 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
3014 struct usb_request *req;
3016 u8 bEndpointAddress;
3019 * We back up bEndpointAddress because autoconfig overwrites
3020 * it with physical endpoint address.
3022 bEndpointAddress = ds->bEndpointAddress;
3023 pr_vdebug("autoconfig\n");
3024 ep = usb_ep_autoconfig(func->gadget, ds);
3027 ep->driver_data = func->eps + idx;
3029 req = usb_ep_alloc_request(ep, GFP_KERNEL);
3035 func->eps_revmap[ds->bEndpointAddress &
3036 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
3038 * If we use virtual address mapping, we restore
3039 * original bEndpointAddress value.
3041 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3042 ds->bEndpointAddress = bEndpointAddress;
3044 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
3051 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
3052 struct usb_descriptor_header *desc,
3055 struct ffs_function *func = priv;
3059 ffs_log("enter: type %d", type);
3063 case FFS_DESCRIPTOR:
3064 /* Handled in previous pass by __ffs_func_bind_do_descs() */
3069 if (func->interfaces_nums[idx] < 0) {
3070 int id = usb_interface_id(func->conf, &func->function);
3071 if (unlikely(id < 0))
3073 func->interfaces_nums[idx] = id;
3075 newValue = func->interfaces_nums[idx];
3079 /* String' IDs are allocated when fsf_data is bound to cdev */
3080 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
3085 * USB_DT_ENDPOINT are handled in
3086 * __ffs_func_bind_do_descs().
3088 if (desc->bDescriptorType == USB_DT_ENDPOINT)
3091 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
3092 if (unlikely(!func->eps[idx].ep))
3096 struct usb_endpoint_descriptor **descs;
3097 descs = func->eps[idx].descs;
3098 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
3103 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
3106 ffs_log("exit: newValue %d", newValue);
3111 static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
3112 struct usb_os_desc_header *h, void *data,
3113 unsigned len, void *priv)
3115 struct ffs_function *func = priv;
3118 ffs_log("enter: type %d", type);
3121 case FFS_OS_DESC_EXT_COMPAT: {
3122 struct usb_ext_compat_desc *desc = data;
3123 struct usb_os_desc_table *t;
3125 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
3126 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
3127 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
3128 ARRAY_SIZE(desc->CompatibleID) +
3129 ARRAY_SIZE(desc->SubCompatibleID));
3130 length = sizeof(*desc);
3133 case FFS_OS_DESC_EXT_PROP: {
3134 struct usb_ext_prop_desc *desc = data;
3135 struct usb_os_desc_table *t;
3136 struct usb_os_desc_ext_prop *ext_prop;
3137 char *ext_prop_name;
3138 char *ext_prop_data;
3140 t = &func->function.os_desc_table[h->interface];
3141 t->if_id = func->interfaces_nums[h->interface];
3143 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
3144 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
3146 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
3147 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
3148 ext_prop->data_len = le32_to_cpu(*(u32 *)
3149 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
3150 length = ext_prop->name_len + ext_prop->data_len + 14;
3152 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
3153 func->ffs->ms_os_descs_ext_prop_name_avail +=
3156 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
3157 func->ffs->ms_os_descs_ext_prop_data_avail +=
3159 memcpy(ext_prop_data,
3160 usb_ext_prop_data_ptr(data, ext_prop->name_len),
3161 ext_prop->data_len);
3162 /* unicode data reported to the host as "WCHAR"s */
3163 switch (ext_prop->type) {
3164 case USB_EXT_PROP_UNICODE:
3165 case USB_EXT_PROP_UNICODE_ENV:
3166 case USB_EXT_PROP_UNICODE_LINK:
3167 case USB_EXT_PROP_UNICODE_MULTI:
3168 ext_prop->data_len *= 2;
3171 ext_prop->data = ext_prop_data;
3173 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
3174 ext_prop->name_len);
3175 /* property name reported to the host as "WCHAR"s */
3176 ext_prop->name_len *= 2;
3177 ext_prop->name = ext_prop_name;
3179 t->os_desc->ext_prop_len +=
3180 ext_prop->name_len + ext_prop->data_len + 14;
3181 ++t->os_desc->ext_prop_count;
3182 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
3186 pr_vdebug("unknown descriptor: %d\n", type);
3194 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
3195 struct usb_configuration *c)
3197 struct ffs_function *func = ffs_func_from_usb(f);
3198 struct f_fs_opts *ffs_opts =
3199 container_of(f->fi, struct f_fs_opts, func_inst);
3207 * Legacy gadget triggers binding in functionfs_ready_callback,
3208 * which already uses locking; taking the same lock here would
3211 * Configfs-enabled gadgets however do need ffs_dev_lock.
3213 if (!ffs_opts->no_configfs)
3215 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
3216 func->ffs = ffs_opts->dev->ffs_data;
3217 if (!ffs_opts->no_configfs)
3220 return ERR_PTR(ret);
3223 func->gadget = c->cdev->gadget;
3226 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
3227 * configurations are bound in sequence with list_for_each_entry,
3228 * in each configuration its functions are bound in sequence
3229 * with list_for_each_entry, so we assume no race condition
3230 * with regard to ffs_opts->bound access
3232 if (!ffs_opts->refcnt) {
3233 ret = functionfs_bind(func->ffs, c->cdev);
3235 return ERR_PTR(ret);
3238 func->function.strings = func->ffs->stringtabs;
3245 static int _ffs_func_bind(struct usb_configuration *c,
3246 struct usb_function *f)
3248 struct ffs_function *func = ffs_func_from_usb(f);
3249 struct ffs_data *ffs = func->ffs;
3251 const int full = !!func->ffs->fs_descs_count;
3252 const int high = !!func->ffs->hs_descs_count;
3253 const int super = !!func->ffs->ss_descs_count;
3255 int fs_len, hs_len, ss_len, ret, i;
3256 struct ffs_ep *eps_ptr;
3258 /* Make it a single chunk, less management later on */
3260 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
3261 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
3262 full ? ffs->fs_descs_count + 1 : 0);
3263 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
3264 high ? ffs->hs_descs_count + 1 : 0);
3265 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
3266 super ? ffs->ss_descs_count + 1 : 0);
3267 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
3268 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
3269 c->cdev->use_os_string ? ffs->interfaces_count : 0);
3270 vla_item_with_sz(d, char[16], ext_compat,
3271 c->cdev->use_os_string ? ffs->interfaces_count : 0);
3272 vla_item_with_sz(d, struct usb_os_desc, os_desc,
3273 c->cdev->use_os_string ? ffs->interfaces_count : 0);
3274 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
3275 ffs->ms_os_descs_ext_prop_count);
3276 vla_item_with_sz(d, char, ext_prop_name,
3277 ffs->ms_os_descs_ext_prop_name_len);
3278 vla_item_with_sz(d, char, ext_prop_data,
3279 ffs->ms_os_descs_ext_prop_data_len);
3280 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
3285 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
3286 ffs->setup_state, ffs->flags);
3288 /* Has descriptors only for speeds gadget does not support */
3289 if (unlikely(!(full | high | super)))
3292 /* Allocate a single chunk, less management later on */
3293 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
3294 if (unlikely(!vlabuf))
3297 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
3298 ffs->ms_os_descs_ext_prop_name_avail =
3299 vla_ptr(vlabuf, d, ext_prop_name);
3300 ffs->ms_os_descs_ext_prop_data_avail =
3301 vla_ptr(vlabuf, d, ext_prop_data);
3303 /* Copy descriptors */
3304 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
3305 ffs->raw_descs_length);
3307 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
3308 eps_ptr = vla_ptr(vlabuf, d, eps);
3309 for (i = 0; i < ffs->eps_count; i++)
3310 eps_ptr[i].num = -1;
3313 * d_eps == vlabuf, func->eps used to kfree vlabuf later
3315 func->eps = vla_ptr(vlabuf, d, eps);
3316 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
3319 * Go through all the endpoint descriptors and allocate
3320 * endpoints first, so that later we can rewrite the endpoint
3321 * numbers without worrying that it may be described later on.
3324 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
3325 fs_len = ffs_do_descs(ffs->fs_descs_count,
3326 vla_ptr(vlabuf, d, raw_descs),
3328 __ffs_func_bind_do_descs, func);
3329 if (unlikely(fs_len < 0)) {
3338 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
3339 hs_len = ffs_do_descs(ffs->hs_descs_count,
3340 vla_ptr(vlabuf, d, raw_descs) + fs_len,
3341 d_raw_descs__sz - fs_len,
3342 __ffs_func_bind_do_descs, func);
3343 if (unlikely(hs_len < 0)) {
3351 if (likely(super)) {
3352 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
3353 ss_len = ffs_do_descs(ffs->ss_descs_count,
3354 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
3355 d_raw_descs__sz - fs_len - hs_len,
3356 __ffs_func_bind_do_descs, func);
3357 if (unlikely(ss_len < 0)) {
3366 * Now handle interface numbers allocation and interface and
3367 * endpoint numbers rewriting. We can do that in one go
3370 ret = ffs_do_descs(ffs->fs_descs_count +
3371 (high ? ffs->hs_descs_count : 0) +
3372 (super ? ffs->ss_descs_count : 0),
3373 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
3374 __ffs_func_bind_do_nums, func);
3375 if (unlikely(ret < 0))
3378 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
3379 if (c->cdev->use_os_string) {
3380 for (i = 0; i < ffs->interfaces_count; ++i) {
3381 struct usb_os_desc *desc;
3383 desc = func->function.os_desc_table[i].os_desc =
3384 vla_ptr(vlabuf, d, os_desc) +
3385 i * sizeof(struct usb_os_desc);
3386 desc->ext_compat_id =
3387 vla_ptr(vlabuf, d, ext_compat) + i * 16;
3388 INIT_LIST_HEAD(&desc->ext_prop);
3390 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
3391 vla_ptr(vlabuf, d, raw_descs) +
3392 fs_len + hs_len + ss_len,
3393 d_raw_descs__sz - fs_len - hs_len -
3395 __ffs_func_bind_do_os_desc, func);
3396 if (unlikely(ret < 0))
3399 func->function.os_desc_n =
3400 c->cdev->use_os_string ? ffs->interfaces_count : 0;
3402 /* And we're done */
3403 ffs_event_add(ffs, FUNCTIONFS_BIND);
3405 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
3406 ffs->setup_state, ffs->flags);
3411 /* XXX Do we need to release all claimed endpoints here? */
3412 ffs_log("exit: ret %d", ret);
3416 static int ffs_func_bind(struct usb_configuration *c,
3417 struct usb_function *f)
3419 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
3420 struct ffs_function *func = ffs_func_from_usb(f);
3425 if (IS_ERR(ffs_opts))
3426 return PTR_ERR(ffs_opts);
3428 ret = _ffs_func_bind(c, f);
3429 if (ret && !--ffs_opts->refcnt)
3430 functionfs_unbind(func->ffs);
3432 ffs_log("exit: ret %d", ret);
3438 /* Other USB function hooks *************************************************/
3440 static void ffs_reset_work(struct work_struct *work)
3442 struct ffs_data *ffs = container_of(work,
3443 struct ffs_data, reset_work);
3447 ffs_data_reset(ffs);
3452 static int ffs_func_set_alt(struct usb_function *f,
3453 unsigned interface, unsigned alt)
3455 struct ffs_function *func = ffs_func_from_usb(f);
3456 struct ffs_data *ffs = func->ffs;
3461 if (alt != (unsigned)-1) {
3462 intf = ffs_func_revmap_intf(func, interface);
3463 if (unlikely(intf < 0))
3468 ffs_func_eps_disable(ffs->func);
3470 /* matching put to allow LPM on disconnect */
3471 usb_gadget_autopm_put_async(ffs->gadget);
3474 if (ffs->state == FFS_DEACTIVATED) {
3475 ffs->state = FFS_CLOSING;
3476 INIT_WORK(&ffs->reset_work, ffs_reset_work);
3477 schedule_work(&ffs->reset_work);
3481 if (ffs->state != FFS_ACTIVE)
3484 if (alt == (unsigned)-1) {
3486 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
3491 ret = ffs_func_eps_enable(func);
3492 if (likely(ret >= 0)) {
3493 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
3494 /* Disable USB LPM later on bus_suspend */
3495 usb_gadget_autopm_get_async(ffs->gadget);
3498 ffs_log("exit: ret %d", ret);
3503 static void ffs_func_disable(struct usb_function *f)
3507 ffs_func_set_alt(f, 0, (unsigned)-1);
3512 static int ffs_func_setup(struct usb_function *f,
3513 const struct usb_ctrlrequest *creq)
3515 struct ffs_function *func = ffs_func_from_usb(f);
3516 struct ffs_data *ffs = func->ffs;
3517 unsigned long flags;
3524 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
3525 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
3526 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
3527 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
3528 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
3531 * Most requests directed to interface go through here
3532 * (notable exceptions are set/get interface) so we need to
3533 * handle them. All other either handled by composite or
3534 * passed to usb_configuration->setup() (if one is set). No
3535 * matter, we will handle requests directed to endpoint here
3536 * as well (as it's straightforward) but what to do with any
3539 if (ffs->state != FFS_ACTIVE)
3542 switch (creq->bRequestType & USB_RECIP_MASK) {
3543 case USB_RECIP_INTERFACE:
3544 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
3545 if (unlikely(ret < 0))
3549 case USB_RECIP_ENDPOINT:
3550 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
3551 if (unlikely(ret < 0))
3553 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3554 ret = func->ffs->eps_addrmap[ret];
3561 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
3562 ffs->ev.setup = *creq;
3563 ffs->ev.setup.wIndex = cpu_to_le16(ret);
3564 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
3565 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
3569 return creq->wLength == 0 ? USB_GADGET_DELAYED_STATUS : 0;
3572 static void ffs_func_suspend(struct usb_function *f)
3578 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
3583 static void ffs_func_resume(struct usb_function *f)
3589 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
3595 /* Endpoint and interface numbers reverse mapping ***************************/
3597 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
3599 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
3600 return num ? num : -EDOM;
3603 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
3605 short *nums = func->interfaces_nums;
3606 unsigned count = func->ffs->interfaces_count;
3610 for (; count; --count, ++nums) {
3611 if (*nums >= 0 && *nums == intf)
3612 return nums - func->interfaces_nums;
3621 /* Devices management *******************************************************/
3623 static LIST_HEAD(ffs_devices);
3625 static struct ffs_dev *_ffs_do_find_dev(const char *name)
3627 struct ffs_dev *dev;
3631 list_for_each_entry(dev, &ffs_devices, entry) {
3632 if (!dev->name || !name)
3634 if (strcmp(dev->name, name) == 0)
3644 * ffs_lock must be taken by the caller of this function
3646 static struct ffs_dev *_ffs_get_single_dev(void)
3648 struct ffs_dev *dev;
3652 if (list_is_singular(&ffs_devices)) {
3653 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3664 * ffs_lock must be taken by the caller of this function
3666 static struct ffs_dev *_ffs_find_dev(const char *name)
3668 struct ffs_dev *dev;
3672 dev = _ffs_get_single_dev();
3676 dev = _ffs_do_find_dev(name);
3683 /* Configfs support *********************************************************/
3685 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3687 return container_of(to_config_group(item), struct f_fs_opts,
3691 static void ffs_attr_release(struct config_item *item)
3693 struct f_fs_opts *opts = to_ffs_opts(item);
3695 usb_put_function_instance(&opts->func_inst);
3698 static struct configfs_item_operations ffs_item_ops = {
3699 .release = ffs_attr_release,
3702 static struct config_item_type ffs_func_type = {
3703 .ct_item_ops = &ffs_item_ops,
3704 .ct_owner = THIS_MODULE,
3708 /* Function registration interface ******************************************/
3710 static struct ffs_inst_status *name_to_inst_status(
3711 const char *inst_name, bool create_inst)
3713 struct ffs_inst_status *inst_status;
3715 list_for_each_entry(inst_status, &inst_list, list) {
3716 if (!strncasecmp(inst_status->inst_name,
3717 inst_name, strlen(inst_name)))
3722 return ERR_PTR(-ENODEV);
3724 inst_status = kzalloc(sizeof(struct ffs_inst_status),
3727 return ERR_PTR(-ENOMEM);
3729 mutex_init(&inst_status->ffs_lock);
3730 snprintf(inst_status->inst_name, INST_NAME_SIZE, inst_name);
3731 list_add_tail(&inst_status->list, &inst_list);
3736 static int ffs_inst_exist_check(const char *inst_name)
3738 struct ffs_inst_status *inst_status;
3740 inst_status = name_to_inst_status(inst_name, false);
3741 if (IS_ERR(inst_status)) {
3743 "%s: failed to find instance (%s)\n",
3744 __func__, inst_name);
3748 mutex_lock(&inst_status->ffs_lock);
3750 if (unlikely(inst_status->inst_exist == false)) {
3751 mutex_unlock(&inst_status->ffs_lock);
3753 "%s: f_fs instance (%s) has been freed already.\n",
3754 __func__, inst_name);
3758 mutex_unlock(&inst_status->ffs_lock);
3763 static void ffs_inst_clean(struct f_fs_opts *opts,
3764 const char *inst_name)
3766 struct ffs_inst_status *inst_status;
3768 inst_status = name_to_inst_status(inst_name, false);
3769 if (IS_ERR(inst_status)) {
3771 "%s: failed to find instance (%s)\n",
3772 __func__, inst_name);
3776 inst_status->opts = NULL;
3779 _ffs_free_dev(opts->dev);
3784 static void ffs_inst_clean_delay(const char *inst_name)
3786 struct ffs_inst_status *inst_status;
3788 inst_status = name_to_inst_status(inst_name, false);
3789 if (IS_ERR(inst_status)) {
3791 "%s: failed to find (%s) instance\n",
3792 __func__, inst_name);
3796 mutex_lock(&inst_status->ffs_lock);
3798 if (unlikely(inst_status->inst_exist == false)) {
3799 if (inst_status->opts) {
3800 ffs_inst_clean(inst_status->opts, inst_name);
3801 pr_err_ratelimited("%s: Delayed free memory\n",
3804 mutex_unlock(&inst_status->ffs_lock);
3808 mutex_unlock(&inst_status->ffs_lock);
3811 static void ffs_free_inst(struct usb_function_instance *f)
3813 struct f_fs_opts *opts;
3814 struct ffs_inst_status *inst_status;
3816 opts = to_f_fs_opts(f);
3818 inst_status = name_to_inst_status(opts->dev->name, false);
3819 if (IS_ERR(inst_status)) {
3820 ffs_log("failed to find (%s) instance\n",
3825 mutex_lock(&inst_status->ffs_lock);
3826 if (opts->dev->ffs_data
3827 && atomic_read(&opts->dev->ffs_data->opened)) {
3828 inst_status->inst_exist = false;
3829 mutex_unlock(&inst_status->ffs_lock);
3830 ffs_log("Dev is open, free mem when dev (%s) close\n",
3835 ffs_inst_clean(opts, opts->dev->name);
3836 inst_status->inst_exist = false;
3837 mutex_unlock(&inst_status->ffs_lock);
3840 #define MAX_INST_NAME_LEN 40
3842 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3844 struct f_fs_opts *opts, *opts_prev;
3845 struct ffs_data *ffs_data_tmp;
3849 struct ffs_inst_status *inst_status;
3851 name_len = strlen(name) + 1;
3852 if (name_len > MAX_INST_NAME_LEN)
3853 return -ENAMETOOLONG;
3855 ptr = kstrndup(name, name_len, GFP_KERNEL);
3859 inst_status = name_to_inst_status(ptr, true);
3860 if (IS_ERR(inst_status)) {
3861 ffs_log("failed to create status struct for (%s) instance\n",
3866 mutex_lock(&inst_status->ffs_lock);
3867 opts_prev = inst_status->opts;
3869 mutex_unlock(&inst_status->ffs_lock);
3870 ffs_log("instance (%s): prev inst do not freed yet\n",
3871 inst_status->inst_name);
3874 mutex_unlock(&inst_status->ffs_lock);
3876 opts = to_f_fs_opts(fi);
3881 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3882 ret = _ffs_name_dev(opts->dev, ptr);
3888 opts->dev->name_allocated = true;
3891 * If ffs instance is freed and created once, new allocated
3892 * opts->dev need to initialize opts->dev->ffs_data, and
3893 * ffs_private_data also need to update new allocated opts->dev
3896 ffs_data_tmp = inst_status->ffs_data;
3898 opts->dev->ffs_data = ffs_data_tmp;
3900 if (opts->dev->ffs_data)
3901 opts->dev->ffs_data->private_data = opts->dev;
3907 mutex_lock(&inst_status->ffs_lock);
3908 inst_status->inst_exist = true;
3909 inst_status->opts = opts;
3910 mutex_unlock(&inst_status->ffs_lock);
3915 static struct usb_function_instance *ffs_alloc_inst(void)
3917 struct f_fs_opts *opts;
3918 struct ffs_dev *dev;
3920 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3922 return ERR_PTR(-ENOMEM);
3924 opts->func_inst.set_inst_name = ffs_set_inst_name;
3925 opts->func_inst.free_func_inst = ffs_free_inst;
3927 dev = _ffs_alloc_dev();
3931 return ERR_CAST(dev);
3936 config_group_init_type_name(&opts->func_inst.group, "",
3938 return &opts->func_inst;
3941 static void ffs_free(struct usb_function *f)
3943 kfree(ffs_func_from_usb(f));
3946 static void ffs_func_unbind(struct usb_configuration *c,
3947 struct usb_function *f)
3949 struct ffs_function *func = ffs_func_from_usb(f);
3950 struct ffs_data *ffs = func->ffs;
3951 struct f_fs_opts *opts =
3952 container_of(f->fi, struct f_fs_opts, func_inst);
3953 struct ffs_ep *ep = func->eps;
3954 unsigned count = ffs->eps_count;
3955 unsigned long flags;
3959 ffs_log("enter: state %d setup_state %d flag %lu", ffs->state,
3960 ffs->setup_state, ffs->flags);
3962 if (ffs->func == func) {
3963 ffs_func_eps_disable(func);
3967 if (!--opts->refcnt)
3968 functionfs_unbind(ffs);
3970 /* cleanup after autoconfig */
3971 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3973 if (ep->ep && ep->req)
3974 usb_ep_free_request(ep->ep, ep->req);
3979 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3983 * eps, descriptors and interfaces_nums are allocated in the
3984 * same chunk so only one free is required.
3986 func->function.fs_descriptors = NULL;
3987 func->function.hs_descriptors = NULL;
3988 func->function.ss_descriptors = NULL;
3989 func->interfaces_nums = NULL;
3991 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3993 ffs_log("exit: state %d setup_state %d flag %lu", ffs->state,
3994 ffs->setup_state, ffs->flags);
3997 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3999 struct ffs_function *func;
4003 func = kzalloc(sizeof(*func), GFP_KERNEL);
4004 if (unlikely(!func))
4005 return ERR_PTR(-ENOMEM);
4007 func->function.name = "Function FS Gadget";
4009 func->function.bind = ffs_func_bind;
4010 func->function.unbind = ffs_func_unbind;
4011 func->function.set_alt = ffs_func_set_alt;
4012 func->function.disable = ffs_func_disable;
4013 func->function.setup = ffs_func_setup;
4014 func->function.suspend = ffs_func_suspend;
4015 func->function.resume = ffs_func_resume;
4016 func->function.free_func = ffs_free;
4018 return &func->function;
4022 * ffs_lock must be taken by the caller of this function
4024 static struct ffs_dev *_ffs_alloc_dev(void)
4026 struct ffs_dev *dev;
4029 if (_ffs_get_single_dev())
4030 return ERR_PTR(-EBUSY);
4032 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
4034 return ERR_PTR(-ENOMEM);
4036 if (list_empty(&ffs_devices)) {
4037 ret = functionfs_init();
4040 return ERR_PTR(ret);
4044 list_add(&dev->entry, &ffs_devices);
4050 * ffs_lock must be taken by the caller of this function
4051 * The caller is responsible for "name" being available whenever f_fs needs it
4053 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
4055 struct ffs_dev *existing;
4059 existing = _ffs_do_find_dev(name);
4071 * The caller is responsible for "name" being available whenever f_fs needs it
4073 int ffs_name_dev(struct ffs_dev *dev, const char *name)
4080 ret = _ffs_name_dev(dev, name);
4087 EXPORT_SYMBOL_GPL(ffs_name_dev);
4089 int ffs_single_dev(struct ffs_dev *dev)
4098 if (!list_is_singular(&ffs_devices))
4109 EXPORT_SYMBOL_GPL(ffs_single_dev);
4112 * ffs_lock must be taken by the caller of this function
4114 static void _ffs_free_dev(struct ffs_dev *dev)
4119 list_del(&dev->entry);
4120 if (dev->name_allocated)
4123 if (list_empty(&ffs_devices))
4124 functionfs_cleanup();
4129 static void *ffs_acquire_dev(const char *dev_name)
4131 struct ffs_dev *ffs_dev;
4139 ffs_dev = _ffs_find_dev(dev_name);
4141 ffs_dev = ERR_PTR(-ENOENT);
4142 else if (ffs_dev->mounted)
4143 ffs_dev = ERR_PTR(-EBUSY);
4144 else if (ffs_dev->ffs_acquire_dev_callback &&
4145 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
4146 ffs_dev = ERR_PTR(-ENOENT);
4148 ffs_dev->mounted = true;
4157 static void ffs_release_dev(struct ffs_data *ffs_data)
4159 struct ffs_dev *ffs_dev;
4167 ffs_dev = ffs_data->private_data;
4169 ffs_dev->mounted = false;
4171 if (ffs_dev->ffs_release_dev_callback)
4172 ffs_dev->ffs_release_dev_callback(ffs_dev);
4180 static int ffs_ready(struct ffs_data *ffs)
4182 struct ffs_dev *ffs_obj;
4191 ffs_obj = ffs->private_data;
4196 if (WARN_ON(ffs_obj->desc_ready)) {
4201 ffs_obj->desc_ready = true;
4202 ffs_obj->ffs_data = ffs;
4204 if (ffs_obj->ffs_ready_callback) {
4205 ret = ffs_obj->ffs_ready_callback(ffs);
4210 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
4219 static void ffs_closed(struct ffs_data *ffs)
4221 struct ffs_dev *ffs_obj;
4222 struct f_fs_opts *opts;
4230 ffs_obj = ffs->private_data;
4236 ffs_obj->desc_ready = false;
4238 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags) &&
4239 ffs_obj->ffs_closed_callback)
4240 ffs_obj->ffs_closed_callback(ffs);
4242 if (ffs_obj->opts) {
4243 opts = ffs_obj->opts;
4249 smp_mb__before_atomic();
4250 if (opts->no_configfs || !opts->func_inst.group.cg_item.ci_parent
4251 || !atomic_read(&opts->func_inst.group.cg_item.ci_kref.refcount)) {
4258 if (test_bit(FFS_FL_BOUND, &ffs->flags)) {
4259 unregister_gadget_item(opts->
4260 func_inst.group.cg_item.ci_parent->ci_parent);
4261 ffs_log("unreg gadget done");
4267 /* Misc helper functions ****************************************************/
4269 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
4272 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
4273 : mutex_lock_interruptible(mutex);
4276 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
4283 data = kmalloc(len, GFP_KERNEL);
4284 if (unlikely(!data))
4285 return ERR_PTR(-ENOMEM);
4287 if (unlikely(copy_from_user(data, buf, len))) {
4289 return ERR_PTR(-EFAULT);
4292 pr_vdebug("Buffer from user space:\n");
4293 ffs_dump_mem("", data, len);
4298 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
4300 static int ffs_init(void)
4302 ffs_ipc_log = ipc_log_context_create(NUM_PAGES, "f_fs", 0);
4303 if (IS_ERR_OR_NULL(ffs_ipc_log))
4308 module_init(ffs_init);
4310 static void __exit ffs_exit(void)
4312 struct ffs_inst_status *inst_status, *inst_status_tmp = NULL;
4314 list_for_each_entry(inst_status, &inst_list, list) {
4315 if (inst_status_tmp) {
4316 list_del(&inst_status_tmp->list);
4317 kfree(inst_status_tmp);
4319 inst_status_tmp = inst_status;
4321 if (inst_status_tmp) {
4322 list_del(&inst_status_tmp->list);
4323 kfree(inst_status_tmp);
4327 ipc_log_context_destroy(ffs_ipc_log);
4331 module_exit(ffs_exit);
4333 MODULE_LICENSE("GPL");
4334 MODULE_AUTHOR("Michal Nazarewicz");