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