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