usb: gadget: f_fs: remove loop from I/O function
[linux-block.git] / drivers / usb / gadget / f_fs.c
CommitLineData
ddf8abd2 1/*
5ab54cf7 2 * f_fs.c -- user mode file system API for USB composite function controllers
ddf8abd2
MN
3 *
4 * Copyright (C) 2010 Samsung Electronics
54b8360f 5 * Author: Michal Nazarewicz <mina86@mina86.com>
ddf8abd2 6 *
5ab54cf7 7 * Based on inode.c (GadgetFS) which was:
ddf8abd2
MN
8 * Copyright (C) 2003-2004 David Brownell
9 * Copyright (C) 2003 Agilent Technologies
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
ddf8abd2
MN
15 */
16
17
18/* #define DEBUG */
19/* #define VERBOSE_DEBUG */
20
21#include <linux/blkdev.h>
b0608690 22#include <linux/pagemap.h>
f940fcd8 23#include <linux/export.h>
560f1187 24#include <linux/hid.h>
ddf8abd2 25#include <asm/unaligned.h>
ddf8abd2
MN
26
27#include <linux/usb/composite.h>
28#include <linux/usb/functionfs.h>
29
30
31#define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
32
33
5ab54cf7 34/* Debugging ****************************************************************/
ddf8abd2
MN
35
36#ifdef VERBOSE_DEBUG
ea0e6276 37#ifndef pr_vdebug
d8df0b61 38# define pr_vdebug pr_debug
ea0e6276 39#endif /* pr_vdebug */
ddf8abd2 40# define ffs_dump_mem(prefix, ptr, len) \
aa02f172 41 print_hex_dump_bytes(pr_fmt(prefix ": "), DUMP_PREFIX_NONE, ptr, len)
ddf8abd2 42#else
ea0e6276 43#ifndef pr_vdebug
d8df0b61 44# define pr_vdebug(...) do { } while (0)
ea0e6276 45#endif /* pr_vdebug */
ddf8abd2 46# define ffs_dump_mem(prefix, ptr, len) do { } while (0)
d8df0b61
MN
47#endif /* VERBOSE_DEBUG */
48
aa02f172 49#define ENTER() pr_vdebug("%s()\n", __func__)
ddf8abd2
MN
50
51
52/* The data structure and setup file ****************************************/
53
54enum ffs_state {
5ab54cf7
MN
55 /*
56 * Waiting for descriptors and strings.
57 *
58 * In this state no open(2), read(2) or write(2) on epfiles
ddf8abd2 59 * may succeed (which should not be the problem as there
5ab54cf7
MN
60 * should be no such files opened in the first place).
61 */
ddf8abd2
MN
62 FFS_READ_DESCRIPTORS,
63 FFS_READ_STRINGS,
64
5ab54cf7
MN
65 /*
66 * We've got descriptors and strings. We are or have called
ddf8abd2 67 * functionfs_ready_callback(). functionfs_bind() may have
5ab54cf7
MN
68 * been called but we don't know.
69 *
70 * This is the only state in which operations on epfiles may
71 * succeed.
72 */
ddf8abd2
MN
73 FFS_ACTIVE,
74
5ab54cf7
MN
75 /*
76 * All endpoints have been closed. This state is also set if
ddf8abd2
MN
77 * we encounter an unrecoverable error. The only
78 * unrecoverable error is situation when after reading strings
5ab54cf7
MN
79 * from user space we fail to initialise epfiles or
80 * functionfs_ready_callback() returns with error (<0).
81 *
82 * In this state no open(2), read(2) or write(2) (both on ep0
ddf8abd2
MN
83 * as well as epfile) may succeed (at this point epfiles are
84 * unlinked and all closed so this is not a problem; ep0 is
85 * also closed but ep0 file exists and so open(2) on ep0 must
5ab54cf7
MN
86 * fail).
87 */
ddf8abd2
MN
88 FFS_CLOSING
89};
90
91
92enum ffs_setup_state {
93 /* There is no setup request pending. */
94 FFS_NO_SETUP,
5ab54cf7
MN
95 /*
96 * User has read events and there was a setup request event
ddf8abd2 97 * there. The next read/write on ep0 will handle the
5ab54cf7
MN
98 * request.
99 */
ddf8abd2 100 FFS_SETUP_PENDING,
5ab54cf7
MN
101 /*
102 * There was event pending but before user space handled it
ddf8abd2
MN
103 * some other event was introduced which canceled existing
104 * setup. If this state is set read/write on ep0 return
5ab54cf7
MN
105 * -EIDRM. This state is only set when adding event.
106 */
ddf8abd2
MN
107 FFS_SETUP_CANCELED
108};
109
110
111
112struct ffs_epfile;
113struct ffs_function;
114
115struct ffs_data {
116 struct usb_gadget *gadget;
117
5ab54cf7
MN
118 /*
119 * Protect access read/write operations, only one read/write
ddf8abd2
MN
120 * at a time. As a consequence protects ep0req and company.
121 * While setup request is being processed (queued) this is
5ab54cf7
MN
122 * held.
123 */
ddf8abd2
MN
124 struct mutex mutex;
125
5ab54cf7
MN
126 /*
127 * Protect access to endpoint related structures (basically
ddf8abd2 128 * usb_ep_queue(), usb_ep_dequeue(), etc. calls) except for
5ab54cf7
MN
129 * endpoint zero.
130 */
ddf8abd2
MN
131 spinlock_t eps_lock;
132
5ab54cf7
MN
133 /*
134 * XXX REVISIT do we need our own request? Since we are not
135 * handling setup requests immediately user space may be so
ddf8abd2
MN
136 * slow that another setup will be sent to the gadget but this
137 * time not to us but another function and then there could be
a4ce96ac 138 * a race. Is that the case? Or maybe we can use cdev->req
5ab54cf7
MN
139 * after all, maybe we just need some spinlock for that?
140 */
ddf8abd2
MN
141 struct usb_request *ep0req; /* P: mutex */
142 struct completion ep0req_completion; /* P: mutex */
143 int ep0req_status; /* P: mutex */
144
145 /* reference counter */
146 atomic_t ref;
147 /* how many files are opened (EP0 and others) */
148 atomic_t opened;
149
150 /* EP0 state */
151 enum ffs_state state;
152
153 /*
5ab54cf7 154 * Possible transitions:
ddf8abd2
MN
155 * + FFS_NO_SETUP -> FFS_SETUP_PENDING -- P: ev.waitq.lock
156 * happens only in ep0 read which is P: mutex
157 * + FFS_SETUP_PENDING -> FFS_NO_SETUP -- P: ev.waitq.lock
158 * happens only in ep0 i/o which is P: mutex
159 * + FFS_SETUP_PENDING -> FFS_SETUP_CANCELED -- P: ev.waitq.lock
160 * + FFS_SETUP_CANCELED -> FFS_NO_SETUP -- cmpxchg
161 */
162 enum ffs_setup_state setup_state;
163
164#define FFS_SETUP_STATE(ffs) \
165 ((enum ffs_setup_state)cmpxchg(&(ffs)->setup_state, \
166 FFS_SETUP_CANCELED, FFS_NO_SETUP))
167
168 /* Events & such. */
169 struct {
170 u8 types[4];
171 unsigned short count;
172 /* XXX REVISIT need to update it in some places, or do we? */
173 unsigned short can_stall;
174 struct usb_ctrlrequest setup;
175
176 wait_queue_head_t waitq;
177 } ev; /* the whole structure, P: ev.waitq.lock */
178
179 /* Flags */
180 unsigned long flags;
181#define FFS_FL_CALL_CLOSED_CALLBACK 0
182#define FFS_FL_BOUND 1
183
184 /* Active function */
185 struct ffs_function *func;
186
5ab54cf7
MN
187 /*
188 * Device name, write once when file system is mounted.
189 * Intended for user to read if she wants.
190 */
ddf8abd2 191 const char *dev_name;
5ab54cf7 192 /* Private data for our user (ie. gadget). Managed by user. */
ddf8abd2
MN
193 void *private_data;
194
195 /* filled by __ffs_data_got_descs() */
5ab54cf7
MN
196 /*
197 * Real descriptors are 16 bytes after raw_descs (so you need
ddf8abd2
MN
198 * to skip 16 bytes (ie. ffs->raw_descs + 16) to get to the
199 * first full speed descriptor). raw_descs_length and
5ab54cf7
MN
200 * raw_fs_descs_length do not have those 16 bytes added.
201 */
ddf8abd2
MN
202 const void *raw_descs;
203 unsigned raw_descs_length;
204 unsigned raw_fs_descs_length;
205 unsigned fs_descs_count;
206 unsigned hs_descs_count;
207
208 unsigned short strings_count;
209 unsigned short interfaces_count;
210 unsigned short eps_count;
211 unsigned short _pad1;
212
213 /* filled by __ffs_data_got_strings() */
214 /* ids in stringtabs are set in functionfs_bind() */
215 const void *raw_strings;
216 struct usb_gadget_strings **stringtabs;
217
5ab54cf7
MN
218 /*
219 * File system's super block, write once when file system is
220 * mounted.
221 */
ddf8abd2
MN
222 struct super_block *sb;
223
5ab54cf7 224 /* File permissions, written once when fs is mounted */
ddf8abd2
MN
225 struct ffs_file_perms {
226 umode_t mode;
b9b73f7c
EB
227 kuid_t uid;
228 kgid_t gid;
ddf8abd2
MN
229 } file_perms;
230
5ab54cf7
MN
231 /*
232 * The endpoint files, filled by ffs_epfiles_create(),
233 * destroyed by ffs_epfiles_destroy().
234 */
ddf8abd2
MN
235 struct ffs_epfile *epfiles;
236};
237
238/* Reference counter handling */
239static void ffs_data_get(struct ffs_data *ffs);
240static void ffs_data_put(struct ffs_data *ffs);
241/* Creates new ffs_data object. */
242static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
243
244/* Opened counter handling. */
245static void ffs_data_opened(struct ffs_data *ffs);
246static void ffs_data_closed(struct ffs_data *ffs);
247
5ab54cf7 248/* Called with ffs->mutex held; take over ownership of data. */
ddf8abd2
MN
249static int __must_check
250__ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
251static int __must_check
252__ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
253
254
255/* The function structure ***************************************************/
256
257struct ffs_ep;
258
259struct ffs_function {
260 struct usb_configuration *conf;
261 struct usb_gadget *gadget;
262 struct ffs_data *ffs;
263
264 struct ffs_ep *eps;
265 u8 eps_revmap[16];
266 short *interfaces_nums;
267
268 struct usb_function function;
269};
270
271
272static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
273{
274 return container_of(f, struct ffs_function, function);
275}
276
277static void ffs_func_free(struct ffs_function *func);
278
ddf8abd2
MN
279static void ffs_func_eps_disable(struct ffs_function *func);
280static int __must_check ffs_func_eps_enable(struct ffs_function *func);
281
ddf8abd2
MN
282static int ffs_func_bind(struct usb_configuration *,
283 struct usb_function *);
284static void ffs_func_unbind(struct usb_configuration *,
285 struct usb_function *);
286static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
287static void ffs_func_disable(struct usb_function *);
288static int ffs_func_setup(struct usb_function *,
289 const struct usb_ctrlrequest *);
290static void ffs_func_suspend(struct usb_function *);
291static void ffs_func_resume(struct usb_function *);
292
293
294static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
295static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
296
297
ddf8abd2
MN
298/* The endpoints structures *************************************************/
299
300struct ffs_ep {
301 struct usb_ep *ep; /* P: ffs->eps_lock */
302 struct usb_request *req; /* P: epfile->mutex */
303
304 /* [0]: full speed, [1]: high speed */
305 struct usb_endpoint_descriptor *descs[2];
306
307 u8 num;
308
309 int status; /* P: epfile->mutex */
310};
311
312struct ffs_epfile {
313 /* Protects ep->ep and ep->req. */
314 struct mutex mutex;
315 wait_queue_head_t wait;
316
317 struct ffs_data *ffs;
318 struct ffs_ep *ep; /* P: ffs->eps_lock */
319
320 struct dentry *dentry;
321
322 char name[5];
323
324 unsigned char in; /* P: ffs->eps_lock */
325 unsigned char isoc; /* P: ffs->eps_lock */
326
327 unsigned char _pad;
328};
329
ddf8abd2
MN
330static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
331static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
332
333static struct inode *__must_check
334ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
335 const struct file_operations *fops,
336 struct dentry **dentry_p);
337
338
339/* Misc helper functions ****************************************************/
340
341static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
342 __attribute__((warn_unused_result, nonnull));
260ef311 343static char *ffs_prepare_buffer(const char __user *buf, size_t len)
ddf8abd2
MN
344 __attribute__((warn_unused_result, nonnull));
345
346
347/* Control file aka ep0 *****************************************************/
348
349static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
350{
351 struct ffs_data *ffs = req->context;
352
353 complete_all(&ffs->ep0req_completion);
354}
355
ddf8abd2
MN
356static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
357{
358 struct usb_request *req = ffs->ep0req;
359 int ret;
360
361 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
362
363 spin_unlock_irq(&ffs->ev.waitq.lock);
364
365 req->buf = data;
366 req->length = len;
367
ce1fd358
MS
368 /*
369 * UDC layer requires to provide a buffer even for ZLP, but should
370 * not use it at all. Let's provide some poisoned pointer to catch
371 * possible bug in the driver.
372 */
373 if (req->buf == NULL)
374 req->buf = (void *)0xDEADBABE;
375
16735d02 376 reinit_completion(&ffs->ep0req_completion);
ddf8abd2
MN
377
378 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
379 if (unlikely(ret < 0))
380 return ret;
381
382 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
383 if (unlikely(ret)) {
384 usb_ep_dequeue(ffs->gadget->ep0, req);
385 return -EINTR;
386 }
387
388 ffs->setup_state = FFS_NO_SETUP;
389 return ffs->ep0req_status;
390}
391
392static int __ffs_ep0_stall(struct ffs_data *ffs)
393{
394 if (ffs->ev.can_stall) {
aa02f172 395 pr_vdebug("ep0 stall\n");
ddf8abd2
MN
396 usb_ep_set_halt(ffs->gadget->ep0);
397 ffs->setup_state = FFS_NO_SETUP;
398 return -EL2HLT;
399 } else {
aa02f172 400 pr_debug("bogus ep0 stall!\n");
ddf8abd2
MN
401 return -ESRCH;
402 }
403}
404
ddf8abd2
MN
405static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
406 size_t len, loff_t *ptr)
407{
408 struct ffs_data *ffs = file->private_data;
409 ssize_t ret;
410 char *data;
411
412 ENTER();
413
414 /* Fast check if setup was canceled */
415 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
416 return -EIDRM;
417
418 /* Acquire mutex */
419 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
420 if (unlikely(ret < 0))
421 return ret;
422
ddf8abd2
MN
423 /* Check state */
424 switch (ffs->state) {
425 case FFS_READ_DESCRIPTORS:
426 case FFS_READ_STRINGS:
427 /* Copy data */
428 if (unlikely(len < 16)) {
429 ret = -EINVAL;
430 break;
431 }
432
433 data = ffs_prepare_buffer(buf, len);
537baabb 434 if (IS_ERR(data)) {
ddf8abd2
MN
435 ret = PTR_ERR(data);
436 break;
437 }
438
439 /* Handle data */
440 if (ffs->state == FFS_READ_DESCRIPTORS) {
aa02f172 441 pr_info("read descriptors\n");
ddf8abd2
MN
442 ret = __ffs_data_got_descs(ffs, data, len);
443 if (unlikely(ret < 0))
444 break;
445
446 ffs->state = FFS_READ_STRINGS;
447 ret = len;
448 } else {
aa02f172 449 pr_info("read strings\n");
ddf8abd2
MN
450 ret = __ffs_data_got_strings(ffs, data, len);
451 if (unlikely(ret < 0))
452 break;
453
454 ret = ffs_epfiles_create(ffs);
455 if (unlikely(ret)) {
456 ffs->state = FFS_CLOSING;
457 break;
458 }
459
460 ffs->state = FFS_ACTIVE;
461 mutex_unlock(&ffs->mutex);
462
463 ret = functionfs_ready_callback(ffs);
464 if (unlikely(ret < 0)) {
465 ffs->state = FFS_CLOSING;
466 return ret;
467 }
468
469 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
470 return len;
471 }
472 break;
473
ddf8abd2
MN
474 case FFS_ACTIVE:
475 data = NULL;
5ab54cf7
MN
476 /*
477 * We're called from user space, we can use _irq
478 * rather then _irqsave
479 */
ddf8abd2
MN
480 spin_lock_irq(&ffs->ev.waitq.lock);
481 switch (FFS_SETUP_STATE(ffs)) {
482 case FFS_SETUP_CANCELED:
483 ret = -EIDRM;
484 goto done_spin;
485
486 case FFS_NO_SETUP:
487 ret = -ESRCH;
488 goto done_spin;
489
490 case FFS_SETUP_PENDING:
491 break;
492 }
493
494 /* FFS_SETUP_PENDING */
495 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
496 spin_unlock_irq(&ffs->ev.waitq.lock);
497 ret = __ffs_ep0_stall(ffs);
498 break;
499 }
500
501 /* FFS_SETUP_PENDING and not stall */
502 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
503
504 spin_unlock_irq(&ffs->ev.waitq.lock);
505
506 data = ffs_prepare_buffer(buf, len);
537baabb 507 if (IS_ERR(data)) {
ddf8abd2
MN
508 ret = PTR_ERR(data);
509 break;
510 }
511
512 spin_lock_irq(&ffs->ev.waitq.lock);
513
5ab54cf7
MN
514 /*
515 * We are guaranteed to be still in FFS_ACTIVE state
ddf8abd2
MN
516 * but the state of setup could have changed from
517 * FFS_SETUP_PENDING to FFS_SETUP_CANCELED so we need
518 * to check for that. If that happened we copied data
5ab54cf7
MN
519 * from user space in vain but it's unlikely.
520 *
521 * For sure we are not in FFS_NO_SETUP since this is
ddf8abd2
MN
522 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
523 * transition can be performed and it's protected by
5ab54cf7
MN
524 * mutex.
525 */
ddf8abd2
MN
526 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
527 ret = -EIDRM;
528done_spin:
529 spin_unlock_irq(&ffs->ev.waitq.lock);
530 } else {
531 /* unlocks spinlock */
532 ret = __ffs_ep0_queue_wait(ffs, data, len);
533 }
534 kfree(data);
535 break;
536
ddf8abd2
MN
537 default:
538 ret = -EBADFD;
539 break;
540 }
541
ddf8abd2
MN
542 mutex_unlock(&ffs->mutex);
543 return ret;
544}
545
ddf8abd2
MN
546static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
547 size_t n)
548{
5ab54cf7
MN
549 /*
550 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
551 * to release them.
552 */
ddf8abd2
MN
553 struct usb_functionfs_event events[n];
554 unsigned i = 0;
555
556 memset(events, 0, sizeof events);
557
558 do {
559 events[i].type = ffs->ev.types[i];
560 if (events[i].type == FUNCTIONFS_SETUP) {
561 events[i].u.setup = ffs->ev.setup;
562 ffs->setup_state = FFS_SETUP_PENDING;
563 }
564 } while (++i < n);
565
566 if (n < ffs->ev.count) {
567 ffs->ev.count -= n;
568 memmove(ffs->ev.types, ffs->ev.types + n,
569 ffs->ev.count * sizeof *ffs->ev.types);
570 } else {
571 ffs->ev.count = 0;
572 }
573
574 spin_unlock_irq(&ffs->ev.waitq.lock);
575 mutex_unlock(&ffs->mutex);
576
577 return unlikely(__copy_to_user(buf, events, sizeof events))
578 ? -EFAULT : sizeof events;
579}
580
ddf8abd2
MN
581static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
582 size_t len, loff_t *ptr)
583{
584 struct ffs_data *ffs = file->private_data;
585 char *data = NULL;
586 size_t n;
587 int ret;
588
589 ENTER();
590
591 /* Fast check if setup was canceled */
592 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
593 return -EIDRM;
594
595 /* Acquire mutex */
596 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
597 if (unlikely(ret < 0))
598 return ret;
599
ddf8abd2
MN
600 /* Check state */
601 if (ffs->state != FFS_ACTIVE) {
602 ret = -EBADFD;
603 goto done_mutex;
604 }
605
5ab54cf7
MN
606 /*
607 * We're called from user space, we can use _irq rather then
608 * _irqsave
609 */
ddf8abd2
MN
610 spin_lock_irq(&ffs->ev.waitq.lock);
611
612 switch (FFS_SETUP_STATE(ffs)) {
613 case FFS_SETUP_CANCELED:
614 ret = -EIDRM;
615 break;
616
617 case FFS_NO_SETUP:
618 n = len / sizeof(struct usb_functionfs_event);
619 if (unlikely(!n)) {
620 ret = -EINVAL;
621 break;
622 }
623
624 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
625 ret = -EAGAIN;
626 break;
627 }
628
5ab54cf7
MN
629 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
630 ffs->ev.count)) {
ddf8abd2
MN
631 ret = -EINTR;
632 break;
633 }
634
635 return __ffs_ep0_read_events(ffs, buf,
636 min(n, (size_t)ffs->ev.count));
637
ddf8abd2
MN
638 case FFS_SETUP_PENDING:
639 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
640 spin_unlock_irq(&ffs->ev.waitq.lock);
641 ret = __ffs_ep0_stall(ffs);
642 goto done_mutex;
643 }
644
645 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
646
647 spin_unlock_irq(&ffs->ev.waitq.lock);
648
649 if (likely(len)) {
650 data = kmalloc(len, GFP_KERNEL);
651 if (unlikely(!data)) {
652 ret = -ENOMEM;
653 goto done_mutex;
654 }
655 }
656
657 spin_lock_irq(&ffs->ev.waitq.lock);
658
659 /* See ffs_ep0_write() */
660 if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
661 ret = -EIDRM;
662 break;
663 }
664
665 /* unlocks spinlock */
666 ret = __ffs_ep0_queue_wait(ffs, data, len);
667 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
668 ret = -EFAULT;
669 goto done_mutex;
670
671 default:
672 ret = -EBADFD;
673 break;
674 }
675
676 spin_unlock_irq(&ffs->ev.waitq.lock);
677done_mutex:
678 mutex_unlock(&ffs->mutex);
679 kfree(data);
680 return ret;
681}
682
ddf8abd2
MN
683static int ffs_ep0_open(struct inode *inode, struct file *file)
684{
685 struct ffs_data *ffs = inode->i_private;
686
687 ENTER();
688
689 if (unlikely(ffs->state == FFS_CLOSING))
690 return -EBUSY;
691
692 file->private_data = ffs;
693 ffs_data_opened(ffs);
694
695 return 0;
696}
697
ddf8abd2
MN
698static int ffs_ep0_release(struct inode *inode, struct file *file)
699{
700 struct ffs_data *ffs = file->private_data;
701
702 ENTER();
703
704 ffs_data_closed(ffs);
705
706 return 0;
707}
708
ddf8abd2
MN
709static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
710{
711 struct ffs_data *ffs = file->private_data;
712 struct usb_gadget *gadget = ffs->gadget;
713 long ret;
714
715 ENTER();
716
717 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
718 struct ffs_function *func = ffs->func;
719 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
92b0abf8 720 } else if (gadget && gadget->ops->ioctl) {
ddf8abd2 721 ret = gadget->ops->ioctl(gadget, code, value);
ddf8abd2
MN
722 } else {
723 ret = -ENOTTY;
724 }
725
726 return ret;
727}
728
ddf8abd2 729static const struct file_operations ffs_ep0_operations = {
ddf8abd2
MN
730 .llseek = no_llseek,
731
732 .open = ffs_ep0_open,
733 .write = ffs_ep0_write,
734 .read = ffs_ep0_read,
735 .release = ffs_ep0_release,
736 .unlocked_ioctl = ffs_ep0_ioctl,
737};
738
739
740/* "Normal" endpoints operations ********************************************/
741
ddf8abd2
MN
742static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
743{
744 ENTER();
745 if (likely(req->context)) {
746 struct ffs_ep *ep = _ep->driver_data;
747 ep->status = req->status ? req->status : req->actual;
748 complete(req->context);
749 }
750}
751
ddf8abd2
MN
752static ssize_t ffs_epfile_io(struct file *file,
753 char __user *buf, size_t len, int read)
754{
755 struct ffs_epfile *epfile = file->private_data;
756 struct ffs_ep *ep;
757 char *data = NULL;
758 ssize_t ret;
759 int halt;
760
7fa68034
MN
761 /* Are we still active? */
762 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
763 ret = -ENODEV;
764 goto error;
765 }
ddf8abd2 766
7fa68034
MN
767 /* Wait for endpoint to be enabled */
768 ep = epfile->ep;
769 if (!ep) {
770 if (file->f_flags & O_NONBLOCK) {
771 ret = -EAGAIN;
ddf8abd2
MN
772 goto error;
773 }
774
7fa68034
MN
775 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
776 if (ret) {
777 ret = -EINTR;
ddf8abd2
MN
778 goto error;
779 }
7fa68034 780 }
ddf8abd2 781
7fa68034
MN
782 /* Do we halt? */
783 halt = !read == !epfile->in;
784 if (halt && epfile->isoc) {
785 ret = -EINVAL;
786 goto error;
787 }
ddf8abd2 788
7fa68034
MN
789 /* Allocate & copy */
790 if (!halt) {
791 data = kmalloc(len, GFP_KERNEL);
792 if (unlikely(!data))
793 return -ENOMEM;
ddf8abd2 794
7fa68034
MN
795 if (!read && unlikely(copy_from_user(data, buf, len))) {
796 ret = -EFAULT;
ddf8abd2 797 goto error;
7fa68034
MN
798 }
799 }
ddf8abd2 800
7fa68034
MN
801 /* We will be using request */
802 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
803 if (unlikely(ret))
804 goto error;
ddf8abd2 805
7fa68034 806 spin_lock_irq(&epfile->ffs->eps_lock);
ddf8abd2 807
7fa68034
MN
808 if (epfile->ep != ep) {
809 /* In the meantime, endpoint got disabled or changed. */
810 ret = -ESHUTDOWN;
811 spin_unlock_irq(&epfile->ffs->eps_lock);
812 } else if (halt) {
813 /* Halt */
ddf8abd2
MN
814 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
815 usb_ep_set_halt(ep->ep);
816 spin_unlock_irq(&epfile->ffs->eps_lock);
817 ret = -EBADMSG;
818 } else {
819 /* Fire the request */
820 DECLARE_COMPLETION_ONSTACK(done);
821
822 struct usb_request *req = ep->req;
823 req->context = &done;
824 req->complete = ffs_epfile_io_complete;
825 req->buf = data;
826 req->length = len;
827
828 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
829
830 spin_unlock_irq(&epfile->ffs->eps_lock);
831
832 if (unlikely(ret < 0)) {
833 /* nop */
834 } else if (unlikely(wait_for_completion_interruptible(&done))) {
835 ret = -EINTR;
836 usb_ep_dequeue(ep->ep, req);
837 } else {
838 ret = ep->status;
839 if (read && ret > 0 &&
840 unlikely(copy_to_user(buf, data, ret)))
841 ret = -EFAULT;
842 }
843 }
844
845 mutex_unlock(&epfile->mutex);
846error:
847 kfree(data);
848 return ret;
849}
850
ddf8abd2
MN
851static ssize_t
852ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
853 loff_t *ptr)
854{
855 ENTER();
856
857 return ffs_epfile_io(file, (char __user *)buf, len, 0);
858}
859
860static ssize_t
861ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
862{
863 ENTER();
864
865 return ffs_epfile_io(file, buf, len, 1);
866}
867
868static int
869ffs_epfile_open(struct inode *inode, struct file *file)
870{
871 struct ffs_epfile *epfile = inode->i_private;
872
873 ENTER();
874
875 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
876 return -ENODEV;
877
878 file->private_data = epfile;
879 ffs_data_opened(epfile->ffs);
880
881 return 0;
882}
883
884static int
885ffs_epfile_release(struct inode *inode, struct file *file)
886{
887 struct ffs_epfile *epfile = inode->i_private;
888
889 ENTER();
890
891 ffs_data_closed(epfile->ffs);
892
893 return 0;
894}
895
ddf8abd2
MN
896static long ffs_epfile_ioctl(struct file *file, unsigned code,
897 unsigned long value)
898{
899 struct ffs_epfile *epfile = file->private_data;
900 int ret;
901
902 ENTER();
903
904 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
905 return -ENODEV;
906
907 spin_lock_irq(&epfile->ffs->eps_lock);
908 if (likely(epfile->ep)) {
909 switch (code) {
910 case FUNCTIONFS_FIFO_STATUS:
911 ret = usb_ep_fifo_status(epfile->ep->ep);
912 break;
913 case FUNCTIONFS_FIFO_FLUSH:
914 usb_ep_fifo_flush(epfile->ep->ep);
915 ret = 0;
916 break;
917 case FUNCTIONFS_CLEAR_HALT:
918 ret = usb_ep_clear_halt(epfile->ep->ep);
919 break;
920 case FUNCTIONFS_ENDPOINT_REVMAP:
921 ret = epfile->ep->num;
922 break;
923 default:
924 ret = -ENOTTY;
925 }
926 } else {
927 ret = -ENODEV;
928 }
929 spin_unlock_irq(&epfile->ffs->eps_lock);
930
931 return ret;
932}
933
ddf8abd2 934static const struct file_operations ffs_epfile_operations = {
ddf8abd2
MN
935 .llseek = no_llseek,
936
937 .open = ffs_epfile_open,
938 .write = ffs_epfile_write,
939 .read = ffs_epfile_read,
940 .release = ffs_epfile_release,
941 .unlocked_ioctl = ffs_epfile_ioctl,
942};
943
944
ddf8abd2
MN
945/* File system and super block operations ***********************************/
946
947/*
5ab54cf7 948 * Mounting the file system creates a controller file, used first for
ddf8abd2
MN
949 * function configuration then later for event monitoring.
950 */
951
ddf8abd2
MN
952static struct inode *__must_check
953ffs_sb_make_inode(struct super_block *sb, void *data,
954 const struct file_operations *fops,
955 const struct inode_operations *iops,
956 struct ffs_file_perms *perms)
957{
958 struct inode *inode;
959
960 ENTER();
961
962 inode = new_inode(sb);
963
964 if (likely(inode)) {
965 struct timespec current_time = CURRENT_TIME;
966
12ba8d1e 967 inode->i_ino = get_next_ino();
ddf8abd2
MN
968 inode->i_mode = perms->mode;
969 inode->i_uid = perms->uid;
970 inode->i_gid = perms->gid;
971 inode->i_atime = current_time;
972 inode->i_mtime = current_time;
973 inode->i_ctime = current_time;
974 inode->i_private = data;
975 if (fops)
976 inode->i_fop = fops;
977 if (iops)
978 inode->i_op = iops;
979 }
980
981 return inode;
982}
983
ddf8abd2 984/* Create "regular" file */
ddf8abd2
MN
985static struct inode *ffs_sb_create_file(struct super_block *sb,
986 const char *name, void *data,
987 const struct file_operations *fops,
988 struct dentry **dentry_p)
989{
990 struct ffs_data *ffs = sb->s_fs_info;
991 struct dentry *dentry;
992 struct inode *inode;
993
994 ENTER();
995
996 dentry = d_alloc_name(sb->s_root, name);
997 if (unlikely(!dentry))
998 return NULL;
999
1000 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1001 if (unlikely(!inode)) {
1002 dput(dentry);
1003 return NULL;
1004 }
1005
1006 d_add(dentry, inode);
1007 if (dentry_p)
1008 *dentry_p = dentry;
1009
1010 return inode;
1011}
1012
ddf8abd2 1013/* Super block */
ddf8abd2
MN
1014static const struct super_operations ffs_sb_operations = {
1015 .statfs = simple_statfs,
1016 .drop_inode = generic_delete_inode,
1017};
1018
1019struct ffs_sb_fill_data {
1020 struct ffs_file_perms perms;
1021 umode_t root_mode;
1022 const char *dev_name;
2606b28a 1023 struct ffs_data *ffs_data;
ddf8abd2
MN
1024};
1025
1026static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1027{
1028 struct ffs_sb_fill_data *data = _data;
1029 struct inode *inode;
2606b28a 1030 struct ffs_data *ffs = data->ffs_data;
ddf8abd2
MN
1031
1032 ENTER();
1033
ddf8abd2 1034 ffs->sb = sb;
2606b28a 1035 data->ffs_data = NULL;
ddf8abd2
MN
1036 sb->s_fs_info = ffs;
1037 sb->s_blocksize = PAGE_CACHE_SIZE;
1038 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1039 sb->s_magic = FUNCTIONFS_MAGIC;
1040 sb->s_op = &ffs_sb_operations;
1041 sb->s_time_gran = 1;
1042
1043 /* Root inode */
1044 data->perms.mode = data->root_mode;
1045 inode = ffs_sb_make_inode(sb, NULL,
1046 &simple_dir_operations,
1047 &simple_dir_inode_operations,
1048 &data->perms);
48fde701
AV
1049 sb->s_root = d_make_root(inode);
1050 if (unlikely(!sb->s_root))
2606b28a 1051 return -ENOMEM;
ddf8abd2
MN
1052
1053 /* EP0 file */
1054 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1055 &ffs_ep0_operations, NULL)))
2606b28a 1056 return -ENOMEM;
ddf8abd2
MN
1057
1058 return 0;
ddf8abd2
MN
1059}
1060
ddf8abd2
MN
1061static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1062{
1063 ENTER();
1064
1065 if (!opts || !*opts)
1066 return 0;
1067
1068 for (;;) {
ddf8abd2 1069 unsigned long value;
afd2e186 1070 char *eq, *comma;
ddf8abd2
MN
1071
1072 /* Option limit */
1073 comma = strchr(opts, ',');
1074 if (comma)
1075 *comma = 0;
1076
1077 /* Value limit */
1078 eq = strchr(opts, '=');
1079 if (unlikely(!eq)) {
aa02f172 1080 pr_err("'=' missing in %s\n", opts);
ddf8abd2
MN
1081 return -EINVAL;
1082 }
1083 *eq = 0;
1084
1085 /* Parse value */
afd2e186 1086 if (kstrtoul(eq + 1, 0, &value)) {
aa02f172 1087 pr_err("%s: invalid value: %s\n", opts, eq + 1);
ddf8abd2
MN
1088 return -EINVAL;
1089 }
1090
1091 /* Interpret option */
1092 switch (eq - opts) {
1093 case 5:
1094 if (!memcmp(opts, "rmode", 5))
1095 data->root_mode = (value & 0555) | S_IFDIR;
1096 else if (!memcmp(opts, "fmode", 5))
1097 data->perms.mode = (value & 0666) | S_IFREG;
1098 else
1099 goto invalid;
1100 break;
1101
1102 case 4:
1103 if (!memcmp(opts, "mode", 4)) {
1104 data->root_mode = (value & 0555) | S_IFDIR;
1105 data->perms.mode = (value & 0666) | S_IFREG;
1106 } else {
1107 goto invalid;
1108 }
1109 break;
1110
1111 case 3:
b9b73f7c
EB
1112 if (!memcmp(opts, "uid", 3)) {
1113 data->perms.uid = make_kuid(current_user_ns(), value);
1114 if (!uid_valid(data->perms.uid)) {
1115 pr_err("%s: unmapped value: %lu\n", opts, value);
1116 return -EINVAL;
1117 }
b8100750 1118 } else if (!memcmp(opts, "gid", 3)) {
b9b73f7c
EB
1119 data->perms.gid = make_kgid(current_user_ns(), value);
1120 if (!gid_valid(data->perms.gid)) {
1121 pr_err("%s: unmapped value: %lu\n", opts, value);
1122 return -EINVAL;
1123 }
b8100750 1124 } else {
ddf8abd2 1125 goto invalid;
b8100750 1126 }
ddf8abd2
MN
1127 break;
1128
1129 default:
1130invalid:
aa02f172 1131 pr_err("%s: invalid option\n", opts);
ddf8abd2
MN
1132 return -EINVAL;
1133 }
1134
1135 /* Next iteration */
1136 if (!comma)
1137 break;
1138 opts = comma + 1;
1139 }
1140
1141 return 0;
1142}
1143
ddf8abd2
MN
1144/* "mount -t functionfs dev_name /dev/function" ends up here */
1145
fc14f2fe
AV
1146static struct dentry *
1147ffs_fs_mount(struct file_system_type *t, int flags,
1148 const char *dev_name, void *opts)
ddf8abd2
MN
1149{
1150 struct ffs_sb_fill_data data = {
1151 .perms = {
1152 .mode = S_IFREG | 0600,
b9b73f7c
EB
1153 .uid = GLOBAL_ROOT_UID,
1154 .gid = GLOBAL_ROOT_GID,
ddf8abd2
MN
1155 },
1156 .root_mode = S_IFDIR | 0500,
1157 };
581791f5 1158 struct dentry *rv;
ddf8abd2 1159 int ret;
581791f5 1160 void *ffs_dev;
2606b28a 1161 struct ffs_data *ffs;
ddf8abd2
MN
1162
1163 ENTER();
1164
ddf8abd2
MN
1165 ret = ffs_fs_parse_opts(&data, opts);
1166 if (unlikely(ret < 0))
fc14f2fe 1167 return ERR_PTR(ret);
ddf8abd2 1168
2606b28a
AV
1169 ffs = ffs_data_new();
1170 if (unlikely(!ffs))
1171 return ERR_PTR(-ENOMEM);
1172 ffs->file_perms = data.perms;
1173
1174 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1175 if (unlikely(!ffs->dev_name)) {
1176 ffs_data_put(ffs);
1177 return ERR_PTR(-ENOMEM);
1178 }
1179
581791f5 1180 ffs_dev = functionfs_acquire_dev_callback(dev_name);
2606b28a
AV
1181 if (IS_ERR(ffs_dev)) {
1182 ffs_data_put(ffs);
1183 return ERR_CAST(ffs_dev);
1184 }
1185 ffs->private_data = ffs_dev;
1186 data.ffs_data = ffs;
581791f5 1187
581791f5 1188 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
2606b28a 1189 if (IS_ERR(rv) && data.ffs_data) {
581791f5 1190 functionfs_release_dev_callback(data.ffs_data);
2606b28a
AV
1191 ffs_data_put(data.ffs_data);
1192 }
581791f5 1193 return rv;
ddf8abd2
MN
1194}
1195
1196static void
1197ffs_fs_kill_sb(struct super_block *sb)
1198{
ddf8abd2
MN
1199 ENTER();
1200
1201 kill_litter_super(sb);
581791f5
AP
1202 if (sb->s_fs_info) {
1203 functionfs_release_dev_callback(sb->s_fs_info);
5b5f9560 1204 ffs_data_put(sb->s_fs_info);
581791f5 1205 }
ddf8abd2
MN
1206}
1207
1208static struct file_system_type ffs_fs_type = {
1209 .owner = THIS_MODULE,
1210 .name = "functionfs",
fc14f2fe 1211 .mount = ffs_fs_mount,
ddf8abd2
MN
1212 .kill_sb = ffs_fs_kill_sb,
1213};
7f78e035 1214MODULE_ALIAS_FS("functionfs");
ddf8abd2
MN
1215
1216
ddf8abd2
MN
1217/* Driver's main init/cleanup functions *************************************/
1218
ddf8abd2
MN
1219static int functionfs_init(void)
1220{
1221 int ret;
1222
1223 ENTER();
1224
1225 ret = register_filesystem(&ffs_fs_type);
1226 if (likely(!ret))
aa02f172 1227 pr_info("file system registered\n");
ddf8abd2 1228 else
aa02f172 1229 pr_err("failed registering file system (%d)\n", ret);
ddf8abd2
MN
1230
1231 return ret;
1232}
1233
1234static void functionfs_cleanup(void)
1235{
1236 ENTER();
1237
aa02f172 1238 pr_info("unloading\n");
ddf8abd2
MN
1239 unregister_filesystem(&ffs_fs_type);
1240}
1241
1242
ddf8abd2
MN
1243/* ffs_data and ffs_function construction and destruction code **************/
1244
1245static void ffs_data_clear(struct ffs_data *ffs);
1246static void ffs_data_reset(struct ffs_data *ffs);
1247
ddf8abd2
MN
1248static void ffs_data_get(struct ffs_data *ffs)
1249{
1250 ENTER();
1251
1252 atomic_inc(&ffs->ref);
1253}
1254
1255static void ffs_data_opened(struct ffs_data *ffs)
1256{
1257 ENTER();
1258
1259 atomic_inc(&ffs->ref);
1260 atomic_inc(&ffs->opened);
1261}
1262
1263static void ffs_data_put(struct ffs_data *ffs)
1264{
1265 ENTER();
1266
1267 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
aa02f172 1268 pr_info("%s(): freeing\n", __func__);
ddf8abd2 1269 ffs_data_clear(ffs);
647d5580 1270 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
ddf8abd2 1271 waitqueue_active(&ffs->ep0req_completion.wait));
581791f5 1272 kfree(ffs->dev_name);
ddf8abd2
MN
1273 kfree(ffs);
1274 }
1275}
1276
ddf8abd2
MN
1277static void ffs_data_closed(struct ffs_data *ffs)
1278{
1279 ENTER();
1280
1281 if (atomic_dec_and_test(&ffs->opened)) {
1282 ffs->state = FFS_CLOSING;
1283 ffs_data_reset(ffs);
1284 }
1285
1286 ffs_data_put(ffs);
1287}
1288
ddf8abd2
MN
1289static struct ffs_data *ffs_data_new(void)
1290{
1291 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1292 if (unlikely(!ffs))
1293 return 0;
1294
1295 ENTER();
1296
1297 atomic_set(&ffs->ref, 1);
1298 atomic_set(&ffs->opened, 0);
1299 ffs->state = FFS_READ_DESCRIPTORS;
1300 mutex_init(&ffs->mutex);
1301 spin_lock_init(&ffs->eps_lock);
1302 init_waitqueue_head(&ffs->ev.waitq);
1303 init_completion(&ffs->ep0req_completion);
1304
1305 /* XXX REVISIT need to update it in some places, or do we? */
1306 ffs->ev.can_stall = 1;
1307
1308 return ffs;
1309}
1310
ddf8abd2
MN
1311static void ffs_data_clear(struct ffs_data *ffs)
1312{
1313 ENTER();
1314
1315 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1316 functionfs_closed_callback(ffs);
1317
1318 BUG_ON(ffs->gadget);
1319
1320 if (ffs->epfiles)
1321 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1322
1323 kfree(ffs->raw_descs);
1324 kfree(ffs->raw_strings);
1325 kfree(ffs->stringtabs);
1326}
1327
ddf8abd2
MN
1328static void ffs_data_reset(struct ffs_data *ffs)
1329{
1330 ENTER();
1331
1332 ffs_data_clear(ffs);
1333
1334 ffs->epfiles = NULL;
1335 ffs->raw_descs = NULL;
1336 ffs->raw_strings = NULL;
1337 ffs->stringtabs = NULL;
1338
1339 ffs->raw_descs_length = 0;
1340 ffs->raw_fs_descs_length = 0;
1341 ffs->fs_descs_count = 0;
1342 ffs->hs_descs_count = 0;
1343
1344 ffs->strings_count = 0;
1345 ffs->interfaces_count = 0;
1346 ffs->eps_count = 0;
1347
1348 ffs->ev.count = 0;
1349
1350 ffs->state = FFS_READ_DESCRIPTORS;
1351 ffs->setup_state = FFS_NO_SETUP;
1352 ffs->flags = 0;
1353}
1354
1355
1356static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1357{
fd7c9a00
MN
1358 struct usb_gadget_strings **lang;
1359 int first_id;
ddf8abd2
MN
1360
1361 ENTER();
1362
1363 if (WARN_ON(ffs->state != FFS_ACTIVE
1364 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1365 return -EBADFD;
1366
fd7c9a00
MN
1367 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1368 if (unlikely(first_id < 0))
1369 return first_id;
ddf8abd2
MN
1370
1371 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1372 if (unlikely(!ffs->ep0req))
1373 return -ENOMEM;
1374 ffs->ep0req->complete = ffs_ep0_complete;
1375 ffs->ep0req->context = ffs;
1376
fd7c9a00
MN
1377 lang = ffs->stringtabs;
1378 for (lang = ffs->stringtabs; *lang; ++lang) {
1379 struct usb_string *str = (*lang)->strings;
1380 int id = first_id;
1381 for (; str->s; ++id, ++str)
1382 str->id = id;
ddf8abd2
MN
1383 }
1384
1385 ffs->gadget = cdev->gadget;
fd7c9a00 1386 ffs_data_get(ffs);
ddf8abd2
MN
1387 return 0;
1388}
1389
ddf8abd2
MN
1390static void functionfs_unbind(struct ffs_data *ffs)
1391{
1392 ENTER();
1393
1394 if (!WARN_ON(!ffs->gadget)) {
1395 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1396 ffs->ep0req = NULL;
1397 ffs->gadget = NULL;
e2190a97 1398 clear_bit(FFS_FL_BOUND, &ffs->flags);
df498995 1399 ffs_data_put(ffs);
ddf8abd2
MN
1400 }
1401}
1402
ddf8abd2
MN
1403static int ffs_epfiles_create(struct ffs_data *ffs)
1404{
1405 struct ffs_epfile *epfile, *epfiles;
1406 unsigned i, count;
1407
1408 ENTER();
1409
1410 count = ffs->eps_count;
9823a525 1411 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
ddf8abd2
MN
1412 if (!epfiles)
1413 return -ENOMEM;
1414
1415 epfile = epfiles;
1416 for (i = 1; i <= count; ++i, ++epfile) {
1417 epfile->ffs = ffs;
1418 mutex_init(&epfile->mutex);
1419 init_waitqueue_head(&epfile->wait);
1420 sprintf(epfiles->name, "ep%u", i);
1421 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1422 &ffs_epfile_operations,
1423 &epfile->dentry))) {
1424 ffs_epfiles_destroy(epfiles, i - 1);
1425 return -ENOMEM;
1426 }
1427 }
1428
1429 ffs->epfiles = epfiles;
1430 return 0;
1431}
1432
ddf8abd2
MN
1433static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1434{
1435 struct ffs_epfile *epfile = epfiles;
1436
1437 ENTER();
1438
1439 for (; count; --count, ++epfile) {
1440 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1441 waitqueue_active(&epfile->wait));
1442 if (epfile->dentry) {
1443 d_delete(epfile->dentry);
1444 dput(epfile->dentry);
1445 epfile->dentry = NULL;
1446 }
1447 }
1448
1449 kfree(epfiles);
1450}
1451
7898aee1
MN
1452static int functionfs_bind_config(struct usb_composite_dev *cdev,
1453 struct usb_configuration *c,
1454 struct ffs_data *ffs)
ddf8abd2
MN
1455{
1456 struct ffs_function *func;
1457 int ret;
1458
1459 ENTER();
1460
1461 func = kzalloc(sizeof *func, GFP_KERNEL);
1462 if (unlikely(!func))
1463 return -ENOMEM;
1464
1465 func->function.name = "Function FS Gadget";
1466 func->function.strings = ffs->stringtabs;
1467
1468 func->function.bind = ffs_func_bind;
1469 func->function.unbind = ffs_func_unbind;
1470 func->function.set_alt = ffs_func_set_alt;
ddf8abd2
MN
1471 func->function.disable = ffs_func_disable;
1472 func->function.setup = ffs_func_setup;
1473 func->function.suspend = ffs_func_suspend;
1474 func->function.resume = ffs_func_resume;
1475
1476 func->conf = c;
1477 func->gadget = cdev->gadget;
1478 func->ffs = ffs;
1479 ffs_data_get(ffs);
1480
1481 ret = usb_add_function(c, &func->function);
1482 if (unlikely(ret))
1483 ffs_func_free(func);
1484
1485 return ret;
1486}
1487
1488static void ffs_func_free(struct ffs_function *func)
1489{
4f06539f
PK
1490 struct ffs_ep *ep = func->eps;
1491 unsigned count = func->ffs->eps_count;
1492 unsigned long flags;
1493
ddf8abd2
MN
1494 ENTER();
1495
4f06539f
PK
1496 /* cleanup after autoconfig */
1497 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1498 do {
1499 if (ep->ep && ep->req)
1500 usb_ep_free_request(ep->ep, ep->req);
1501 ep->req = NULL;
1502 ++ep;
1503 } while (--count);
1504 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1505
ddf8abd2
MN
1506 ffs_data_put(func->ffs);
1507
1508 kfree(func->eps);
5ab54cf7
MN
1509 /*
1510 * eps and interfaces_nums are allocated in the same chunk so
ddf8abd2 1511 * only one free is required. Descriptors are also allocated
5ab54cf7
MN
1512 * in the same chunk.
1513 */
ddf8abd2
MN
1514
1515 kfree(func);
1516}
1517
ddf8abd2
MN
1518static void ffs_func_eps_disable(struct ffs_function *func)
1519{
1520 struct ffs_ep *ep = func->eps;
1521 struct ffs_epfile *epfile = func->ffs->epfiles;
1522 unsigned count = func->ffs->eps_count;
1523 unsigned long flags;
1524
1525 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1526 do {
1527 /* pending requests get nuked */
1528 if (likely(ep->ep))
1529 usb_ep_disable(ep->ep);
1530 epfile->ep = NULL;
1531
1532 ++ep;
1533 ++epfile;
1534 } while (--count);
1535 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1536}
1537
1538static int ffs_func_eps_enable(struct ffs_function *func)
1539{
1540 struct ffs_data *ffs = func->ffs;
1541 struct ffs_ep *ep = func->eps;
1542 struct ffs_epfile *epfile = ffs->epfiles;
1543 unsigned count = ffs->eps_count;
1544 unsigned long flags;
1545 int ret = 0;
1546
1547 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1548 do {
1549 struct usb_endpoint_descriptor *ds;
1550 ds = ep->descs[ep->descs[1] ? 1 : 0];
1551
1552 ep->ep->driver_data = ep;
72c973dd
TB
1553 ep->ep->desc = ds;
1554 ret = usb_ep_enable(ep->ep);
ddf8abd2
MN
1555 if (likely(!ret)) {
1556 epfile->ep = ep;
1557 epfile->in = usb_endpoint_dir_in(ds);
1558 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1559 } else {
1560 break;
1561 }
1562
1563 wake_up(&epfile->wait);
1564
1565 ++ep;
1566 ++epfile;
1567 } while (--count);
1568 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1569
1570 return ret;
1571}
1572
1573
1574/* Parsing and building descriptors and strings *****************************/
1575
5ab54cf7
MN
1576/*
1577 * This validates if data pointed by data is a valid USB descriptor as
ddf8abd2 1578 * well as record how many interfaces, endpoints and strings are
5ab54cf7
MN
1579 * required by given configuration. Returns address after the
1580 * descriptor or NULL if data is invalid.
1581 */
ddf8abd2
MN
1582
1583enum ffs_entity_type {
1584 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1585};
1586
1587typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1588 u8 *valuep,
1589 struct usb_descriptor_header *desc,
1590 void *priv);
1591
1592static int __must_check ffs_do_desc(char *data, unsigned len,
1593 ffs_entity_callback entity, void *priv)
1594{
1595 struct usb_descriptor_header *_ds = (void *)data;
1596 u8 length;
1597 int ret;
1598
1599 ENTER();
1600
1601 /* At least two bytes are required: length and type */
1602 if (len < 2) {
aa02f172 1603 pr_vdebug("descriptor too short\n");
ddf8abd2
MN
1604 return -EINVAL;
1605 }
1606
1607 /* If we have at least as many bytes as the descriptor takes? */
1608 length = _ds->bLength;
1609 if (len < length) {
aa02f172 1610 pr_vdebug("descriptor longer then available data\n");
ddf8abd2
MN
1611 return -EINVAL;
1612 }
1613
1614#define __entity_check_INTERFACE(val) 1
1615#define __entity_check_STRING(val) (val)
1616#define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1617#define __entity(type, val) do { \
aa02f172 1618 pr_vdebug("entity " #type "(%02x)\n", (val)); \
ddf8abd2 1619 if (unlikely(!__entity_check_ ##type(val))) { \
aa02f172 1620 pr_vdebug("invalid entity's value\n"); \
ddf8abd2
MN
1621 return -EINVAL; \
1622 } \
1623 ret = entity(FFS_ ##type, &val, _ds, priv); \
1624 if (unlikely(ret < 0)) { \
aa02f172 1625 pr_debug("entity " #type "(%02x); ret = %d\n", \
d8df0b61 1626 (val), ret); \
ddf8abd2
MN
1627 return ret; \
1628 } \
1629 } while (0)
1630
1631 /* Parse descriptor depending on type. */
1632 switch (_ds->bDescriptorType) {
1633 case USB_DT_DEVICE:
1634 case USB_DT_CONFIG:
1635 case USB_DT_STRING:
1636 case USB_DT_DEVICE_QUALIFIER:
1637 /* function can't have any of those */
aa02f172 1638 pr_vdebug("descriptor reserved for gadget: %d\n",
5ab54cf7 1639 _ds->bDescriptorType);
ddf8abd2
MN
1640 return -EINVAL;
1641
1642 case USB_DT_INTERFACE: {
1643 struct usb_interface_descriptor *ds = (void *)_ds;
aa02f172 1644 pr_vdebug("interface descriptor\n");
ddf8abd2
MN
1645 if (length != sizeof *ds)
1646 goto inv_length;
1647
1648 __entity(INTERFACE, ds->bInterfaceNumber);
1649 if (ds->iInterface)
1650 __entity(STRING, ds->iInterface);
1651 }
1652 break;
1653
1654 case USB_DT_ENDPOINT: {
1655 struct usb_endpoint_descriptor *ds = (void *)_ds;
aa02f172 1656 pr_vdebug("endpoint descriptor\n");
ddf8abd2
MN
1657 if (length != USB_DT_ENDPOINT_SIZE &&
1658 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1659 goto inv_length;
1660 __entity(ENDPOINT, ds->bEndpointAddress);
1661 }
1662 break;
1663
560f1187
KB
1664 case HID_DT_HID:
1665 pr_vdebug("hid descriptor\n");
1666 if (length != sizeof(struct hid_descriptor))
1667 goto inv_length;
1668 break;
1669
ddf8abd2
MN
1670 case USB_DT_OTG:
1671 if (length != sizeof(struct usb_otg_descriptor))
1672 goto inv_length;
1673 break;
1674
1675 case USB_DT_INTERFACE_ASSOCIATION: {
1676 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
aa02f172 1677 pr_vdebug("interface association descriptor\n");
ddf8abd2
MN
1678 if (length != sizeof *ds)
1679 goto inv_length;
1680 if (ds->iFunction)
1681 __entity(STRING, ds->iFunction);
1682 }
1683 break;
1684
1685 case USB_DT_OTHER_SPEED_CONFIG:
1686 case USB_DT_INTERFACE_POWER:
1687 case USB_DT_DEBUG:
1688 case USB_DT_SECURITY:
1689 case USB_DT_CS_RADIO_CONTROL:
1690 /* TODO */
aa02f172 1691 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
ddf8abd2
MN
1692 return -EINVAL;
1693
1694 default:
1695 /* We should never be here */
aa02f172 1696 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
ddf8abd2
MN
1697 return -EINVAL;
1698
5ab54cf7 1699inv_length:
aa02f172 1700 pr_vdebug("invalid length: %d (descriptor %d)\n",
d8df0b61 1701 _ds->bLength, _ds->bDescriptorType);
ddf8abd2
MN
1702 return -EINVAL;
1703 }
1704
1705#undef __entity
1706#undef __entity_check_DESCRIPTOR
1707#undef __entity_check_INTERFACE
1708#undef __entity_check_STRING
1709#undef __entity_check_ENDPOINT
1710
1711 return length;
1712}
1713
ddf8abd2
MN
1714static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1715 ffs_entity_callback entity, void *priv)
1716{
1717 const unsigned _len = len;
1718 unsigned long num = 0;
1719
1720 ENTER();
1721
1722 for (;;) {
1723 int ret;
1724
1725 if (num == count)
1726 data = NULL;
1727
5ab54cf7 1728 /* Record "descriptor" entity */
ddf8abd2
MN
1729 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1730 if (unlikely(ret < 0)) {
aa02f172 1731 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
d8df0b61 1732 num, ret);
ddf8abd2
MN
1733 return ret;
1734 }
1735
1736 if (!data)
1737 return _len - len;
1738
1739 ret = ffs_do_desc(data, len, entity, priv);
1740 if (unlikely(ret < 0)) {
aa02f172 1741 pr_debug("%s returns %d\n", __func__, ret);
ddf8abd2
MN
1742 return ret;
1743 }
1744
1745 len -= ret;
1746 data += ret;
1747 ++num;
1748 }
1749}
1750
ddf8abd2
MN
1751static int __ffs_data_do_entity(enum ffs_entity_type type,
1752 u8 *valuep, struct usb_descriptor_header *desc,
1753 void *priv)
1754{
1755 struct ffs_data *ffs = priv;
1756
1757 ENTER();
1758
1759 switch (type) {
1760 case FFS_DESCRIPTOR:
1761 break;
1762
1763 case FFS_INTERFACE:
5ab54cf7
MN
1764 /*
1765 * Interfaces are indexed from zero so if we
ddf8abd2 1766 * encountered interface "n" then there are at least
5ab54cf7
MN
1767 * "n+1" interfaces.
1768 */
ddf8abd2
MN
1769 if (*valuep >= ffs->interfaces_count)
1770 ffs->interfaces_count = *valuep + 1;
1771 break;
1772
1773 case FFS_STRING:
5ab54cf7
MN
1774 /*
1775 * Strings are indexed from 1 (0 is magic ;) reserved
1776 * for languages list or some such)
1777 */
ddf8abd2
MN
1778 if (*valuep > ffs->strings_count)
1779 ffs->strings_count = *valuep;
1780 break;
1781
1782 case FFS_ENDPOINT:
1783 /* Endpoints are indexed from 1 as well. */
1784 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1785 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1786 break;
1787 }
1788
1789 return 0;
1790}
1791
ddf8abd2
MN
1792static int __ffs_data_got_descs(struct ffs_data *ffs,
1793 char *const _data, size_t len)
1794{
1795 unsigned fs_count, hs_count;
1796 int fs_len, ret = -EINVAL;
1797 char *data = _data;
1798
1799 ENTER();
1800
1801 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
1802 get_unaligned_le32(data + 4) != len))
1803 goto error;
1804 fs_count = get_unaligned_le32(data + 8);
1805 hs_count = get_unaligned_le32(data + 12);
1806
1807 if (!fs_count && !hs_count)
1808 goto einval;
1809
1810 data += 16;
1811 len -= 16;
1812
1813 if (likely(fs_count)) {
1814 fs_len = ffs_do_descs(fs_count, data, len,
1815 __ffs_data_do_entity, ffs);
1816 if (unlikely(fs_len < 0)) {
1817 ret = fs_len;
1818 goto error;
1819 }
1820
1821 data += fs_len;
1822 len -= fs_len;
1823 } else {
1824 fs_len = 0;
1825 }
1826
1827 if (likely(hs_count)) {
1828 ret = ffs_do_descs(hs_count, data, len,
1829 __ffs_data_do_entity, ffs);
1830 if (unlikely(ret < 0))
1831 goto error;
1832 } else {
1833 ret = 0;
1834 }
1835
1836 if (unlikely(len != ret))
1837 goto einval;
1838
1839 ffs->raw_fs_descs_length = fs_len;
1840 ffs->raw_descs_length = fs_len + ret;
1841 ffs->raw_descs = _data;
1842 ffs->fs_descs_count = fs_count;
1843 ffs->hs_descs_count = hs_count;
1844
1845 return 0;
1846
1847einval:
1848 ret = -EINVAL;
1849error:
1850 kfree(_data);
1851 return ret;
1852}
1853
ddf8abd2
MN
1854static int __ffs_data_got_strings(struct ffs_data *ffs,
1855 char *const _data, size_t len)
1856{
1857 u32 str_count, needed_count, lang_count;
1858 struct usb_gadget_strings **stringtabs, *t;
1859 struct usb_string *strings, *s;
1860 const char *data = _data;
1861
1862 ENTER();
1863
1864 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1865 get_unaligned_le32(data + 4) != len))
1866 goto error;
1867 str_count = get_unaligned_le32(data + 8);
1868 lang_count = get_unaligned_le32(data + 12);
1869
1870 /* if one is zero the other must be zero */
1871 if (unlikely(!str_count != !lang_count))
1872 goto error;
1873
1874 /* Do we have at least as many strings as descriptors need? */
1875 needed_count = ffs->strings_count;
1876 if (unlikely(str_count < needed_count))
1877 goto error;
1878
5ab54cf7
MN
1879 /*
1880 * If we don't need any strings just return and free all
1881 * memory.
1882 */
ddf8abd2
MN
1883 if (!needed_count) {
1884 kfree(_data);
1885 return 0;
1886 }
1887
5ab54cf7 1888 /* Allocate everything in one chunk so there's less maintenance. */
ddf8abd2 1889 {
ddf8abd2
MN
1890 struct {
1891 struct usb_gadget_strings *stringtabs[lang_count + 1];
1892 struct usb_gadget_strings stringtab[lang_count];
1893 struct usb_string strings[lang_count*(needed_count+1)];
1894 } *d;
1895 unsigned i = 0;
1896
1897 d = kmalloc(sizeof *d, GFP_KERNEL);
1898 if (unlikely(!d)) {
1899 kfree(_data);
1900 return -ENOMEM;
1901 }
1902
1903 stringtabs = d->stringtabs;
1904 t = d->stringtab;
1905 i = lang_count;
1906 do {
1907 *stringtabs++ = t++;
1908 } while (--i);
1909 *stringtabs = NULL;
1910
1911 stringtabs = d->stringtabs;
1912 t = d->stringtab;
1913 s = d->strings;
1914 strings = s;
1915 }
1916
1917 /* For each language */
1918 data += 16;
1919 len -= 16;
1920
1921 do { /* lang_count > 0 so we can use do-while */
1922 unsigned needed = needed_count;
1923
1924 if (unlikely(len < 3))
1925 goto error_free;
1926 t->language = get_unaligned_le16(data);
1927 t->strings = s;
1928 ++t;
1929
1930 data += 2;
1931 len -= 2;
1932
1933 /* For each string */
1934 do { /* str_count > 0 so we can use do-while */
1935 size_t length = strnlen(data, len);
1936
1937 if (unlikely(length == len))
1938 goto error_free;
1939
5ab54cf7
MN
1940 /*
1941 * User may provide more strings then we need,
1942 * if that's the case we simply ignore the
1943 * rest
1944 */
ddf8abd2 1945 if (likely(needed)) {
5ab54cf7
MN
1946 /*
1947 * s->id will be set while adding
ddf8abd2 1948 * function to configuration so for
5ab54cf7
MN
1949 * now just leave garbage here.
1950 */
ddf8abd2
MN
1951 s->s = data;
1952 --needed;
1953 ++s;
1954 }
1955
1956 data += length + 1;
1957 len -= length + 1;
1958 } while (--str_count);
1959
1960 s->id = 0; /* terminator */
1961 s->s = NULL;
1962 ++s;
1963
1964 } while (--lang_count);
1965
1966 /* Some garbage left? */
1967 if (unlikely(len))
1968 goto error_free;
1969
1970 /* Done! */
1971 ffs->stringtabs = stringtabs;
1972 ffs->raw_strings = _data;
1973
1974 return 0;
1975
1976error_free:
1977 kfree(stringtabs);
1978error:
1979 kfree(_data);
1980 return -EINVAL;
1981}
1982
1983
ddf8abd2
MN
1984/* Events handling and management *******************************************/
1985
1986static void __ffs_event_add(struct ffs_data *ffs,
1987 enum usb_functionfs_event_type type)
1988{
1989 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
1990 int neg = 0;
1991
5ab54cf7
MN
1992 /*
1993 * Abort any unhandled setup
1994 *
1995 * We do not need to worry about some cmpxchg() changing value
ddf8abd2
MN
1996 * of ffs->setup_state without holding the lock because when
1997 * state is FFS_SETUP_PENDING cmpxchg() in several places in
5ab54cf7
MN
1998 * the source does nothing.
1999 */
ddf8abd2
MN
2000 if (ffs->setup_state == FFS_SETUP_PENDING)
2001 ffs->setup_state = FFS_SETUP_CANCELED;
2002
2003 switch (type) {
2004 case FUNCTIONFS_RESUME:
2005 rem_type2 = FUNCTIONFS_SUSPEND;
5ab54cf7 2006 /* FALL THROUGH */
ddf8abd2
MN
2007 case FUNCTIONFS_SUSPEND:
2008 case FUNCTIONFS_SETUP:
2009 rem_type1 = type;
5ab54cf7 2010 /* Discard all similar events */
ddf8abd2
MN
2011 break;
2012
2013 case FUNCTIONFS_BIND:
2014 case FUNCTIONFS_UNBIND:
2015 case FUNCTIONFS_DISABLE:
2016 case FUNCTIONFS_ENABLE:
5ab54cf7 2017 /* Discard everything other then power management. */
ddf8abd2
MN
2018 rem_type1 = FUNCTIONFS_SUSPEND;
2019 rem_type2 = FUNCTIONFS_RESUME;
2020 neg = 1;
2021 break;
2022
2023 default:
2024 BUG();
2025 }
2026
2027 {
2028 u8 *ev = ffs->ev.types, *out = ev;
2029 unsigned n = ffs->ev.count;
2030 for (; n; --n, ++ev)
2031 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2032 *out++ = *ev;
2033 else
aa02f172 2034 pr_vdebug("purging event %d\n", *ev);
ddf8abd2
MN
2035 ffs->ev.count = out - ffs->ev.types;
2036 }
2037
aa02f172 2038 pr_vdebug("adding event %d\n", type);
ddf8abd2
MN
2039 ffs->ev.types[ffs->ev.count++] = type;
2040 wake_up_locked(&ffs->ev.waitq);
2041}
2042
2043static void ffs_event_add(struct ffs_data *ffs,
2044 enum usb_functionfs_event_type type)
2045{
2046 unsigned long flags;
2047 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2048 __ffs_event_add(ffs, type);
2049 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2050}
2051
2052
2053/* Bind/unbind USB function hooks *******************************************/
2054
2055static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2056 struct usb_descriptor_header *desc,
2057 void *priv)
2058{
2059 struct usb_endpoint_descriptor *ds = (void *)desc;
2060 struct ffs_function *func = priv;
2061 struct ffs_ep *ffs_ep;
2062
5ab54cf7
MN
2063 /*
2064 * If hs_descriptors is not NULL then we are reading hs
2065 * descriptors now
2066 */
ddf8abd2
MN
2067 const int isHS = func->function.hs_descriptors != NULL;
2068 unsigned idx;
2069
2070 if (type != FFS_DESCRIPTOR)
2071 return 0;
2072
2073 if (isHS)
2074 func->function.hs_descriptors[(long)valuep] = desc;
2075 else
10287bae 2076 func->function.fs_descriptors[(long)valuep] = desc;
ddf8abd2
MN
2077
2078 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2079 return 0;
2080
2081 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2082 ffs_ep = func->eps + idx;
2083
2084 if (unlikely(ffs_ep->descs[isHS])) {
aa02f172 2085 pr_vdebug("two %sspeed descriptors for EP %d\n",
d8df0b61
MN
2086 isHS ? "high" : "full",
2087 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
ddf8abd2
MN
2088 return -EINVAL;
2089 }
2090 ffs_ep->descs[isHS] = ds;
2091
2092 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2093 if (ffs_ep->ep) {
2094 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2095 if (!ds->wMaxPacketSize)
2096 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2097 } else {
2098 struct usb_request *req;
2099 struct usb_ep *ep;
2100
aa02f172 2101 pr_vdebug("autoconfig\n");
ddf8abd2
MN
2102 ep = usb_ep_autoconfig(func->gadget, ds);
2103 if (unlikely(!ep))
2104 return -ENOTSUPP;
cc7e6056 2105 ep->driver_data = func->eps + idx;
ddf8abd2
MN
2106
2107 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2108 if (unlikely(!req))
2109 return -ENOMEM;
2110
2111 ffs_ep->ep = ep;
2112 ffs_ep->req = req;
2113 func->eps_revmap[ds->bEndpointAddress &
2114 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2115 }
2116 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2117
2118 return 0;
2119}
2120
ddf8abd2
MN
2121static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2122 struct usb_descriptor_header *desc,
2123 void *priv)
2124{
2125 struct ffs_function *func = priv;
2126 unsigned idx;
2127 u8 newValue;
2128
2129 switch (type) {
2130 default:
2131 case FFS_DESCRIPTOR:
2132 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2133 return 0;
2134
2135 case FFS_INTERFACE:
2136 idx = *valuep;
2137 if (func->interfaces_nums[idx] < 0) {
2138 int id = usb_interface_id(func->conf, &func->function);
2139 if (unlikely(id < 0))
2140 return id;
2141 func->interfaces_nums[idx] = id;
2142 }
2143 newValue = func->interfaces_nums[idx];
2144 break;
2145
2146 case FFS_STRING:
2147 /* String' IDs are allocated when fsf_data is bound to cdev */
2148 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2149 break;
2150
2151 case FFS_ENDPOINT:
5ab54cf7
MN
2152 /*
2153 * USB_DT_ENDPOINT are handled in
2154 * __ffs_func_bind_do_descs().
2155 */
ddf8abd2
MN
2156 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2157 return 0;
2158
2159 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2160 if (unlikely(!func->eps[idx].ep))
2161 return -EINVAL;
2162
2163 {
2164 struct usb_endpoint_descriptor **descs;
2165 descs = func->eps[idx].descs;
2166 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2167 }
2168 break;
2169 }
2170
aa02f172 2171 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
ddf8abd2
MN
2172 *valuep = newValue;
2173 return 0;
2174}
2175
2176static int ffs_func_bind(struct usb_configuration *c,
2177 struct usb_function *f)
2178{
2179 struct ffs_function *func = ffs_func_from_usb(f);
2180 struct ffs_data *ffs = func->ffs;
2181
2182 const int full = !!func->ffs->fs_descs_count;
2183 const int high = gadget_is_dualspeed(func->gadget) &&
2184 func->ffs->hs_descs_count;
2185
2186 int ret;
2187
2188 /* Make it a single chunk, less management later on */
2189 struct {
2190 struct ffs_ep eps[ffs->eps_count];
2191 struct usb_descriptor_header
2192 *fs_descs[full ? ffs->fs_descs_count + 1 : 0];
2193 struct usb_descriptor_header
2194 *hs_descs[high ? ffs->hs_descs_count + 1 : 0];
2195 short inums[ffs->interfaces_count];
2196 char raw_descs[high ? ffs->raw_descs_length
2197 : ffs->raw_fs_descs_length];
2198 } *data;
2199
2200 ENTER();
2201
2202 /* Only high speed but not supported by gadget? */
2203 if (unlikely(!(full | high)))
2204 return -ENOTSUPP;
2205
2206 /* Allocate */
2207 data = kmalloc(sizeof *data, GFP_KERNEL);
2208 if (unlikely(!data))
2209 return -ENOMEM;
2210
2211 /* Zero */
2212 memset(data->eps, 0, sizeof data->eps);
2213 memcpy(data->raw_descs, ffs->raw_descs + 16, sizeof data->raw_descs);
2214 memset(data->inums, 0xff, sizeof data->inums);
2215 for (ret = ffs->eps_count; ret; --ret)
2216 data->eps[ret].num = -1;
2217
2218 /* Save pointers */
2219 func->eps = data->eps;
2220 func->interfaces_nums = data->inums;
2221
5ab54cf7
MN
2222 /*
2223 * Go through all the endpoint descriptors and allocate
ddf8abd2 2224 * endpoints first, so that later we can rewrite the endpoint
5ab54cf7
MN
2225 * numbers without worrying that it may be described later on.
2226 */
ddf8abd2 2227 if (likely(full)) {
10287bae 2228 func->function.fs_descriptors = data->fs_descs;
ddf8abd2
MN
2229 ret = ffs_do_descs(ffs->fs_descs_count,
2230 data->raw_descs,
2231 sizeof data->raw_descs,
2232 __ffs_func_bind_do_descs, func);
2233 if (unlikely(ret < 0))
2234 goto error;
2235 } else {
2236 ret = 0;
2237 }
2238
2239 if (likely(high)) {
2240 func->function.hs_descriptors = data->hs_descs;
2241 ret = ffs_do_descs(ffs->hs_descs_count,
2242 data->raw_descs + ret,
2243 (sizeof data->raw_descs) - ret,
2244 __ffs_func_bind_do_descs, func);
8854894c
RB
2245 if (unlikely(ret < 0))
2246 goto error;
ddf8abd2
MN
2247 }
2248
5ab54cf7
MN
2249 /*
2250 * Now handle interface numbers allocation and interface and
2251 * endpoint numbers rewriting. We can do that in one go
2252 * now.
2253 */
ddf8abd2
MN
2254 ret = ffs_do_descs(ffs->fs_descs_count +
2255 (high ? ffs->hs_descs_count : 0),
2256 data->raw_descs, sizeof data->raw_descs,
2257 __ffs_func_bind_do_nums, func);
2258 if (unlikely(ret < 0))
2259 goto error;
2260
2261 /* And we're done */
2262 ffs_event_add(ffs, FUNCTIONFS_BIND);
2263 return 0;
2264
2265error:
2266 /* XXX Do we need to release all claimed endpoints here? */
2267 return ret;
2268}
2269
2270
2271/* Other USB function hooks *************************************************/
2272
2273static void ffs_func_unbind(struct usb_configuration *c,
2274 struct usb_function *f)
2275{
2276 struct ffs_function *func = ffs_func_from_usb(f);
2277 struct ffs_data *ffs = func->ffs;
2278
2279 ENTER();
2280
2281 if (ffs->func == func) {
2282 ffs_func_eps_disable(func);
2283 ffs->func = NULL;
2284 }
2285
2286 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2287
2288 ffs_func_free(func);
2289}
2290
ddf8abd2
MN
2291static int ffs_func_set_alt(struct usb_function *f,
2292 unsigned interface, unsigned alt)
2293{
2294 struct ffs_function *func = ffs_func_from_usb(f);
2295 struct ffs_data *ffs = func->ffs;
2296 int ret = 0, intf;
2297
2298 if (alt != (unsigned)-1) {
2299 intf = ffs_func_revmap_intf(func, interface);
2300 if (unlikely(intf < 0))
2301 return intf;
2302 }
2303
2304 if (ffs->func)
2305 ffs_func_eps_disable(ffs->func);
2306
2307 if (ffs->state != FFS_ACTIVE)
2308 return -ENODEV;
2309
2310 if (alt == (unsigned)-1) {
2311 ffs->func = NULL;
2312 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2313 return 0;
2314 }
2315
2316 ffs->func = func;
2317 ret = ffs_func_eps_enable(func);
2318 if (likely(ret >= 0))
2319 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2320 return ret;
2321}
2322
2323static void ffs_func_disable(struct usb_function *f)
2324{
2325 ffs_func_set_alt(f, 0, (unsigned)-1);
2326}
2327
2328static int ffs_func_setup(struct usb_function *f,
2329 const struct usb_ctrlrequest *creq)
2330{
2331 struct ffs_function *func = ffs_func_from_usb(f);
2332 struct ffs_data *ffs = func->ffs;
2333 unsigned long flags;
2334 int ret;
2335
2336 ENTER();
2337
aa02f172
MN
2338 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2339 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2340 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2341 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2342 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
ddf8abd2 2343
5ab54cf7
MN
2344 /*
2345 * Most requests directed to interface go through here
ddf8abd2
MN
2346 * (notable exceptions are set/get interface) so we need to
2347 * handle them. All other either handled by composite or
2348 * passed to usb_configuration->setup() (if one is set). No
2349 * matter, we will handle requests directed to endpoint here
2350 * as well (as it's straightforward) but what to do with any
5ab54cf7
MN
2351 * other request?
2352 */
ddf8abd2
MN
2353 if (ffs->state != FFS_ACTIVE)
2354 return -ENODEV;
2355
2356 switch (creq->bRequestType & USB_RECIP_MASK) {
2357 case USB_RECIP_INTERFACE:
2358 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2359 if (unlikely(ret < 0))
2360 return ret;
2361 break;
2362
2363 case USB_RECIP_ENDPOINT:
2364 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2365 if (unlikely(ret < 0))
2366 return ret;
2367 break;
2368
2369 default:
2370 return -EOPNOTSUPP;
2371 }
2372
2373 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2374 ffs->ev.setup = *creq;
2375 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2376 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2377 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2378
2379 return 0;
2380}
2381
2382static void ffs_func_suspend(struct usb_function *f)
2383{
2384 ENTER();
2385 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2386}
2387
2388static void ffs_func_resume(struct usb_function *f)
2389{
2390 ENTER();
2391 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2392}
2393
2394
5ab54cf7 2395/* Endpoint and interface numbers reverse mapping ***************************/
ddf8abd2
MN
2396
2397static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2398{
2399 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2400 return num ? num : -EDOM;
2401}
2402
2403static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2404{
2405 short *nums = func->interfaces_nums;
2406 unsigned count = func->ffs->interfaces_count;
2407
2408 for (; count; --count, ++nums) {
2409 if (*nums >= 0 && *nums == intf)
2410 return nums - func->interfaces_nums;
2411 }
2412
2413 return -EDOM;
2414}
2415
2416
2417/* Misc helper functions ****************************************************/
2418
2419static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2420{
2421 return nonblock
2422 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2423 : mutex_lock_interruptible(mutex);
2424}
2425
260ef311 2426static char *ffs_prepare_buffer(const char __user *buf, size_t len)
ddf8abd2
MN
2427{
2428 char *data;
2429
2430 if (unlikely(!len))
2431 return NULL;
2432
2433 data = kmalloc(len, GFP_KERNEL);
2434 if (unlikely(!data))
2435 return ERR_PTR(-ENOMEM);
2436
2437 if (unlikely(__copy_from_user(data, buf, len))) {
2438 kfree(data);
2439 return ERR_PTR(-EFAULT);
2440 }
2441
aa02f172 2442 pr_vdebug("Buffer from user space:\n");
ddf8abd2
MN
2443 ffs_dump_mem("", data, len);
2444
2445 return data;
2446}