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