blob: 9b5f9d503ff0d3d5ea24af1f9e7c1d4d5c12d896 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0+
2/*
3 * f_fs.c -- user mode file system API for USB composite function controllers
4 *
5 * Copyright (C) 2010 Samsung Electronics
6 * Author: Michal Nazarewicz <mina86@mina86.com>
7 *
8 * Based on inode.c (GadgetFS) which was:
9 * Copyright (C) 2003-2004 David Brownell
10 * Copyright (C) 2003 Agilent Technologies
11 */
12
13
14/* #define DEBUG */
15/* #define VERBOSE_DEBUG */
16
17#include <linux/blkdev.h>
18#include <linux/pagemap.h>
19#include <linux/export.h>
20#include <linux/fs_parser.h>
21#include <linux/hid.h>
22#include <linux/mm.h>
23#include <linux/module.h>
24#include <linux/scatterlist.h>
25#include <linux/sched/signal.h>
26#include <linux/uio.h>
27#include <linux/vmalloc.h>
28#include <asm/unaligned.h>
29
30#include <linux/usb/ccid.h>
31#include <linux/usb/composite.h>
32#include <linux/usb/functionfs.h>
33
34#include <linux/aio.h>
35#include <linux/mmu_context.h>
36#include <linux/poll.h>
37#include <linux/eventfd.h>
38
39#include "u_fs.h"
40#include "u_f.h"
41#include "u_os_desc.h"
42#include "configfs.h"
43
44#define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
45
46/* Reference counter handling */
47static void ffs_data_get(struct ffs_data *ffs);
48static void ffs_data_put(struct ffs_data *ffs);
49/* Creates new ffs_data object. */
50static struct ffs_data *__must_check ffs_data_new(const char *dev_name)
51 __attribute__((malloc));
52
53/* Opened counter handling. */
54static void ffs_data_opened(struct ffs_data *ffs);
55static void ffs_data_closed(struct ffs_data *ffs);
56
57/* Called with ffs->mutex held; take over ownership of data. */
58static int __must_check
59__ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
60static int __must_check
61__ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
62
63
64/* The function structure ***************************************************/
65
66struct ffs_ep;
67
68struct ffs_function {
69 struct usb_configuration *conf;
70 struct usb_gadget *gadget;
71 struct ffs_data *ffs;
72
73 struct ffs_ep *eps;
74 u8 eps_revmap[16];
75 short *interfaces_nums;
76
77 struct usb_function function;
78};
79
80
81static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
82{
83 return container_of(f, struct ffs_function, function);
84}
85
86
87static inline enum ffs_setup_state
88ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
89{
90 return (enum ffs_setup_state)
91 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
92}
93
94
95static void ffs_func_eps_disable(struct ffs_function *func);
96static int __must_check ffs_func_eps_enable(struct ffs_function *func);
97
98static int ffs_func_bind(struct usb_configuration *,
99 struct usb_function *);
100static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
101static void ffs_func_disable(struct usb_function *);
102static int ffs_func_setup(struct usb_function *,
103 const struct usb_ctrlrequest *);
104static bool ffs_func_req_match(struct usb_function *,
105 const struct usb_ctrlrequest *,
106 bool config0);
107static void ffs_func_suspend(struct usb_function *);
108static void ffs_func_resume(struct usb_function *);
109
110
111static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
112static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
113
114
115/* The endpoints structures *************************************************/
116
117struct ffs_ep {
118 struct usb_ep *ep; /* P: ffs->eps_lock */
119 struct usb_request *req; /* P: epfile->mutex */
120
121 /* [0]: full speed, [1]: high speed, [2]: super speed */
122 struct usb_endpoint_descriptor *descs[3];
123
124 u8 num;
125
126 int status; /* P: epfile->mutex */
127};
128
129struct ffs_epfile {
130 /* Protects ep->ep and ep->req. */
131 struct mutex mutex;
132
133 struct ffs_data *ffs;
134 struct ffs_ep *ep; /* P: ffs->eps_lock */
135
136 struct dentry *dentry;
137
138 /*
139 * Buffer for holding data from partial reads which may happen since
140 * we’re rounding user read requests to a multiple of a max packet size.
141 *
142 * The pointer is initialised with NULL value and may be set by
143 * __ffs_epfile_read_data function to point to a temporary buffer.
144 *
145 * In normal operation, calls to __ffs_epfile_read_buffered will consume
146 * data from said buffer and eventually free it. Importantly, while the
147 * function is using the buffer, it sets the pointer to NULL. This is
148 * all right since __ffs_epfile_read_data and __ffs_epfile_read_buffered
149 * can never run concurrently (they are synchronised by epfile->mutex)
150 * so the latter will not assign a new value to the pointer.
151 *
152 * Meanwhile ffs_func_eps_disable frees the buffer (if the pointer is
153 * valid) and sets the pointer to READ_BUFFER_DROP value. This special
154 * value is crux of the synchronisation between ffs_func_eps_disable and
155 * __ffs_epfile_read_data.
156 *
157 * Once __ffs_epfile_read_data is about to finish it will try to set the
158 * pointer back to its old value (as described above), but seeing as the
159 * pointer is not-NULL (namely READ_BUFFER_DROP) it will instead free
160 * the buffer.
161 *
162 * == State transitions ==
163 *
164 * • ptr == NULL: (initial state)
165 * ◦ __ffs_epfile_read_buffer_free: go to ptr == DROP
166 * ◦ __ffs_epfile_read_buffered: nop
167 * ◦ __ffs_epfile_read_data allocates temp buffer: go to ptr == buf
168 * ◦ reading finishes: n/a, not in ‘and reading’ state
169 * • ptr == DROP:
170 * ◦ __ffs_epfile_read_buffer_free: nop
171 * ◦ __ffs_epfile_read_buffered: go to ptr == NULL
172 * ◦ __ffs_epfile_read_data allocates temp buffer: free buf, nop
173 * ◦ reading finishes: n/a, not in ‘and reading’ state
174 * • ptr == buf:
175 * ◦ __ffs_epfile_read_buffer_free: free buf, go to ptr == DROP
176 * ◦ __ffs_epfile_read_buffered: go to ptr == NULL and reading
177 * ◦ __ffs_epfile_read_data: n/a, __ffs_epfile_read_buffered
178 * is always called first
179 * ◦ reading finishes: n/a, not in ‘and reading’ state
180 * • ptr == NULL and reading:
181 * ◦ __ffs_epfile_read_buffer_free: go to ptr == DROP and reading
182 * ◦ __ffs_epfile_read_buffered: n/a, mutex is held
183 * ◦ __ffs_epfile_read_data: n/a, mutex is held
184 * ◦ reading finishes and …
185 * … all data read: free buf, go to ptr == NULL
186 * … otherwise: go to ptr == buf and reading
187 * • ptr == DROP and reading:
188 * ◦ __ffs_epfile_read_buffer_free: nop
189 * ◦ __ffs_epfile_read_buffered: n/a, mutex is held
190 * ◦ __ffs_epfile_read_data: n/a, mutex is held
191 * ◦ reading finishes: free buf, go to ptr == DROP
192 */
193 struct ffs_buffer *read_buffer;
194#define READ_BUFFER_DROP ((struct ffs_buffer *)ERR_PTR(-ESHUTDOWN))
195
196 char name[5];
197
198 unsigned char in; /* P: ffs->eps_lock */
199 unsigned char isoc; /* P: ffs->eps_lock */
200
201 unsigned char _pad;
202};
203
204struct ffs_buffer {
205 size_t length;
206 char *data;
207 char storage[];
208};
209
210/* ffs_io_data structure ***************************************************/
211
212struct ffs_io_data {
213 bool aio;
214 bool read;
215
216 struct kiocb *kiocb;
217 struct iov_iter data;
218 const void *to_free;
219 char *buf;
220
221 struct mm_struct *mm;
222 struct work_struct work;
223
224 struct usb_ep *ep;
225 struct usb_request *req;
226 struct sg_table sgt;
227 bool use_sg;
228
229 struct ffs_data *ffs;
230};
231
232struct ffs_desc_helper {
233 struct ffs_data *ffs;
234 unsigned interfaces_count;
235 unsigned eps_count;
236};
237
238static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
239static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
240
241static struct dentry *
242ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
243 const struct file_operations *fops);
244
245/* Devices management *******************************************************/
246
247DEFINE_MUTEX(ffs_lock);
248EXPORT_SYMBOL_GPL(ffs_lock);
249
250static struct ffs_dev *_ffs_find_dev(const char *name);
251static struct ffs_dev *_ffs_alloc_dev(void);
252static void _ffs_free_dev(struct ffs_dev *dev);
253static int ffs_acquire_dev(const char *dev_name, struct ffs_data *ffs_data);
254static void ffs_release_dev(struct ffs_dev *ffs_dev);
255static int ffs_ready(struct ffs_data *ffs);
256static void ffs_closed(struct ffs_data *ffs);
257
258/* Misc helper functions ****************************************************/
259
260static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
261 __attribute__((warn_unused_result, nonnull));
262static char *ffs_prepare_buffer(const char __user *buf, size_t len)
263 __attribute__((warn_unused_result, nonnull));
264
265
266/* Control file aka ep0 *****************************************************/
267
268static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
269{
270 struct ffs_data *ffs = req->context;
271
272 complete(&ffs->ep0req_completion);
273}
274
275static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
276 __releases(&ffs->ev.waitq.lock)
277{
278 struct usb_request *req = ffs->ep0req;
279 int ret;
280
281 if (!req) {
282 spin_unlock_irq(&ffs->ev.waitq.lock);
283 return -EINVAL;
284 }
285
286 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
287
288 spin_unlock_irq(&ffs->ev.waitq.lock);
289
290 req->buf = data;
291 req->length = len;
292
293 /*
294 * UDC layer requires to provide a buffer even for ZLP, but should
295 * not use it at all. Let's provide some poisoned pointer to catch
296 * possible bug in the driver.
297 */
298 if (req->buf == NULL)
299 req->buf = (void *)0xDEADBABE;
300
301 reinit_completion(&ffs->ep0req_completion);
302
303 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
304 if (unlikely(ret < 0))
305 return ret;
306
307 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
308 if (unlikely(ret)) {
309 usb_ep_dequeue(ffs->gadget->ep0, req);
310 return -EINTR;
311 }
312
313 ffs->setup_state = FFS_NO_SETUP;
314 return req->status ? req->status : req->actual;
315}
316
317static int __ffs_ep0_stall(struct ffs_data *ffs)
318{
319 if (ffs->ev.can_stall) {
320 pr_vdebug("ep0 stall\n");
321 usb_ep_set_halt(ffs->gadget->ep0);
322 ffs->setup_state = FFS_NO_SETUP;
323 return -EL2HLT;
324 } else {
325 pr_debug("bogus ep0 stall!\n");
326 return -ESRCH;
327 }
328}
329
330static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
331 size_t len, loff_t *ptr)
332{
333 struct ffs_data *ffs = file->private_data;
334 ssize_t ret;
335 char *data;
336
337 ENTER();
338
339 /* Fast check if setup was canceled */
340 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
341 return -EIDRM;
342
343 /* Acquire mutex */
344 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
345 if (unlikely(ret < 0))
346 return ret;
347
348 /* Check state */
349 switch (ffs->state) {
350 case FFS_READ_DESCRIPTORS:
351 case FFS_READ_STRINGS:
352 /* Copy data */
353 if (unlikely(len < 16)) {
354 ret = -EINVAL;
355 break;
356 }
357
358 data = ffs_prepare_buffer(buf, len);
359 if (IS_ERR(data)) {
360 ret = PTR_ERR(data);
361 break;
362 }
363
364 /* Handle data */
365 if (ffs->state == FFS_READ_DESCRIPTORS) {
366 pr_info("read descriptors\n");
367 ret = __ffs_data_got_descs(ffs, data, len);
368 if (unlikely(ret < 0))
369 break;
370
371 ffs->state = FFS_READ_STRINGS;
372 ret = len;
373 } else {
374 pr_info("read strings\n");
375 ret = __ffs_data_got_strings(ffs, data, len);
376 if (unlikely(ret < 0))
377 break;
378
379 ret = ffs_epfiles_create(ffs);
380 if (unlikely(ret)) {
381 ffs->state = FFS_CLOSING;
382 break;
383 }
384
385 ffs->state = FFS_ACTIVE;
386 mutex_unlock(&ffs->mutex);
387
388 ret = ffs_ready(ffs);
389 if (unlikely(ret < 0)) {
390 ffs->state = FFS_CLOSING;
391 return ret;
392 }
393
394 return len;
395 }
396 break;
397
398 case FFS_ACTIVE:
399 data = NULL;
400 /*
401 * We're called from user space, we can use _irq
402 * rather then _irqsave
403 */
404 spin_lock_irq(&ffs->ev.waitq.lock);
405 switch (ffs_setup_state_clear_cancelled(ffs)) {
406 case FFS_SETUP_CANCELLED:
407 ret = -EIDRM;
408 goto done_spin;
409
410 case FFS_NO_SETUP:
411 ret = -ESRCH;
412 goto done_spin;
413
414 case FFS_SETUP_PENDING:
415 break;
416 }
417
418 /* FFS_SETUP_PENDING */
419 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
420 spin_unlock_irq(&ffs->ev.waitq.lock);
421 ret = __ffs_ep0_stall(ffs);
422 break;
423 }
424
425 /* FFS_SETUP_PENDING and not stall */
426 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
427
428 spin_unlock_irq(&ffs->ev.waitq.lock);
429
430 data = ffs_prepare_buffer(buf, len);
431 if (IS_ERR(data)) {
432 ret = PTR_ERR(data);
433 break;
434 }
435
436 spin_lock_irq(&ffs->ev.waitq.lock);
437
438 /*
439 * We are guaranteed to be still in FFS_ACTIVE state
440 * but the state of setup could have changed from
441 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
442 * to check for that. If that happened we copied data
443 * from user space in vain but it's unlikely.
444 *
445 * For sure we are not in FFS_NO_SETUP since this is
446 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
447 * transition can be performed and it's protected by
448 * mutex.
449 */
450 if (ffs_setup_state_clear_cancelled(ffs) ==
451 FFS_SETUP_CANCELLED) {
452 ret = -EIDRM;
453done_spin:
454 spin_unlock_irq(&ffs->ev.waitq.lock);
455 } else {
456 /* unlocks spinlock */
457 ret = __ffs_ep0_queue_wait(ffs, data, len);
458 }
459 kfree(data);
460 break;
461
462 default:
463 ret = -EBADFD;
464 break;
465 }
466
467 mutex_unlock(&ffs->mutex);
468 return ret;
469}
470
471/* Called with ffs->ev.waitq.lock and ffs->mutex held, both released on exit. */
472static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
473 size_t n)
474 __releases(&ffs->ev.waitq.lock)
475{
476 /*
477 * n cannot be bigger than ffs->ev.count, which cannot be bigger than
478 * size of ffs->ev.types array (which is four) so that's how much space
479 * we reserve.
480 */
481 struct usb_functionfs_event events[ARRAY_SIZE(ffs->ev.types)];
482 const size_t size = n * sizeof *events;
483 unsigned i = 0;
484
485 memset(events, 0, size);
486
487 do {
488 events[i].type = ffs->ev.types[i];
489 if (events[i].type == FUNCTIONFS_SETUP) {
490 events[i].u.setup = ffs->ev.setup;
491 ffs->setup_state = FFS_SETUP_PENDING;
492 }
493 } while (++i < n);
494
495 ffs->ev.count -= n;
496 if (ffs->ev.count)
497 memmove(ffs->ev.types, ffs->ev.types + n,
498 ffs->ev.count * sizeof *ffs->ev.types);
499
500 spin_unlock_irq(&ffs->ev.waitq.lock);
501 mutex_unlock(&ffs->mutex);
502
503 return unlikely(copy_to_user(buf, events, size)) ? -EFAULT : size;
504}
505
506static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
507 size_t len, loff_t *ptr)
508{
509 struct ffs_data *ffs = file->private_data;
510 char *data = NULL;
511 size_t n;
512 int ret;
513
514 ENTER();
515
516 /* Fast check if setup was canceled */
517 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
518 return -EIDRM;
519
520 /* Acquire mutex */
521 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
522 if (unlikely(ret < 0))
523 return ret;
524
525 /* Check state */
526 if (ffs->state != FFS_ACTIVE) {
527 ret = -EBADFD;
528 goto done_mutex;
529 }
530
531 /*
532 * We're called from user space, we can use _irq rather then
533 * _irqsave
534 */
535 spin_lock_irq(&ffs->ev.waitq.lock);
536
537 switch (ffs_setup_state_clear_cancelled(ffs)) {
538 case FFS_SETUP_CANCELLED:
539 ret = -EIDRM;
540 break;
541
542 case FFS_NO_SETUP:
543 n = len / sizeof(struct usb_functionfs_event);
544 if (unlikely(!n)) {
545 ret = -EINVAL;
546 break;
547 }
548
549 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
550 ret = -EAGAIN;
551 break;
552 }
553
554 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
555 ffs->ev.count)) {
556 ret = -EINTR;
557 break;
558 }
559
560 /* unlocks spinlock */
561 return __ffs_ep0_read_events(ffs, buf,
562 min(n, (size_t)ffs->ev.count));
563
564 case FFS_SETUP_PENDING:
565 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
566 spin_unlock_irq(&ffs->ev.waitq.lock);
567 ret = __ffs_ep0_stall(ffs);
568 goto done_mutex;
569 }
570
571 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
572
573 spin_unlock_irq(&ffs->ev.waitq.lock);
574
575 if (likely(len)) {
576 data = kmalloc(len, GFP_KERNEL);
577 if (unlikely(!data)) {
578 ret = -ENOMEM;
579 goto done_mutex;
580 }
581 }
582
583 spin_lock_irq(&ffs->ev.waitq.lock);
584
585 /* See ffs_ep0_write() */
586 if (ffs_setup_state_clear_cancelled(ffs) ==
587 FFS_SETUP_CANCELLED) {
588 ret = -EIDRM;
589 break;
590 }
591
592 /* unlocks spinlock */
593 ret = __ffs_ep0_queue_wait(ffs, data, len);
594 if (likely(ret > 0) && unlikely(copy_to_user(buf, data, len)))
595 ret = -EFAULT;
596 goto done_mutex;
597
598 default:
599 ret = -EBADFD;
600 break;
601 }
602
603 spin_unlock_irq(&ffs->ev.waitq.lock);
604done_mutex:
605 mutex_unlock(&ffs->mutex);
606 kfree(data);
607 return ret;
608}
609
610static int ffs_ep0_open(struct inode *inode, struct file *file)
611{
612 struct ffs_data *ffs = inode->i_private;
613
614 ENTER();
615
616 if (unlikely(ffs->state == FFS_CLOSING))
617 return -EBUSY;
618
619 file->private_data = ffs;
620 ffs_data_opened(ffs);
621
622 return stream_open(inode, file);
623}
624
625static int ffs_ep0_release(struct inode *inode, struct file *file)
626{
627 struct ffs_data *ffs = file->private_data;
628
629 ENTER();
630
631 ffs_data_closed(ffs);
632
633 return 0;
634}
635
636static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
637{
638 struct ffs_data *ffs = file->private_data;
639 struct usb_gadget *gadget = ffs->gadget;
640 long ret;
641
642 ENTER();
643
644 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
645 struct ffs_function *func = ffs->func;
646 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
647 } else if (gadget && gadget->ops->ioctl) {
648 ret = gadget->ops->ioctl(gadget, code, value);
649 } else {
650 ret = -ENOTTY;
651 }
652
653 return ret;
654}
655
656static __poll_t ffs_ep0_poll(struct file *file, poll_table *wait)
657{
658 struct ffs_data *ffs = file->private_data;
659 __poll_t mask = EPOLLWRNORM;
660 int ret;
661
662 poll_wait(file, &ffs->ev.waitq, wait);
663
664 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
665 if (unlikely(ret < 0))
666 return mask;
667
668 switch (ffs->state) {
669 case FFS_READ_DESCRIPTORS:
670 case FFS_READ_STRINGS:
671 mask |= EPOLLOUT;
672 break;
673
674 case FFS_ACTIVE:
675 switch (ffs->setup_state) {
676 case FFS_NO_SETUP:
677 if (ffs->ev.count)
678 mask |= EPOLLIN;
679 break;
680
681 case FFS_SETUP_PENDING:
682 case FFS_SETUP_CANCELLED:
683 mask |= (EPOLLIN | EPOLLOUT);
684 break;
685 }
686 case FFS_CLOSING:
687 break;
688 case FFS_DEACTIVATED:
689 break;
690 }
691
692 mutex_unlock(&ffs->mutex);
693
694 return mask;
695}
696
697static const struct file_operations ffs_ep0_operations = {
698 .llseek = no_llseek,
699
700 .open = ffs_ep0_open,
701 .write = ffs_ep0_write,
702 .read = ffs_ep0_read,
703 .release = ffs_ep0_release,
704 .unlocked_ioctl = ffs_ep0_ioctl,
705 .poll = ffs_ep0_poll,
706};
707
708
709/* "Normal" endpoints operations ********************************************/
710
711static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
712{
713 ENTER();
714 if (likely(req->context)) {
715 struct ffs_ep *ep = _ep->driver_data;
716 ep->status = req->status ? req->status : req->actual;
717 complete(req->context);
718 }
719}
720
721static ssize_t ffs_copy_to_iter(void *data, int data_len, struct iov_iter *iter)
722{
723 ssize_t ret = copy_to_iter(data, data_len, iter);
724 if (likely(ret == data_len))
725 return ret;
726
727 if (unlikely(iov_iter_count(iter)))
728 return -EFAULT;
729
730 /*
731 * Dear user space developer!
732 *
733 * TL;DR: To stop getting below error message in your kernel log, change
734 * user space code using functionfs to align read buffers to a max
735 * packet size.
736 *
737 * Some UDCs (e.g. dwc3) require request sizes to be a multiple of a max
738 * packet size. When unaligned buffer is passed to functionfs, it
739 * internally uses a larger, aligned buffer so that such UDCs are happy.
740 *
741 * Unfortunately, this means that host may send more data than was
742 * requested in read(2) system call. f_fs doesn’t know what to do with
743 * that excess data so it simply drops it.
744 *
745 * Was the buffer aligned in the first place, no such problem would
746 * happen.
747 *
748 * Data may be dropped only in AIO reads. Synchronous reads are handled
749 * by splitting a request into multiple parts. This splitting may still
750 * be a problem though so it’s likely best to align the buffer
751 * regardless of it being AIO or not..
752 *
753 * This only affects OUT endpoints, i.e. reading data with a read(2),
754 * aio_read(2) etc. system calls. Writing data to an IN endpoint is not
755 * affected.
756 */
757 pr_err("functionfs read size %d > requested size %zd, dropping excess data. "
758 "Align read buffer size to max packet size to avoid the problem.\n",
759 data_len, ret);
760
761 return ret;
762}
763
764/*
765 * allocate a virtually contiguous buffer and create a scatterlist describing it
766 * @sg_table - pointer to a place to be filled with sg_table contents
767 * @size - required buffer size
768 */
769static void *ffs_build_sg_list(struct sg_table *sgt, size_t sz)
770{
771 struct page **pages;
772 void *vaddr, *ptr;
773 unsigned int n_pages;
774 int i;
775
776 vaddr = vmalloc(sz);
777 if (!vaddr)
778 return NULL;
779
780 n_pages = PAGE_ALIGN(sz) >> PAGE_SHIFT;
781 pages = kvmalloc_array(n_pages, sizeof(struct page *), GFP_KERNEL);
782 if (!pages) {
783 vfree(vaddr);
784
785 return NULL;
786 }
787 for (i = 0, ptr = vaddr; i < n_pages; ++i, ptr += PAGE_SIZE)
788 pages[i] = vmalloc_to_page(ptr);
789
790 if (sg_alloc_table_from_pages(sgt, pages, n_pages, 0, sz, GFP_KERNEL)) {
791 kvfree(pages);
792 vfree(vaddr);
793
794 return NULL;
795 }
796 kvfree(pages);
797
798 return vaddr;
799}
800
801static inline void *ffs_alloc_buffer(struct ffs_io_data *io_data,
802 size_t data_len)
803{
804 if (io_data->use_sg)
805 return ffs_build_sg_list(&io_data->sgt, data_len);
806
807 return kmalloc(data_len, GFP_KERNEL);
808}
809
810static inline void ffs_free_buffer(struct ffs_io_data *io_data)
811{
812 if (!io_data->buf)
813 return;
814
815 if (io_data->use_sg) {
816 sg_free_table(&io_data->sgt);
817 vfree(io_data->buf);
818 } else {
819 kfree(io_data->buf);
820 }
821}
822
823static void ffs_user_copy_worker(struct work_struct *work)
824{
825 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
826 work);
827 int ret = io_data->req->status ? io_data->req->status :
828 io_data->req->actual;
829 bool kiocb_has_eventfd = io_data->kiocb->ki_flags & IOCB_EVENTFD;
830 unsigned long flags;
831
832 if (io_data->read && ret > 0) {
833 mm_segment_t oldfs = get_fs();
834
835 set_fs(USER_DS);
836 use_mm(io_data->mm);
837 ret = ffs_copy_to_iter(io_data->buf, ret, &io_data->data);
838 unuse_mm(io_data->mm);
839 set_fs(oldfs);
840 }
841
842 io_data->kiocb->ki_complete(io_data->kiocb, ret, ret);
843
844 if (io_data->ffs->ffs_eventfd && !kiocb_has_eventfd)
845 eventfd_signal(io_data->ffs->ffs_eventfd, 1);
846
847 spin_lock_irqsave(&io_data->ffs->eps_lock, flags);
848 usb_ep_free_request(io_data->ep, io_data->req);
849 io_data->req = NULL;
850 spin_unlock_irqrestore(&io_data->ffs->eps_lock, flags);
851
852 if (io_data->read)
853 kfree(io_data->to_free);
854 ffs_free_buffer(io_data);
855 kfree(io_data);
856}
857
858static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
859 struct usb_request *req)
860{
861 struct ffs_io_data *io_data = req->context;
862 struct ffs_data *ffs = io_data->ffs;
863
864 ENTER();
865
866 INIT_WORK(&io_data->work, ffs_user_copy_worker);
867 queue_work(ffs->io_completion_wq, &io_data->work);
868}
869
870static void __ffs_epfile_read_buffer_free(struct ffs_epfile *epfile)
871{
872 /*
873 * See comment in struct ffs_epfile for full read_buffer pointer
874 * synchronisation story.
875 */
876 struct ffs_buffer *buf = xchg(&epfile->read_buffer, READ_BUFFER_DROP);
877 if (buf && buf != READ_BUFFER_DROP)
878 kfree(buf);
879}
880
881/* Assumes epfile->mutex is held. */
882static ssize_t __ffs_epfile_read_buffered(struct ffs_epfile *epfile,
883 struct iov_iter *iter)
884{
885 /*
886 * Null out epfile->read_buffer so ffs_func_eps_disable does not free
887 * the buffer while we are using it. See comment in struct ffs_epfile
888 * for full read_buffer pointer synchronisation story.
889 */
890 struct ffs_buffer *buf = xchg(&epfile->read_buffer, NULL);
891 ssize_t ret;
892 if (!buf || buf == READ_BUFFER_DROP)
893 return 0;
894
895 ret = copy_to_iter(buf->data, buf->length, iter);
896 if (buf->length == ret) {
897 kfree(buf);
898 return ret;
899 }
900
901 if (unlikely(iov_iter_count(iter))) {
902 ret = -EFAULT;
903 } else {
904 buf->length -= ret;
905 buf->data += ret;
906 }
907
908 if (cmpxchg(&epfile->read_buffer, NULL, buf))
909 kfree(buf);
910
911 return ret;
912}
913
914/* Assumes epfile->mutex is held. */
915static ssize_t __ffs_epfile_read_data(struct ffs_epfile *epfile,
916 void *data, int data_len,
917 struct iov_iter *iter)
918{
919 struct ffs_buffer *buf;
920
921 ssize_t ret = copy_to_iter(data, data_len, iter);
922 if (likely(data_len == ret))
923 return ret;
924
925 if (unlikely(iov_iter_count(iter)))
926 return -EFAULT;
927
928 /* See ffs_copy_to_iter for more context. */
929 pr_warn("functionfs read size %d > requested size %zd, splitting request into multiple reads.",
930 data_len, ret);
931
932 data_len -= ret;
933 buf = kmalloc(sizeof(*buf) + data_len, GFP_KERNEL);
934 if (!buf)
935 return -ENOMEM;
936 buf->length = data_len;
937 buf->data = buf->storage;
938 memcpy(buf->storage, data + ret, data_len);
939
940 /*
941 * At this point read_buffer is NULL or READ_BUFFER_DROP (if
942 * ffs_func_eps_disable has been called in the meanwhile). See comment
943 * in struct ffs_epfile for full read_buffer pointer synchronisation
944 * story.
945 */
946 if (unlikely(cmpxchg(&epfile->read_buffer, NULL, buf)))
947 kfree(buf);
948
949 return ret;
950}
951
952static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
953{
954 struct ffs_epfile *epfile = file->private_data;
955 struct usb_request *req;
956 struct ffs_ep *ep;
957 char *data = NULL;
958 ssize_t ret, data_len = -EINVAL;
959 int halt;
960
961 /* Are we still active? */
962 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
963 return -ENODEV;
964
965 /* Wait for endpoint to be enabled */
966 ep = epfile->ep;
967 if (!ep) {
968 if (file->f_flags & O_NONBLOCK)
969 return -EAGAIN;
970
971 ret = wait_event_interruptible(
972 epfile->ffs->wait, (ep = epfile->ep));
973 if (ret)
974 return -EINTR;
975 }
976
977 /* Do we halt? */
978 halt = (!io_data->read == !epfile->in);
979 if (halt && epfile->isoc)
980 return -EINVAL;
981
982 /* We will be using request and read_buffer */
983 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
984 if (unlikely(ret))
985 goto error;
986
987 /* Allocate & copy */
988 if (!halt) {
989 struct usb_gadget *gadget;
990
991 /*
992 * Do we have buffered data from previous partial read? Check
993 * that for synchronous case only because we do not have
994 * facility to ‘wake up’ a pending asynchronous read and push
995 * buffered data to it which we would need to make things behave
996 * consistently.
997 */
998 if (!io_data->aio && io_data->read) {
999 ret = __ffs_epfile_read_buffered(epfile, &io_data->data);
1000 if (ret)
1001 goto error_mutex;
1002 }
1003
1004 /*
1005 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
1006 * before the waiting completes, so do not assign to 'gadget'
1007 * earlier
1008 */
1009 gadget = epfile->ffs->gadget;
1010
1011 spin_lock_irq(&epfile->ffs->eps_lock);
1012 /* In the meantime, endpoint got disabled or changed. */
1013 if (epfile->ep != ep) {
1014 ret = -ESHUTDOWN;
1015 goto error_lock;
1016 }
1017 data_len = iov_iter_count(&io_data->data);
1018 /*
1019 * Controller may require buffer size to be aligned to
1020 * maxpacketsize of an out endpoint.
1021 */
1022 if (io_data->read)
1023 data_len = usb_ep_align_maybe(gadget, ep->ep, data_len);
1024
1025 io_data->use_sg = gadget->sg_supported && data_len > PAGE_SIZE;
1026 spin_unlock_irq(&epfile->ffs->eps_lock);
1027
1028 data = ffs_alloc_buffer(io_data, data_len);
1029 if (unlikely(!data)) {
1030 ret = -ENOMEM;
1031 goto error_mutex;
1032 }
1033 if (!io_data->read &&
1034 !copy_from_iter_full(data, data_len, &io_data->data)) {
1035 ret = -EFAULT;
1036 goto error_mutex;
1037 }
1038 }
1039
1040 spin_lock_irq(&epfile->ffs->eps_lock);
1041
1042 if (epfile->ep != ep) {
1043 /* In the meantime, endpoint got disabled or changed. */
1044 ret = -ESHUTDOWN;
1045 } else if (halt) {
1046 ret = usb_ep_set_halt(ep->ep);
1047 if (!ret)
1048 ret = -EBADMSG;
1049 } else if (unlikely(data_len == -EINVAL)) {
1050 /*
1051 * Sanity Check: even though data_len can't be used
1052 * uninitialized at the time I write this comment, some
1053 * compilers complain about this situation.
1054 * In order to keep the code clean from warnings, data_len is
1055 * being initialized to -EINVAL during its declaration, which
1056 * means we can't rely on compiler anymore to warn no future
1057 * changes won't result in data_len being used uninitialized.
1058 * For such reason, we're adding this redundant sanity check
1059 * here.
1060 */
1061 WARN(1, "%s: data_len == -EINVAL\n", __func__);
1062 ret = -EINVAL;
1063 } else if (!io_data->aio) {
1064 DECLARE_COMPLETION_ONSTACK(done);
1065 bool interrupted = false;
1066
1067 req = ep->req;
1068 if (io_data->use_sg) {
1069 req->buf = NULL;
1070 req->sg = io_data->sgt.sgl;
1071 req->num_sgs = io_data->sgt.nents;
1072 } else {
1073 req->buf = data;
1074 req->num_sgs = 0;
1075 }
1076 req->length = data_len;
1077
1078 io_data->buf = data;
1079
1080 req->context = &done;
1081 req->complete = ffs_epfile_io_complete;
1082
1083 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
1084 if (unlikely(ret < 0))
1085 goto error_lock;
1086
1087 spin_unlock_irq(&epfile->ffs->eps_lock);
1088
1089 if (unlikely(wait_for_completion_interruptible(&done))) {
1090 /*
1091 * To avoid race condition with ffs_epfile_io_complete,
1092 * dequeue the request first then check
1093 * status. usb_ep_dequeue API should guarantee no race
1094 * condition with req->complete callback.
1095 */
1096 usb_ep_dequeue(ep->ep, req);
1097 wait_for_completion(&done);
1098 interrupted = ep->status < 0;
1099 }
1100
1101 if (interrupted)
1102 ret = -EINTR;
1103 else if (io_data->read && ep->status > 0)
1104 ret = __ffs_epfile_read_data(epfile, data, ep->status,
1105 &io_data->data);
1106 else
1107 ret = ep->status;
1108 goto error_mutex;
1109 } else if (!(req = usb_ep_alloc_request(ep->ep, GFP_ATOMIC))) {
1110 ret = -ENOMEM;
1111 } else {
1112 if (io_data->use_sg) {
1113 req->buf = NULL;
1114 req->sg = io_data->sgt.sgl;
1115 req->num_sgs = io_data->sgt.nents;
1116 } else {
1117 req->buf = data;
1118 req->num_sgs = 0;
1119 }
1120 req->length = data_len;
1121
1122 io_data->buf = data;
1123 io_data->ep = ep->ep;
1124 io_data->req = req;
1125 io_data->ffs = epfile->ffs;
1126
1127 req->context = io_data;
1128 req->complete = ffs_epfile_async_io_complete;
1129
1130 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
1131 if (unlikely(ret)) {
1132 io_data->req = NULL;
1133 usb_ep_free_request(ep->ep, req);
1134 goto error_lock;
1135 }
1136
1137 ret = -EIOCBQUEUED;
1138 /*
1139 * Do not kfree the buffer in this function. It will be freed
1140 * by ffs_user_copy_worker.
1141 */
1142 data = NULL;
1143 }
1144
1145error_lock:
1146 spin_unlock_irq(&epfile->ffs->eps_lock);
1147error_mutex:
1148 mutex_unlock(&epfile->mutex);
1149error:
1150 if (ret != -EIOCBQUEUED) /* don't free if there is iocb queued */
1151 ffs_free_buffer(io_data);
1152 return ret;
1153}
1154
1155static int
1156ffs_epfile_open(struct inode *inode, struct file *file)
1157{
1158 struct ffs_epfile *epfile = inode->i_private;
1159
1160 ENTER();
1161
1162 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1163 return -ENODEV;
1164
1165 file->private_data = epfile;
1166 ffs_data_opened(epfile->ffs);
1167
1168 return stream_open(inode, file);
1169}
1170
1171static int ffs_aio_cancel(struct kiocb *kiocb)
1172{
1173 struct ffs_io_data *io_data = kiocb->private;
1174 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
1175 unsigned long flags;
1176 int value;
1177
1178 ENTER();
1179
1180 spin_lock_irqsave(&epfile->ffs->eps_lock, flags);
1181
1182 if (likely(io_data && io_data->ep && io_data->req))
1183 value = usb_ep_dequeue(io_data->ep, io_data->req);
1184 else
1185 value = -EINVAL;
1186
1187 spin_unlock_irqrestore(&epfile->ffs->eps_lock, flags);
1188
1189 return value;
1190}
1191
1192static ssize_t ffs_epfile_write_iter(struct kiocb *kiocb, struct iov_iter *from)
1193{
1194 struct ffs_io_data io_data, *p = &io_data;
1195 ssize_t res;
1196
1197 ENTER();
1198
1199 if (!is_sync_kiocb(kiocb)) {
1200 p = kzalloc(sizeof(io_data), GFP_KERNEL);
1201 if (unlikely(!p))
1202 return -ENOMEM;
1203 p->aio = true;
1204 } else {
1205 memset(p, 0, sizeof(*p));
1206 p->aio = false;
1207 }
1208
1209 p->read = false;
1210 p->kiocb = kiocb;
1211 p->data = *from;
1212 p->mm = current->mm;
1213
1214 kiocb->private = p;
1215
1216 if (p->aio)
1217 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1218
1219 res = ffs_epfile_io(kiocb->ki_filp, p);
1220 if (res == -EIOCBQUEUED)
1221 return res;
1222 if (p->aio)
1223 kfree(p);
1224 else
1225 *from = p->data;
1226 return res;
1227}
1228
1229static ssize_t ffs_epfile_read_iter(struct kiocb *kiocb, struct iov_iter *to)
1230{
1231 struct ffs_io_data io_data, *p = &io_data;
1232 ssize_t res;
1233
1234 ENTER();
1235
1236 if (!is_sync_kiocb(kiocb)) {
1237 p = kzalloc(sizeof(io_data), GFP_KERNEL);
1238 if (unlikely(!p))
1239 return -ENOMEM;
1240 p->aio = true;
1241 } else {
1242 memset(p, 0, sizeof(*p));
1243 p->aio = false;
1244 }
1245
1246 p->read = true;
1247 p->kiocb = kiocb;
1248 if (p->aio) {
1249 p->to_free = dup_iter(&p->data, to, GFP_KERNEL);
1250 if (!p->to_free) {
1251 kfree(p);
1252 return -ENOMEM;
1253 }
1254 } else {
1255 p->data = *to;
1256 p->to_free = NULL;
1257 }
1258 p->mm = current->mm;
1259
1260 kiocb->private = p;
1261
1262 if (p->aio)
1263 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
1264
1265 res = ffs_epfile_io(kiocb->ki_filp, p);
1266 if (res == -EIOCBQUEUED)
1267 return res;
1268
1269 if (p->aio) {
1270 kfree(p->to_free);
1271 kfree(p);
1272 } else {
1273 *to = p->data;
1274 }
1275 return res;
1276}
1277
1278static int
1279ffs_epfile_release(struct inode *inode, struct file *file)
1280{
1281 struct ffs_epfile *epfile = inode->i_private;
1282
1283 ENTER();
1284
1285 __ffs_epfile_read_buffer_free(epfile);
1286 ffs_data_closed(epfile->ffs);
1287
1288 return 0;
1289}
1290
1291static long ffs_epfile_ioctl(struct file *file, unsigned code,
1292 unsigned long value)
1293{
1294 struct ffs_epfile *epfile = file->private_data;
1295 struct ffs_ep *ep;
1296 int ret;
1297
1298 ENTER();
1299
1300 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1301 return -ENODEV;
1302
1303 /* Wait for endpoint to be enabled */
1304 ep = epfile->ep;
1305 if (!ep) {
1306 if (file->f_flags & O_NONBLOCK)
1307 return -EAGAIN;
1308
1309 ret = wait_event_interruptible(
1310 epfile->ffs->wait, (ep = epfile->ep));
1311 if (ret)
1312 return -EINTR;
1313 }
1314
1315 spin_lock_irq(&epfile->ffs->eps_lock);
1316
1317 /* In the meantime, endpoint got disabled or changed. */
1318 if (epfile->ep != ep) {
1319 spin_unlock_irq(&epfile->ffs->eps_lock);
1320 return -ESHUTDOWN;
1321 }
1322
1323 switch (code) {
1324 case FUNCTIONFS_FIFO_STATUS:
1325 ret = usb_ep_fifo_status(epfile->ep->ep);
1326 break;
1327 case FUNCTIONFS_FIFO_FLUSH:
1328 usb_ep_fifo_flush(epfile->ep->ep);
1329 ret = 0;
1330 break;
1331 case FUNCTIONFS_CLEAR_HALT:
1332 ret = usb_ep_clear_halt(epfile->ep->ep);
1333 break;
1334 case FUNCTIONFS_ENDPOINT_REVMAP:
1335 ret = epfile->ep->num;
1336 break;
1337 case FUNCTIONFS_ENDPOINT_DESC:
1338 {
1339 int desc_idx;
1340 struct usb_endpoint_descriptor desc1, *desc;
1341
1342 switch (epfile->ffs->gadget->speed) {
1343 case USB_SPEED_SUPER:
1344 case USB_SPEED_SUPER_PLUS:
1345 desc_idx = 2;
1346 break;
1347 case USB_SPEED_HIGH:
1348 desc_idx = 1;
1349 break;
1350 default:
1351 desc_idx = 0;
1352 }
1353
1354 desc = epfile->ep->descs[desc_idx];
1355 memcpy(&desc1, desc, desc->bLength);
1356
1357 spin_unlock_irq(&epfile->ffs->eps_lock);
1358 ret = copy_to_user((void __user *)value, &desc1, desc1.bLength);
1359 if (ret)
1360 ret = -EFAULT;
1361 return ret;
1362 }
1363 default:
1364 ret = -ENOTTY;
1365 }
1366 spin_unlock_irq(&epfile->ffs->eps_lock);
1367
1368 return ret;
1369}
1370
1371#ifdef CONFIG_COMPAT
1372static long ffs_epfile_compat_ioctl(struct file *file, unsigned code,
1373 unsigned long value)
1374{
1375 return ffs_epfile_ioctl(file, code, value);
1376}
1377#endif
1378
1379static const struct file_operations ffs_epfile_operations = {
1380 .llseek = no_llseek,
1381
1382 .open = ffs_epfile_open,
1383 .write_iter = ffs_epfile_write_iter,
1384 .read_iter = ffs_epfile_read_iter,
1385 .release = ffs_epfile_release,
1386 .unlocked_ioctl = ffs_epfile_ioctl,
1387#ifdef CONFIG_COMPAT
1388 .compat_ioctl = ffs_epfile_compat_ioctl,
1389#endif
1390};
1391
1392
1393/* File system and super block operations ***********************************/
1394
1395/*
1396 * Mounting the file system creates a controller file, used first for
1397 * function configuration then later for event monitoring.
1398 */
1399
1400static struct inode *__must_check
1401ffs_sb_make_inode(struct super_block *sb, void *data,
1402 const struct file_operations *fops,
1403 const struct inode_operations *iops,
1404 struct ffs_file_perms *perms)
1405{
1406 struct inode *inode;
1407
1408 ENTER();
1409
1410 inode = new_inode(sb);
1411
1412 if (likely(inode)) {
1413 struct timespec64 ts = current_time(inode);
1414
1415 inode->i_ino = get_next_ino();
1416 inode->i_mode = perms->mode;
1417 inode->i_uid = perms->uid;
1418 inode->i_gid = perms->gid;
1419 inode->i_atime = ts;
1420 inode->i_mtime = ts;
1421 inode->i_ctime = ts;
1422 inode->i_private = data;
1423 if (fops)
1424 inode->i_fop = fops;
1425 if (iops)
1426 inode->i_op = iops;
1427 }
1428
1429 return inode;
1430}
1431
1432/* Create "regular" file */
1433static struct dentry *ffs_sb_create_file(struct super_block *sb,
1434 const char *name, void *data,
1435 const struct file_operations *fops)
1436{
1437 struct ffs_data *ffs = sb->s_fs_info;
1438 struct dentry *dentry;
1439 struct inode *inode;
1440
1441 ENTER();
1442
1443 dentry = d_alloc_name(sb->s_root, name);
1444 if (unlikely(!dentry))
1445 return NULL;
1446
1447 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1448 if (unlikely(!inode)) {
1449 dput(dentry);
1450 return NULL;
1451 }
1452
1453 d_add(dentry, inode);
1454 return dentry;
1455}
1456
1457/* Super block */
1458static const struct super_operations ffs_sb_operations = {
1459 .statfs = simple_statfs,
1460 .drop_inode = generic_delete_inode,
1461};
1462
1463struct ffs_sb_fill_data {
1464 struct ffs_file_perms perms;
1465 umode_t root_mode;
1466 const char *dev_name;
1467 bool no_disconnect;
1468 struct ffs_data *ffs_data;
1469};
1470
1471static int ffs_sb_fill(struct super_block *sb, struct fs_context *fc)
1472{
1473 struct ffs_sb_fill_data *data = fc->fs_private;
1474 struct inode *inode;
1475 struct ffs_data *ffs = data->ffs_data;
1476
1477 ENTER();
1478
1479 ffs->sb = sb;
1480 data->ffs_data = NULL;
1481 sb->s_fs_info = ffs;
1482 sb->s_blocksize = PAGE_SIZE;
1483 sb->s_blocksize_bits = PAGE_SHIFT;
1484 sb->s_magic = FUNCTIONFS_MAGIC;
1485 sb->s_op = &ffs_sb_operations;
1486 sb->s_time_gran = 1;
1487
1488 /* Root inode */
1489 data->perms.mode = data->root_mode;
1490 inode = ffs_sb_make_inode(sb, NULL,
1491 &simple_dir_operations,
1492 &simple_dir_inode_operations,
1493 &data->perms);
1494 sb->s_root = d_make_root(inode);
1495 if (unlikely(!sb->s_root))
1496 return -ENOMEM;
1497
1498 /* EP0 file */
1499 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1500 &ffs_ep0_operations)))
1501 return -ENOMEM;
1502
1503 return 0;
1504}
1505
1506enum {
1507 Opt_no_disconnect,
1508 Opt_rmode,
1509 Opt_fmode,
1510 Opt_mode,
1511 Opt_uid,
1512 Opt_gid,
1513};
1514
1515static const struct fs_parameter_spec ffs_fs_param_specs[] = {
1516 fsparam_bool ("no_disconnect", Opt_no_disconnect),
1517 fsparam_u32 ("rmode", Opt_rmode),
1518 fsparam_u32 ("fmode", Opt_fmode),
1519 fsparam_u32 ("mode", Opt_mode),
1520 fsparam_u32 ("uid", Opt_uid),
1521 fsparam_u32 ("gid", Opt_gid),
1522 {}
1523};
1524
1525static const struct fs_parameter_description ffs_fs_fs_parameters = {
1526 .name = "kAFS",
1527 .specs = ffs_fs_param_specs,
1528};
1529
1530static int ffs_fs_parse_param(struct fs_context *fc, struct fs_parameter *param)
1531{
1532 struct ffs_sb_fill_data *data = fc->fs_private;
1533 struct fs_parse_result result;
1534 int opt;
1535
1536 ENTER();
1537
1538 opt = fs_parse(fc, &ffs_fs_fs_parameters, param, &result);
1539 if (opt < 0)
1540 return opt;
1541
1542 switch (opt) {
1543 case Opt_no_disconnect:
1544 data->no_disconnect = result.boolean;
1545 break;
1546 case Opt_rmode:
1547 data->root_mode = (result.uint_32 & 0555) | S_IFDIR;
1548 break;
1549 case Opt_fmode:
1550 data->perms.mode = (result.uint_32 & 0666) | S_IFREG;
1551 break;
1552 case Opt_mode:
1553 data->root_mode = (result.uint_32 & 0555) | S_IFDIR;
1554 data->perms.mode = (result.uint_32 & 0666) | S_IFREG;
1555 break;
1556
1557 case Opt_uid:
1558 data->perms.uid = make_kuid(current_user_ns(), result.uint_32);
1559 if (!uid_valid(data->perms.uid))
1560 goto unmapped_value;
1561 break;
1562 case Opt_gid:
1563 data->perms.gid = make_kgid(current_user_ns(), result.uint_32);
1564 if (!gid_valid(data->perms.gid))
1565 goto unmapped_value;
1566 break;
1567
1568 default:
1569 return -ENOPARAM;
1570 }
1571
1572 return 0;
1573
1574unmapped_value:
1575 return invalf(fc, "%s: unmapped value: %u", param->key, result.uint_32);
1576}
1577
1578/*
1579 * Set up the superblock for a mount.
1580 */
1581static int ffs_fs_get_tree(struct fs_context *fc)
1582{
1583 struct ffs_sb_fill_data *ctx = fc->fs_private;
1584 struct ffs_data *ffs;
1585 int ret;
1586
1587 ENTER();
1588
1589 if (!fc->source)
1590 return invalf(fc, "No source specified");
1591
1592 ffs = ffs_data_new(fc->source);
1593 if (unlikely(!ffs))
1594 return -ENOMEM;
1595 ffs->file_perms = ctx->perms;
1596 ffs->no_disconnect = ctx->no_disconnect;
1597
1598 ffs->dev_name = kstrdup(fc->source, GFP_KERNEL);
1599 if (unlikely(!ffs->dev_name)) {
1600 ffs_data_put(ffs);
1601 return -ENOMEM;
1602 }
1603
1604 ret = ffs_acquire_dev(ffs->dev_name, ffs);
1605 if (ret) {
1606 ffs_data_put(ffs);
1607 return ret;
1608 }
1609
1610 ctx->ffs_data = ffs;
1611 return get_tree_nodev(fc, ffs_sb_fill);
1612}
1613
1614static void ffs_fs_free_fc(struct fs_context *fc)
1615{
1616 struct ffs_sb_fill_data *ctx = fc->fs_private;
1617
1618 if (ctx) {
1619 if (ctx->ffs_data) {
1620 ffs_data_put(ctx->ffs_data);
1621 }
1622
1623 kfree(ctx);
1624 }
1625}
1626
1627static const struct fs_context_operations ffs_fs_context_ops = {
1628 .free = ffs_fs_free_fc,
1629 .parse_param = ffs_fs_parse_param,
1630 .get_tree = ffs_fs_get_tree,
1631};
1632
1633static int ffs_fs_init_fs_context(struct fs_context *fc)
1634{
1635 struct ffs_sb_fill_data *ctx;
1636
1637 ctx = kzalloc(sizeof(struct ffs_sb_fill_data), GFP_KERNEL);
1638 if (!ctx)
1639 return -ENOMEM;
1640
1641 ctx->perms.mode = S_IFREG | 0600;
1642 ctx->perms.uid = GLOBAL_ROOT_UID;
1643 ctx->perms.gid = GLOBAL_ROOT_GID;
1644 ctx->root_mode = S_IFDIR | 0500;
1645 ctx->no_disconnect = false;
1646
1647 fc->fs_private = ctx;
1648 fc->ops = &ffs_fs_context_ops;
1649 return 0;
1650}
1651
1652static void
1653ffs_fs_kill_sb(struct super_block *sb)
1654{
1655 ENTER();
1656
1657 kill_litter_super(sb);
1658 if (sb->s_fs_info)
1659 ffs_data_closed(sb->s_fs_info);
1660}
1661
1662static struct file_system_type ffs_fs_type = {
1663 .owner = THIS_MODULE,
1664 .name = "functionfs",
1665 .init_fs_context = ffs_fs_init_fs_context,
1666 .parameters = &ffs_fs_fs_parameters,
1667 .kill_sb = ffs_fs_kill_sb,
1668};
1669MODULE_ALIAS_FS("functionfs");
1670
1671
1672/* Driver's main init/cleanup functions *************************************/
1673
1674static int functionfs_init(void)
1675{
1676 int ret;
1677
1678 ENTER();
1679
1680 ret = register_filesystem(&ffs_fs_type);
1681 if (likely(!ret))
1682 pr_info("file system registered\n");
1683 else
1684 pr_err("failed registering file system (%d)\n", ret);
1685
1686 return ret;
1687}
1688
1689static void functionfs_cleanup(void)
1690{
1691 ENTER();
1692
1693 pr_info("unloading\n");
1694 unregister_filesystem(&ffs_fs_type);
1695}
1696
1697
1698/* ffs_data and ffs_function construction and destruction code **************/
1699
1700static void ffs_data_clear(struct ffs_data *ffs);
1701static void ffs_data_reset(struct ffs_data *ffs);
1702
1703static void ffs_data_get(struct ffs_data *ffs)
1704{
1705 ENTER();
1706
1707 refcount_inc(&ffs->ref);
1708}
1709
1710static void ffs_data_opened(struct ffs_data *ffs)
1711{
1712 ENTER();
1713
1714 refcount_inc(&ffs->ref);
1715 if (atomic_add_return(1, &ffs->opened) == 1 &&
1716 ffs->state == FFS_DEACTIVATED) {
1717 ffs->state = FFS_CLOSING;
1718 ffs_data_reset(ffs);
1719 }
1720}
1721
1722static void ffs_data_put(struct ffs_data *ffs)
1723{
1724 ENTER();
1725
1726 if (unlikely(refcount_dec_and_test(&ffs->ref))) {
1727 pr_info("%s(): freeing\n", __func__);
1728 ffs_data_clear(ffs);
1729 ffs_release_dev(ffs->private_data);
1730 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1731 waitqueue_active(&ffs->ep0req_completion.wait) ||
1732 waitqueue_active(&ffs->wait));
1733 destroy_workqueue(ffs->io_completion_wq);
1734 kfree(ffs->dev_name);
1735 kfree(ffs);
1736 }
1737}
1738
1739static void ffs_data_closed(struct ffs_data *ffs)
1740{
1741 struct ffs_epfile *epfiles;
1742 unsigned long flags;
1743
1744 ENTER();
1745
1746 if (atomic_dec_and_test(&ffs->opened)) {
1747 if (ffs->no_disconnect) {
1748 ffs->state = FFS_DEACTIVATED;
1749 spin_lock_irqsave(&ffs->eps_lock, flags);
1750 epfiles = ffs->epfiles;
1751 ffs->epfiles = NULL;
1752 spin_unlock_irqrestore(&ffs->eps_lock,
1753 flags);
1754
1755 if (epfiles)
1756 ffs_epfiles_destroy(epfiles,
1757 ffs->eps_count);
1758
1759 if (ffs->setup_state == FFS_SETUP_PENDING)
1760 __ffs_ep0_stall(ffs);
1761 } else {
1762 ffs->state = FFS_CLOSING;
1763 ffs_data_reset(ffs);
1764 }
1765 }
1766 if (atomic_read(&ffs->opened) < 0) {
1767 ffs->state = FFS_CLOSING;
1768 ffs_data_reset(ffs);
1769 }
1770
1771 ffs_data_put(ffs);
1772}
1773
1774static struct ffs_data *ffs_data_new(const char *dev_name)
1775{
1776 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1777 if (unlikely(!ffs))
1778 return NULL;
1779
1780 ENTER();
1781
1782 ffs->io_completion_wq = alloc_ordered_workqueue("%s", 0, dev_name);
1783 if (!ffs->io_completion_wq) {
1784 kfree(ffs);
1785 return NULL;
1786 }
1787
1788 refcount_set(&ffs->ref, 1);
1789 atomic_set(&ffs->opened, 0);
1790 ffs->state = FFS_READ_DESCRIPTORS;
1791 mutex_init(&ffs->mutex);
1792 spin_lock_init(&ffs->eps_lock);
1793 init_waitqueue_head(&ffs->ev.waitq);
1794 init_waitqueue_head(&ffs->wait);
1795 init_completion(&ffs->ep0req_completion);
1796
1797 /* XXX REVISIT need to update it in some places, or do we? */
1798 ffs->ev.can_stall = 1;
1799
1800 return ffs;
1801}
1802
1803static void ffs_data_clear(struct ffs_data *ffs)
1804{
1805 struct ffs_epfile *epfiles;
1806 unsigned long flags;
1807
1808 ENTER();
1809
1810 ffs_closed(ffs);
1811
1812 BUG_ON(ffs->gadget);
1813
1814 spin_lock_irqsave(&ffs->eps_lock, flags);
1815 epfiles = ffs->epfiles;
1816 ffs->epfiles = NULL;
1817 spin_unlock_irqrestore(&ffs->eps_lock, flags);
1818
1819 /*
1820 * potential race possible between ffs_func_eps_disable
1821 * & ffs_epfile_release therefore maintaining a local
1822 * copy of epfile will save us from use-after-free.
1823 */
1824 if (epfiles) {
1825 ffs_epfiles_destroy(epfiles, ffs->eps_count);
1826 ffs->epfiles = NULL;
1827 }
1828
1829 if (ffs->ffs_eventfd) {
1830 eventfd_ctx_put(ffs->ffs_eventfd);
1831 ffs->ffs_eventfd = NULL;
1832 }
1833
1834 kfree(ffs->raw_descs_data);
1835 kfree(ffs->raw_strings);
1836 kfree(ffs->stringtabs);
1837}
1838
1839static void ffs_data_reset(struct ffs_data *ffs)
1840{
1841 ENTER();
1842
1843 ffs_data_clear(ffs);
1844
1845 ffs->raw_descs_data = NULL;
1846 ffs->raw_descs = NULL;
1847 ffs->raw_strings = NULL;
1848 ffs->stringtabs = NULL;
1849
1850 ffs->raw_descs_length = 0;
1851 ffs->fs_descs_count = 0;
1852 ffs->hs_descs_count = 0;
1853 ffs->ss_descs_count = 0;
1854
1855 ffs->strings_count = 0;
1856 ffs->interfaces_count = 0;
1857 ffs->eps_count = 0;
1858
1859 ffs->ev.count = 0;
1860
1861 ffs->state = FFS_READ_DESCRIPTORS;
1862 ffs->setup_state = FFS_NO_SETUP;
1863 ffs->flags = 0;
1864
1865 ffs->ms_os_descs_ext_prop_count = 0;
1866 ffs->ms_os_descs_ext_prop_name_len = 0;
1867 ffs->ms_os_descs_ext_prop_data_len = 0;
1868}
1869
1870
1871static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1872{
1873 struct usb_gadget_strings **lang;
1874 int first_id;
1875
1876 ENTER();
1877
1878 if ((ffs->state != FFS_ACTIVE
1879 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1880 return -EBADFD;
1881
1882 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1883 if (unlikely(first_id < 0))
1884 return first_id;
1885
1886 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1887 if (unlikely(!ffs->ep0req))
1888 return -ENOMEM;
1889 ffs->ep0req->complete = ffs_ep0_complete;
1890 ffs->ep0req->context = ffs;
1891
1892 lang = ffs->stringtabs;
1893 if (lang) {
1894 for (; *lang; ++lang) {
1895 struct usb_string *str = (*lang)->strings;
1896 int id = first_id;
1897 for (; str->s; ++id, ++str)
1898 str->id = id;
1899 }
1900 }
1901
1902 ffs->gadget = cdev->gadget;
1903 ffs_data_get(ffs);
1904 return 0;
1905}
1906
1907static void functionfs_unbind(struct ffs_data *ffs)
1908{
1909 ENTER();
1910
1911 if (!WARN_ON(!ffs->gadget)) {
1912 /* dequeue before freeing ep0req */
1913 usb_ep_dequeue(ffs->gadget->ep0, ffs->ep0req);
1914 mutex_lock(&ffs->mutex);
1915 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1916 ffs->ep0req = NULL;
1917 ffs->gadget = NULL;
1918 clear_bit(FFS_FL_BOUND, &ffs->flags);
1919 mutex_unlock(&ffs->mutex);
1920 ffs_data_put(ffs);
1921 }
1922}
1923
1924static int ffs_epfiles_create(struct ffs_data *ffs)
1925{
1926 struct ffs_epfile *epfile, *epfiles;
1927 unsigned i, count;
1928
1929 ENTER();
1930
1931 count = ffs->eps_count;
1932 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1933 if (!epfiles)
1934 return -ENOMEM;
1935
1936 epfile = epfiles;
1937 for (i = 1; i <= count; ++i, ++epfile) {
1938 epfile->ffs = ffs;
1939 mutex_init(&epfile->mutex);
1940 if (ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
1941 sprintf(epfile->name, "ep%02x", ffs->eps_addrmap[i]);
1942 else
1943 sprintf(epfile->name, "ep%u", i);
1944 epfile->dentry = ffs_sb_create_file(ffs->sb, epfile->name,
1945 epfile,
1946 &ffs_epfile_operations);
1947 if (unlikely(!epfile->dentry)) {
1948 ffs_epfiles_destroy(epfiles, i - 1);
1949 return -ENOMEM;
1950 }
1951 }
1952
1953 ffs->epfiles = epfiles;
1954 return 0;
1955}
1956
1957static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1958{
1959 struct ffs_epfile *epfile = epfiles;
1960
1961 ENTER();
1962
1963 for (; count; --count, ++epfile) {
1964 BUG_ON(mutex_is_locked(&epfile->mutex));
1965 if (epfile->dentry) {
1966 d_delete(epfile->dentry);
1967 dput(epfile->dentry);
1968 epfile->dentry = NULL;
1969 }
1970 }
1971
1972 kfree(epfiles);
1973}
1974
1975static void ffs_func_eps_disable(struct ffs_function *func)
1976{
1977 struct ffs_ep *ep;
1978 struct ffs_epfile *epfile;
1979 unsigned short count;
1980 unsigned long flags;
1981
1982 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1983 count = func->ffs->eps_count;
1984 epfile = func->ffs->epfiles;
1985 ep = func->eps;
1986 while (count--) {
1987 /* pending requests get nuked */
1988 if (likely(ep->ep))
1989 usb_ep_disable(ep->ep);
1990 ++ep;
1991
1992 if (epfile) {
1993 epfile->ep = NULL;
1994 __ffs_epfile_read_buffer_free(epfile);
1995 ++epfile;
1996 }
1997 }
1998 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1999}
2000
2001static int ffs_func_eps_enable(struct ffs_function *func)
2002{
2003 struct ffs_data *ffs;
2004 struct ffs_ep *ep;
2005 struct ffs_epfile *epfile;
2006 unsigned short count;
2007 unsigned long flags;
2008 int ret = 0;
2009
2010 spin_lock_irqsave(&func->ffs->eps_lock, flags);
2011 ffs = func->ffs;
2012 ep = func->eps;
2013 epfile = ffs->epfiles;
2014 count = ffs->eps_count;
2015 while(count--) {
2016 ep->ep->driver_data = ep;
2017
2018 ret = config_ep_by_speed(func->gadget, &func->function, ep->ep);
2019 if (ret) {
2020 pr_err("%s: config_ep_by_speed(%s) returned %d\n",
2021 __func__, ep->ep->name, ret);
2022 break;
2023 }
2024
2025 ret = usb_ep_enable(ep->ep);
2026 if (likely(!ret)) {
2027 epfile->ep = ep;
2028 epfile->in = usb_endpoint_dir_in(ep->ep->desc);
2029 epfile->isoc = usb_endpoint_xfer_isoc(ep->ep->desc);
2030 } else {
2031 break;
2032 }
2033
2034 ++ep;
2035 ++epfile;
2036 }
2037
2038 wake_up_interruptible(&ffs->wait);
2039 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
2040
2041 return ret;
2042}
2043
2044
2045/* Parsing and building descriptors and strings *****************************/
2046
2047/*
2048 * This validates if data pointed by data is a valid USB descriptor as
2049 * well as record how many interfaces, endpoints and strings are
2050 * required by given configuration. Returns address after the
2051 * descriptor or NULL if data is invalid.
2052 */
2053
2054enum ffs_entity_type {
2055 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
2056};
2057
2058enum ffs_os_desc_type {
2059 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
2060};
2061
2062typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
2063 u8 *valuep,
2064 struct usb_descriptor_header *desc,
2065 void *priv);
2066
2067typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
2068 struct usb_os_desc_header *h, void *data,
2069 unsigned len, void *priv);
2070
2071static int __must_check ffs_do_single_desc(char *data, unsigned len,
2072 ffs_entity_callback entity,
2073 void *priv, int *current_class)
2074{
2075 struct usb_descriptor_header *_ds = (void *)data;
2076 u8 length;
2077 int ret;
2078
2079 ENTER();
2080
2081 /* At least two bytes are required: length and type */
2082 if (len < 2) {
2083 pr_vdebug("descriptor too short\n");
2084 return -EINVAL;
2085 }
2086
2087 /* If we have at least as many bytes as the descriptor takes? */
2088 length = _ds->bLength;
2089 if (len < length) {
2090 pr_vdebug("descriptor longer then available data\n");
2091 return -EINVAL;
2092 }
2093
2094#define __entity_check_INTERFACE(val) 1
2095#define __entity_check_STRING(val) (val)
2096#define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
2097#define __entity(type, val) do { \
2098 pr_vdebug("entity " #type "(%02x)\n", (val)); \
2099 if (unlikely(!__entity_check_ ##type(val))) { \
2100 pr_vdebug("invalid entity's value\n"); \
2101 return -EINVAL; \
2102 } \
2103 ret = entity(FFS_ ##type, &val, _ds, priv); \
2104 if (unlikely(ret < 0)) { \
2105 pr_debug("entity " #type "(%02x); ret = %d\n", \
2106 (val), ret); \
2107 return ret; \
2108 } \
2109 } while (0)
2110
2111 /* Parse descriptor depending on type. */
2112 switch (_ds->bDescriptorType) {
2113 case USB_DT_DEVICE:
2114 case USB_DT_CONFIG:
2115 case USB_DT_STRING:
2116 case USB_DT_DEVICE_QUALIFIER:
2117 /* function can't have any of those */
2118 pr_vdebug("descriptor reserved for gadget: %d\n",
2119 _ds->bDescriptorType);
2120 return -EINVAL;
2121
2122 case USB_DT_INTERFACE: {
2123 struct usb_interface_descriptor *ds = (void *)_ds;
2124 pr_vdebug("interface descriptor\n");
2125 if (length != sizeof *ds)
2126 goto inv_length;
2127
2128 __entity(INTERFACE, ds->bInterfaceNumber);
2129 if (ds->iInterface)
2130 __entity(STRING, ds->iInterface);
2131 *current_class = ds->bInterfaceClass;
2132 }
2133 break;
2134
2135 case USB_DT_ENDPOINT: {
2136 struct usb_endpoint_descriptor *ds = (void *)_ds;
2137 pr_vdebug("endpoint descriptor\n");
2138 if (length != USB_DT_ENDPOINT_SIZE &&
2139 length != USB_DT_ENDPOINT_AUDIO_SIZE)
2140 goto inv_length;
2141 __entity(ENDPOINT, ds->bEndpointAddress);
2142 }
2143 break;
2144
2145 case USB_TYPE_CLASS | 0x01:
2146 if (*current_class == USB_INTERFACE_CLASS_HID) {
2147 pr_vdebug("hid descriptor\n");
2148 if (length != sizeof(struct hid_descriptor))
2149 goto inv_length;
2150 break;
2151 } else if (*current_class == USB_INTERFACE_CLASS_CCID) {
2152 pr_vdebug("ccid descriptor\n");
2153 if (length != sizeof(struct ccid_descriptor))
2154 goto inv_length;
2155 break;
2156 } else {
2157 pr_vdebug("unknown descriptor: %d for class %d\n",
2158 _ds->bDescriptorType, *current_class);
2159 return -EINVAL;
2160 }
2161
2162 case USB_DT_OTG:
2163 if (length != sizeof(struct usb_otg_descriptor))
2164 goto inv_length;
2165 break;
2166
2167 case USB_DT_INTERFACE_ASSOCIATION: {
2168 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
2169 pr_vdebug("interface association descriptor\n");
2170 if (length != sizeof *ds)
2171 goto inv_length;
2172 if (ds->iFunction)
2173 __entity(STRING, ds->iFunction);
2174 }
2175 break;
2176
2177 case USB_DT_SS_ENDPOINT_COMP:
2178 pr_vdebug("EP SS companion descriptor\n");
2179 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
2180 goto inv_length;
2181 break;
2182
2183 case USB_DT_OTHER_SPEED_CONFIG:
2184 case USB_DT_INTERFACE_POWER:
2185 case USB_DT_DEBUG:
2186 case USB_DT_SECURITY:
2187 case USB_DT_CS_RADIO_CONTROL:
2188 /* TODO */
2189 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
2190 return -EINVAL;
2191
2192 default:
2193 /* We should never be here */
2194 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
2195 return -EINVAL;
2196
2197inv_length:
2198 pr_vdebug("invalid length: %d (descriptor %d)\n",
2199 _ds->bLength, _ds->bDescriptorType);
2200 return -EINVAL;
2201 }
2202
2203#undef __entity
2204#undef __entity_check_DESCRIPTOR
2205#undef __entity_check_INTERFACE
2206#undef __entity_check_STRING
2207#undef __entity_check_ENDPOINT
2208
2209 return length;
2210}
2211
2212static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
2213 ffs_entity_callback entity, void *priv)
2214{
2215 const unsigned _len = len;
2216 unsigned long num = 0;
2217 int current_class = -1;
2218
2219 ENTER();
2220
2221 for (;;) {
2222 int ret;
2223
2224 if (num == count)
2225 data = NULL;
2226
2227 /* Record "descriptor" entity */
2228 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
2229 if (unlikely(ret < 0)) {
2230 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
2231 num, ret);
2232 return ret;
2233 }
2234
2235 if (!data)
2236 return _len - len;
2237
2238 ret = ffs_do_single_desc(data, len, entity, priv,
2239 &current_class);
2240 if (unlikely(ret < 0)) {
2241 pr_debug("%s returns %d\n", __func__, ret);
2242 return ret;
2243 }
2244
2245 len -= ret;
2246 data += ret;
2247 ++num;
2248 }
2249}
2250
2251static int __ffs_data_do_entity(enum ffs_entity_type type,
2252 u8 *valuep, struct usb_descriptor_header *desc,
2253 void *priv)
2254{
2255 struct ffs_desc_helper *helper = priv;
2256 struct usb_endpoint_descriptor *d;
2257
2258 ENTER();
2259
2260 switch (type) {
2261 case FFS_DESCRIPTOR:
2262 break;
2263
2264 case FFS_INTERFACE:
2265 /*
2266 * Interfaces are indexed from zero so if we
2267 * encountered interface "n" then there are at least
2268 * "n+1" interfaces.
2269 */
2270 if (*valuep >= helper->interfaces_count)
2271 helper->interfaces_count = *valuep + 1;
2272 break;
2273
2274 case FFS_STRING:
2275 /*
2276 * Strings are indexed from 1 (0 is reserved
2277 * for languages list)
2278 */
2279 if (*valuep > helper->ffs->strings_count)
2280 helper->ffs->strings_count = *valuep;
2281 break;
2282
2283 case FFS_ENDPOINT:
2284 d = (void *)desc;
2285 helper->eps_count++;
2286 if (helper->eps_count >= FFS_MAX_EPS_COUNT)
2287 return -EINVAL;
2288 /* Check if descriptors for any speed were already parsed */
2289 if (!helper->ffs->eps_count && !helper->ffs->interfaces_count)
2290 helper->ffs->eps_addrmap[helper->eps_count] =
2291 d->bEndpointAddress;
2292 else if (helper->ffs->eps_addrmap[helper->eps_count] !=
2293 d->bEndpointAddress)
2294 return -EINVAL;
2295 break;
2296 }
2297
2298 return 0;
2299}
2300
2301static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
2302 struct usb_os_desc_header *desc)
2303{
2304 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
2305 u16 w_index = le16_to_cpu(desc->wIndex);
2306
2307 if (bcd_version != 1) {
2308 pr_vdebug("unsupported os descriptors version: %d",
2309 bcd_version);
2310 return -EINVAL;
2311 }
2312 switch (w_index) {
2313 case 0x4:
2314 *next_type = FFS_OS_DESC_EXT_COMPAT;
2315 break;
2316 case 0x5:
2317 *next_type = FFS_OS_DESC_EXT_PROP;
2318 break;
2319 default:
2320 pr_vdebug("unsupported os descriptor type: %d", w_index);
2321 return -EINVAL;
2322 }
2323
2324 return sizeof(*desc);
2325}
2326
2327/*
2328 * Process all extended compatibility/extended property descriptors
2329 * of a feature descriptor
2330 */
2331static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
2332 enum ffs_os_desc_type type,
2333 u16 feature_count,
2334 ffs_os_desc_callback entity,
2335 void *priv,
2336 struct usb_os_desc_header *h)
2337{
2338 int ret;
2339 const unsigned _len = len;
2340
2341 ENTER();
2342
2343 /* loop over all ext compat/ext prop descriptors */
2344 while (feature_count--) {
2345 ret = entity(type, h, data, len, priv);
2346 if (unlikely(ret < 0)) {
2347 pr_debug("bad OS descriptor, type: %d\n", type);
2348 return ret;
2349 }
2350 data += ret;
2351 len -= ret;
2352 }
2353 return _len - len;
2354}
2355
2356/* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
2357static int __must_check ffs_do_os_descs(unsigned count,
2358 char *data, unsigned len,
2359 ffs_os_desc_callback entity, void *priv)
2360{
2361 const unsigned _len = len;
2362 unsigned long num = 0;
2363
2364 ENTER();
2365
2366 for (num = 0; num < count; ++num) {
2367 int ret;
2368 enum ffs_os_desc_type type;
2369 u16 feature_count;
2370 struct usb_os_desc_header *desc = (void *)data;
2371
2372 if (len < sizeof(*desc))
2373 return -EINVAL;
2374
2375 /*
2376 * Record "descriptor" entity.
2377 * Process dwLength, bcdVersion, wIndex, get b/wCount.
2378 * Move the data pointer to the beginning of extended
2379 * compatibilities proper or extended properties proper
2380 * portions of the data
2381 */
2382 if (le32_to_cpu(desc->dwLength) > len)
2383 return -EINVAL;
2384
2385 ret = __ffs_do_os_desc_header(&type, desc);
2386 if (unlikely(ret < 0)) {
2387 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
2388 num, ret);
2389 return ret;
2390 }
2391 /*
2392 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
2393 */
2394 feature_count = le16_to_cpu(desc->wCount);
2395 if (type == FFS_OS_DESC_EXT_COMPAT &&
2396 (feature_count > 255 || desc->Reserved))
2397 return -EINVAL;
2398 len -= ret;
2399 data += ret;
2400
2401 /*
2402 * Process all function/property descriptors
2403 * of this Feature Descriptor
2404 */
2405 ret = ffs_do_single_os_desc(data, len, type,
2406 feature_count, entity, priv, desc);
2407 if (unlikely(ret < 0)) {
2408 pr_debug("%s returns %d\n", __func__, ret);
2409 return ret;
2410 }
2411
2412 len -= ret;
2413 data += ret;
2414 }
2415 return _len - len;
2416}
2417
2418/**
2419 * Validate contents of the buffer from userspace related to OS descriptors.
2420 */
2421static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
2422 struct usb_os_desc_header *h, void *data,
2423 unsigned len, void *priv)
2424{
2425 struct ffs_data *ffs = priv;
2426 u8 length;
2427
2428 ENTER();
2429
2430 switch (type) {
2431 case FFS_OS_DESC_EXT_COMPAT: {
2432 struct usb_ext_compat_desc *d = data;
2433 int i;
2434
2435 if (len < sizeof(*d) ||
2436 d->bFirstInterfaceNumber >= ffs->interfaces_count)
2437 return -EINVAL;
2438 if (d->Reserved1 != 1) {
2439 /*
2440 * According to the spec, Reserved1 must be set to 1
2441 * but older kernels incorrectly rejected non-zero
2442 * values. We fix it here to avoid returning EINVAL
2443 * in response to values we used to accept.
2444 */
2445 pr_debug("usb_ext_compat_desc::Reserved1 forced to 1\n");
2446 d->Reserved1 = 1;
2447 }
2448 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2449 if (d->Reserved2[i])
2450 return -EINVAL;
2451
2452 length = sizeof(struct usb_ext_compat_desc);
2453 }
2454 break;
2455 case FFS_OS_DESC_EXT_PROP: {
2456 struct usb_ext_prop_desc *d = data;
2457 u32 type, pdl;
2458 u16 pnl;
2459
2460 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2461 return -EINVAL;
2462 length = le32_to_cpu(d->dwSize);
2463 if (len < length)
2464 return -EINVAL;
2465 type = le32_to_cpu(d->dwPropertyDataType);
2466 if (type < USB_EXT_PROP_UNICODE ||
2467 type > USB_EXT_PROP_UNICODE_MULTI) {
2468 pr_vdebug("unsupported os descriptor property type: %d",
2469 type);
2470 return -EINVAL;
2471 }
2472 pnl = le16_to_cpu(d->wPropertyNameLength);
2473 if (length < 14 + pnl) {
2474 pr_vdebug("invalid os descriptor length: %d pnl:%d (descriptor %d)\n",
2475 length, pnl, type);
2476 return -EINVAL;
2477 }
2478 pdl = le32_to_cpu(*(__le32 *)((u8 *)data + 10 + pnl));
2479 if (length != 14 + pnl + pdl) {
2480 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2481 length, pnl, pdl, type);
2482 return -EINVAL;
2483 }
2484 ++ffs->ms_os_descs_ext_prop_count;
2485 /* property name reported to the host as "WCHAR"s */
2486 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2487 ffs->ms_os_descs_ext_prop_data_len += pdl;
2488 }
2489 break;
2490 default:
2491 pr_vdebug("unknown descriptor: %d\n", type);
2492 return -EINVAL;
2493 }
2494 return length;
2495}
2496
2497static int __ffs_data_got_descs(struct ffs_data *ffs,
2498 char *const _data, size_t len)
2499{
2500 char *data = _data, *raw_descs;
2501 unsigned os_descs_count = 0, counts[3], flags;
2502 int ret = -EINVAL, i;
2503 struct ffs_desc_helper helper;
2504
2505 ENTER();
2506
2507 if (get_unaligned_le32(data + 4) != len)
2508 goto error;
2509
2510 switch (get_unaligned_le32(data)) {
2511 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2512 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2513 data += 8;
2514 len -= 8;
2515 break;
2516 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2517 flags = get_unaligned_le32(data + 8);
2518 ffs->user_flags = flags;
2519 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2520 FUNCTIONFS_HAS_HS_DESC |
2521 FUNCTIONFS_HAS_SS_DESC |
2522 FUNCTIONFS_HAS_MS_OS_DESC |
2523 FUNCTIONFS_VIRTUAL_ADDR |
2524 FUNCTIONFS_EVENTFD |
2525 FUNCTIONFS_ALL_CTRL_RECIP |
2526 FUNCTIONFS_CONFIG0_SETUP)) {
2527 ret = -ENOSYS;
2528 goto error;
2529 }
2530 data += 12;
2531 len -= 12;
2532 break;
2533 default:
2534 goto error;
2535 }
2536
2537 if (flags & FUNCTIONFS_EVENTFD) {
2538 if (len < 4)
2539 goto error;
2540 ffs->ffs_eventfd =
2541 eventfd_ctx_fdget((int)get_unaligned_le32(data));
2542 if (IS_ERR(ffs->ffs_eventfd)) {
2543 ret = PTR_ERR(ffs->ffs_eventfd);
2544 ffs->ffs_eventfd = NULL;
2545 goto error;
2546 }
2547 data += 4;
2548 len -= 4;
2549 }
2550
2551 /* Read fs_count, hs_count and ss_count (if present) */
2552 for (i = 0; i < 3; ++i) {
2553 if (!(flags & (1 << i))) {
2554 counts[i] = 0;
2555 } else if (len < 4) {
2556 goto error;
2557 } else {
2558 counts[i] = get_unaligned_le32(data);
2559 data += 4;
2560 len -= 4;
2561 }
2562 }
2563 if (flags & (1 << i)) {
2564 if (len < 4) {
2565 goto error;
2566 }
2567 os_descs_count = get_unaligned_le32(data);
2568 data += 4;
2569 len -= 4;
2570 };
2571
2572 /* Read descriptors */
2573 raw_descs = data;
2574 helper.ffs = ffs;
2575 for (i = 0; i < 3; ++i) {
2576 if (!counts[i])
2577 continue;
2578 helper.interfaces_count = 0;
2579 helper.eps_count = 0;
2580 ret = ffs_do_descs(counts[i], data, len,
2581 __ffs_data_do_entity, &helper);
2582 if (ret < 0)
2583 goto error;
2584 if (!ffs->eps_count && !ffs->interfaces_count) {
2585 ffs->eps_count = helper.eps_count;
2586 ffs->interfaces_count = helper.interfaces_count;
2587 } else {
2588 if (ffs->eps_count != helper.eps_count) {
2589 ret = -EINVAL;
2590 goto error;
2591 }
2592 if (ffs->interfaces_count != helper.interfaces_count) {
2593 ret = -EINVAL;
2594 goto error;
2595 }
2596 }
2597 data += ret;
2598 len -= ret;
2599 }
2600 if (os_descs_count) {
2601 ret = ffs_do_os_descs(os_descs_count, data, len,
2602 __ffs_data_do_os_desc, ffs);
2603 if (ret < 0)
2604 goto error;
2605 data += ret;
2606 len -= ret;
2607 }
2608
2609 if (raw_descs == data || len) {
2610 ret = -EINVAL;
2611 goto error;
2612 }
2613
2614 ffs->raw_descs_data = _data;
2615 ffs->raw_descs = raw_descs;
2616 ffs->raw_descs_length = data - raw_descs;
2617 ffs->fs_descs_count = counts[0];
2618 ffs->hs_descs_count = counts[1];
2619 ffs->ss_descs_count = counts[2];
2620 ffs->ms_os_descs_count = os_descs_count;
2621
2622 return 0;
2623
2624error:
2625 kfree(_data);
2626 return ret;
2627}
2628
2629static int __ffs_data_got_strings(struct ffs_data *ffs,
2630 char *const _data, size_t len)
2631{
2632 u32 str_count, needed_count, lang_count;
2633 struct usb_gadget_strings **stringtabs, *t;
2634 const char *data = _data;
2635 struct usb_string *s;
2636
2637 ENTER();
2638
2639 if (unlikely(len < 16 ||
2640 get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2641 get_unaligned_le32(data + 4) != len))
2642 goto error;
2643 str_count = get_unaligned_le32(data + 8);
2644 lang_count = get_unaligned_le32(data + 12);
2645
2646 /* if one is zero the other must be zero */
2647 if (unlikely(!str_count != !lang_count))
2648 goto error;
2649
2650 /* Do we have at least as many strings as descriptors need? */
2651 needed_count = ffs->strings_count;
2652 if (unlikely(str_count < needed_count))
2653 goto error;
2654
2655 /*
2656 * If we don't need any strings just return and free all
2657 * memory.
2658 */
2659 if (!needed_count) {
2660 kfree(_data);
2661 return 0;
2662 }
2663
2664 /* Allocate everything in one chunk so there's less maintenance. */
2665 {
2666 unsigned i = 0;
2667 vla_group(d);
2668 vla_item(d, struct usb_gadget_strings *, stringtabs,
2669 lang_count + 1);
2670 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2671 vla_item(d, struct usb_string, strings,
2672 lang_count*(needed_count+1));
2673
2674 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2675
2676 if (unlikely(!vlabuf)) {
2677 kfree(_data);
2678 return -ENOMEM;
2679 }
2680
2681 /* Initialize the VLA pointers */
2682 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2683 t = vla_ptr(vlabuf, d, stringtab);
2684 i = lang_count;
2685 do {
2686 *stringtabs++ = t++;
2687 } while (--i);
2688 *stringtabs = NULL;
2689
2690 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2691 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2692 t = vla_ptr(vlabuf, d, stringtab);
2693 s = vla_ptr(vlabuf, d, strings);
2694 }
2695
2696 /* For each language */
2697 data += 16;
2698 len -= 16;
2699
2700 do { /* lang_count > 0 so we can use do-while */
2701 unsigned needed = needed_count;
2702 u32 str_per_lang = str_count;
2703
2704 if (unlikely(len < 3))
2705 goto error_free;
2706 t->language = get_unaligned_le16(data);
2707 t->strings = s;
2708 ++t;
2709
2710 data += 2;
2711 len -= 2;
2712
2713 /* For each string */
2714 do { /* str_count > 0 so we can use do-while */
2715 size_t length = strnlen(data, len);
2716
2717 if (unlikely(length == len))
2718 goto error_free;
2719
2720 /*
2721 * User may provide more strings then we need,
2722 * if that's the case we simply ignore the
2723 * rest
2724 */
2725 if (likely(needed)) {
2726 /*
2727 * s->id will be set while adding
2728 * function to configuration so for
2729 * now just leave garbage here.
2730 */
2731 s->s = data;
2732 --needed;
2733 ++s;
2734 }
2735
2736 data += length + 1;
2737 len -= length + 1;
2738 } while (--str_per_lang);
2739
2740 s->id = 0; /* terminator */
2741 s->s = NULL;
2742 ++s;
2743
2744 } while (--lang_count);
2745
2746 /* Some garbage left? */
2747 if (unlikely(len))
2748 goto error_free;
2749
2750 /* Done! */
2751 ffs->stringtabs = stringtabs;
2752 ffs->raw_strings = _data;
2753
2754 return 0;
2755
2756error_free:
2757 kfree(stringtabs);
2758error:
2759 kfree(_data);
2760 return -EINVAL;
2761}
2762
2763
2764/* Events handling and management *******************************************/
2765
2766static void __ffs_event_add(struct ffs_data *ffs,
2767 enum usb_functionfs_event_type type)
2768{
2769 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2770 int neg = 0;
2771
2772 /*
2773 * Abort any unhandled setup
2774 *
2775 * We do not need to worry about some cmpxchg() changing value
2776 * of ffs->setup_state without holding the lock because when
2777 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2778 * the source does nothing.
2779 */
2780 if (ffs->setup_state == FFS_SETUP_PENDING)
2781 ffs->setup_state = FFS_SETUP_CANCELLED;
2782
2783 /*
2784 * Logic of this function guarantees that there are at most four pending
2785 * evens on ffs->ev.types queue. This is important because the queue
2786 * has space for four elements only and __ffs_ep0_read_events function
2787 * depends on that limit as well. If more event types are added, those
2788 * limits have to be revisited or guaranteed to still hold.
2789 */
2790 switch (type) {
2791 case FUNCTIONFS_RESUME:
2792 rem_type2 = FUNCTIONFS_SUSPEND;
2793 /* FALL THROUGH */
2794 case FUNCTIONFS_SUSPEND:
2795 case FUNCTIONFS_SETUP:
2796 rem_type1 = type;
2797 /* Discard all similar events */
2798 break;
2799
2800 case FUNCTIONFS_BIND:
2801 case FUNCTIONFS_UNBIND:
2802 case FUNCTIONFS_DISABLE:
2803 case FUNCTIONFS_ENABLE:
2804 /* Discard everything other then power management. */
2805 rem_type1 = FUNCTIONFS_SUSPEND;
2806 rem_type2 = FUNCTIONFS_RESUME;
2807 neg = 1;
2808 break;
2809
2810 default:
2811 WARN(1, "%d: unknown event, this should not happen\n", type);
2812 return;
2813 }
2814
2815 {
2816 u8 *ev = ffs->ev.types, *out = ev;
2817 unsigned n = ffs->ev.count;
2818 for (; n; --n, ++ev)
2819 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2820 *out++ = *ev;
2821 else
2822 pr_vdebug("purging event %d\n", *ev);
2823 ffs->ev.count = out - ffs->ev.types;
2824 }
2825
2826 pr_vdebug("adding event %d\n", type);
2827 ffs->ev.types[ffs->ev.count++] = type;
2828 wake_up_locked(&ffs->ev.waitq);
2829 if (ffs->ffs_eventfd)
2830 eventfd_signal(ffs->ffs_eventfd, 1);
2831}
2832
2833static void ffs_event_add(struct ffs_data *ffs,
2834 enum usb_functionfs_event_type type)
2835{
2836 unsigned long flags;
2837 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2838 __ffs_event_add(ffs, type);
2839 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2840}
2841
2842/* Bind/unbind USB function hooks *******************************************/
2843
2844static int ffs_ep_addr2idx(struct ffs_data *ffs, u8 endpoint_address)
2845{
2846 int i;
2847
2848 for (i = 1; i < ARRAY_SIZE(ffs->eps_addrmap); ++i)
2849 if (ffs->eps_addrmap[i] == endpoint_address)
2850 return i;
2851 return -ENOENT;
2852}
2853
2854static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2855 struct usb_descriptor_header *desc,
2856 void *priv)
2857{
2858 struct usb_endpoint_descriptor *ds = (void *)desc;
2859 struct ffs_function *func = priv;
2860 struct ffs_ep *ffs_ep;
2861 unsigned ep_desc_id;
2862 int idx;
2863 static const char *speed_names[] = { "full", "high", "super" };
2864
2865 if (type != FFS_DESCRIPTOR)
2866 return 0;
2867
2868 /*
2869 * If ss_descriptors is not NULL, we are reading super speed
2870 * descriptors; if hs_descriptors is not NULL, we are reading high
2871 * speed descriptors; otherwise, we are reading full speed
2872 * descriptors.
2873 */
2874 if (func->function.ss_descriptors) {
2875 ep_desc_id = 2;
2876 func->function.ss_descriptors[(long)valuep] = desc;
2877 } else if (func->function.hs_descriptors) {
2878 ep_desc_id = 1;
2879 func->function.hs_descriptors[(long)valuep] = desc;
2880 } else {
2881 ep_desc_id = 0;
2882 func->function.fs_descriptors[(long)valuep] = desc;
2883 }
2884
2885 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2886 return 0;
2887
2888 idx = ffs_ep_addr2idx(func->ffs, ds->bEndpointAddress) - 1;
2889 if (idx < 0)
2890 return idx;
2891
2892 ffs_ep = func->eps + idx;
2893
2894 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2895 pr_err("two %sspeed descriptors for EP %d\n",
2896 speed_names[ep_desc_id],
2897 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2898 return -EINVAL;
2899 }
2900 ffs_ep->descs[ep_desc_id] = ds;
2901
2902 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2903 if (ffs_ep->ep) {
2904 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2905 if (!ds->wMaxPacketSize)
2906 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2907 } else {
2908 struct usb_request *req;
2909 struct usb_ep *ep;
2910 u8 bEndpointAddress;
2911 u16 wMaxPacketSize;
2912
2913 /*
2914 * We back up bEndpointAddress because autoconfig overwrites
2915 * it with physical endpoint address.
2916 */
2917 bEndpointAddress = ds->bEndpointAddress;
2918 /*
2919 * We back up wMaxPacketSize because autoconfig treats
2920 * endpoint descriptors as if they were full speed.
2921 */
2922 wMaxPacketSize = ds->wMaxPacketSize;
2923 pr_vdebug("autoconfig\n");
2924 ep = usb_ep_autoconfig(func->gadget, ds);
2925 if (unlikely(!ep))
2926 return -ENOTSUPP;
2927 ep->driver_data = func->eps + idx;
2928
2929 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2930 if (unlikely(!req))
2931 return -ENOMEM;
2932
2933 ffs_ep->ep = ep;
2934 ffs_ep->req = req;
2935 func->eps_revmap[ds->bEndpointAddress &
2936 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2937 /*
2938 * If we use virtual address mapping, we restore
2939 * original bEndpointAddress value.
2940 */
2941 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
2942 ds->bEndpointAddress = bEndpointAddress;
2943 /*
2944 * Restore wMaxPacketSize which was potentially
2945 * overwritten by autoconfig.
2946 */
2947 ds->wMaxPacketSize = wMaxPacketSize;
2948 }
2949 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2950
2951 return 0;
2952}
2953
2954static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2955 struct usb_descriptor_header *desc,
2956 void *priv)
2957{
2958 struct ffs_function *func = priv;
2959 unsigned idx;
2960 u8 newValue;
2961
2962 switch (type) {
2963 default:
2964 case FFS_DESCRIPTOR:
2965 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2966 return 0;
2967
2968 case FFS_INTERFACE:
2969 idx = *valuep;
2970 if (func->interfaces_nums[idx] < 0) {
2971 int id = usb_interface_id(func->conf, &func->function);
2972 if (unlikely(id < 0))
2973 return id;
2974 func->interfaces_nums[idx] = id;
2975 }
2976 newValue = func->interfaces_nums[idx];
2977 break;
2978
2979 case FFS_STRING:
2980 /* String' IDs are allocated when fsf_data is bound to cdev */
2981 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2982 break;
2983
2984 case FFS_ENDPOINT:
2985 /*
2986 * USB_DT_ENDPOINT are handled in
2987 * __ffs_func_bind_do_descs().
2988 */
2989 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2990 return 0;
2991
2992 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2993 if (unlikely(!func->eps[idx].ep))
2994 return -EINVAL;
2995
2996 {
2997 struct usb_endpoint_descriptor **descs;
2998 descs = func->eps[idx].descs;
2999 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
3000 }
3001 break;
3002 }
3003
3004 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
3005 *valuep = newValue;
3006 return 0;
3007}
3008
3009static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
3010 struct usb_os_desc_header *h, void *data,
3011 unsigned len, void *priv)
3012{
3013 struct ffs_function *func = priv;
3014 u8 length = 0;
3015
3016 switch (type) {
3017 case FFS_OS_DESC_EXT_COMPAT: {
3018 struct usb_ext_compat_desc *desc = data;
3019 struct usb_os_desc_table *t;
3020
3021 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
3022 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
3023 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
3024 ARRAY_SIZE(desc->CompatibleID) +
3025 ARRAY_SIZE(desc->SubCompatibleID));
3026 length = sizeof(*desc);
3027 }
3028 break;
3029 case FFS_OS_DESC_EXT_PROP: {
3030 struct usb_ext_prop_desc *desc = data;
3031 struct usb_os_desc_table *t;
3032 struct usb_os_desc_ext_prop *ext_prop;
3033 char *ext_prop_name;
3034 char *ext_prop_data;
3035
3036 t = &func->function.os_desc_table[h->interface];
3037 t->if_id = func->interfaces_nums[h->interface];
3038
3039 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
3040 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
3041
3042 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
3043 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
3044 ext_prop->data_len = le32_to_cpu(*(__le32 *)
3045 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
3046 length = ext_prop->name_len + ext_prop->data_len + 14;
3047
3048 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
3049 func->ffs->ms_os_descs_ext_prop_name_avail +=
3050 ext_prop->name_len;
3051
3052 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
3053 func->ffs->ms_os_descs_ext_prop_data_avail +=
3054 ext_prop->data_len;
3055 memcpy(ext_prop_data,
3056 usb_ext_prop_data_ptr(data, ext_prop->name_len),
3057 ext_prop->data_len);
3058 /* unicode data reported to the host as "WCHAR"s */
3059 switch (ext_prop->type) {
3060 case USB_EXT_PROP_UNICODE:
3061 case USB_EXT_PROP_UNICODE_ENV:
3062 case USB_EXT_PROP_UNICODE_LINK:
3063 case USB_EXT_PROP_UNICODE_MULTI:
3064 ext_prop->data_len *= 2;
3065 break;
3066 }
3067 ext_prop->data = ext_prop_data;
3068
3069 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
3070 ext_prop->name_len);
3071 /* property name reported to the host as "WCHAR"s */
3072 ext_prop->name_len *= 2;
3073 ext_prop->name = ext_prop_name;
3074
3075 t->os_desc->ext_prop_len +=
3076 ext_prop->name_len + ext_prop->data_len + 14;
3077 ++t->os_desc->ext_prop_count;
3078 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
3079 }
3080 break;
3081 default:
3082 pr_vdebug("unknown descriptor: %d\n", type);
3083 }
3084
3085 return length;
3086}
3087
3088static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
3089 struct usb_configuration *c)
3090{
3091 struct ffs_function *func = ffs_func_from_usb(f);
3092 struct f_fs_opts *ffs_opts =
3093 container_of(f->fi, struct f_fs_opts, func_inst);
3094 struct ffs_data *ffs_data;
3095 int ret;
3096
3097 ENTER();
3098
3099 /*
3100 * Legacy gadget triggers binding in functionfs_ready_callback,
3101 * which already uses locking; taking the same lock here would
3102 * cause a deadlock.
3103 *
3104 * Configfs-enabled gadgets however do need ffs_dev_lock.
3105 */
3106 if (!ffs_opts->no_configfs)
3107 ffs_dev_lock();
3108 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
3109 ffs_data = ffs_opts->dev->ffs_data;
3110 if (!ffs_opts->no_configfs)
3111 ffs_dev_unlock();
3112 if (ret)
3113 return ERR_PTR(ret);
3114
3115 func->ffs = ffs_data;
3116 func->conf = c;
3117 func->gadget = c->cdev->gadget;
3118
3119 /*
3120 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
3121 * configurations are bound in sequence with list_for_each_entry,
3122 * in each configuration its functions are bound in sequence
3123 * with list_for_each_entry, so we assume no race condition
3124 * with regard to ffs_opts->bound access
3125 */
3126 if (!ffs_opts->refcnt) {
3127 ret = functionfs_bind(func->ffs, c->cdev);
3128 if (ret)
3129 return ERR_PTR(ret);
3130 }
3131 ffs_opts->refcnt++;
3132 func->function.strings = func->ffs->stringtabs;
3133
3134 return ffs_opts;
3135}
3136
3137static int _ffs_func_bind(struct usb_configuration *c,
3138 struct usb_function *f)
3139{
3140 struct ffs_function *func = ffs_func_from_usb(f);
3141 struct ffs_data *ffs = func->ffs;
3142
3143 const int full = !!func->ffs->fs_descs_count;
3144 const int high = !!func->ffs->hs_descs_count;
3145 const int super = !!func->ffs->ss_descs_count;
3146
3147 int fs_len, hs_len, ss_len, ret, i;
3148 struct ffs_ep *eps_ptr;
3149
3150 /* Make it a single chunk, less management later on */
3151 vla_group(d);
3152 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
3153 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
3154 full ? ffs->fs_descs_count + 1 : 0);
3155 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
3156 high ? ffs->hs_descs_count + 1 : 0);
3157 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
3158 super ? ffs->ss_descs_count + 1 : 0);
3159 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
3160 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
3161 c->cdev->use_os_string ? ffs->interfaces_count : 0);
3162 vla_item_with_sz(d, char[16], ext_compat,
3163 c->cdev->use_os_string ? ffs->interfaces_count : 0);
3164 vla_item_with_sz(d, struct usb_os_desc, os_desc,
3165 c->cdev->use_os_string ? ffs->interfaces_count : 0);
3166 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
3167 ffs->ms_os_descs_ext_prop_count);
3168 vla_item_with_sz(d, char, ext_prop_name,
3169 ffs->ms_os_descs_ext_prop_name_len);
3170 vla_item_with_sz(d, char, ext_prop_data,
3171 ffs->ms_os_descs_ext_prop_data_len);
3172 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
3173 char *vlabuf;
3174
3175 ENTER();
3176
3177 /* Has descriptors only for speeds gadget does not support */
3178 if (unlikely(!(full | high | super)))
3179 return -ENOTSUPP;
3180
3181 /* Allocate a single chunk, less management later on */
3182 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
3183 if (unlikely(!vlabuf))
3184 return -ENOMEM;
3185
3186 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
3187 ffs->ms_os_descs_ext_prop_name_avail =
3188 vla_ptr(vlabuf, d, ext_prop_name);
3189 ffs->ms_os_descs_ext_prop_data_avail =
3190 vla_ptr(vlabuf, d, ext_prop_data);
3191
3192 /* Copy descriptors */
3193 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
3194 ffs->raw_descs_length);
3195
3196 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
3197 eps_ptr = vla_ptr(vlabuf, d, eps);
3198 for (i = 0; i < ffs->eps_count; i++)
3199 eps_ptr[i].num = -1;
3200
3201 /* Save pointers
3202 * d_eps == vlabuf, func->eps used to kfree vlabuf later
3203 */
3204 func->eps = vla_ptr(vlabuf, d, eps);
3205 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
3206
3207 /*
3208 * Go through all the endpoint descriptors and allocate
3209 * endpoints first, so that later we can rewrite the endpoint
3210 * numbers without worrying that it may be described later on.
3211 */
3212 if (likely(full)) {
3213 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
3214 fs_len = ffs_do_descs(ffs->fs_descs_count,
3215 vla_ptr(vlabuf, d, raw_descs),
3216 d_raw_descs__sz,
3217 __ffs_func_bind_do_descs, func);
3218 if (unlikely(fs_len < 0)) {
3219 ret = fs_len;
3220 goto error;
3221 }
3222 } else {
3223 fs_len = 0;
3224 }
3225
3226 if (likely(high)) {
3227 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
3228 hs_len = ffs_do_descs(ffs->hs_descs_count,
3229 vla_ptr(vlabuf, d, raw_descs) + fs_len,
3230 d_raw_descs__sz - fs_len,
3231 __ffs_func_bind_do_descs, func);
3232 if (unlikely(hs_len < 0)) {
3233 ret = hs_len;
3234 goto error;
3235 }
3236 } else {
3237 hs_len = 0;
3238 }
3239
3240 if (likely(super)) {
3241 func->function.ss_descriptors = func->function.ssp_descriptors =
3242 vla_ptr(vlabuf, d, ss_descs);
3243 ss_len = ffs_do_descs(ffs->ss_descs_count,
3244 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
3245 d_raw_descs__sz - fs_len - hs_len,
3246 __ffs_func_bind_do_descs, func);
3247 if (unlikely(ss_len < 0)) {
3248 ret = ss_len;
3249 goto error;
3250 }
3251 } else {
3252 ss_len = 0;
3253 }
3254
3255 /*
3256 * Now handle interface numbers allocation and interface and
3257 * endpoint numbers rewriting. We can do that in one go
3258 * now.
3259 */
3260 ret = ffs_do_descs(ffs->fs_descs_count +
3261 (high ? ffs->hs_descs_count : 0) +
3262 (super ? ffs->ss_descs_count : 0),
3263 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
3264 __ffs_func_bind_do_nums, func);
3265 if (unlikely(ret < 0))
3266 goto error;
3267
3268 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
3269 if (c->cdev->use_os_string) {
3270 for (i = 0; i < ffs->interfaces_count; ++i) {
3271 struct usb_os_desc *desc;
3272
3273 desc = func->function.os_desc_table[i].os_desc =
3274 vla_ptr(vlabuf, d, os_desc) +
3275 i * sizeof(struct usb_os_desc);
3276 desc->ext_compat_id =
3277 vla_ptr(vlabuf, d, ext_compat) + i * 16;
3278 INIT_LIST_HEAD(&desc->ext_prop);
3279 }
3280 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
3281 vla_ptr(vlabuf, d, raw_descs) +
3282 fs_len + hs_len + ss_len,
3283 d_raw_descs__sz - fs_len - hs_len -
3284 ss_len,
3285 __ffs_func_bind_do_os_desc, func);
3286 if (unlikely(ret < 0))
3287 goto error;
3288 }
3289 func->function.os_desc_n =
3290 c->cdev->use_os_string ? ffs->interfaces_count : 0;
3291
3292 /* And we're done */
3293 ffs_event_add(ffs, FUNCTIONFS_BIND);
3294 return 0;
3295
3296error:
3297 /* XXX Do we need to release all claimed endpoints here? */
3298 return ret;
3299}
3300
3301static int ffs_func_bind(struct usb_configuration *c,
3302 struct usb_function *f)
3303{
3304 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
3305 struct ffs_function *func = ffs_func_from_usb(f);
3306 int ret;
3307
3308 if (IS_ERR(ffs_opts))
3309 return PTR_ERR(ffs_opts);
3310
3311 ret = _ffs_func_bind(c, f);
3312 if (ret && !--ffs_opts->refcnt)
3313 functionfs_unbind(func->ffs);
3314
3315 return ret;
3316}
3317
3318
3319/* Other USB function hooks *************************************************/
3320
3321static void ffs_reset_work(struct work_struct *work)
3322{
3323 struct ffs_data *ffs = container_of(work,
3324 struct ffs_data, reset_work);
3325 ffs_data_reset(ffs);
3326}
3327
3328static int ffs_func_set_alt(struct usb_function *f,
3329 unsigned interface, unsigned alt)
3330{
3331 struct ffs_function *func = ffs_func_from_usb(f);
3332 struct ffs_data *ffs = func->ffs;
3333 int ret = 0, intf;
3334
3335 if (alt != (unsigned)-1) {
3336 intf = ffs_func_revmap_intf(func, interface);
3337 if (unlikely(intf < 0))
3338 return intf;
3339 }
3340
3341 if (ffs->func)
3342 ffs_func_eps_disable(ffs->func);
3343
3344 if (ffs->state == FFS_DEACTIVATED) {
3345 ffs->state = FFS_CLOSING;
3346 INIT_WORK(&ffs->reset_work, ffs_reset_work);
3347 schedule_work(&ffs->reset_work);
3348 return -ENODEV;
3349 }
3350
3351 if (ffs->state != FFS_ACTIVE)
3352 return -ENODEV;
3353
3354 if (alt == (unsigned)-1) {
3355 ffs->func = NULL;
3356 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
3357 return 0;
3358 }
3359
3360 ffs->func = func;
3361 ret = ffs_func_eps_enable(func);
3362 if (likely(ret >= 0))
3363 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
3364 return ret;
3365}
3366
3367static void ffs_func_disable(struct usb_function *f)
3368{
3369 ffs_func_set_alt(f, 0, (unsigned)-1);
3370}
3371
3372static int ffs_func_setup(struct usb_function *f,
3373 const struct usb_ctrlrequest *creq)
3374{
3375 struct ffs_function *func = ffs_func_from_usb(f);
3376 struct ffs_data *ffs = func->ffs;
3377 unsigned long flags;
3378 int ret;
3379
3380 ENTER();
3381
3382 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
3383 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
3384 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
3385 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
3386 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
3387
3388 /*
3389 * Most requests directed to interface go through here
3390 * (notable exceptions are set/get interface) so we need to
3391 * handle them. All other either handled by composite or
3392 * passed to usb_configuration->setup() (if one is set). No
3393 * matter, we will handle requests directed to endpoint here
3394 * as well (as it's straightforward). Other request recipient
3395 * types are only handled when the user flag FUNCTIONFS_ALL_CTRL_RECIP
3396 * is being used.
3397 */
3398 if (ffs->state != FFS_ACTIVE)
3399 return -ENODEV;
3400
3401 switch (creq->bRequestType & USB_RECIP_MASK) {
3402 case USB_RECIP_INTERFACE:
3403 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
3404 if (unlikely(ret < 0))
3405 return ret;
3406 break;
3407
3408 case USB_RECIP_ENDPOINT:
3409 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
3410 if (unlikely(ret < 0))
3411 return ret;
3412 if (func->ffs->user_flags & FUNCTIONFS_VIRTUAL_ADDR)
3413 ret = func->ffs->eps_addrmap[ret];
3414 break;
3415
3416 default:
3417 if (func->ffs->user_flags & FUNCTIONFS_ALL_CTRL_RECIP)
3418 ret = le16_to_cpu(creq->wIndex);
3419 else
3420 return -EOPNOTSUPP;
3421 }
3422
3423 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
3424 ffs->ev.setup = *creq;
3425 ffs->ev.setup.wIndex = cpu_to_le16(ret);
3426 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
3427 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
3428
3429 return ffs->ev.setup.wLength == 0 ? USB_GADGET_DELAYED_STATUS : 0;
3430}
3431
3432static bool ffs_func_req_match(struct usb_function *f,
3433 const struct usb_ctrlrequest *creq,
3434 bool config0)
3435{
3436 struct ffs_function *func = ffs_func_from_usb(f);
3437
3438 if (config0 && !(func->ffs->user_flags & FUNCTIONFS_CONFIG0_SETUP))
3439 return false;
3440
3441 switch (creq->bRequestType & USB_RECIP_MASK) {
3442 case USB_RECIP_INTERFACE:
3443 return (ffs_func_revmap_intf(func,
3444 le16_to_cpu(creq->wIndex)) >= 0);
3445 case USB_RECIP_ENDPOINT:
3446 return (ffs_func_revmap_ep(func,
3447 le16_to_cpu(creq->wIndex)) >= 0);
3448 default:
3449 return (bool) (func->ffs->user_flags &
3450 FUNCTIONFS_ALL_CTRL_RECIP);
3451 }
3452}
3453
3454static void ffs_func_suspend(struct usb_function *f)
3455{
3456 ENTER();
3457 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
3458}
3459
3460static void ffs_func_resume(struct usb_function *f)
3461{
3462 ENTER();
3463 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
3464}
3465
3466
3467/* Endpoint and interface numbers reverse mapping ***************************/
3468
3469static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
3470{
3471 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
3472 return num ? num : -EDOM;
3473}
3474
3475static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
3476{
3477 short *nums = func->interfaces_nums;
3478 unsigned count = func->ffs->interfaces_count;
3479
3480 for (; count; --count, ++nums) {
3481 if (*nums >= 0 && *nums == intf)
3482 return nums - func->interfaces_nums;
3483 }
3484
3485 return -EDOM;
3486}
3487
3488
3489/* Devices management *******************************************************/
3490
3491static LIST_HEAD(ffs_devices);
3492
3493static struct ffs_dev *_ffs_do_find_dev(const char *name)
3494{
3495 struct ffs_dev *dev;
3496
3497 if (!name)
3498 return NULL;
3499
3500 list_for_each_entry(dev, &ffs_devices, entry) {
3501 if (strcmp(dev->name, name) == 0)
3502 return dev;
3503 }
3504
3505 return NULL;
3506}
3507
3508/*
3509 * ffs_lock must be taken by the caller of this function
3510 */
3511static struct ffs_dev *_ffs_get_single_dev(void)
3512{
3513 struct ffs_dev *dev;
3514
3515 if (list_is_singular(&ffs_devices)) {
3516 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
3517 if (dev->single)
3518 return dev;
3519 }
3520
3521 return NULL;
3522}
3523
3524/*
3525 * ffs_lock must be taken by the caller of this function
3526 */
3527static struct ffs_dev *_ffs_find_dev(const char *name)
3528{
3529 struct ffs_dev *dev;
3530
3531 dev = _ffs_get_single_dev();
3532 if (dev)
3533 return dev;
3534
3535 return _ffs_do_find_dev(name);
3536}
3537
3538/* Configfs support *********************************************************/
3539
3540static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
3541{
3542 return container_of(to_config_group(item), struct f_fs_opts,
3543 func_inst.group);
3544}
3545
3546static void ffs_attr_release(struct config_item *item)
3547{
3548 struct f_fs_opts *opts = to_ffs_opts(item);
3549
3550 usb_put_function_instance(&opts->func_inst);
3551}
3552
3553static struct configfs_item_operations ffs_item_ops = {
3554 .release = ffs_attr_release,
3555};
3556
3557static const struct config_item_type ffs_func_type = {
3558 .ct_item_ops = &ffs_item_ops,
3559 .ct_owner = THIS_MODULE,
3560};
3561
3562
3563/* Function registration interface ******************************************/
3564
3565static void ffs_free_inst(struct usb_function_instance *f)
3566{
3567 struct f_fs_opts *opts;
3568
3569 opts = to_f_fs_opts(f);
3570 ffs_release_dev(opts->dev);
3571 ffs_dev_lock();
3572 _ffs_free_dev(opts->dev);
3573 ffs_dev_unlock();
3574 kfree(opts);
3575}
3576
3577static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
3578{
3579 if (strlen(name) >= FIELD_SIZEOF(struct ffs_dev, name))
3580 return -ENAMETOOLONG;
3581 return ffs_name_dev(to_f_fs_opts(fi)->dev, name);
3582}
3583
3584static struct usb_function_instance *ffs_alloc_inst(void)
3585{
3586 struct f_fs_opts *opts;
3587 struct ffs_dev *dev;
3588
3589 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3590 if (!opts)
3591 return ERR_PTR(-ENOMEM);
3592
3593 opts->func_inst.set_inst_name = ffs_set_inst_name;
3594 opts->func_inst.free_func_inst = ffs_free_inst;
3595 ffs_dev_lock();
3596 dev = _ffs_alloc_dev();
3597 ffs_dev_unlock();
3598 if (IS_ERR(dev)) {
3599 kfree(opts);
3600 return ERR_CAST(dev);
3601 }
3602 opts->dev = dev;
3603 dev->opts = opts;
3604
3605 config_group_init_type_name(&opts->func_inst.group, "",
3606 &ffs_func_type);
3607 return &opts->func_inst;
3608}
3609
3610static void ffs_free(struct usb_function *f)
3611{
3612 kfree(ffs_func_from_usb(f));
3613}
3614
3615static void ffs_func_unbind(struct usb_configuration *c,
3616 struct usb_function *f)
3617{
3618 struct ffs_function *func = ffs_func_from_usb(f);
3619 struct ffs_data *ffs = func->ffs;
3620 struct f_fs_opts *opts =
3621 container_of(f->fi, struct f_fs_opts, func_inst);
3622 struct ffs_ep *ep = func->eps;
3623 unsigned count = ffs->eps_count;
3624 unsigned long flags;
3625
3626 ENTER();
3627 if (ffs->func == func) {
3628 ffs_func_eps_disable(func);
3629 ffs->func = NULL;
3630 }
3631
3632 /* Drain any pending AIO completions */
3633 drain_workqueue(ffs->io_completion_wq);
3634
3635 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3636 if (!--opts->refcnt)
3637 functionfs_unbind(ffs);
3638
3639 /* cleanup after autoconfig */
3640 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3641 while (count--) {
3642 if (ep->ep && ep->req)
3643 usb_ep_free_request(ep->ep, ep->req);
3644 ep->req = NULL;
3645 ++ep;
3646 }
3647 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3648 kfree(func->eps);
3649 func->eps = NULL;
3650 /*
3651 * eps, descriptors and interfaces_nums are allocated in the
3652 * same chunk so only one free is required.
3653 */
3654 func->function.fs_descriptors = NULL;
3655 func->function.hs_descriptors = NULL;
3656 func->function.ss_descriptors = NULL;
3657 func->function.ssp_descriptors = NULL;
3658 func->interfaces_nums = NULL;
3659
3660}
3661
3662static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3663{
3664 struct ffs_function *func;
3665
3666 ENTER();
3667
3668 func = kzalloc(sizeof(*func), GFP_KERNEL);
3669 if (unlikely(!func))
3670 return ERR_PTR(-ENOMEM);
3671
3672 func->function.name = "Function FS Gadget";
3673
3674 func->function.bind = ffs_func_bind;
3675 func->function.unbind = ffs_func_unbind;
3676 func->function.set_alt = ffs_func_set_alt;
3677 func->function.disable = ffs_func_disable;
3678 func->function.setup = ffs_func_setup;
3679 func->function.req_match = ffs_func_req_match;
3680 func->function.suspend = ffs_func_suspend;
3681 func->function.resume = ffs_func_resume;
3682 func->function.free_func = ffs_free;
3683
3684 return &func->function;
3685}
3686
3687/*
3688 * ffs_lock must be taken by the caller of this function
3689 */
3690static struct ffs_dev *_ffs_alloc_dev(void)
3691{
3692 struct ffs_dev *dev;
3693 int ret;
3694
3695 if (_ffs_get_single_dev())
3696 return ERR_PTR(-EBUSY);
3697
3698 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3699 if (!dev)
3700 return ERR_PTR(-ENOMEM);
3701
3702 if (list_empty(&ffs_devices)) {
3703 ret = functionfs_init();
3704 if (ret) {
3705 kfree(dev);
3706 return ERR_PTR(ret);
3707 }
3708 }
3709
3710 list_add(&dev->entry, &ffs_devices);
3711
3712 return dev;
3713}
3714
3715int ffs_name_dev(struct ffs_dev *dev, const char *name)
3716{
3717 struct ffs_dev *existing;
3718 int ret = 0;
3719
3720 ffs_dev_lock();
3721
3722 existing = _ffs_do_find_dev(name);
3723 if (!existing)
3724 strlcpy(dev->name, name, ARRAY_SIZE(dev->name));
3725 else if (existing != dev)
3726 ret = -EBUSY;
3727
3728 ffs_dev_unlock();
3729
3730 return ret;
3731}
3732EXPORT_SYMBOL_GPL(ffs_name_dev);
3733
3734int ffs_single_dev(struct ffs_dev *dev)
3735{
3736 int ret;
3737
3738 ret = 0;
3739 ffs_dev_lock();
3740
3741 if (!list_is_singular(&ffs_devices))
3742 ret = -EBUSY;
3743 else
3744 dev->single = true;
3745
3746 ffs_dev_unlock();
3747 return ret;
3748}
3749EXPORT_SYMBOL_GPL(ffs_single_dev);
3750
3751/*
3752 * ffs_lock must be taken by the caller of this function
3753 */
3754static void _ffs_free_dev(struct ffs_dev *dev)
3755{
3756 list_del(&dev->entry);
3757
3758 kfree(dev);
3759 if (list_empty(&ffs_devices))
3760 functionfs_cleanup();
3761}
3762
3763static int ffs_acquire_dev(const char *dev_name, struct ffs_data *ffs_data)
3764{
3765 int ret = 0;
3766 struct ffs_dev *ffs_dev;
3767
3768 ENTER();
3769 ffs_dev_lock();
3770
3771 ffs_dev = _ffs_find_dev(dev_name);
3772 if (!ffs_dev) {
3773 ret = -ENOENT;
3774 } else if (ffs_dev->mounted) {
3775 ret = -EBUSY;
3776 } else if (ffs_dev->ffs_acquire_dev_callback &&
3777 ffs_dev->ffs_acquire_dev_callback(ffs_dev)) {
3778 ret = -ENOENT;
3779 } else {
3780 ffs_dev->mounted = true;
3781 ffs_dev->ffs_data = ffs_data;
3782 ffs_data->private_data = ffs_dev;
3783 }
3784
3785 ffs_dev_unlock();
3786 return ret;
3787}
3788
3789static void ffs_release_dev(struct ffs_dev *ffs_dev)
3790{
3791 ENTER();
3792 ffs_dev_lock();
3793
3794 if (ffs_dev && ffs_dev->mounted) {
3795 ffs_dev->mounted = false;
3796 if (ffs_dev->ffs_data) {
3797 ffs_dev->ffs_data->private_data = NULL;
3798 ffs_dev->ffs_data = NULL;
3799 }
3800
3801 if (ffs_dev->ffs_release_dev_callback)
3802 ffs_dev->ffs_release_dev_callback(ffs_dev);
3803 }
3804
3805 ffs_dev_unlock();
3806}
3807
3808static int ffs_ready(struct ffs_data *ffs)
3809{
3810 struct ffs_dev *ffs_obj;
3811 int ret = 0;
3812
3813 ENTER();
3814 ffs_dev_lock();
3815
3816 ffs_obj = ffs->private_data;
3817 if (!ffs_obj) {
3818 ret = -EINVAL;
3819 goto done;
3820 }
3821 if (WARN_ON(ffs_obj->desc_ready)) {
3822 ret = -EBUSY;
3823 goto done;
3824 }
3825
3826 ffs_obj->desc_ready = true;
3827
3828 if (ffs_obj->ffs_ready_callback) {
3829 ret = ffs_obj->ffs_ready_callback(ffs);
3830 if (ret)
3831 goto done;
3832 }
3833
3834 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
3835done:
3836 ffs_dev_unlock();
3837 return ret;
3838}
3839
3840static void ffs_closed(struct ffs_data *ffs)
3841{
3842 struct ffs_dev *ffs_obj;
3843 struct f_fs_opts *opts;
3844 struct config_item *ci;
3845
3846 ENTER();
3847 ffs_dev_lock();
3848
3849 ffs_obj = ffs->private_data;
3850 if (!ffs_obj)
3851 goto done;
3852
3853 ffs_obj->desc_ready = false;
3854
3855 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags) &&
3856 ffs_obj->ffs_closed_callback)
3857 ffs_obj->ffs_closed_callback(ffs);
3858
3859 if (ffs_obj->opts)
3860 opts = ffs_obj->opts;
3861 else
3862 goto done;
3863
3864 if (opts->no_configfs || !opts->func_inst.group.cg_item.ci_parent
3865 || !kref_read(&opts->func_inst.group.cg_item.ci_kref))
3866 goto done;
3867
3868 ci = opts->func_inst.group.cg_item.ci_parent->ci_parent;
3869 ffs_dev_unlock();
3870
3871 if (test_bit(FFS_FL_BOUND, &ffs->flags))
3872 unregister_gadget_item(ci);
3873 return;
3874done:
3875 ffs_dev_unlock();
3876}
3877
3878/* Misc helper functions ****************************************************/
3879
3880static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3881{
3882 return nonblock
3883 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3884 : mutex_lock_interruptible(mutex);
3885}
3886
3887static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3888{
3889 char *data;
3890
3891 if (unlikely(!len))
3892 return NULL;
3893
3894 data = kmalloc(len, GFP_KERNEL);
3895 if (unlikely(!data))
3896 return ERR_PTR(-ENOMEM);
3897
3898 if (unlikely(copy_from_user(data, buf, len))) {
3899 kfree(data);
3900 return ERR_PTR(-EFAULT);
3901 }
3902
3903 pr_vdebug("Buffer from user space:\n");
3904 ffs_dump_mem("", data, len);
3905
3906 return data;
3907}
3908
3909DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3910MODULE_LICENSE("GPL");
3911MODULE_AUTHOR("Michal Nazarewicz");