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