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