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