Btrfs: device_list_add() should not update list when mounted
[linux/fpc-iii.git] / drivers / usb / gadget / f_fs.c
blob8598c27c7d4344e6448dc4fcae7ff38577156278
1 /*
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.
18 /* #define DEBUG */
19 /* #define VERBOSE_DEBUG */
21 #include <linux/blkdev.h>
22 #include <linux/pagemap.h>
23 #include <linux/export.h>
24 #include <linux/hid.h>
25 #include <linux/module.h>
26 #include <asm/unaligned.h>
28 #include <linux/usb/composite.h>
29 #include <linux/usb/functionfs.h>
31 #include <linux/aio.h>
32 #include <linux/mmu_context.h>
33 #include <linux/poll.h>
35 #include "u_fs.h"
36 #include "u_f.h"
37 #include "configfs.h"
39 #define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
41 /* Reference counter handling */
42 static void ffs_data_get(struct ffs_data *ffs);
43 static void ffs_data_put(struct ffs_data *ffs);
44 /* Creates new ffs_data object. */
45 static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
47 /* Opened counter handling. */
48 static void ffs_data_opened(struct ffs_data *ffs);
49 static void ffs_data_closed(struct ffs_data *ffs);
51 /* Called with ffs->mutex held; take over ownership of data. */
52 static int __must_check
53 __ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
54 static int __must_check
55 __ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
58 /* The function structure ***************************************************/
60 struct ffs_ep;
62 struct ffs_function {
63 struct usb_configuration *conf;
64 struct usb_gadget *gadget;
65 struct ffs_data *ffs;
67 struct ffs_ep *eps;
68 u8 eps_revmap[16];
69 short *interfaces_nums;
71 struct usb_function function;
75 static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
77 return container_of(f, struct ffs_function, function);
81 static inline enum ffs_setup_state
82 ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
84 return (enum ffs_setup_state)
85 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
89 static void ffs_func_eps_disable(struct ffs_function *func);
90 static int __must_check ffs_func_eps_enable(struct ffs_function *func);
92 static int ffs_func_bind(struct usb_configuration *,
93 struct usb_function *);
94 static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
95 static void ffs_func_disable(struct usb_function *);
96 static int ffs_func_setup(struct usb_function *,
97 const struct usb_ctrlrequest *);
98 static void ffs_func_suspend(struct usb_function *);
99 static void ffs_func_resume(struct usb_function *);
102 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
103 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
106 /* The endpoints structures *************************************************/
108 struct ffs_ep {
109 struct usb_ep *ep; /* P: ffs->eps_lock */
110 struct usb_request *req; /* P: epfile->mutex */
112 /* [0]: full speed, [1]: high speed, [2]: super speed */
113 struct usb_endpoint_descriptor *descs[3];
115 u8 num;
117 int status; /* P: epfile->mutex */
120 struct ffs_epfile {
121 /* Protects ep->ep and ep->req. */
122 struct mutex mutex;
123 wait_queue_head_t wait;
125 struct ffs_data *ffs;
126 struct ffs_ep *ep; /* P: ffs->eps_lock */
128 struct dentry *dentry;
130 char name[5];
132 unsigned char in; /* P: ffs->eps_lock */
133 unsigned char isoc; /* P: ffs->eps_lock */
135 unsigned char _pad;
138 /* ffs_io_data structure ***************************************************/
140 struct ffs_io_data {
141 bool aio;
142 bool read;
144 struct kiocb *kiocb;
145 const struct iovec *iovec;
146 unsigned long nr_segs;
147 char __user *buf;
148 size_t len;
150 struct mm_struct *mm;
151 struct work_struct work;
153 struct usb_ep *ep;
154 struct usb_request *req;
157 static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
158 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
160 static struct inode *__must_check
161 ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
162 const struct file_operations *fops,
163 struct dentry **dentry_p);
165 /* Devices management *******************************************************/
167 DEFINE_MUTEX(ffs_lock);
168 EXPORT_SYMBOL_GPL(ffs_lock);
170 static struct ffs_dev *_ffs_find_dev(const char *name);
171 static struct ffs_dev *_ffs_alloc_dev(void);
172 static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
173 static void _ffs_free_dev(struct ffs_dev *dev);
174 static void *ffs_acquire_dev(const char *dev_name);
175 static void ffs_release_dev(struct ffs_data *ffs_data);
176 static int ffs_ready(struct ffs_data *ffs);
177 static void ffs_closed(struct ffs_data *ffs);
179 /* Misc helper functions ****************************************************/
181 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
182 __attribute__((warn_unused_result, nonnull));
183 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
184 __attribute__((warn_unused_result, nonnull));
187 /* Control file aka ep0 *****************************************************/
189 static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
191 struct ffs_data *ffs = req->context;
193 complete_all(&ffs->ep0req_completion);
196 static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
198 struct usb_request *req = ffs->ep0req;
199 int ret;
201 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
203 spin_unlock_irq(&ffs->ev.waitq.lock);
205 req->buf = data;
206 req->length = len;
209 * UDC layer requires to provide a buffer even for ZLP, but should
210 * not use it at all. Let's provide some poisoned pointer to catch
211 * possible bug in the driver.
213 if (req->buf == NULL)
214 req->buf = (void *)0xDEADBABE;
216 reinit_completion(&ffs->ep0req_completion);
218 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
219 if (unlikely(ret < 0))
220 return ret;
222 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
223 if (unlikely(ret)) {
224 usb_ep_dequeue(ffs->gadget->ep0, req);
225 return -EINTR;
228 ffs->setup_state = FFS_NO_SETUP;
229 return req->status ? req->status : req->actual;
232 static int __ffs_ep0_stall(struct ffs_data *ffs)
234 if (ffs->ev.can_stall) {
235 pr_vdebug("ep0 stall\n");
236 usb_ep_set_halt(ffs->gadget->ep0);
237 ffs->setup_state = FFS_NO_SETUP;
238 return -EL2HLT;
239 } else {
240 pr_debug("bogus ep0 stall!\n");
241 return -ESRCH;
245 static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
246 size_t len, loff_t *ptr)
248 struct ffs_data *ffs = file->private_data;
249 ssize_t ret;
250 char *data;
252 ENTER();
254 /* Fast check if setup was canceled */
255 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
256 return -EIDRM;
258 /* Acquire mutex */
259 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
260 if (unlikely(ret < 0))
261 return ret;
263 /* Check state */
264 switch (ffs->state) {
265 case FFS_READ_DESCRIPTORS:
266 case FFS_READ_STRINGS:
267 /* Copy data */
268 if (unlikely(len < 16)) {
269 ret = -EINVAL;
270 break;
273 data = ffs_prepare_buffer(buf, len);
274 if (IS_ERR(data)) {
275 ret = PTR_ERR(data);
276 break;
279 /* Handle data */
280 if (ffs->state == FFS_READ_DESCRIPTORS) {
281 pr_info("read descriptors\n");
282 ret = __ffs_data_got_descs(ffs, data, len);
283 if (unlikely(ret < 0))
284 break;
286 ffs->state = FFS_READ_STRINGS;
287 ret = len;
288 } else {
289 pr_info("read strings\n");
290 ret = __ffs_data_got_strings(ffs, data, len);
291 if (unlikely(ret < 0))
292 break;
294 ret = ffs_epfiles_create(ffs);
295 if (unlikely(ret)) {
296 ffs->state = FFS_CLOSING;
297 break;
300 ffs->state = FFS_ACTIVE;
301 mutex_unlock(&ffs->mutex);
303 ret = ffs_ready(ffs);
304 if (unlikely(ret < 0)) {
305 ffs->state = FFS_CLOSING;
306 return ret;
309 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
310 return len;
312 break;
314 case FFS_ACTIVE:
315 data = NULL;
317 * We're called from user space, we can use _irq
318 * rather then _irqsave
320 spin_lock_irq(&ffs->ev.waitq.lock);
321 switch (ffs_setup_state_clear_cancelled(ffs)) {
322 case FFS_SETUP_CANCELLED:
323 ret = -EIDRM;
324 goto done_spin;
326 case FFS_NO_SETUP:
327 ret = -ESRCH;
328 goto done_spin;
330 case FFS_SETUP_PENDING:
331 break;
334 /* FFS_SETUP_PENDING */
335 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
336 spin_unlock_irq(&ffs->ev.waitq.lock);
337 ret = __ffs_ep0_stall(ffs);
338 break;
341 /* FFS_SETUP_PENDING and not stall */
342 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
344 spin_unlock_irq(&ffs->ev.waitq.lock);
346 data = ffs_prepare_buffer(buf, len);
347 if (IS_ERR(data)) {
348 ret = PTR_ERR(data);
349 break;
352 spin_lock_irq(&ffs->ev.waitq.lock);
355 * We are guaranteed to be still in FFS_ACTIVE state
356 * but the state of setup could have changed from
357 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
358 * to check for that. If that happened we copied data
359 * from user space in vain but it's unlikely.
361 * For sure we are not in FFS_NO_SETUP since this is
362 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
363 * transition can be performed and it's protected by
364 * mutex.
366 if (ffs_setup_state_clear_cancelled(ffs) ==
367 FFS_SETUP_CANCELLED) {
368 ret = -EIDRM;
369 done_spin:
370 spin_unlock_irq(&ffs->ev.waitq.lock);
371 } else {
372 /* unlocks spinlock */
373 ret = __ffs_ep0_queue_wait(ffs, data, len);
375 kfree(data);
376 break;
378 default:
379 ret = -EBADFD;
380 break;
383 mutex_unlock(&ffs->mutex);
384 return ret;
387 static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
388 size_t n)
391 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
392 * to release them.
394 struct usb_functionfs_event events[n];
395 unsigned i = 0;
397 memset(events, 0, sizeof events);
399 do {
400 events[i].type = ffs->ev.types[i];
401 if (events[i].type == FUNCTIONFS_SETUP) {
402 events[i].u.setup = ffs->ev.setup;
403 ffs->setup_state = FFS_SETUP_PENDING;
405 } while (++i < n);
407 if (n < ffs->ev.count) {
408 ffs->ev.count -= n;
409 memmove(ffs->ev.types, ffs->ev.types + n,
410 ffs->ev.count * sizeof *ffs->ev.types);
411 } else {
412 ffs->ev.count = 0;
415 spin_unlock_irq(&ffs->ev.waitq.lock);
416 mutex_unlock(&ffs->mutex);
418 return unlikely(__copy_to_user(buf, events, sizeof events))
419 ? -EFAULT : sizeof events;
422 static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
423 size_t len, loff_t *ptr)
425 struct ffs_data *ffs = file->private_data;
426 char *data = NULL;
427 size_t n;
428 int ret;
430 ENTER();
432 /* Fast check if setup was canceled */
433 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
434 return -EIDRM;
436 /* Acquire mutex */
437 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
438 if (unlikely(ret < 0))
439 return ret;
441 /* Check state */
442 if (ffs->state != FFS_ACTIVE) {
443 ret = -EBADFD;
444 goto done_mutex;
448 * We're called from user space, we can use _irq rather then
449 * _irqsave
451 spin_lock_irq(&ffs->ev.waitq.lock);
453 switch (ffs_setup_state_clear_cancelled(ffs)) {
454 case FFS_SETUP_CANCELLED:
455 ret = -EIDRM;
456 break;
458 case FFS_NO_SETUP:
459 n = len / sizeof(struct usb_functionfs_event);
460 if (unlikely(!n)) {
461 ret = -EINVAL;
462 break;
465 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
466 ret = -EAGAIN;
467 break;
470 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
471 ffs->ev.count)) {
472 ret = -EINTR;
473 break;
476 return __ffs_ep0_read_events(ffs, buf,
477 min(n, (size_t)ffs->ev.count));
479 case FFS_SETUP_PENDING:
480 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
481 spin_unlock_irq(&ffs->ev.waitq.lock);
482 ret = __ffs_ep0_stall(ffs);
483 goto done_mutex;
486 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
488 spin_unlock_irq(&ffs->ev.waitq.lock);
490 if (likely(len)) {
491 data = kmalloc(len, GFP_KERNEL);
492 if (unlikely(!data)) {
493 ret = -ENOMEM;
494 goto done_mutex;
498 spin_lock_irq(&ffs->ev.waitq.lock);
500 /* See ffs_ep0_write() */
501 if (ffs_setup_state_clear_cancelled(ffs) ==
502 FFS_SETUP_CANCELLED) {
503 ret = -EIDRM;
504 break;
507 /* unlocks spinlock */
508 ret = __ffs_ep0_queue_wait(ffs, data, len);
509 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
510 ret = -EFAULT;
511 goto done_mutex;
513 default:
514 ret = -EBADFD;
515 break;
518 spin_unlock_irq(&ffs->ev.waitq.lock);
519 done_mutex:
520 mutex_unlock(&ffs->mutex);
521 kfree(data);
522 return ret;
525 static int ffs_ep0_open(struct inode *inode, struct file *file)
527 struct ffs_data *ffs = inode->i_private;
529 ENTER();
531 if (unlikely(ffs->state == FFS_CLOSING))
532 return -EBUSY;
534 file->private_data = ffs;
535 ffs_data_opened(ffs);
537 return 0;
540 static int ffs_ep0_release(struct inode *inode, struct file *file)
542 struct ffs_data *ffs = file->private_data;
544 ENTER();
546 ffs_data_closed(ffs);
548 return 0;
551 static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
553 struct ffs_data *ffs = file->private_data;
554 struct usb_gadget *gadget = ffs->gadget;
555 long ret;
557 ENTER();
559 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
560 struct ffs_function *func = ffs->func;
561 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
562 } else if (gadget && gadget->ops->ioctl) {
563 ret = gadget->ops->ioctl(gadget, code, value);
564 } else {
565 ret = -ENOTTY;
568 return ret;
571 static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
573 struct ffs_data *ffs = file->private_data;
574 unsigned int mask = POLLWRNORM;
575 int ret;
577 poll_wait(file, &ffs->ev.waitq, wait);
579 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
580 if (unlikely(ret < 0))
581 return mask;
583 switch (ffs->state) {
584 case FFS_READ_DESCRIPTORS:
585 case FFS_READ_STRINGS:
586 mask |= POLLOUT;
587 break;
589 case FFS_ACTIVE:
590 switch (ffs->setup_state) {
591 case FFS_NO_SETUP:
592 if (ffs->ev.count)
593 mask |= POLLIN;
594 break;
596 case FFS_SETUP_PENDING:
597 case FFS_SETUP_CANCELLED:
598 mask |= (POLLIN | POLLOUT);
599 break;
601 case FFS_CLOSING:
602 break;
605 mutex_unlock(&ffs->mutex);
607 return mask;
610 static const struct file_operations ffs_ep0_operations = {
611 .llseek = no_llseek,
613 .open = ffs_ep0_open,
614 .write = ffs_ep0_write,
615 .read = ffs_ep0_read,
616 .release = ffs_ep0_release,
617 .unlocked_ioctl = ffs_ep0_ioctl,
618 .poll = ffs_ep0_poll,
622 /* "Normal" endpoints operations ********************************************/
624 static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
626 ENTER();
627 if (likely(req->context)) {
628 struct ffs_ep *ep = _ep->driver_data;
629 ep->status = req->status ? req->status : req->actual;
630 complete(req->context);
634 static void ffs_user_copy_worker(struct work_struct *work)
636 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
637 work);
638 int ret = io_data->req->status ? io_data->req->status :
639 io_data->req->actual;
641 if (io_data->read && ret > 0) {
642 int i;
643 size_t pos = 0;
644 use_mm(io_data->mm);
645 for (i = 0; i < io_data->nr_segs; i++) {
646 if (unlikely(copy_to_user(io_data->iovec[i].iov_base,
647 &io_data->buf[pos],
648 io_data->iovec[i].iov_len))) {
649 ret = -EFAULT;
650 break;
652 pos += io_data->iovec[i].iov_len;
654 unuse_mm(io_data->mm);
657 aio_complete(io_data->kiocb, ret, ret);
659 usb_ep_free_request(io_data->ep, io_data->req);
661 io_data->kiocb->private = NULL;
662 if (io_data->read)
663 kfree(io_data->iovec);
664 kfree(io_data->buf);
665 kfree(io_data);
668 static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
669 struct usb_request *req)
671 struct ffs_io_data *io_data = req->context;
673 ENTER();
675 INIT_WORK(&io_data->work, ffs_user_copy_worker);
676 schedule_work(&io_data->work);
679 static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
681 struct ffs_epfile *epfile = file->private_data;
682 struct ffs_ep *ep;
683 char *data = NULL;
684 ssize_t ret, data_len;
685 int halt;
687 /* Are we still active? */
688 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
689 ret = -ENODEV;
690 goto error;
693 /* Wait for endpoint to be enabled */
694 ep = epfile->ep;
695 if (!ep) {
696 if (file->f_flags & O_NONBLOCK) {
697 ret = -EAGAIN;
698 goto error;
701 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
702 if (ret) {
703 ret = -EINTR;
704 goto error;
708 /* Do we halt? */
709 halt = (!io_data->read == !epfile->in);
710 if (halt && epfile->isoc) {
711 ret = -EINVAL;
712 goto error;
715 /* Allocate & copy */
716 if (!halt) {
718 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
719 * before the waiting completes, so do not assign to 'gadget' earlier
721 struct usb_gadget *gadget = epfile->ffs->gadget;
723 spin_lock_irq(&epfile->ffs->eps_lock);
724 /* In the meantime, endpoint got disabled or changed. */
725 if (epfile->ep != ep) {
726 spin_unlock_irq(&epfile->ffs->eps_lock);
727 return -ESHUTDOWN;
730 * Controller may require buffer size to be aligned to
731 * maxpacketsize of an out endpoint.
733 data_len = io_data->read ?
734 usb_ep_align_maybe(gadget, ep->ep, io_data->len) :
735 io_data->len;
736 spin_unlock_irq(&epfile->ffs->eps_lock);
738 data = kmalloc(data_len, GFP_KERNEL);
739 if (unlikely(!data))
740 return -ENOMEM;
741 if (io_data->aio && !io_data->read) {
742 int i;
743 size_t pos = 0;
744 for (i = 0; i < io_data->nr_segs; i++) {
745 if (unlikely(copy_from_user(&data[pos],
746 io_data->iovec[i].iov_base,
747 io_data->iovec[i].iov_len))) {
748 ret = -EFAULT;
749 goto error;
751 pos += io_data->iovec[i].iov_len;
753 } else {
754 if (!io_data->read &&
755 unlikely(__copy_from_user(data, io_data->buf,
756 io_data->len))) {
757 ret = -EFAULT;
758 goto error;
763 /* We will be using request */
764 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
765 if (unlikely(ret))
766 goto error;
768 spin_lock_irq(&epfile->ffs->eps_lock);
770 if (epfile->ep != ep) {
771 /* In the meantime, endpoint got disabled or changed. */
772 ret = -ESHUTDOWN;
773 spin_unlock_irq(&epfile->ffs->eps_lock);
774 } else if (halt) {
775 /* Halt */
776 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
777 usb_ep_set_halt(ep->ep);
778 spin_unlock_irq(&epfile->ffs->eps_lock);
779 ret = -EBADMSG;
780 } else {
781 /* Fire the request */
782 struct usb_request *req;
784 if (io_data->aio) {
785 req = usb_ep_alloc_request(ep->ep, GFP_KERNEL);
786 if (unlikely(!req))
787 goto error_lock;
789 req->buf = data;
790 req->length = io_data->len;
792 io_data->buf = data;
793 io_data->ep = ep->ep;
794 io_data->req = req;
796 req->context = io_data;
797 req->complete = ffs_epfile_async_io_complete;
799 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
800 if (unlikely(ret)) {
801 usb_ep_free_request(ep->ep, req);
802 goto error_lock;
804 ret = -EIOCBQUEUED;
806 spin_unlock_irq(&epfile->ffs->eps_lock);
807 } else {
808 DECLARE_COMPLETION_ONSTACK(done);
810 req = ep->req;
811 req->buf = data;
812 req->length = io_data->len;
814 req->context = &done;
815 req->complete = ffs_epfile_io_complete;
817 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
819 spin_unlock_irq(&epfile->ffs->eps_lock);
821 if (unlikely(ret < 0)) {
822 /* nop */
823 } else if (unlikely(
824 wait_for_completion_interruptible(&done))) {
825 ret = -EINTR;
826 usb_ep_dequeue(ep->ep, req);
827 } else {
829 * XXX We may end up silently droping data
830 * here. Since data_len (i.e. req->length) may
831 * be bigger than len (after being rounded up
832 * to maxpacketsize), we may end up with more
833 * data then user space has space for.
835 ret = ep->status;
836 if (io_data->read && ret > 0) {
837 ret = min_t(size_t, ret, io_data->len);
839 if (unlikely(copy_to_user(io_data->buf,
840 data, ret)))
841 ret = -EFAULT;
844 kfree(data);
848 mutex_unlock(&epfile->mutex);
849 return ret;
851 error_lock:
852 spin_unlock_irq(&epfile->ffs->eps_lock);
853 mutex_unlock(&epfile->mutex);
854 error:
855 kfree(data);
856 return ret;
859 static ssize_t
860 ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
861 loff_t *ptr)
863 struct ffs_io_data io_data;
865 ENTER();
867 io_data.aio = false;
868 io_data.read = false;
869 io_data.buf = (char * __user)buf;
870 io_data.len = len;
872 return ffs_epfile_io(file, &io_data);
875 static ssize_t
876 ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
878 struct ffs_io_data io_data;
880 ENTER();
882 io_data.aio = false;
883 io_data.read = true;
884 io_data.buf = buf;
885 io_data.len = len;
887 return ffs_epfile_io(file, &io_data);
890 static int
891 ffs_epfile_open(struct inode *inode, struct file *file)
893 struct ffs_epfile *epfile = inode->i_private;
895 ENTER();
897 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
898 return -ENODEV;
900 file->private_data = epfile;
901 ffs_data_opened(epfile->ffs);
903 return 0;
906 static int ffs_aio_cancel(struct kiocb *kiocb)
908 struct ffs_io_data *io_data = kiocb->private;
909 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
910 int value;
912 ENTER();
914 spin_lock_irq(&epfile->ffs->eps_lock);
916 if (likely(io_data && io_data->ep && io_data->req))
917 value = usb_ep_dequeue(io_data->ep, io_data->req);
918 else
919 value = -EINVAL;
921 spin_unlock_irq(&epfile->ffs->eps_lock);
923 return value;
926 static ssize_t ffs_epfile_aio_write(struct kiocb *kiocb,
927 const struct iovec *iovec,
928 unsigned long nr_segs, loff_t loff)
930 struct ffs_io_data *io_data;
932 ENTER();
934 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
935 if (unlikely(!io_data))
936 return -ENOMEM;
938 io_data->aio = true;
939 io_data->read = false;
940 io_data->kiocb = kiocb;
941 io_data->iovec = iovec;
942 io_data->nr_segs = nr_segs;
943 io_data->len = kiocb->ki_nbytes;
944 io_data->mm = current->mm;
946 kiocb->private = io_data;
948 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
950 return ffs_epfile_io(kiocb->ki_filp, io_data);
953 static ssize_t ffs_epfile_aio_read(struct kiocb *kiocb,
954 const struct iovec *iovec,
955 unsigned long nr_segs, loff_t loff)
957 struct ffs_io_data *io_data;
958 struct iovec *iovec_copy;
960 ENTER();
962 iovec_copy = kmalloc_array(nr_segs, sizeof(*iovec_copy), GFP_KERNEL);
963 if (unlikely(!iovec_copy))
964 return -ENOMEM;
966 memcpy(iovec_copy, iovec, sizeof(struct iovec)*nr_segs);
968 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
969 if (unlikely(!io_data)) {
970 kfree(iovec_copy);
971 return -ENOMEM;
974 io_data->aio = true;
975 io_data->read = true;
976 io_data->kiocb = kiocb;
977 io_data->iovec = iovec_copy;
978 io_data->nr_segs = nr_segs;
979 io_data->len = kiocb->ki_nbytes;
980 io_data->mm = current->mm;
982 kiocb->private = io_data;
984 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
986 return ffs_epfile_io(kiocb->ki_filp, io_data);
989 static int
990 ffs_epfile_release(struct inode *inode, struct file *file)
992 struct ffs_epfile *epfile = inode->i_private;
994 ENTER();
996 ffs_data_closed(epfile->ffs);
998 return 0;
1001 static long ffs_epfile_ioctl(struct file *file, unsigned code,
1002 unsigned long value)
1004 struct ffs_epfile *epfile = file->private_data;
1005 int ret;
1007 ENTER();
1009 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1010 return -ENODEV;
1012 spin_lock_irq(&epfile->ffs->eps_lock);
1013 if (likely(epfile->ep)) {
1014 switch (code) {
1015 case FUNCTIONFS_FIFO_STATUS:
1016 ret = usb_ep_fifo_status(epfile->ep->ep);
1017 break;
1018 case FUNCTIONFS_FIFO_FLUSH:
1019 usb_ep_fifo_flush(epfile->ep->ep);
1020 ret = 0;
1021 break;
1022 case FUNCTIONFS_CLEAR_HALT:
1023 ret = usb_ep_clear_halt(epfile->ep->ep);
1024 break;
1025 case FUNCTIONFS_ENDPOINT_REVMAP:
1026 ret = epfile->ep->num;
1027 break;
1028 default:
1029 ret = -ENOTTY;
1031 } else {
1032 ret = -ENODEV;
1034 spin_unlock_irq(&epfile->ffs->eps_lock);
1036 return ret;
1039 static const struct file_operations ffs_epfile_operations = {
1040 .llseek = no_llseek,
1042 .open = ffs_epfile_open,
1043 .write = ffs_epfile_write,
1044 .read = ffs_epfile_read,
1045 .aio_write = ffs_epfile_aio_write,
1046 .aio_read = ffs_epfile_aio_read,
1047 .release = ffs_epfile_release,
1048 .unlocked_ioctl = ffs_epfile_ioctl,
1052 /* File system and super block operations ***********************************/
1055 * Mounting the file system creates a controller file, used first for
1056 * function configuration then later for event monitoring.
1059 static struct inode *__must_check
1060 ffs_sb_make_inode(struct super_block *sb, void *data,
1061 const struct file_operations *fops,
1062 const struct inode_operations *iops,
1063 struct ffs_file_perms *perms)
1065 struct inode *inode;
1067 ENTER();
1069 inode = new_inode(sb);
1071 if (likely(inode)) {
1072 struct timespec current_time = CURRENT_TIME;
1074 inode->i_ino = get_next_ino();
1075 inode->i_mode = perms->mode;
1076 inode->i_uid = perms->uid;
1077 inode->i_gid = perms->gid;
1078 inode->i_atime = current_time;
1079 inode->i_mtime = current_time;
1080 inode->i_ctime = current_time;
1081 inode->i_private = data;
1082 if (fops)
1083 inode->i_fop = fops;
1084 if (iops)
1085 inode->i_op = iops;
1088 return inode;
1091 /* Create "regular" file */
1092 static struct inode *ffs_sb_create_file(struct super_block *sb,
1093 const char *name, void *data,
1094 const struct file_operations *fops,
1095 struct dentry **dentry_p)
1097 struct ffs_data *ffs = sb->s_fs_info;
1098 struct dentry *dentry;
1099 struct inode *inode;
1101 ENTER();
1103 dentry = d_alloc_name(sb->s_root, name);
1104 if (unlikely(!dentry))
1105 return NULL;
1107 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1108 if (unlikely(!inode)) {
1109 dput(dentry);
1110 return NULL;
1113 d_add(dentry, inode);
1114 if (dentry_p)
1115 *dentry_p = dentry;
1117 return inode;
1120 /* Super block */
1121 static const struct super_operations ffs_sb_operations = {
1122 .statfs = simple_statfs,
1123 .drop_inode = generic_delete_inode,
1126 struct ffs_sb_fill_data {
1127 struct ffs_file_perms perms;
1128 umode_t root_mode;
1129 const char *dev_name;
1130 struct ffs_data *ffs_data;
1133 static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1135 struct ffs_sb_fill_data *data = _data;
1136 struct inode *inode;
1137 struct ffs_data *ffs = data->ffs_data;
1139 ENTER();
1141 ffs->sb = sb;
1142 data->ffs_data = NULL;
1143 sb->s_fs_info = ffs;
1144 sb->s_blocksize = PAGE_CACHE_SIZE;
1145 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1146 sb->s_magic = FUNCTIONFS_MAGIC;
1147 sb->s_op = &ffs_sb_operations;
1148 sb->s_time_gran = 1;
1150 /* Root inode */
1151 data->perms.mode = data->root_mode;
1152 inode = ffs_sb_make_inode(sb, NULL,
1153 &simple_dir_operations,
1154 &simple_dir_inode_operations,
1155 &data->perms);
1156 sb->s_root = d_make_root(inode);
1157 if (unlikely(!sb->s_root))
1158 return -ENOMEM;
1160 /* EP0 file */
1161 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1162 &ffs_ep0_operations, NULL)))
1163 return -ENOMEM;
1165 return 0;
1168 static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1170 ENTER();
1172 if (!opts || !*opts)
1173 return 0;
1175 for (;;) {
1176 unsigned long value;
1177 char *eq, *comma;
1179 /* Option limit */
1180 comma = strchr(opts, ',');
1181 if (comma)
1182 *comma = 0;
1184 /* Value limit */
1185 eq = strchr(opts, '=');
1186 if (unlikely(!eq)) {
1187 pr_err("'=' missing in %s\n", opts);
1188 return -EINVAL;
1190 *eq = 0;
1192 /* Parse value */
1193 if (kstrtoul(eq + 1, 0, &value)) {
1194 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1195 return -EINVAL;
1198 /* Interpret option */
1199 switch (eq - opts) {
1200 case 5:
1201 if (!memcmp(opts, "rmode", 5))
1202 data->root_mode = (value & 0555) | S_IFDIR;
1203 else if (!memcmp(opts, "fmode", 5))
1204 data->perms.mode = (value & 0666) | S_IFREG;
1205 else
1206 goto invalid;
1207 break;
1209 case 4:
1210 if (!memcmp(opts, "mode", 4)) {
1211 data->root_mode = (value & 0555) | S_IFDIR;
1212 data->perms.mode = (value & 0666) | S_IFREG;
1213 } else {
1214 goto invalid;
1216 break;
1218 case 3:
1219 if (!memcmp(opts, "uid", 3)) {
1220 data->perms.uid = make_kuid(current_user_ns(), value);
1221 if (!uid_valid(data->perms.uid)) {
1222 pr_err("%s: unmapped value: %lu\n", opts, value);
1223 return -EINVAL;
1225 } else if (!memcmp(opts, "gid", 3)) {
1226 data->perms.gid = make_kgid(current_user_ns(), value);
1227 if (!gid_valid(data->perms.gid)) {
1228 pr_err("%s: unmapped value: %lu\n", opts, value);
1229 return -EINVAL;
1231 } else {
1232 goto invalid;
1234 break;
1236 default:
1237 invalid:
1238 pr_err("%s: invalid option\n", opts);
1239 return -EINVAL;
1242 /* Next iteration */
1243 if (!comma)
1244 break;
1245 opts = comma + 1;
1248 return 0;
1251 /* "mount -t functionfs dev_name /dev/function" ends up here */
1253 static struct dentry *
1254 ffs_fs_mount(struct file_system_type *t, int flags,
1255 const char *dev_name, void *opts)
1257 struct ffs_sb_fill_data data = {
1258 .perms = {
1259 .mode = S_IFREG | 0600,
1260 .uid = GLOBAL_ROOT_UID,
1261 .gid = GLOBAL_ROOT_GID,
1263 .root_mode = S_IFDIR | 0500,
1265 struct dentry *rv;
1266 int ret;
1267 void *ffs_dev;
1268 struct ffs_data *ffs;
1270 ENTER();
1272 ret = ffs_fs_parse_opts(&data, opts);
1273 if (unlikely(ret < 0))
1274 return ERR_PTR(ret);
1276 ffs = ffs_data_new();
1277 if (unlikely(!ffs))
1278 return ERR_PTR(-ENOMEM);
1279 ffs->file_perms = data.perms;
1281 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1282 if (unlikely(!ffs->dev_name)) {
1283 ffs_data_put(ffs);
1284 return ERR_PTR(-ENOMEM);
1287 ffs_dev = ffs_acquire_dev(dev_name);
1288 if (IS_ERR(ffs_dev)) {
1289 ffs_data_put(ffs);
1290 return ERR_CAST(ffs_dev);
1292 ffs->private_data = ffs_dev;
1293 data.ffs_data = ffs;
1295 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1296 if (IS_ERR(rv) && data.ffs_data) {
1297 ffs_release_dev(data.ffs_data);
1298 ffs_data_put(data.ffs_data);
1300 return rv;
1303 static void
1304 ffs_fs_kill_sb(struct super_block *sb)
1306 ENTER();
1308 kill_litter_super(sb);
1309 if (sb->s_fs_info) {
1310 ffs_release_dev(sb->s_fs_info);
1311 ffs_data_put(sb->s_fs_info);
1315 static struct file_system_type ffs_fs_type = {
1316 .owner = THIS_MODULE,
1317 .name = "functionfs",
1318 .mount = ffs_fs_mount,
1319 .kill_sb = ffs_fs_kill_sb,
1321 MODULE_ALIAS_FS("functionfs");
1324 /* Driver's main init/cleanup functions *************************************/
1326 static int functionfs_init(void)
1328 int ret;
1330 ENTER();
1332 ret = register_filesystem(&ffs_fs_type);
1333 if (likely(!ret))
1334 pr_info("file system registered\n");
1335 else
1336 pr_err("failed registering file system (%d)\n", ret);
1338 return ret;
1341 static void functionfs_cleanup(void)
1343 ENTER();
1345 pr_info("unloading\n");
1346 unregister_filesystem(&ffs_fs_type);
1350 /* ffs_data and ffs_function construction and destruction code **************/
1352 static void ffs_data_clear(struct ffs_data *ffs);
1353 static void ffs_data_reset(struct ffs_data *ffs);
1355 static void ffs_data_get(struct ffs_data *ffs)
1357 ENTER();
1359 atomic_inc(&ffs->ref);
1362 static void ffs_data_opened(struct ffs_data *ffs)
1364 ENTER();
1366 atomic_inc(&ffs->ref);
1367 atomic_inc(&ffs->opened);
1370 static void ffs_data_put(struct ffs_data *ffs)
1372 ENTER();
1374 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1375 pr_info("%s(): freeing\n", __func__);
1376 ffs_data_clear(ffs);
1377 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1378 waitqueue_active(&ffs->ep0req_completion.wait));
1379 kfree(ffs->dev_name);
1380 kfree(ffs);
1384 static void ffs_data_closed(struct ffs_data *ffs)
1386 ENTER();
1388 if (atomic_dec_and_test(&ffs->opened)) {
1389 ffs->state = FFS_CLOSING;
1390 ffs_data_reset(ffs);
1393 ffs_data_put(ffs);
1396 static struct ffs_data *ffs_data_new(void)
1398 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1399 if (unlikely(!ffs))
1400 return NULL;
1402 ENTER();
1404 atomic_set(&ffs->ref, 1);
1405 atomic_set(&ffs->opened, 0);
1406 ffs->state = FFS_READ_DESCRIPTORS;
1407 mutex_init(&ffs->mutex);
1408 spin_lock_init(&ffs->eps_lock);
1409 init_waitqueue_head(&ffs->ev.waitq);
1410 init_completion(&ffs->ep0req_completion);
1412 /* XXX REVISIT need to update it in some places, or do we? */
1413 ffs->ev.can_stall = 1;
1415 return ffs;
1418 static void ffs_data_clear(struct ffs_data *ffs)
1420 ENTER();
1422 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1423 ffs_closed(ffs);
1425 BUG_ON(ffs->gadget);
1427 if (ffs->epfiles)
1428 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1430 kfree(ffs->raw_descs_data);
1431 kfree(ffs->raw_strings);
1432 kfree(ffs->stringtabs);
1435 static void ffs_data_reset(struct ffs_data *ffs)
1437 ENTER();
1439 ffs_data_clear(ffs);
1441 ffs->epfiles = NULL;
1442 ffs->raw_descs_data = NULL;
1443 ffs->raw_descs = NULL;
1444 ffs->raw_strings = NULL;
1445 ffs->stringtabs = NULL;
1447 ffs->raw_descs_length = 0;
1448 ffs->fs_descs_count = 0;
1449 ffs->hs_descs_count = 0;
1450 ffs->ss_descs_count = 0;
1452 ffs->strings_count = 0;
1453 ffs->interfaces_count = 0;
1454 ffs->eps_count = 0;
1456 ffs->ev.count = 0;
1458 ffs->state = FFS_READ_DESCRIPTORS;
1459 ffs->setup_state = FFS_NO_SETUP;
1460 ffs->flags = 0;
1464 static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1466 struct usb_gadget_strings **lang;
1467 int first_id;
1469 ENTER();
1471 if (WARN_ON(ffs->state != FFS_ACTIVE
1472 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1473 return -EBADFD;
1475 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1476 if (unlikely(first_id < 0))
1477 return first_id;
1479 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1480 if (unlikely(!ffs->ep0req))
1481 return -ENOMEM;
1482 ffs->ep0req->complete = ffs_ep0_complete;
1483 ffs->ep0req->context = ffs;
1485 lang = ffs->stringtabs;
1486 if (lang) {
1487 for (; *lang; ++lang) {
1488 struct usb_string *str = (*lang)->strings;
1489 int id = first_id;
1490 for (; str->s; ++id, ++str)
1491 str->id = id;
1495 ffs->gadget = cdev->gadget;
1496 ffs_data_get(ffs);
1497 return 0;
1500 static void functionfs_unbind(struct ffs_data *ffs)
1502 ENTER();
1504 if (!WARN_ON(!ffs->gadget)) {
1505 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1506 ffs->ep0req = NULL;
1507 ffs->gadget = NULL;
1508 clear_bit(FFS_FL_BOUND, &ffs->flags);
1509 ffs_data_put(ffs);
1513 static int ffs_epfiles_create(struct ffs_data *ffs)
1515 struct ffs_epfile *epfile, *epfiles;
1516 unsigned i, count;
1518 ENTER();
1520 count = ffs->eps_count;
1521 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1522 if (!epfiles)
1523 return -ENOMEM;
1525 epfile = epfiles;
1526 for (i = 1; i <= count; ++i, ++epfile) {
1527 epfile->ffs = ffs;
1528 mutex_init(&epfile->mutex);
1529 init_waitqueue_head(&epfile->wait);
1530 sprintf(epfiles->name, "ep%u", i);
1531 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1532 &ffs_epfile_operations,
1533 &epfile->dentry))) {
1534 ffs_epfiles_destroy(epfiles, i - 1);
1535 return -ENOMEM;
1539 ffs->epfiles = epfiles;
1540 return 0;
1543 static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1545 struct ffs_epfile *epfile = epfiles;
1547 ENTER();
1549 for (; count; --count, ++epfile) {
1550 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1551 waitqueue_active(&epfile->wait));
1552 if (epfile->dentry) {
1553 d_delete(epfile->dentry);
1554 dput(epfile->dentry);
1555 epfile->dentry = NULL;
1559 kfree(epfiles);
1563 static void ffs_func_eps_disable(struct ffs_function *func)
1565 struct ffs_ep *ep = func->eps;
1566 struct ffs_epfile *epfile = func->ffs->epfiles;
1567 unsigned count = func->ffs->eps_count;
1568 unsigned long flags;
1570 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1571 do {
1572 /* pending requests get nuked */
1573 if (likely(ep->ep))
1574 usb_ep_disable(ep->ep);
1575 epfile->ep = NULL;
1577 ++ep;
1578 ++epfile;
1579 } while (--count);
1580 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1583 static int ffs_func_eps_enable(struct ffs_function *func)
1585 struct ffs_data *ffs = func->ffs;
1586 struct ffs_ep *ep = func->eps;
1587 struct ffs_epfile *epfile = ffs->epfiles;
1588 unsigned count = ffs->eps_count;
1589 unsigned long flags;
1590 int ret = 0;
1592 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1593 do {
1594 struct usb_endpoint_descriptor *ds;
1595 int desc_idx;
1597 if (ffs->gadget->speed == USB_SPEED_SUPER)
1598 desc_idx = 2;
1599 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1600 desc_idx = 1;
1601 else
1602 desc_idx = 0;
1604 /* fall-back to lower speed if desc missing for current speed */
1605 do {
1606 ds = ep->descs[desc_idx];
1607 } while (!ds && --desc_idx >= 0);
1609 if (!ds) {
1610 ret = -EINVAL;
1611 break;
1614 ep->ep->driver_data = ep;
1615 ep->ep->desc = ds;
1616 ret = usb_ep_enable(ep->ep);
1617 if (likely(!ret)) {
1618 epfile->ep = ep;
1619 epfile->in = usb_endpoint_dir_in(ds);
1620 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1621 } else {
1622 break;
1625 wake_up(&epfile->wait);
1627 ++ep;
1628 ++epfile;
1629 } while (--count);
1630 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1632 return ret;
1636 /* Parsing and building descriptors and strings *****************************/
1639 * This validates if data pointed by data is a valid USB descriptor as
1640 * well as record how many interfaces, endpoints and strings are
1641 * required by given configuration. Returns address after the
1642 * descriptor or NULL if data is invalid.
1645 enum ffs_entity_type {
1646 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1649 typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1650 u8 *valuep,
1651 struct usb_descriptor_header *desc,
1652 void *priv);
1654 static int __must_check ffs_do_desc(char *data, unsigned len,
1655 ffs_entity_callback entity, void *priv)
1657 struct usb_descriptor_header *_ds = (void *)data;
1658 u8 length;
1659 int ret;
1661 ENTER();
1663 /* At least two bytes are required: length and type */
1664 if (len < 2) {
1665 pr_vdebug("descriptor too short\n");
1666 return -EINVAL;
1669 /* If we have at least as many bytes as the descriptor takes? */
1670 length = _ds->bLength;
1671 if (len < length) {
1672 pr_vdebug("descriptor longer then available data\n");
1673 return -EINVAL;
1676 #define __entity_check_INTERFACE(val) 1
1677 #define __entity_check_STRING(val) (val)
1678 #define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1679 #define __entity(type, val) do { \
1680 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1681 if (unlikely(!__entity_check_ ##type(val))) { \
1682 pr_vdebug("invalid entity's value\n"); \
1683 return -EINVAL; \
1685 ret = entity(FFS_ ##type, &val, _ds, priv); \
1686 if (unlikely(ret < 0)) { \
1687 pr_debug("entity " #type "(%02x); ret = %d\n", \
1688 (val), ret); \
1689 return ret; \
1691 } while (0)
1693 /* Parse descriptor depending on type. */
1694 switch (_ds->bDescriptorType) {
1695 case USB_DT_DEVICE:
1696 case USB_DT_CONFIG:
1697 case USB_DT_STRING:
1698 case USB_DT_DEVICE_QUALIFIER:
1699 /* function can't have any of those */
1700 pr_vdebug("descriptor reserved for gadget: %d\n",
1701 _ds->bDescriptorType);
1702 return -EINVAL;
1704 case USB_DT_INTERFACE: {
1705 struct usb_interface_descriptor *ds = (void *)_ds;
1706 pr_vdebug("interface descriptor\n");
1707 if (length != sizeof *ds)
1708 goto inv_length;
1710 __entity(INTERFACE, ds->bInterfaceNumber);
1711 if (ds->iInterface)
1712 __entity(STRING, ds->iInterface);
1714 break;
1716 case USB_DT_ENDPOINT: {
1717 struct usb_endpoint_descriptor *ds = (void *)_ds;
1718 pr_vdebug("endpoint descriptor\n");
1719 if (length != USB_DT_ENDPOINT_SIZE &&
1720 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1721 goto inv_length;
1722 __entity(ENDPOINT, ds->bEndpointAddress);
1724 break;
1726 case HID_DT_HID:
1727 pr_vdebug("hid descriptor\n");
1728 if (length != sizeof(struct hid_descriptor))
1729 goto inv_length;
1730 break;
1732 case USB_DT_OTG:
1733 if (length != sizeof(struct usb_otg_descriptor))
1734 goto inv_length;
1735 break;
1737 case USB_DT_INTERFACE_ASSOCIATION: {
1738 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1739 pr_vdebug("interface association descriptor\n");
1740 if (length != sizeof *ds)
1741 goto inv_length;
1742 if (ds->iFunction)
1743 __entity(STRING, ds->iFunction);
1745 break;
1747 case USB_DT_SS_ENDPOINT_COMP:
1748 pr_vdebug("EP SS companion descriptor\n");
1749 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1750 goto inv_length;
1751 break;
1753 case USB_DT_OTHER_SPEED_CONFIG:
1754 case USB_DT_INTERFACE_POWER:
1755 case USB_DT_DEBUG:
1756 case USB_DT_SECURITY:
1757 case USB_DT_CS_RADIO_CONTROL:
1758 /* TODO */
1759 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1760 return -EINVAL;
1762 default:
1763 /* We should never be here */
1764 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1765 return -EINVAL;
1767 inv_length:
1768 pr_vdebug("invalid length: %d (descriptor %d)\n",
1769 _ds->bLength, _ds->bDescriptorType);
1770 return -EINVAL;
1773 #undef __entity
1774 #undef __entity_check_DESCRIPTOR
1775 #undef __entity_check_INTERFACE
1776 #undef __entity_check_STRING
1777 #undef __entity_check_ENDPOINT
1779 return length;
1782 static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1783 ffs_entity_callback entity, void *priv)
1785 const unsigned _len = len;
1786 unsigned long num = 0;
1788 ENTER();
1790 for (;;) {
1791 int ret;
1793 if (num == count)
1794 data = NULL;
1796 /* Record "descriptor" entity */
1797 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1798 if (unlikely(ret < 0)) {
1799 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1800 num, ret);
1801 return ret;
1804 if (!data)
1805 return _len - len;
1807 ret = ffs_do_desc(data, len, entity, priv);
1808 if (unlikely(ret < 0)) {
1809 pr_debug("%s returns %d\n", __func__, ret);
1810 return ret;
1813 len -= ret;
1814 data += ret;
1815 ++num;
1819 static int __ffs_data_do_entity(enum ffs_entity_type type,
1820 u8 *valuep, struct usb_descriptor_header *desc,
1821 void *priv)
1823 struct ffs_data *ffs = priv;
1825 ENTER();
1827 switch (type) {
1828 case FFS_DESCRIPTOR:
1829 break;
1831 case FFS_INTERFACE:
1833 * Interfaces are indexed from zero so if we
1834 * encountered interface "n" then there are at least
1835 * "n+1" interfaces.
1837 if (*valuep >= ffs->interfaces_count)
1838 ffs->interfaces_count = *valuep + 1;
1839 break;
1841 case FFS_STRING:
1843 * Strings are indexed from 1 (0 is magic ;) reserved
1844 * for languages list or some such)
1846 if (*valuep > ffs->strings_count)
1847 ffs->strings_count = *valuep;
1848 break;
1850 case FFS_ENDPOINT:
1851 /* Endpoints are indexed from 1 as well. */
1852 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1853 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1854 break;
1857 return 0;
1860 static int __ffs_data_got_descs(struct ffs_data *ffs,
1861 char *const _data, size_t len)
1863 char *data = _data, *raw_descs;
1864 unsigned counts[3], flags;
1865 int ret = -EINVAL, i;
1867 ENTER();
1869 if (get_unaligned_le32(data + 4) != len)
1870 goto error;
1872 switch (get_unaligned_le32(data)) {
1873 case FUNCTIONFS_DESCRIPTORS_MAGIC:
1874 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
1875 data += 8;
1876 len -= 8;
1877 break;
1878 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
1879 flags = get_unaligned_le32(data + 8);
1880 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
1881 FUNCTIONFS_HAS_HS_DESC |
1882 FUNCTIONFS_HAS_SS_DESC)) {
1883 ret = -ENOSYS;
1884 goto error;
1886 data += 12;
1887 len -= 12;
1888 break;
1889 default:
1890 goto error;
1893 /* Read fs_count, hs_count and ss_count (if present) */
1894 for (i = 0; i < 3; ++i) {
1895 if (!(flags & (1 << i))) {
1896 counts[i] = 0;
1897 } else if (len < 4) {
1898 goto error;
1899 } else {
1900 counts[i] = get_unaligned_le32(data);
1901 data += 4;
1902 len -= 4;
1906 /* Read descriptors */
1907 raw_descs = data;
1908 for (i = 0; i < 3; ++i) {
1909 if (!counts[i])
1910 continue;
1911 ret = ffs_do_descs(counts[i], data, len,
1912 __ffs_data_do_entity, ffs);
1913 if (ret < 0)
1914 goto error;
1915 data += ret;
1916 len -= ret;
1919 if (raw_descs == data || len) {
1920 ret = -EINVAL;
1921 goto error;
1924 ffs->raw_descs_data = _data;
1925 ffs->raw_descs = raw_descs;
1926 ffs->raw_descs_length = data - raw_descs;
1927 ffs->fs_descs_count = counts[0];
1928 ffs->hs_descs_count = counts[1];
1929 ffs->ss_descs_count = counts[2];
1931 return 0;
1933 error:
1934 kfree(_data);
1935 return ret;
1938 static int __ffs_data_got_strings(struct ffs_data *ffs,
1939 char *const _data, size_t len)
1941 u32 str_count, needed_count, lang_count;
1942 struct usb_gadget_strings **stringtabs, *t;
1943 struct usb_string *strings, *s;
1944 const char *data = _data;
1946 ENTER();
1948 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1949 get_unaligned_le32(data + 4) != len))
1950 goto error;
1951 str_count = get_unaligned_le32(data + 8);
1952 lang_count = get_unaligned_le32(data + 12);
1954 /* if one is zero the other must be zero */
1955 if (unlikely(!str_count != !lang_count))
1956 goto error;
1958 /* Do we have at least as many strings as descriptors need? */
1959 needed_count = ffs->strings_count;
1960 if (unlikely(str_count < needed_count))
1961 goto error;
1964 * If we don't need any strings just return and free all
1965 * memory.
1967 if (!needed_count) {
1968 kfree(_data);
1969 return 0;
1972 /* Allocate everything in one chunk so there's less maintenance. */
1974 unsigned i = 0;
1975 vla_group(d);
1976 vla_item(d, struct usb_gadget_strings *, stringtabs,
1977 lang_count + 1);
1978 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
1979 vla_item(d, struct usb_string, strings,
1980 lang_count*(needed_count+1));
1982 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
1984 if (unlikely(!vlabuf)) {
1985 kfree(_data);
1986 return -ENOMEM;
1989 /* Initialize the VLA pointers */
1990 stringtabs = vla_ptr(vlabuf, d, stringtabs);
1991 t = vla_ptr(vlabuf, d, stringtab);
1992 i = lang_count;
1993 do {
1994 *stringtabs++ = t++;
1995 } while (--i);
1996 *stringtabs = NULL;
1998 /* stringtabs = vlabuf = d_stringtabs for later kfree */
1999 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2000 t = vla_ptr(vlabuf, d, stringtab);
2001 s = vla_ptr(vlabuf, d, strings);
2002 strings = s;
2005 /* For each language */
2006 data += 16;
2007 len -= 16;
2009 do { /* lang_count > 0 so we can use do-while */
2010 unsigned needed = needed_count;
2012 if (unlikely(len < 3))
2013 goto error_free;
2014 t->language = get_unaligned_le16(data);
2015 t->strings = s;
2016 ++t;
2018 data += 2;
2019 len -= 2;
2021 /* For each string */
2022 do { /* str_count > 0 so we can use do-while */
2023 size_t length = strnlen(data, len);
2025 if (unlikely(length == len))
2026 goto error_free;
2029 * User may provide more strings then we need,
2030 * if that's the case we simply ignore the
2031 * rest
2033 if (likely(needed)) {
2035 * s->id will be set while adding
2036 * function to configuration so for
2037 * now just leave garbage here.
2039 s->s = data;
2040 --needed;
2041 ++s;
2044 data += length + 1;
2045 len -= length + 1;
2046 } while (--str_count);
2048 s->id = 0; /* terminator */
2049 s->s = NULL;
2050 ++s;
2052 } while (--lang_count);
2054 /* Some garbage left? */
2055 if (unlikely(len))
2056 goto error_free;
2058 /* Done! */
2059 ffs->stringtabs = stringtabs;
2060 ffs->raw_strings = _data;
2062 return 0;
2064 error_free:
2065 kfree(stringtabs);
2066 error:
2067 kfree(_data);
2068 return -EINVAL;
2072 /* Events handling and management *******************************************/
2074 static void __ffs_event_add(struct ffs_data *ffs,
2075 enum usb_functionfs_event_type type)
2077 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2078 int neg = 0;
2081 * Abort any unhandled setup
2083 * We do not need to worry about some cmpxchg() changing value
2084 * of ffs->setup_state without holding the lock because when
2085 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2086 * the source does nothing.
2088 if (ffs->setup_state == FFS_SETUP_PENDING)
2089 ffs->setup_state = FFS_SETUP_CANCELLED;
2091 switch (type) {
2092 case FUNCTIONFS_RESUME:
2093 rem_type2 = FUNCTIONFS_SUSPEND;
2094 /* FALL THROUGH */
2095 case FUNCTIONFS_SUSPEND:
2096 case FUNCTIONFS_SETUP:
2097 rem_type1 = type;
2098 /* Discard all similar events */
2099 break;
2101 case FUNCTIONFS_BIND:
2102 case FUNCTIONFS_UNBIND:
2103 case FUNCTIONFS_DISABLE:
2104 case FUNCTIONFS_ENABLE:
2105 /* Discard everything other then power management. */
2106 rem_type1 = FUNCTIONFS_SUSPEND;
2107 rem_type2 = FUNCTIONFS_RESUME;
2108 neg = 1;
2109 break;
2111 default:
2112 BUG();
2116 u8 *ev = ffs->ev.types, *out = ev;
2117 unsigned n = ffs->ev.count;
2118 for (; n; --n, ++ev)
2119 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2120 *out++ = *ev;
2121 else
2122 pr_vdebug("purging event %d\n", *ev);
2123 ffs->ev.count = out - ffs->ev.types;
2126 pr_vdebug("adding event %d\n", type);
2127 ffs->ev.types[ffs->ev.count++] = type;
2128 wake_up_locked(&ffs->ev.waitq);
2131 static void ffs_event_add(struct ffs_data *ffs,
2132 enum usb_functionfs_event_type type)
2134 unsigned long flags;
2135 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2136 __ffs_event_add(ffs, type);
2137 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2141 /* Bind/unbind USB function hooks *******************************************/
2143 static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2144 struct usb_descriptor_header *desc,
2145 void *priv)
2147 struct usb_endpoint_descriptor *ds = (void *)desc;
2148 struct ffs_function *func = priv;
2149 struct ffs_ep *ffs_ep;
2150 unsigned ep_desc_id, idx;
2151 static const char *speed_names[] = { "full", "high", "super" };
2153 if (type != FFS_DESCRIPTOR)
2154 return 0;
2157 * If ss_descriptors is not NULL, we are reading super speed
2158 * descriptors; if hs_descriptors is not NULL, we are reading high
2159 * speed descriptors; otherwise, we are reading full speed
2160 * descriptors.
2162 if (func->function.ss_descriptors) {
2163 ep_desc_id = 2;
2164 func->function.ss_descriptors[(long)valuep] = desc;
2165 } else if (func->function.hs_descriptors) {
2166 ep_desc_id = 1;
2167 func->function.hs_descriptors[(long)valuep] = desc;
2168 } else {
2169 ep_desc_id = 0;
2170 func->function.fs_descriptors[(long)valuep] = desc;
2173 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2174 return 0;
2176 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2177 ffs_ep = func->eps + idx;
2179 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2180 pr_err("two %sspeed descriptors for EP %d\n",
2181 speed_names[ep_desc_id],
2182 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2183 return -EINVAL;
2185 ffs_ep->descs[ep_desc_id] = ds;
2187 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2188 if (ffs_ep->ep) {
2189 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2190 if (!ds->wMaxPacketSize)
2191 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2192 } else {
2193 struct usb_request *req;
2194 struct usb_ep *ep;
2196 pr_vdebug("autoconfig\n");
2197 ep = usb_ep_autoconfig(func->gadget, ds);
2198 if (unlikely(!ep))
2199 return -ENOTSUPP;
2200 ep->driver_data = func->eps + idx;
2202 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2203 if (unlikely(!req))
2204 return -ENOMEM;
2206 ffs_ep->ep = ep;
2207 ffs_ep->req = req;
2208 func->eps_revmap[ds->bEndpointAddress &
2209 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2211 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2213 return 0;
2216 static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2217 struct usb_descriptor_header *desc,
2218 void *priv)
2220 struct ffs_function *func = priv;
2221 unsigned idx;
2222 u8 newValue;
2224 switch (type) {
2225 default:
2226 case FFS_DESCRIPTOR:
2227 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2228 return 0;
2230 case FFS_INTERFACE:
2231 idx = *valuep;
2232 if (func->interfaces_nums[idx] < 0) {
2233 int id = usb_interface_id(func->conf, &func->function);
2234 if (unlikely(id < 0))
2235 return id;
2236 func->interfaces_nums[idx] = id;
2238 newValue = func->interfaces_nums[idx];
2239 break;
2241 case FFS_STRING:
2242 /* String' IDs are allocated when fsf_data is bound to cdev */
2243 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2244 break;
2246 case FFS_ENDPOINT:
2248 * USB_DT_ENDPOINT are handled in
2249 * __ffs_func_bind_do_descs().
2251 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2252 return 0;
2254 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2255 if (unlikely(!func->eps[idx].ep))
2256 return -EINVAL;
2259 struct usb_endpoint_descriptor **descs;
2260 descs = func->eps[idx].descs;
2261 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2263 break;
2266 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2267 *valuep = newValue;
2268 return 0;
2271 static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2272 struct usb_configuration *c)
2274 struct ffs_function *func = ffs_func_from_usb(f);
2275 struct f_fs_opts *ffs_opts =
2276 container_of(f->fi, struct f_fs_opts, func_inst);
2277 int ret;
2279 ENTER();
2282 * Legacy gadget triggers binding in functionfs_ready_callback,
2283 * which already uses locking; taking the same lock here would
2284 * cause a deadlock.
2286 * Configfs-enabled gadgets however do need ffs_dev_lock.
2288 if (!ffs_opts->no_configfs)
2289 ffs_dev_lock();
2290 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2291 func->ffs = ffs_opts->dev->ffs_data;
2292 if (!ffs_opts->no_configfs)
2293 ffs_dev_unlock();
2294 if (ret)
2295 return ERR_PTR(ret);
2297 func->conf = c;
2298 func->gadget = c->cdev->gadget;
2300 ffs_data_get(func->ffs);
2303 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2304 * configurations are bound in sequence with list_for_each_entry,
2305 * in each configuration its functions are bound in sequence
2306 * with list_for_each_entry, so we assume no race condition
2307 * with regard to ffs_opts->bound access
2309 if (!ffs_opts->refcnt) {
2310 ret = functionfs_bind(func->ffs, c->cdev);
2311 if (ret)
2312 return ERR_PTR(ret);
2314 ffs_opts->refcnt++;
2315 func->function.strings = func->ffs->stringtabs;
2317 return ffs_opts;
2320 static int _ffs_func_bind(struct usb_configuration *c,
2321 struct usb_function *f)
2323 struct ffs_function *func = ffs_func_from_usb(f);
2324 struct ffs_data *ffs = func->ffs;
2326 const int full = !!func->ffs->fs_descs_count;
2327 const int high = gadget_is_dualspeed(func->gadget) &&
2328 func->ffs->hs_descs_count;
2329 const int super = gadget_is_superspeed(func->gadget) &&
2330 func->ffs->ss_descs_count;
2332 int fs_len, hs_len, ret;
2334 /* Make it a single chunk, less management later on */
2335 vla_group(d);
2336 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2337 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2338 full ? ffs->fs_descs_count + 1 : 0);
2339 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2340 high ? ffs->hs_descs_count + 1 : 0);
2341 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2342 super ? ffs->ss_descs_count + 1 : 0);
2343 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2344 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2345 char *vlabuf;
2347 ENTER();
2349 /* Has descriptors only for speeds gadget does not support */
2350 if (unlikely(!(full | high | super)))
2351 return -ENOTSUPP;
2353 /* Allocate a single chunk, less management later on */
2354 vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2355 if (unlikely(!vlabuf))
2356 return -ENOMEM;
2358 /* Zero */
2359 memset(vla_ptr(vlabuf, d, eps), 0, d_eps__sz);
2360 /* Copy descriptors */
2361 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2362 ffs->raw_descs_length);
2364 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2365 for (ret = ffs->eps_count; ret; --ret) {
2366 struct ffs_ep *ptr;
2368 ptr = vla_ptr(vlabuf, d, eps);
2369 ptr[ret].num = -1;
2372 /* Save pointers
2373 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2375 func->eps = vla_ptr(vlabuf, d, eps);
2376 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2379 * Go through all the endpoint descriptors and allocate
2380 * endpoints first, so that later we can rewrite the endpoint
2381 * numbers without worrying that it may be described later on.
2383 if (likely(full)) {
2384 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2385 fs_len = ffs_do_descs(ffs->fs_descs_count,
2386 vla_ptr(vlabuf, d, raw_descs),
2387 d_raw_descs__sz,
2388 __ffs_func_bind_do_descs, func);
2389 if (unlikely(fs_len < 0)) {
2390 ret = fs_len;
2391 goto error;
2393 } else {
2394 fs_len = 0;
2397 if (likely(high)) {
2398 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2399 hs_len = ffs_do_descs(ffs->hs_descs_count,
2400 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2401 d_raw_descs__sz - fs_len,
2402 __ffs_func_bind_do_descs, func);
2403 if (unlikely(hs_len < 0)) {
2404 ret = hs_len;
2405 goto error;
2407 } else {
2408 hs_len = 0;
2411 if (likely(super)) {
2412 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2413 ret = ffs_do_descs(ffs->ss_descs_count,
2414 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2415 d_raw_descs__sz - fs_len - hs_len,
2416 __ffs_func_bind_do_descs, func);
2417 if (unlikely(ret < 0))
2418 goto error;
2422 * Now handle interface numbers allocation and interface and
2423 * endpoint numbers rewriting. We can do that in one go
2424 * now.
2426 ret = ffs_do_descs(ffs->fs_descs_count +
2427 (high ? ffs->hs_descs_count : 0) +
2428 (super ? ffs->ss_descs_count : 0),
2429 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2430 __ffs_func_bind_do_nums, func);
2431 if (unlikely(ret < 0))
2432 goto error;
2434 /* And we're done */
2435 ffs_event_add(ffs, FUNCTIONFS_BIND);
2436 return 0;
2438 error:
2439 /* XXX Do we need to release all claimed endpoints here? */
2440 return ret;
2443 static int ffs_func_bind(struct usb_configuration *c,
2444 struct usb_function *f)
2446 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2448 if (IS_ERR(ffs_opts))
2449 return PTR_ERR(ffs_opts);
2451 return _ffs_func_bind(c, f);
2455 /* Other USB function hooks *************************************************/
2457 static int ffs_func_set_alt(struct usb_function *f,
2458 unsigned interface, unsigned alt)
2460 struct ffs_function *func = ffs_func_from_usb(f);
2461 struct ffs_data *ffs = func->ffs;
2462 int ret = 0, intf;
2464 if (alt != (unsigned)-1) {
2465 intf = ffs_func_revmap_intf(func, interface);
2466 if (unlikely(intf < 0))
2467 return intf;
2470 if (ffs->func)
2471 ffs_func_eps_disable(ffs->func);
2473 if (ffs->state != FFS_ACTIVE)
2474 return -ENODEV;
2476 if (alt == (unsigned)-1) {
2477 ffs->func = NULL;
2478 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2479 return 0;
2482 ffs->func = func;
2483 ret = ffs_func_eps_enable(func);
2484 if (likely(ret >= 0))
2485 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2486 return ret;
2489 static void ffs_func_disable(struct usb_function *f)
2491 ffs_func_set_alt(f, 0, (unsigned)-1);
2494 static int ffs_func_setup(struct usb_function *f,
2495 const struct usb_ctrlrequest *creq)
2497 struct ffs_function *func = ffs_func_from_usb(f);
2498 struct ffs_data *ffs = func->ffs;
2499 unsigned long flags;
2500 int ret;
2502 ENTER();
2504 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2505 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2506 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2507 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2508 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2511 * Most requests directed to interface go through here
2512 * (notable exceptions are set/get interface) so we need to
2513 * handle them. All other either handled by composite or
2514 * passed to usb_configuration->setup() (if one is set). No
2515 * matter, we will handle requests directed to endpoint here
2516 * as well (as it's straightforward) but what to do with any
2517 * other request?
2519 if (ffs->state != FFS_ACTIVE)
2520 return -ENODEV;
2522 switch (creq->bRequestType & USB_RECIP_MASK) {
2523 case USB_RECIP_INTERFACE:
2524 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2525 if (unlikely(ret < 0))
2526 return ret;
2527 break;
2529 case USB_RECIP_ENDPOINT:
2530 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2531 if (unlikely(ret < 0))
2532 return ret;
2533 break;
2535 default:
2536 return -EOPNOTSUPP;
2539 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2540 ffs->ev.setup = *creq;
2541 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2542 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2543 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2545 return 0;
2548 static void ffs_func_suspend(struct usb_function *f)
2550 ENTER();
2551 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2554 static void ffs_func_resume(struct usb_function *f)
2556 ENTER();
2557 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2561 /* Endpoint and interface numbers reverse mapping ***************************/
2563 static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2565 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2566 return num ? num : -EDOM;
2569 static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2571 short *nums = func->interfaces_nums;
2572 unsigned count = func->ffs->interfaces_count;
2574 for (; count; --count, ++nums) {
2575 if (*nums >= 0 && *nums == intf)
2576 return nums - func->interfaces_nums;
2579 return -EDOM;
2583 /* Devices management *******************************************************/
2585 static LIST_HEAD(ffs_devices);
2587 static struct ffs_dev *_ffs_do_find_dev(const char *name)
2589 struct ffs_dev *dev;
2591 list_for_each_entry(dev, &ffs_devices, entry) {
2592 if (!dev->name || !name)
2593 continue;
2594 if (strcmp(dev->name, name) == 0)
2595 return dev;
2598 return NULL;
2602 * ffs_lock must be taken by the caller of this function
2604 static struct ffs_dev *_ffs_get_single_dev(void)
2606 struct ffs_dev *dev;
2608 if (list_is_singular(&ffs_devices)) {
2609 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
2610 if (dev->single)
2611 return dev;
2614 return NULL;
2618 * ffs_lock must be taken by the caller of this function
2620 static struct ffs_dev *_ffs_find_dev(const char *name)
2622 struct ffs_dev *dev;
2624 dev = _ffs_get_single_dev();
2625 if (dev)
2626 return dev;
2628 return _ffs_do_find_dev(name);
2631 /* Configfs support *********************************************************/
2633 static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
2635 return container_of(to_config_group(item), struct f_fs_opts,
2636 func_inst.group);
2639 static void ffs_attr_release(struct config_item *item)
2641 struct f_fs_opts *opts = to_ffs_opts(item);
2643 usb_put_function_instance(&opts->func_inst);
2646 static struct configfs_item_operations ffs_item_ops = {
2647 .release = ffs_attr_release,
2650 static struct config_item_type ffs_func_type = {
2651 .ct_item_ops = &ffs_item_ops,
2652 .ct_owner = THIS_MODULE,
2656 /* Function registration interface ******************************************/
2658 static void ffs_free_inst(struct usb_function_instance *f)
2660 struct f_fs_opts *opts;
2662 opts = to_f_fs_opts(f);
2663 ffs_dev_lock();
2664 _ffs_free_dev(opts->dev);
2665 ffs_dev_unlock();
2666 kfree(opts);
2669 #define MAX_INST_NAME_LEN 40
2671 static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
2673 struct f_fs_opts *opts;
2674 char *ptr;
2675 const char *tmp;
2676 int name_len, ret;
2678 name_len = strlen(name) + 1;
2679 if (name_len > MAX_INST_NAME_LEN)
2680 return -ENAMETOOLONG;
2682 ptr = kstrndup(name, name_len, GFP_KERNEL);
2683 if (!ptr)
2684 return -ENOMEM;
2686 opts = to_f_fs_opts(fi);
2687 tmp = NULL;
2689 ffs_dev_lock();
2691 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
2692 ret = _ffs_name_dev(opts->dev, ptr);
2693 if (ret) {
2694 kfree(ptr);
2695 ffs_dev_unlock();
2696 return ret;
2698 opts->dev->name_allocated = true;
2700 ffs_dev_unlock();
2702 kfree(tmp);
2704 return 0;
2707 static struct usb_function_instance *ffs_alloc_inst(void)
2709 struct f_fs_opts *opts;
2710 struct ffs_dev *dev;
2712 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
2713 if (!opts)
2714 return ERR_PTR(-ENOMEM);
2716 opts->func_inst.set_inst_name = ffs_set_inst_name;
2717 opts->func_inst.free_func_inst = ffs_free_inst;
2718 ffs_dev_lock();
2719 dev = _ffs_alloc_dev();
2720 ffs_dev_unlock();
2721 if (IS_ERR(dev)) {
2722 kfree(opts);
2723 return ERR_CAST(dev);
2725 opts->dev = dev;
2726 dev->opts = opts;
2728 config_group_init_type_name(&opts->func_inst.group, "",
2729 &ffs_func_type);
2730 return &opts->func_inst;
2733 static void ffs_free(struct usb_function *f)
2735 kfree(ffs_func_from_usb(f));
2738 static void ffs_func_unbind(struct usb_configuration *c,
2739 struct usb_function *f)
2741 struct ffs_function *func = ffs_func_from_usb(f);
2742 struct ffs_data *ffs = func->ffs;
2743 struct f_fs_opts *opts =
2744 container_of(f->fi, struct f_fs_opts, func_inst);
2745 struct ffs_ep *ep = func->eps;
2746 unsigned count = ffs->eps_count;
2747 unsigned long flags;
2749 ENTER();
2750 if (ffs->func == func) {
2751 ffs_func_eps_disable(func);
2752 ffs->func = NULL;
2755 if (!--opts->refcnt)
2756 functionfs_unbind(ffs);
2758 /* cleanup after autoconfig */
2759 spin_lock_irqsave(&func->ffs->eps_lock, flags);
2760 do {
2761 if (ep->ep && ep->req)
2762 usb_ep_free_request(ep->ep, ep->req);
2763 ep->req = NULL;
2764 ++ep;
2765 } while (--count);
2766 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2767 kfree(func->eps);
2768 func->eps = NULL;
2770 * eps, descriptors and interfaces_nums are allocated in the
2771 * same chunk so only one free is required.
2773 func->function.fs_descriptors = NULL;
2774 func->function.hs_descriptors = NULL;
2775 func->function.ss_descriptors = NULL;
2776 func->interfaces_nums = NULL;
2778 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2781 static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
2783 struct ffs_function *func;
2785 ENTER();
2787 func = kzalloc(sizeof(*func), GFP_KERNEL);
2788 if (unlikely(!func))
2789 return ERR_PTR(-ENOMEM);
2791 func->function.name = "Function FS Gadget";
2793 func->function.bind = ffs_func_bind;
2794 func->function.unbind = ffs_func_unbind;
2795 func->function.set_alt = ffs_func_set_alt;
2796 func->function.disable = ffs_func_disable;
2797 func->function.setup = ffs_func_setup;
2798 func->function.suspend = ffs_func_suspend;
2799 func->function.resume = ffs_func_resume;
2800 func->function.free_func = ffs_free;
2802 return &func->function;
2806 * ffs_lock must be taken by the caller of this function
2808 static struct ffs_dev *_ffs_alloc_dev(void)
2810 struct ffs_dev *dev;
2811 int ret;
2813 if (_ffs_get_single_dev())
2814 return ERR_PTR(-EBUSY);
2816 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2817 if (!dev)
2818 return ERR_PTR(-ENOMEM);
2820 if (list_empty(&ffs_devices)) {
2821 ret = functionfs_init();
2822 if (ret) {
2823 kfree(dev);
2824 return ERR_PTR(ret);
2828 list_add(&dev->entry, &ffs_devices);
2830 return dev;
2834 * ffs_lock must be taken by the caller of this function
2835 * The caller is responsible for "name" being available whenever f_fs needs it
2837 static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
2839 struct ffs_dev *existing;
2841 existing = _ffs_do_find_dev(name);
2842 if (existing)
2843 return -EBUSY;
2845 dev->name = name;
2847 return 0;
2851 * The caller is responsible for "name" being available whenever f_fs needs it
2853 int ffs_name_dev(struct ffs_dev *dev, const char *name)
2855 int ret;
2857 ffs_dev_lock();
2858 ret = _ffs_name_dev(dev, name);
2859 ffs_dev_unlock();
2861 return ret;
2863 EXPORT_SYMBOL_GPL(ffs_name_dev);
2865 int ffs_single_dev(struct ffs_dev *dev)
2867 int ret;
2869 ret = 0;
2870 ffs_dev_lock();
2872 if (!list_is_singular(&ffs_devices))
2873 ret = -EBUSY;
2874 else
2875 dev->single = true;
2877 ffs_dev_unlock();
2878 return ret;
2880 EXPORT_SYMBOL_GPL(ffs_single_dev);
2883 * ffs_lock must be taken by the caller of this function
2885 static void _ffs_free_dev(struct ffs_dev *dev)
2887 list_del(&dev->entry);
2888 if (dev->name_allocated)
2889 kfree(dev->name);
2890 kfree(dev);
2891 if (list_empty(&ffs_devices))
2892 functionfs_cleanup();
2895 static void *ffs_acquire_dev(const char *dev_name)
2897 struct ffs_dev *ffs_dev;
2899 ENTER();
2900 ffs_dev_lock();
2902 ffs_dev = _ffs_find_dev(dev_name);
2903 if (!ffs_dev)
2904 ffs_dev = ERR_PTR(-ENODEV);
2905 else if (ffs_dev->mounted)
2906 ffs_dev = ERR_PTR(-EBUSY);
2907 else if (ffs_dev->ffs_acquire_dev_callback &&
2908 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
2909 ffs_dev = ERR_PTR(-ENODEV);
2910 else
2911 ffs_dev->mounted = true;
2913 ffs_dev_unlock();
2914 return ffs_dev;
2917 static void ffs_release_dev(struct ffs_data *ffs_data)
2919 struct ffs_dev *ffs_dev;
2921 ENTER();
2922 ffs_dev_lock();
2924 ffs_dev = ffs_data->private_data;
2925 if (ffs_dev) {
2926 ffs_dev->mounted = false;
2928 if (ffs_dev->ffs_release_dev_callback)
2929 ffs_dev->ffs_release_dev_callback(ffs_dev);
2932 ffs_dev_unlock();
2935 static int ffs_ready(struct ffs_data *ffs)
2937 struct ffs_dev *ffs_obj;
2938 int ret = 0;
2940 ENTER();
2941 ffs_dev_lock();
2943 ffs_obj = ffs->private_data;
2944 if (!ffs_obj) {
2945 ret = -EINVAL;
2946 goto done;
2948 if (WARN_ON(ffs_obj->desc_ready)) {
2949 ret = -EBUSY;
2950 goto done;
2953 ffs_obj->desc_ready = true;
2954 ffs_obj->ffs_data = ffs;
2956 if (ffs_obj->ffs_ready_callback)
2957 ret = ffs_obj->ffs_ready_callback(ffs);
2959 done:
2960 ffs_dev_unlock();
2961 return ret;
2964 static void ffs_closed(struct ffs_data *ffs)
2966 struct ffs_dev *ffs_obj;
2968 ENTER();
2969 ffs_dev_lock();
2971 ffs_obj = ffs->private_data;
2972 if (!ffs_obj)
2973 goto done;
2975 ffs_obj->desc_ready = false;
2977 if (ffs_obj->ffs_closed_callback)
2978 ffs_obj->ffs_closed_callback(ffs);
2980 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
2981 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
2982 goto done;
2984 unregister_gadget_item(ffs_obj->opts->
2985 func_inst.group.cg_item.ci_parent->ci_parent);
2986 done:
2987 ffs_dev_unlock();
2990 /* Misc helper functions ****************************************************/
2992 static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2994 return nonblock
2995 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2996 : mutex_lock_interruptible(mutex);
2999 static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3001 char *data;
3003 if (unlikely(!len))
3004 return NULL;
3006 data = kmalloc(len, GFP_KERNEL);
3007 if (unlikely(!data))
3008 return ERR_PTR(-ENOMEM);
3010 if (unlikely(__copy_from_user(data, buf, len))) {
3011 kfree(data);
3012 return ERR_PTR(-EFAULT);
3015 pr_vdebug("Buffer from user space:\n");
3016 ffs_dump_mem("", data, len);
3018 return data;
3021 DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3022 MODULE_LICENSE("GPL");
3023 MODULE_AUTHOR("Michal Nazarewicz");