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