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