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