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