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