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