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