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