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