• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /asuswrt-rt-n18u-9.0.0.4.380.2695/release/src-rt-6.x.4708/linux/linux-2.6.36/drivers/usb/gadget/
1/*
2 * f_fs.c -- user mode filesystem api for usb composite funtcion controllers
3 *
4 * Copyright (C) 2010 Samsung Electronics
5 * Author: Michal Nazarewicz <m.nazarewicz@samsung.com>
6 *
7 * Based on inode.c (GadgetFS):
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 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
24 */
25
26
27/* #define DEBUG */
28/* #define VERBOSE_DEBUG */
29
30#include <linux/blkdev.h>
31#include <linux/pagemap.h>
32#include <asm/unaligned.h>
33#include <linux/smp_lock.h>
34
35#include <linux/usb/composite.h>
36#include <linux/usb/functionfs.h>
37
38
39#define FUNCTIONFS_MAGIC	0xa647361 /* Chosen by a honest dice roll ;) */
40
41
42/* Debuging *****************************************************************/
43
44#define ffs_printk(level, fmt, args...) printk(level "f_fs: " fmt "\n", ## args)
45
46#define FERR(...)  ffs_printk(KERN_ERR,  __VA_ARGS__)
47#define FINFO(...) ffs_printk(KERN_INFO, __VA_ARGS__)
48
49#ifdef DEBUG
50#  define FDBG(...) ffs_printk(KERN_DEBUG, __VA_ARGS__)
51#else
52#  define FDBG(...) do { } while (0)
53#endif /* DEBUG */
54
55#ifdef VERBOSE_DEBUG
56#  define FVDBG FDBG
57#else
58#  define FVDBG(...) do { } while (0)
59#endif /* VERBOSE_DEBUG */
60
61#define ENTER()    FVDBG("%s()", __func__)
62
63#ifdef VERBOSE_DEBUG
64#  define ffs_dump_mem(prefix, ptr, len) \
65	print_hex_dump_bytes("f_fs" prefix ": ", DUMP_PREFIX_NONE, ptr, len)
66#else
67#  define ffs_dump_mem(prefix, ptr, len) do { } while (0)
68#endif
69
70
71/* The data structure and setup file ****************************************/
72
73enum ffs_state {
74	/* Waiting for descriptors and strings. */
75	/* In this state no open(2), read(2) or write(2) on epfiles
76	 * may succeed (which should not be the problem as there
77	 * should be no such files opened in the firts place). */
78	FFS_READ_DESCRIPTORS,
79	FFS_READ_STRINGS,
80
81	/* We've got descriptors and strings.  We are or have called
82	 * functionfs_ready_callback().  functionfs_bind() may have
83	 * been called but we don't know. */
84	/* This is the only state in which operations on epfiles may
85	 * succeed. */
86	FFS_ACTIVE,
87
88	/* All endpoints have been closed.  This state is also set if
89	 * we encounter an unrecoverable error.  The only
90	 * unrecoverable error is situation when after reading strings
91	 * from user space we fail to initialise EP files or
92	 * functionfs_ready_callback() returns with error (<0). */
93	/* In this state no open(2), read(2) or write(2) (both on ep0
94	 * as well as epfile) may succeed (at this point epfiles are
95	 * unlinked and all closed so this is not a problem; ep0 is
96	 * also closed but ep0 file exists and so open(2) on ep0 must
97	 * fail). */
98	FFS_CLOSING
99};
100
101
102enum ffs_setup_state {
103	/* There is no setup request pending. */
104	FFS_NO_SETUP,
105	/* User has read events and there was a setup request event
106	 * there.  The next read/write on ep0 will handle the
107	 * request. */
108	FFS_SETUP_PENDING,
109	/* There was event pending but before user space handled it
110	 * some other event was introduced which canceled existing
111	 * setup.  If this state is set read/write on ep0 return
112	 * -EIDRM.  This state is only set when adding event. */
113	FFS_SETUP_CANCELED
114};
115
116
117
118struct ffs_epfile;
119struct ffs_function;
120
121struct ffs_data {
122	struct usb_gadget		*gadget;
123
124	/* Protect access read/write operations, only one read/write
125	 * at a time.  As a consequence protects ep0req and company.
126	 * While setup request is being processed (queued) this is
127	 * held. */
128	struct mutex			mutex;
129
130	/* Protect access to enpoint related structures (basically
131	 * usb_ep_queue(), usb_ep_dequeue(), etc. calls) except for
132	 * endpint zero. */
133	spinlock_t			eps_lock;
134
135	struct usb_request		*ep0req;		/* P: mutex */
136	struct completion		ep0req_completion;	/* P: mutex */
137	int				ep0req_status;		/* P: mutex */
138
139	/* reference counter */
140	atomic_t			ref;
141	/* how many files are opened (EP0 and others) */
142	atomic_t			opened;
143
144	/* EP0 state */
145	enum ffs_state			state;
146
147	/*
148	 * Possible transations:
149	 * + FFS_NO_SETUP       -> FFS_SETUP_PENDING  -- P: ev.waitq.lock
150	 *               happens only in ep0 read which is P: mutex
151	 * + FFS_SETUP_PENDING  -> FFS_NO_SETUP       -- P: ev.waitq.lock
152	 *               happens only in ep0 i/o  which is P: mutex
153	 * + FFS_SETUP_PENDING  -> FFS_SETUP_CANCELED -- P: ev.waitq.lock
154	 * + FFS_SETUP_CANCELED -> FFS_NO_SETUP       -- cmpxchg
155	 */
156	enum ffs_setup_state		setup_state;
157
158#define FFS_SETUP_STATE(ffs)					\
159	((enum ffs_setup_state)cmpxchg(&(ffs)->setup_state,	\
160				       FFS_SETUP_CANCELED, FFS_NO_SETUP))
161
162	/* Events & such. */
163	struct {
164		u8				types[4];
165		unsigned short			count;
166		unsigned short			can_stall;
167		struct usb_ctrlrequest		setup;
168
169		wait_queue_head_t		waitq;
170	} ev; /* the whole structure, P: ev.waitq.lock */
171
172	/* Flags */
173	unsigned long			flags;
174#define FFS_FL_CALL_CLOSED_CALLBACK 0
175#define FFS_FL_BOUND                1
176
177	/* Active function */
178	struct ffs_function		*func;
179
180	/* Device name, write once when file system is mounted.
181	 * Intendet for user to read if she wants. */
182	const char			*dev_name;
183	/* Private data for our user (ie. gadget).  Managed by
184	 * user. */
185	void				*private_data;
186
187	/* filled by __ffs_data_got_descs() */
188	/* real descriptors are 16 bytes after raw_descs (so you need
189	 * to skip 16 bytes (ie. ffs->raw_descs + 16) to get to the
190	 * first full speed descriptor).  raw_descs_length and
191	 * raw_fs_descs_length do not have those 16 bytes added. */
192	const void			*raw_descs;
193	unsigned			raw_descs_length;
194	unsigned			raw_fs_descs_length;
195	unsigned			fs_descs_count;
196	unsigned			hs_descs_count;
197
198	unsigned short			strings_count;
199	unsigned short			interfaces_count;
200	unsigned short			eps_count;
201	unsigned short			_pad1;
202
203	/* filled by __ffs_data_got_strings() */
204	/* ids in stringtabs are set in functionfs_bind() */
205	const void			*raw_strings;
206	struct usb_gadget_strings	**stringtabs;
207
208	/* File system's super block, write once when file system is mounted. */
209	struct super_block		*sb;
210
211	/* File permissions, written once when fs is mounted*/
212	struct ffs_file_perms {
213		umode_t				mode;
214		uid_t				uid;
215		gid_t				gid;
216	}				file_perms;
217
218	/* The endpoint files, filled by ffs_epfiles_create(),
219	 * destroyed by ffs_epfiles_destroy(). */
220	struct ffs_epfile		*epfiles;
221};
222
223/* Reference counter handling */
224static void ffs_data_get(struct ffs_data *ffs);
225static void ffs_data_put(struct ffs_data *ffs);
226/* Creates new ffs_data object. */
227static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
228
229/* Opened counter handling. */
230static void ffs_data_opened(struct ffs_data *ffs);
231static void ffs_data_closed(struct ffs_data *ffs);
232
233/* Called with ffs->mutex held; take over ownerrship of data. */
234static int __must_check
235__ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
236static int __must_check
237__ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
238
239
240/* The function structure ***************************************************/
241
242struct ffs_ep;
243
244struct ffs_function {
245	struct usb_configuration	*conf;
246	struct usb_gadget		*gadget;
247	struct ffs_data			*ffs;
248
249	struct ffs_ep			*eps;
250	u8				eps_revmap[16];
251	short				*interfaces_nums;
252
253	struct usb_function		function;
254};
255
256
257static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
258{
259	return container_of(f, struct ffs_function, function);
260}
261
262static void ffs_func_free(struct ffs_function *func);
263
264
265static void ffs_func_eps_disable(struct ffs_function *func);
266static int __must_check ffs_func_eps_enable(struct ffs_function *func);
267
268
269static int ffs_func_bind(struct usb_configuration *,
270			 struct usb_function *);
271static void ffs_func_unbind(struct usb_configuration *,
272			    struct usb_function *);
273static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
274static void ffs_func_disable(struct usb_function *);
275static int ffs_func_setup(struct usb_function *,
276			  const struct usb_ctrlrequest *);
277static void ffs_func_suspend(struct usb_function *);
278static void ffs_func_resume(struct usb_function *);
279
280
281static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
282static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
283
284
285
286/* The endpoints structures *************************************************/
287
288struct ffs_ep {
289	struct usb_ep			*ep;	/* P: ffs->eps_lock */
290	struct usb_request		*req;	/* P: epfile->mutex */
291
292	/* [0]: full speed, [1]: high speed */
293	struct usb_endpoint_descriptor	*descs[2];
294
295	u8				num;
296
297	int				status;	/* P: epfile->mutex */
298};
299
300struct ffs_epfile {
301	/* Protects ep->ep and ep->req. */
302	struct mutex			mutex;
303	wait_queue_head_t		wait;
304
305	struct ffs_data			*ffs;
306	struct ffs_ep			*ep;	/* P: ffs->eps_lock */
307
308	struct dentry			*dentry;
309
310	char				name[5];
311
312	unsigned char			in;	/* P: ffs->eps_lock */
313	unsigned char			isoc;	/* P: ffs->eps_lock */
314
315	unsigned char			_pad;
316};
317
318
319static int  __must_check ffs_epfiles_create(struct ffs_data *ffs);
320static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
321
322static struct inode *__must_check
323ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
324		   const struct file_operations *fops,
325		   struct dentry **dentry_p);
326
327
328/* Misc helper functions ****************************************************/
329
330static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
331	__attribute__((warn_unused_result, nonnull));
332static char *ffs_prepare_buffer(const char * __user buf, size_t len)
333	__attribute__((warn_unused_result, nonnull));
334
335
336/* Control file aka ep0 *****************************************************/
337
338static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
339{
340	struct ffs_data *ffs = req->context;
341
342	complete_all(&ffs->ep0req_completion);
343}
344
345
346static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
347{
348	struct usb_request *req = ffs->ep0req;
349	int ret;
350
351	req->zero     = len < le16_to_cpu(ffs->ev.setup.wLength);
352
353	spin_unlock_irq(&ffs->ev.waitq.lock);
354
355	req->buf      = data;
356	req->length   = len;
357
358	INIT_COMPLETION(ffs->ep0req_completion);
359
360	ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
361	if (unlikely(ret < 0))
362		return ret;
363
364	ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
365	if (unlikely(ret)) {
366		usb_ep_dequeue(ffs->gadget->ep0, req);
367		return -EINTR;
368	}
369
370	ffs->setup_state = FFS_NO_SETUP;
371	return ffs->ep0req_status;
372}
373
374static int __ffs_ep0_stall(struct ffs_data *ffs)
375{
376	if (ffs->ev.can_stall) {
377		FVDBG("ep0 stall\n");
378		usb_ep_set_halt(ffs->gadget->ep0);
379		ffs->setup_state = FFS_NO_SETUP;
380		return -EL2HLT;
381	} else {
382		FDBG("bogus ep0 stall!\n");
383		return -ESRCH;
384	}
385}
386
387
388static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
389			     size_t len, loff_t *ptr)
390{
391	struct ffs_data *ffs = file->private_data;
392	ssize_t ret;
393	char *data;
394
395	ENTER();
396
397	/* Fast check if setup was canceled */
398	if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
399		return -EIDRM;
400
401	/* Acquire mutex */
402	ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
403	if (unlikely(ret < 0))
404		return ret;
405
406
407	/* Check state */
408	switch (ffs->state) {
409	case FFS_READ_DESCRIPTORS:
410	case FFS_READ_STRINGS:
411		/* Copy data */
412		if (unlikely(len < 16)) {
413			ret = -EINVAL;
414			break;
415		}
416
417		data = ffs_prepare_buffer(buf, len);
418		if (unlikely(IS_ERR(data))) {
419			ret = PTR_ERR(data);
420			break;
421		}
422
423		/* Handle data */
424		if (ffs->state == FFS_READ_DESCRIPTORS) {
425			FINFO("read descriptors");
426			ret = __ffs_data_got_descs(ffs, data, len);
427			if (unlikely(ret < 0))
428				break;
429
430			ffs->state = FFS_READ_STRINGS;
431			ret = len;
432		} else {
433			FINFO("read strings");
434			ret = __ffs_data_got_strings(ffs, data, len);
435			if (unlikely(ret < 0))
436				break;
437
438			ret = ffs_epfiles_create(ffs);
439			if (unlikely(ret)) {
440				ffs->state = FFS_CLOSING;
441				break;
442			}
443
444			ffs->state = FFS_ACTIVE;
445			mutex_unlock(&ffs->mutex);
446
447			ret = functionfs_ready_callback(ffs);
448			if (unlikely(ret < 0)) {
449				ffs->state = FFS_CLOSING;
450				return ret;
451			}
452
453			set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
454			return len;
455		}
456		break;
457
458
459	case FFS_ACTIVE:
460		data = NULL;
461		/* We're called from user space, we can use _irq
462		 * rather then _irqsave */
463		spin_lock_irq(&ffs->ev.waitq.lock);
464		switch (FFS_SETUP_STATE(ffs)) {
465		case FFS_SETUP_CANCELED:
466			ret = -EIDRM;
467			goto done_spin;
468
469		case FFS_NO_SETUP:
470			ret = -ESRCH;
471			goto done_spin;
472
473		case FFS_SETUP_PENDING:
474			break;
475		}
476
477		/* FFS_SETUP_PENDING */
478		if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
479			spin_unlock_irq(&ffs->ev.waitq.lock);
480			ret = __ffs_ep0_stall(ffs);
481			break;
482		}
483
484		/* FFS_SETUP_PENDING and not stall */
485		len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
486
487		spin_unlock_irq(&ffs->ev.waitq.lock);
488
489		data = ffs_prepare_buffer(buf, len);
490		if (unlikely(IS_ERR(data))) {
491			ret = PTR_ERR(data);
492			break;
493		}
494
495		spin_lock_irq(&ffs->ev.waitq.lock);
496
497		/* We are guaranteed to be still in FFS_ACTIVE state
498		 * but the state of setup could have changed from
499		 * FFS_SETUP_PENDING to FFS_SETUP_CANCELED so we need
500		 * to check for that.  If that happened we copied data
501		 * from user space in vain but it's unlikely. */
502		/* For sure we are not in FFS_NO_SETUP since this is
503		 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
504		 * transition can be performed and it's protected by
505		 * mutex. */
506
507		if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
508			ret = -EIDRM;
509done_spin:
510			spin_unlock_irq(&ffs->ev.waitq.lock);
511		} else {
512			/* unlocks spinlock */
513			ret = __ffs_ep0_queue_wait(ffs, data, len);
514		}
515		kfree(data);
516		break;
517
518
519	default:
520		ret = -EBADFD;
521		break;
522	}
523
524
525	mutex_unlock(&ffs->mutex);
526	return ret;
527}
528
529
530
531static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
532				     size_t n)
533{
534	/* We are holding ffs->ev.waitq.lock and ffs->mutex and we need
535	 * to release them. */
536
537	struct usb_functionfs_event events[n];
538	unsigned i = 0;
539
540	memset(events, 0, sizeof events);
541
542	do {
543		events[i].type = ffs->ev.types[i];
544		if (events[i].type == FUNCTIONFS_SETUP) {
545			events[i].u.setup = ffs->ev.setup;
546			ffs->setup_state = FFS_SETUP_PENDING;
547		}
548	} while (++i < n);
549
550	if (n < ffs->ev.count) {
551		ffs->ev.count -= n;
552		memmove(ffs->ev.types, ffs->ev.types + n,
553			ffs->ev.count * sizeof *ffs->ev.types);
554	} else {
555		ffs->ev.count = 0;
556	}
557
558	spin_unlock_irq(&ffs->ev.waitq.lock);
559	mutex_unlock(&ffs->mutex);
560
561	return unlikely(__copy_to_user(buf, events, sizeof events))
562		? -EFAULT : sizeof events;
563}
564
565
566static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
567			    size_t len, loff_t *ptr)
568{
569	struct ffs_data *ffs = file->private_data;
570	char *data = NULL;
571	size_t n;
572	int ret;
573
574	ENTER();
575
576	/* Fast check if setup was canceled */
577	if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED)
578		return -EIDRM;
579
580	/* Acquire mutex */
581	ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
582	if (unlikely(ret < 0))
583		return ret;
584
585
586	/* Check state */
587	if (ffs->state != FFS_ACTIVE) {
588		ret = -EBADFD;
589		goto done_mutex;
590	}
591
592
593	/* We're called from user space, we can use _irq rather then
594	 * _irqsave */
595	spin_lock_irq(&ffs->ev.waitq.lock);
596
597	switch (FFS_SETUP_STATE(ffs)) {
598	case FFS_SETUP_CANCELED:
599		ret = -EIDRM;
600		break;
601
602	case FFS_NO_SETUP:
603		n = len / sizeof(struct usb_functionfs_event);
604		if (unlikely(!n)) {
605			ret = -EINVAL;
606			break;
607		}
608
609		if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
610			ret = -EAGAIN;
611			break;
612		}
613
614		if (unlikely(wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq, ffs->ev.count))) {
615			ret = -EINTR;
616			break;
617		}
618
619		return __ffs_ep0_read_events(ffs, buf,
620					     min(n, (size_t)ffs->ev.count));
621
622
623	case FFS_SETUP_PENDING:
624		if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
625			spin_unlock_irq(&ffs->ev.waitq.lock);
626			ret = __ffs_ep0_stall(ffs);
627			goto done_mutex;
628		}
629
630		len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
631
632		spin_unlock_irq(&ffs->ev.waitq.lock);
633
634		if (likely(len)) {
635			data = kmalloc(len, GFP_KERNEL);
636			if (unlikely(!data)) {
637				ret = -ENOMEM;
638				goto done_mutex;
639			}
640		}
641
642		spin_lock_irq(&ffs->ev.waitq.lock);
643
644		/* See ffs_ep0_write() */
645		if (FFS_SETUP_STATE(ffs) == FFS_SETUP_CANCELED) {
646			ret = -EIDRM;
647			break;
648		}
649
650		/* unlocks spinlock */
651		ret = __ffs_ep0_queue_wait(ffs, data, len);
652		if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
653			ret = -EFAULT;
654		goto done_mutex;
655
656	default:
657		ret = -EBADFD;
658		break;
659	}
660
661	spin_unlock_irq(&ffs->ev.waitq.lock);
662done_mutex:
663	mutex_unlock(&ffs->mutex);
664	kfree(data);
665	return ret;
666}
667
668
669
670static int ffs_ep0_open(struct inode *inode, struct file *file)
671{
672	struct ffs_data *ffs = inode->i_private;
673
674	ENTER();
675
676	if (unlikely(ffs->state == FFS_CLOSING))
677		return -EBUSY;
678
679	file->private_data = ffs;
680	ffs_data_opened(ffs);
681
682	return 0;
683}
684
685
686static int ffs_ep0_release(struct inode *inode, struct file *file)
687{
688	struct ffs_data *ffs = file->private_data;
689
690	ENTER();
691
692	ffs_data_closed(ffs);
693
694	return 0;
695}
696
697
698static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
699{
700	struct ffs_data *ffs = file->private_data;
701	struct usb_gadget *gadget = ffs->gadget;
702	long ret;
703
704	ENTER();
705
706	if (code == FUNCTIONFS_INTERFACE_REVMAP) {
707		struct ffs_function *func = ffs->func;
708		ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
709	} else if (gadget->ops->ioctl) {
710		ret = gadget->ops->ioctl(gadget, code, value);
711	} else {
712		ret = -ENOTTY;
713	}
714
715	return ret;
716}
717
718
719static const struct file_operations ffs_ep0_operations = {
720	.owner =	THIS_MODULE,
721	.llseek =	no_llseek,
722
723	.open =		ffs_ep0_open,
724	.write =	ffs_ep0_write,
725	.read =		ffs_ep0_read,
726	.release =	ffs_ep0_release,
727	.unlocked_ioctl =	ffs_ep0_ioctl,
728};
729
730
731/* "Normal" endpoints operations ********************************************/
732
733
734static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
735{
736	ENTER();
737	if (likely(req->context)) {
738		struct ffs_ep *ep = _ep->driver_data;
739		ep->status = req->status ? req->status : req->actual;
740		complete(req->context);
741	}
742}
743
744
745static ssize_t ffs_epfile_io(struct file *file,
746			     char __user *buf, size_t len, int read)
747{
748	struct ffs_epfile *epfile = file->private_data;
749	struct ffs_ep *ep;
750	char *data = NULL;
751	ssize_t ret;
752	int halt;
753
754	goto first_try;
755	do {
756		spin_unlock_irq(&epfile->ffs->eps_lock);
757		mutex_unlock(&epfile->mutex);
758
759first_try:
760		/* Are we still active? */
761		if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
762			ret = -ENODEV;
763			goto error;
764		}
765
766		/* Wait for endpoint to be enabled */
767		ep = epfile->ep;
768		if (!ep) {
769			if (file->f_flags & O_NONBLOCK) {
770				ret = -EAGAIN;
771				goto error;
772			}
773
774			if (unlikely(wait_event_interruptible
775				     (epfile->wait, (ep = epfile->ep)))) {
776				ret = -EINTR;
777				goto error;
778			}
779		}
780
781		/* Do we halt? */
782		halt = !read == !epfile->in;
783		if (halt && epfile->isoc) {
784			ret = -EINVAL;
785			goto error;
786		}
787
788		/* Allocate & copy */
789		if (!halt && !data) {
790			data = kzalloc(len, GFP_KERNEL);
791			if (unlikely(!data))
792				return -ENOMEM;
793
794			if (!read &&
795			    unlikely(__copy_from_user(data, buf, len))) {
796				ret = -EFAULT;
797				goto error;
798			}
799		}
800
801		/* We will be using request */
802		ret = ffs_mutex_lock(&epfile->mutex,
803				     file->f_flags & O_NONBLOCK);
804		if (unlikely(ret))
805			goto error;
806
807		/* We're called from user space, we can use _irq rather then
808		 * _irqsave */
809		spin_lock_irq(&epfile->ffs->eps_lock);
810
811		/* While we were acquiring mutex endpoint got disabled
812		 * or changed? */
813	} while (unlikely(epfile->ep != ep));
814
815	/* Halt */
816	if (unlikely(halt)) {
817		if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
818			usb_ep_set_halt(ep->ep);
819		spin_unlock_irq(&epfile->ffs->eps_lock);
820		ret = -EBADMSG;
821	} else {
822		/* Fire the request */
823		DECLARE_COMPLETION_ONSTACK(done);
824
825		struct usb_request *req = ep->req;
826		req->context  = &done;
827		req->complete = ffs_epfile_io_complete;
828		req->buf      = data;
829		req->length   = len;
830
831		ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
832
833		spin_unlock_irq(&epfile->ffs->eps_lock);
834
835		if (unlikely(ret < 0)) {
836			/* nop */
837		} else if (unlikely(wait_for_completion_interruptible(&done))) {
838			ret = -EINTR;
839			usb_ep_dequeue(ep->ep, req);
840		} else {
841			ret = ep->status;
842			if (read && ret > 0 &&
843			    unlikely(copy_to_user(buf, data, ret)))
844				ret = -EFAULT;
845		}
846	}
847
848	mutex_unlock(&epfile->mutex);
849error:
850	kfree(data);
851	return ret;
852}
853
854
855static ssize_t
856ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
857		 loff_t *ptr)
858{
859	ENTER();
860
861	return ffs_epfile_io(file, (char __user *)buf, len, 0);
862}
863
864static ssize_t
865ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
866{
867	ENTER();
868
869	return ffs_epfile_io(file, buf, len, 1);
870}
871
872static int
873ffs_epfile_open(struct inode *inode, struct file *file)
874{
875	struct ffs_epfile *epfile = inode->i_private;
876
877	ENTER();
878
879	if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
880		return -ENODEV;
881
882	file->private_data = epfile;
883	ffs_data_opened(epfile->ffs);
884
885	return 0;
886}
887
888static int
889ffs_epfile_release(struct inode *inode, struct file *file)
890{
891	struct ffs_epfile *epfile = inode->i_private;
892
893	ENTER();
894
895	ffs_data_closed(epfile->ffs);
896
897	return 0;
898}
899
900
901static long ffs_epfile_ioctl(struct file *file, unsigned code,
902			     unsigned long value)
903{
904	struct ffs_epfile *epfile = file->private_data;
905	int ret;
906
907	ENTER();
908
909	if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
910		return -ENODEV;
911
912	spin_lock_irq(&epfile->ffs->eps_lock);
913	if (likely(epfile->ep)) {
914		switch (code) {
915		case FUNCTIONFS_FIFO_STATUS:
916			ret = usb_ep_fifo_status(epfile->ep->ep);
917			break;
918		case FUNCTIONFS_FIFO_FLUSH:
919			usb_ep_fifo_flush(epfile->ep->ep);
920			ret = 0;
921			break;
922		case FUNCTIONFS_CLEAR_HALT:
923			ret = usb_ep_clear_halt(epfile->ep->ep);
924			break;
925		case FUNCTIONFS_ENDPOINT_REVMAP:
926			ret = epfile->ep->num;
927			break;
928		default:
929			ret = -ENOTTY;
930		}
931	} else {
932		ret = -ENODEV;
933	}
934	spin_unlock_irq(&epfile->ffs->eps_lock);
935
936	return ret;
937}
938
939
940static const struct file_operations ffs_epfile_operations = {
941	.owner =	THIS_MODULE,
942	.llseek =	no_llseek,
943
944	.open =		ffs_epfile_open,
945	.write =	ffs_epfile_write,
946	.read =		ffs_epfile_read,
947	.release =	ffs_epfile_release,
948	.unlocked_ioctl =	ffs_epfile_ioctl,
949};
950
951
952
953/* File system and super block operations ***********************************/
954
955/*
956 * Mounting the filesystem creates a controller file, used first for
957 * function configuration then later for event monitoring.
958 */
959
960
961static struct inode *__must_check
962ffs_sb_make_inode(struct super_block *sb, void *data,
963		  const struct file_operations *fops,
964		  const struct inode_operations *iops,
965		  struct ffs_file_perms *perms)
966{
967	struct inode *inode;
968
969	ENTER();
970
971	inode = new_inode(sb);
972
973	if (likely(inode)) {
974		struct timespec current_time = CURRENT_TIME;
975
976		inode->i_mode    = perms->mode;
977		inode->i_uid     = perms->uid;
978		inode->i_gid     = perms->gid;
979		inode->i_atime   = current_time;
980		inode->i_mtime   = current_time;
981		inode->i_ctime   = current_time;
982		inode->i_private = data;
983		if (fops)
984			inode->i_fop = fops;
985		if (iops)
986			inode->i_op  = iops;
987	}
988
989	return inode;
990}
991
992
993/* Create "regular" file */
994
995static struct inode *ffs_sb_create_file(struct super_block *sb,
996					const char *name, void *data,
997					const struct file_operations *fops,
998					struct dentry **dentry_p)
999{
1000	struct ffs_data	*ffs = sb->s_fs_info;
1001	struct dentry	*dentry;
1002	struct inode	*inode;
1003
1004	ENTER();
1005
1006	dentry = d_alloc_name(sb->s_root, name);
1007	if (unlikely(!dentry))
1008		return NULL;
1009
1010	inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1011	if (unlikely(!inode)) {
1012		dput(dentry);
1013		return NULL;
1014	}
1015
1016	d_add(dentry, inode);
1017	if (dentry_p)
1018		*dentry_p = dentry;
1019
1020	return inode;
1021}
1022
1023
1024/* Super block */
1025
1026static const struct super_operations ffs_sb_operations = {
1027	.statfs =	simple_statfs,
1028	.drop_inode =	generic_delete_inode,
1029};
1030
1031struct ffs_sb_fill_data {
1032	struct ffs_file_perms perms;
1033	umode_t root_mode;
1034	const char *dev_name;
1035};
1036
1037static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1038{
1039	struct ffs_sb_fill_data *data = _data;
1040	struct inode	*inode;
1041	struct dentry	*d;
1042	struct ffs_data	*ffs;
1043
1044	ENTER();
1045
1046	/* Initialize data */
1047	ffs = ffs_data_new();
1048	if (unlikely(!ffs))
1049		goto enomem0;
1050
1051	ffs->sb              = sb;
1052	ffs->dev_name        = data->dev_name;
1053	ffs->file_perms      = data->perms;
1054
1055	sb->s_fs_info        = ffs;
1056	sb->s_blocksize      = PAGE_CACHE_SIZE;
1057	sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1058	sb->s_magic          = FUNCTIONFS_MAGIC;
1059	sb->s_op             = &ffs_sb_operations;
1060	sb->s_time_gran      = 1;
1061
1062	/* Root inode */
1063	data->perms.mode = data->root_mode;
1064	inode = ffs_sb_make_inode(sb, NULL,
1065				  &simple_dir_operations,
1066				  &simple_dir_inode_operations,
1067				  &data->perms);
1068	if (unlikely(!inode))
1069		goto enomem1;
1070	d = d_alloc_root(inode);
1071	if (unlikely(!d))
1072		goto enomem2;
1073	sb->s_root = d;
1074
1075	/* EP0 file */
1076	if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1077					 &ffs_ep0_operations, NULL)))
1078		goto enomem3;
1079
1080	return 0;
1081
1082enomem3:
1083	dput(d);
1084enomem2:
1085	iput(inode);
1086enomem1:
1087	ffs_data_put(ffs);
1088enomem0:
1089	return -ENOMEM;
1090}
1091
1092
1093static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1094{
1095	ENTER();
1096
1097	if (!opts || !*opts)
1098		return 0;
1099
1100	for (;;) {
1101		char *end, *eq, *comma;
1102		unsigned long value;
1103
1104		/* Option limit */
1105		comma = strchr(opts, ',');
1106		if (comma)
1107			*comma = 0;
1108
1109		/* Value limit */
1110		eq = strchr(opts, '=');
1111		if (unlikely(!eq)) {
1112			FERR("'=' missing in %s", opts);
1113			return -EINVAL;
1114		}
1115		*eq = 0;
1116
1117		/* Parse value */
1118		value = simple_strtoul(eq + 1, &end, 0);
1119		if (unlikely(*end != ',' && *end != 0)) {
1120			FERR("%s: invalid value: %s", opts, eq + 1);
1121			return -EINVAL;
1122		}
1123
1124		/* Interpret option */
1125		switch (eq - opts) {
1126		case 5:
1127			if (!memcmp(opts, "rmode", 5))
1128				data->root_mode  = (value & 0555) | S_IFDIR;
1129			else if (!memcmp(opts, "fmode", 5))
1130				data->perms.mode = (value & 0666) | S_IFREG;
1131			else
1132				goto invalid;
1133			break;
1134
1135		case 4:
1136			if (!memcmp(opts, "mode", 4)) {
1137				data->root_mode  = (value & 0555) | S_IFDIR;
1138				data->perms.mode = (value & 0666) | S_IFREG;
1139			} else {
1140				goto invalid;
1141			}
1142			break;
1143
1144		case 3:
1145			if (!memcmp(opts, "uid", 3))
1146				data->perms.uid = value;
1147			else if (!memcmp(opts, "gid", 3))
1148				data->perms.gid = value;
1149			else
1150				goto invalid;
1151			break;
1152
1153		default:
1154invalid:
1155			FERR("%s: invalid option", opts);
1156			return -EINVAL;
1157		}
1158
1159		/* Next iteration */
1160		if (!comma)
1161			break;
1162		opts = comma + 1;
1163	}
1164
1165	return 0;
1166}
1167
1168
1169/* "mount -t functionfs dev_name /dev/function" ends up here */
1170
1171static int
1172ffs_fs_get_sb(struct file_system_type *t, int flags,
1173	      const char *dev_name, void *opts, struct vfsmount *mnt)
1174{
1175	struct ffs_sb_fill_data data = {
1176		.perms = {
1177			.mode = S_IFREG | 0600,
1178			.uid = 0,
1179			.gid = 0
1180		},
1181		.root_mode = S_IFDIR | 0500,
1182	};
1183	int ret;
1184
1185	ENTER();
1186
1187	ret = functionfs_check_dev_callback(dev_name);
1188	if (unlikely(ret < 0))
1189		return ret;
1190
1191	ret = ffs_fs_parse_opts(&data, opts);
1192	if (unlikely(ret < 0))
1193		return ret;
1194
1195	data.dev_name = dev_name;
1196	return get_sb_single(t, flags, &data, ffs_sb_fill, mnt);
1197}
1198
1199static void
1200ffs_fs_kill_sb(struct super_block *sb)
1201{
1202	void *ptr;
1203
1204	ENTER();
1205
1206	kill_litter_super(sb);
1207	ptr = xchg(&sb->s_fs_info, NULL);
1208	if (ptr)
1209		ffs_data_put(ptr);
1210}
1211
1212static struct file_system_type ffs_fs_type = {
1213	.owner		= THIS_MODULE,
1214	.name		= "functionfs",
1215	.get_sb		= ffs_fs_get_sb,
1216	.kill_sb	= ffs_fs_kill_sb,
1217};
1218
1219
1220
1221/* Driver's main init/cleanup functions *************************************/
1222
1223
1224static int functionfs_init(void)
1225{
1226	int ret;
1227
1228	ENTER();
1229
1230	ret = register_filesystem(&ffs_fs_type);
1231	if (likely(!ret))
1232		FINFO("file system registered");
1233	else
1234		FERR("failed registering file system (%d)", ret);
1235
1236	return ret;
1237}
1238
1239static void functionfs_cleanup(void)
1240{
1241	ENTER();
1242
1243	FINFO("unloading");
1244	unregister_filesystem(&ffs_fs_type);
1245}
1246
1247
1248
1249/* ffs_data and ffs_function construction and destruction code **************/
1250
1251static void ffs_data_clear(struct ffs_data *ffs);
1252static void ffs_data_reset(struct ffs_data *ffs);
1253
1254
1255static void ffs_data_get(struct ffs_data *ffs)
1256{
1257	ENTER();
1258
1259	atomic_inc(&ffs->ref);
1260}
1261
1262static void ffs_data_opened(struct ffs_data *ffs)
1263{
1264	ENTER();
1265
1266	atomic_inc(&ffs->ref);
1267	atomic_inc(&ffs->opened);
1268}
1269
1270static void ffs_data_put(struct ffs_data *ffs)
1271{
1272	ENTER();
1273
1274	if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1275		FINFO("%s(): freeing", __func__);
1276		ffs_data_clear(ffs);
1277		BUG_ON(mutex_is_locked(&ffs->mutex) ||
1278		       spin_is_locked(&ffs->ev.waitq.lock) ||
1279		       waitqueue_active(&ffs->ev.waitq) ||
1280		       waitqueue_active(&ffs->ep0req_completion.wait));
1281		kfree(ffs);
1282	}
1283}
1284
1285
1286
1287static void ffs_data_closed(struct ffs_data *ffs)
1288{
1289	ENTER();
1290
1291	if (atomic_dec_and_test(&ffs->opened)) {
1292		ffs->state = FFS_CLOSING;
1293		ffs_data_reset(ffs);
1294	}
1295
1296	ffs_data_put(ffs);
1297}
1298
1299
1300static struct ffs_data *ffs_data_new(void)
1301{
1302	struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1303	if (unlikely(!ffs))
1304		return 0;
1305
1306	ENTER();
1307
1308	atomic_set(&ffs->ref, 1);
1309	atomic_set(&ffs->opened, 0);
1310	ffs->state = FFS_READ_DESCRIPTORS;
1311	mutex_init(&ffs->mutex);
1312	spin_lock_init(&ffs->eps_lock);
1313	init_waitqueue_head(&ffs->ev.waitq);
1314	init_completion(&ffs->ep0req_completion);
1315
1316	ffs->ev.can_stall = 1;
1317
1318	return ffs;
1319}
1320
1321
1322static void ffs_data_clear(struct ffs_data *ffs)
1323{
1324	ENTER();
1325
1326	if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1327		functionfs_closed_callback(ffs);
1328
1329	BUG_ON(ffs->gadget);
1330
1331	if (ffs->epfiles)
1332		ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1333
1334	kfree(ffs->raw_descs);
1335	kfree(ffs->raw_strings);
1336	kfree(ffs->stringtabs);
1337}
1338
1339
1340static void ffs_data_reset(struct ffs_data *ffs)
1341{
1342	ENTER();
1343
1344	ffs_data_clear(ffs);
1345
1346	ffs->epfiles = NULL;
1347	ffs->raw_descs = NULL;
1348	ffs->raw_strings = NULL;
1349	ffs->stringtabs = NULL;
1350
1351	ffs->raw_descs_length = 0;
1352	ffs->raw_fs_descs_length = 0;
1353	ffs->fs_descs_count = 0;
1354	ffs->hs_descs_count = 0;
1355
1356	ffs->strings_count = 0;
1357	ffs->interfaces_count = 0;
1358	ffs->eps_count = 0;
1359
1360	ffs->ev.count = 0;
1361
1362	ffs->state = FFS_READ_DESCRIPTORS;
1363	ffs->setup_state = FFS_NO_SETUP;
1364	ffs->flags = 0;
1365}
1366
1367
1368static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1369{
1370	struct usb_gadget_strings **lang;
1371	int first_id;
1372
1373	ENTER();
1374
1375	if (WARN_ON(ffs->state != FFS_ACTIVE
1376		 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1377		return -EBADFD;
1378
1379	first_id = usb_string_ids_n(cdev, ffs->strings_count);
1380	if (unlikely(first_id < 0))
1381		return first_id;
1382
1383	ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1384	if (unlikely(!ffs->ep0req))
1385		return -ENOMEM;
1386	ffs->ep0req->complete = ffs_ep0_complete;
1387	ffs->ep0req->context = ffs;
1388
1389	lang = ffs->stringtabs;
1390	for (lang = ffs->stringtabs; *lang; ++lang) {
1391		struct usb_string *str = (*lang)->strings;
1392		int id = first_id;
1393		for (; str->s; ++id, ++str)
1394			str->id = id;
1395	}
1396
1397	ffs->gadget = cdev->gadget;
1398	ffs_data_get(ffs);
1399	return 0;
1400}
1401
1402
1403static void functionfs_unbind(struct ffs_data *ffs)
1404{
1405	ENTER();
1406
1407	if (!WARN_ON(!ffs->gadget)) {
1408		usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1409		ffs->ep0req = NULL;
1410		ffs->gadget = NULL;
1411		ffs_data_put(ffs);
1412	}
1413}
1414
1415
1416static int ffs_epfiles_create(struct ffs_data *ffs)
1417{
1418	struct ffs_epfile *epfile, *epfiles;
1419	unsigned i, count;
1420
1421	ENTER();
1422
1423	count = ffs->eps_count;
1424	epfiles = kzalloc(count * sizeof *epfiles, GFP_KERNEL);
1425	if (!epfiles)
1426		return -ENOMEM;
1427
1428	epfile = epfiles;
1429	for (i = 1; i <= count; ++i, ++epfile) {
1430		epfile->ffs = ffs;
1431		mutex_init(&epfile->mutex);
1432		init_waitqueue_head(&epfile->wait);
1433		sprintf(epfiles->name, "ep%u",  i);
1434		if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1435						 &ffs_epfile_operations,
1436						 &epfile->dentry))) {
1437			ffs_epfiles_destroy(epfiles, i - 1);
1438			return -ENOMEM;
1439		}
1440	}
1441
1442	ffs->epfiles = epfiles;
1443	return 0;
1444}
1445
1446
1447static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1448{
1449	struct ffs_epfile *epfile = epfiles;
1450
1451	ENTER();
1452
1453	for (; count; --count, ++epfile) {
1454		BUG_ON(mutex_is_locked(&epfile->mutex) ||
1455		       waitqueue_active(&epfile->wait));
1456		if (epfile->dentry) {
1457			d_delete(epfile->dentry);
1458			dput(epfile->dentry);
1459			epfile->dentry = NULL;
1460		}
1461	}
1462
1463	kfree(epfiles);
1464}
1465
1466
1467static int functionfs_bind_config(struct usb_composite_dev *cdev,
1468				  struct usb_configuration *c,
1469				  struct ffs_data *ffs)
1470{
1471	struct ffs_function *func;
1472	int ret;
1473
1474	ENTER();
1475
1476	func = kzalloc(sizeof *func, GFP_KERNEL);
1477	if (unlikely(!func))
1478		return -ENOMEM;
1479
1480	func->function.name    = "Function FS Gadget";
1481	func->function.strings = ffs->stringtabs;
1482
1483	func->function.bind    = ffs_func_bind;
1484	func->function.unbind  = ffs_func_unbind;
1485	func->function.set_alt = ffs_func_set_alt;
1486	/*func->function.get_alt = ffs_func_get_alt;*/
1487	func->function.disable = ffs_func_disable;
1488	func->function.setup   = ffs_func_setup;
1489	func->function.suspend = ffs_func_suspend;
1490	func->function.resume  = ffs_func_resume;
1491
1492	func->conf   = c;
1493	func->gadget = cdev->gadget;
1494	func->ffs = ffs;
1495	ffs_data_get(ffs);
1496
1497	ret = usb_add_function(c, &func->function);
1498	if (unlikely(ret))
1499		ffs_func_free(func);
1500
1501	return ret;
1502}
1503
1504static void ffs_func_free(struct ffs_function *func)
1505{
1506	ENTER();
1507
1508	ffs_data_put(func->ffs);
1509
1510	kfree(func->eps);
1511	/* eps and interfaces_nums are allocated in the same chunk so
1512	 * only one free is required.  Descriptors are also allocated
1513	 * in the same chunk. */
1514
1515	kfree(func);
1516}
1517
1518
1519static void ffs_func_eps_disable(struct ffs_function *func)
1520{
1521	struct ffs_ep *ep         = func->eps;
1522	struct ffs_epfile *epfile = func->ffs->epfiles;
1523	unsigned count            = func->ffs->eps_count;
1524	unsigned long flags;
1525
1526	spin_lock_irqsave(&func->ffs->eps_lock, flags);
1527	do {
1528		/* pending requests get nuked */
1529		if (likely(ep->ep))
1530			usb_ep_disable(ep->ep);
1531		epfile->ep = NULL;
1532
1533		++ep;
1534		++epfile;
1535	} while (--count);
1536	spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1537}
1538
1539static int ffs_func_eps_enable(struct ffs_function *func)
1540{
1541	struct ffs_data *ffs      = func->ffs;
1542	struct ffs_ep *ep         = func->eps;
1543	struct ffs_epfile *epfile = ffs->epfiles;
1544	unsigned count            = ffs->eps_count;
1545	unsigned long flags;
1546	int ret = 0;
1547
1548	spin_lock_irqsave(&func->ffs->eps_lock, flags);
1549	do {
1550		struct usb_endpoint_descriptor *ds;
1551		ds = ep->descs[ep->descs[1] ? 1 : 0];
1552
1553		ep->ep->driver_data = ep;
1554		ret = usb_ep_enable(ep->ep, ds);
1555		if (likely(!ret)) {
1556			epfile->ep = ep;
1557			epfile->in = usb_endpoint_dir_in(ds);
1558			epfile->isoc = usb_endpoint_xfer_isoc(ds);
1559		} else {
1560			break;
1561		}
1562
1563		wake_up(&epfile->wait);
1564
1565		++ep;
1566		++epfile;
1567	} while (--count);
1568	spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1569
1570	return ret;
1571}
1572
1573
1574/* Parsing and building descriptors and strings *****************************/
1575
1576
1577/* This validates if data pointed by data is a valid USB descriptor as
1578 * well as record how many interfaces, endpoints and strings are
1579 * required by given configuration.  Returns address afther the
1580 * descriptor or NULL if data is invalid. */
1581
1582enum ffs_entity_type {
1583	FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1584};
1585
1586typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1587				   u8 *valuep,
1588				   struct usb_descriptor_header *desc,
1589				   void *priv);
1590
1591static int __must_check ffs_do_desc(char *data, unsigned len,
1592				    ffs_entity_callback entity, void *priv)
1593{
1594	struct usb_descriptor_header *_ds = (void *)data;
1595	u8 length;
1596	int ret;
1597
1598	ENTER();
1599
1600	/* At least two bytes are required: length and type */
1601	if (len < 2) {
1602		FVDBG("descriptor too short");
1603		return -EINVAL;
1604	}
1605
1606	/* If we have at least as many bytes as the descriptor takes? */
1607	length = _ds->bLength;
1608	if (len < length) {
1609		FVDBG("descriptor longer then available data");
1610		return -EINVAL;
1611	}
1612
1613#define __entity_check_INTERFACE(val)  1
1614#define __entity_check_STRING(val)     (val)
1615#define __entity_check_ENDPOINT(val)   ((val) & USB_ENDPOINT_NUMBER_MASK)
1616#define __entity(type, val) do {					\
1617		FVDBG("entity " #type "(%02x)", (val));			\
1618		if (unlikely(!__entity_check_ ##type(val))) {		\
1619			FVDBG("invalid entity's value");		\
1620			return -EINVAL;					\
1621		}							\
1622		ret = entity(FFS_ ##type, &val, _ds, priv);		\
1623		if (unlikely(ret < 0)) {				\
1624			FDBG("entity " #type "(%02x); ret = %d",	\
1625			     (val), ret);				\
1626			return ret;					\
1627		}							\
1628	} while (0)
1629
1630	/* Parse descriptor depending on type. */
1631	switch (_ds->bDescriptorType) {
1632	case USB_DT_DEVICE:
1633	case USB_DT_CONFIG:
1634	case USB_DT_STRING:
1635	case USB_DT_DEVICE_QUALIFIER:
1636		/* function can't have any of those */
1637		FVDBG("descriptor reserved for gadget: %d", _ds->bDescriptorType);
1638		return -EINVAL;
1639
1640	case USB_DT_INTERFACE: {
1641		struct usb_interface_descriptor *ds = (void *)_ds;
1642		FVDBG("interface descriptor");
1643		if (length != sizeof *ds)
1644			goto inv_length;
1645
1646		__entity(INTERFACE, ds->bInterfaceNumber);
1647		if (ds->iInterface)
1648			__entity(STRING, ds->iInterface);
1649	}
1650		break;
1651
1652	case USB_DT_ENDPOINT: {
1653		struct usb_endpoint_descriptor *ds = (void *)_ds;
1654		FVDBG("endpoint descriptor");
1655		if (length != USB_DT_ENDPOINT_SIZE &&
1656		    length != USB_DT_ENDPOINT_AUDIO_SIZE)
1657			goto inv_length;
1658		__entity(ENDPOINT, ds->bEndpointAddress);
1659	}
1660		break;
1661
1662	case USB_DT_OTG:
1663		if (length != sizeof(struct usb_otg_descriptor))
1664			goto inv_length;
1665		break;
1666
1667	case USB_DT_INTERFACE_ASSOCIATION: {
1668		struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1669		FVDBG("interface association descriptor");
1670		if (length != sizeof *ds)
1671			goto inv_length;
1672		if (ds->iFunction)
1673			__entity(STRING, ds->iFunction);
1674	}
1675		break;
1676
1677	case USB_DT_OTHER_SPEED_CONFIG:
1678	case USB_DT_INTERFACE_POWER:
1679	case USB_DT_DEBUG:
1680	case USB_DT_SECURITY:
1681	case USB_DT_CS_RADIO_CONTROL:
1682		/* TODO */
1683		FVDBG("unimplemented descriptor: %d", _ds->bDescriptorType);
1684		return -EINVAL;
1685
1686	default:
1687		/* We should never be here */
1688		FVDBG("unknown descriptor: %d", _ds->bDescriptorType);
1689		return -EINVAL;
1690
1691	inv_length:
1692		FVDBG("invalid length: %d (descriptor %d)",
1693		      _ds->bLength, _ds->bDescriptorType);
1694		return -EINVAL;
1695	}
1696
1697#undef __entity
1698#undef __entity_check_DESCRIPTOR
1699#undef __entity_check_INTERFACE
1700#undef __entity_check_STRING
1701#undef __entity_check_ENDPOINT
1702
1703	return length;
1704}
1705
1706
1707static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1708				     ffs_entity_callback entity, void *priv)
1709{
1710	const unsigned _len = len;
1711	unsigned long num = 0;
1712
1713	ENTER();
1714
1715	for (;;) {
1716		int ret;
1717
1718		if (num == count)
1719			data = NULL;
1720
1721		/* Record "descriptor" entitny */
1722		ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1723		if (unlikely(ret < 0)) {
1724			FDBG("entity DESCRIPTOR(%02lx); ret = %d", num, ret);
1725			return ret;
1726		}
1727
1728		if (!data)
1729			return _len - len;
1730
1731		ret = ffs_do_desc(data, len, entity, priv);
1732		if (unlikely(ret < 0)) {
1733			FDBG("%s returns %d", __func__, ret);
1734			return ret;
1735		}
1736
1737		len -= ret;
1738		data += ret;
1739		++num;
1740	}
1741}
1742
1743
1744static int __ffs_data_do_entity(enum ffs_entity_type type,
1745				u8 *valuep, struct usb_descriptor_header *desc,
1746				void *priv)
1747{
1748	struct ffs_data *ffs = priv;
1749
1750	ENTER();
1751
1752	switch (type) {
1753	case FFS_DESCRIPTOR:
1754		break;
1755
1756	case FFS_INTERFACE:
1757		/* Interfaces are indexed from zero so if we
1758		 * encountered interface "n" then there are at least
1759		 * "n+1" interfaces. */
1760		if (*valuep >= ffs->interfaces_count)
1761			ffs->interfaces_count = *valuep + 1;
1762		break;
1763
1764	case FFS_STRING:
1765		/* Strings are indexed from 1 (0 is magic ;) reserved
1766		 * for languages list or some such) */
1767		if (*valuep > ffs->strings_count)
1768			ffs->strings_count = *valuep;
1769		break;
1770
1771	case FFS_ENDPOINT:
1772		/* Endpoints are indexed from 1 as well. */
1773		if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1774			ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1775		break;
1776	}
1777
1778	return 0;
1779}
1780
1781
1782static int __ffs_data_got_descs(struct ffs_data *ffs,
1783				char *const _data, size_t len)
1784{
1785	unsigned fs_count, hs_count;
1786	int fs_len, ret = -EINVAL;
1787	char *data = _data;
1788
1789	ENTER();
1790
1791	if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_DESCRIPTORS_MAGIC ||
1792		     get_unaligned_le32(data + 4) != len))
1793		goto error;
1794	fs_count = get_unaligned_le32(data +  8);
1795	hs_count = get_unaligned_le32(data + 12);
1796
1797	if (!fs_count && !hs_count)
1798		goto einval;
1799
1800	data += 16;
1801	len  -= 16;
1802
1803	if (likely(fs_count)) {
1804		fs_len = ffs_do_descs(fs_count, data, len,
1805				      __ffs_data_do_entity, ffs);
1806		if (unlikely(fs_len < 0)) {
1807			ret = fs_len;
1808			goto error;
1809		}
1810
1811		data += fs_len;
1812		len  -= fs_len;
1813	} else {
1814		fs_len = 0;
1815	}
1816
1817	if (likely(hs_count)) {
1818		ret = ffs_do_descs(hs_count, data, len,
1819				   __ffs_data_do_entity, ffs);
1820		if (unlikely(ret < 0))
1821			goto error;
1822	} else {
1823		ret = 0;
1824	}
1825
1826	if (unlikely(len != ret))
1827		goto einval;
1828
1829	ffs->raw_fs_descs_length = fs_len;
1830	ffs->raw_descs_length    = fs_len + ret;
1831	ffs->raw_descs           = _data;
1832	ffs->fs_descs_count      = fs_count;
1833	ffs->hs_descs_count      = hs_count;
1834
1835	return 0;
1836
1837einval:
1838	ret = -EINVAL;
1839error:
1840	kfree(_data);
1841	return ret;
1842}
1843
1844
1845
1846static int __ffs_data_got_strings(struct ffs_data *ffs,
1847				  char *const _data, size_t len)
1848{
1849	u32 str_count, needed_count, lang_count;
1850	struct usb_gadget_strings **stringtabs, *t;
1851	struct usb_string *strings, *s;
1852	const char *data = _data;
1853
1854	ENTER();
1855
1856	if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
1857		     get_unaligned_le32(data + 4) != len))
1858		goto error;
1859	str_count  = get_unaligned_le32(data + 8);
1860	lang_count = get_unaligned_le32(data + 12);
1861
1862	/* if one is zero the other must be zero */
1863	if (unlikely(!str_count != !lang_count))
1864		goto error;
1865
1866	/* Do we have at least as many strings as descriptors need? */
1867	needed_count = ffs->strings_count;
1868	if (unlikely(str_count < needed_count))
1869		goto error;
1870
1871	/* If we don't need any strings just return and free all
1872	 * memory */
1873	if (!needed_count) {
1874		kfree(_data);
1875		return 0;
1876	}
1877
1878	/* Allocate */
1879	{
1880		/* Allocate everything in one chunk so there's less
1881		 * maintanance. */
1882		struct {
1883			struct usb_gadget_strings *stringtabs[lang_count + 1];
1884			struct usb_gadget_strings stringtab[lang_count];
1885			struct usb_string strings[lang_count*(needed_count+1)];
1886		} *d;
1887		unsigned i = 0;
1888
1889		d = kmalloc(sizeof *d, GFP_KERNEL);
1890		if (unlikely(!d)) {
1891			kfree(_data);
1892			return -ENOMEM;
1893		}
1894
1895		stringtabs = d->stringtabs;
1896		t = d->stringtab;
1897		i = lang_count;
1898		do {
1899			*stringtabs++ = t++;
1900		} while (--i);
1901		*stringtabs = NULL;
1902
1903		stringtabs = d->stringtabs;
1904		t = d->stringtab;
1905		s = d->strings;
1906		strings = s;
1907	}
1908
1909	/* For each language */
1910	data += 16;
1911	len -= 16;
1912
1913	do { /* lang_count > 0 so we can use do-while */
1914		unsigned needed = needed_count;
1915
1916		if (unlikely(len < 3))
1917			goto error_free;
1918		t->language = get_unaligned_le16(data);
1919		t->strings  = s;
1920		++t;
1921
1922		data += 2;
1923		len -= 2;
1924
1925		/* For each string */
1926		do { /* str_count > 0 so we can use do-while */
1927			size_t length = strnlen(data, len);
1928
1929			if (unlikely(length == len))
1930				goto error_free;
1931
1932			/* user may provide more strings then we need,
1933			 * if that's the case we simply ingore the
1934			 * rest */
1935			if (likely(needed)) {
1936				/* s->id will be set while adding
1937				 * function to configuration so for
1938				 * now just leave garbage here. */
1939				s->s = data;
1940				--needed;
1941				++s;
1942			}
1943
1944			data += length + 1;
1945			len -= length + 1;
1946		} while (--str_count);
1947
1948		s->id = 0;   /* terminator */
1949		s->s = NULL;
1950		++s;
1951
1952	} while (--lang_count);
1953
1954	/* Some garbage left? */
1955	if (unlikely(len))
1956		goto error_free;
1957
1958	/* Done! */
1959	ffs->stringtabs = stringtabs;
1960	ffs->raw_strings = _data;
1961
1962	return 0;
1963
1964error_free:
1965	kfree(stringtabs);
1966error:
1967	kfree(_data);
1968	return -EINVAL;
1969}
1970
1971
1972
1973
1974/* Events handling and management *******************************************/
1975
1976static void __ffs_event_add(struct ffs_data *ffs,
1977			    enum usb_functionfs_event_type type)
1978{
1979	enum usb_functionfs_event_type rem_type1, rem_type2 = type;
1980	int neg = 0;
1981
1982	/* Abort any unhandled setup */
1983	/* We do not need to worry about some cmpxchg() changing value
1984	 * of ffs->setup_state without holding the lock because when
1985	 * state is FFS_SETUP_PENDING cmpxchg() in several places in
1986	 * the source does nothing. */
1987	if (ffs->setup_state == FFS_SETUP_PENDING)
1988		ffs->setup_state = FFS_SETUP_CANCELED;
1989
1990	switch (type) {
1991	case FUNCTIONFS_RESUME:
1992		rem_type2 = FUNCTIONFS_SUSPEND;
1993		/* FALL THGOUTH */
1994	case FUNCTIONFS_SUSPEND:
1995	case FUNCTIONFS_SETUP:
1996		rem_type1 = type;
1997		/* discard all similar events */
1998		break;
1999
2000	case FUNCTIONFS_BIND:
2001	case FUNCTIONFS_UNBIND:
2002	case FUNCTIONFS_DISABLE:
2003	case FUNCTIONFS_ENABLE:
2004		/* discard everything other then power management. */
2005		rem_type1 = FUNCTIONFS_SUSPEND;
2006		rem_type2 = FUNCTIONFS_RESUME;
2007		neg = 1;
2008		break;
2009
2010	default:
2011		BUG();
2012	}
2013
2014	{
2015		u8 *ev  = ffs->ev.types, *out = ev;
2016		unsigned n = ffs->ev.count;
2017		for (; n; --n, ++ev)
2018			if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2019				*out++ = *ev;
2020			else
2021				FVDBG("purging event %d", *ev);
2022		ffs->ev.count = out - ffs->ev.types;
2023	}
2024
2025	FVDBG("adding event %d", type);
2026	ffs->ev.types[ffs->ev.count++] = type;
2027	wake_up_locked(&ffs->ev.waitq);
2028}
2029
2030static void ffs_event_add(struct ffs_data *ffs,
2031			  enum usb_functionfs_event_type type)
2032{
2033	unsigned long flags;
2034	spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2035	__ffs_event_add(ffs, type);
2036	spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2037}
2038
2039
2040/* Bind/unbind USB function hooks *******************************************/
2041
2042static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2043				    struct usb_descriptor_header *desc,
2044				    void *priv)
2045{
2046	struct usb_endpoint_descriptor *ds = (void *)desc;
2047	struct ffs_function *func = priv;
2048	struct ffs_ep *ffs_ep;
2049
2050	/* If hs_descriptors is not NULL then we are reading hs
2051	 * descriptors now */
2052	const int isHS = func->function.hs_descriptors != NULL;
2053	unsigned idx;
2054
2055	if (type != FFS_DESCRIPTOR)
2056		return 0;
2057
2058	if (isHS)
2059		func->function.hs_descriptors[(long)valuep] = desc;
2060	else
2061		func->function.descriptors[(long)valuep]    = desc;
2062
2063	if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2064		return 0;
2065
2066	idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2067	ffs_ep = func->eps + idx;
2068
2069	if (unlikely(ffs_ep->descs[isHS])) {
2070		FVDBG("two %sspeed descriptors for EP %d",
2071		      isHS ? "high" : "full",
2072		      ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2073		return -EINVAL;
2074	}
2075	ffs_ep->descs[isHS] = ds;
2076
2077	ffs_dump_mem(": Original  ep desc", ds, ds->bLength);
2078	if (ffs_ep->ep) {
2079		ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2080		if (!ds->wMaxPacketSize)
2081			ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2082	} else {
2083		struct usb_request *req;
2084		struct usb_ep *ep;
2085
2086		FVDBG("autoconfig");
2087		ep = usb_ep_autoconfig(func->gadget, ds);
2088		if (unlikely(!ep))
2089			return -ENOTSUPP;
2090		ep->driver_data = func->eps + idx;;
2091
2092		req = usb_ep_alloc_request(ep, GFP_KERNEL);
2093		if (unlikely(!req))
2094			return -ENOMEM;
2095
2096		ffs_ep->ep  = ep;
2097		ffs_ep->req = req;
2098		func->eps_revmap[ds->bEndpointAddress &
2099				 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2100	}
2101	ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2102
2103	return 0;
2104}
2105
2106
2107static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2108				   struct usb_descriptor_header *desc,
2109				   void *priv)
2110{
2111	struct ffs_function *func = priv;
2112	unsigned idx;
2113	u8 newValue;
2114
2115	switch (type) {
2116	default:
2117	case FFS_DESCRIPTOR:
2118		/* Handled in previous pass by __ffs_func_bind_do_descs() */
2119		return 0;
2120
2121	case FFS_INTERFACE:
2122		idx = *valuep;
2123		if (func->interfaces_nums[idx] < 0) {
2124			int id = usb_interface_id(func->conf, &func->function);
2125			if (unlikely(id < 0))
2126				return id;
2127			func->interfaces_nums[idx] = id;
2128		}
2129		newValue = func->interfaces_nums[idx];
2130		break;
2131
2132	case FFS_STRING:
2133		/* String' IDs are allocated when fsf_data is bound to cdev */
2134		newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2135		break;
2136
2137	case FFS_ENDPOINT:
2138		/* USB_DT_ENDPOINT are handled in
2139		 * __ffs_func_bind_do_descs(). */
2140		if (desc->bDescriptorType == USB_DT_ENDPOINT)
2141			return 0;
2142
2143		idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2144		if (unlikely(!func->eps[idx].ep))
2145			return -EINVAL;
2146
2147		{
2148			struct usb_endpoint_descriptor **descs;
2149			descs = func->eps[idx].descs;
2150			newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2151		}
2152		break;
2153	}
2154
2155	FVDBG("%02x -> %02x", *valuep, newValue);
2156	*valuep = newValue;
2157	return 0;
2158}
2159
2160static int ffs_func_bind(struct usb_configuration *c,
2161			 struct usb_function *f)
2162{
2163	struct ffs_function *func = ffs_func_from_usb(f);
2164	struct ffs_data *ffs = func->ffs;
2165
2166	const int full = !!func->ffs->fs_descs_count;
2167	const int high = gadget_is_dualspeed(func->gadget) &&
2168		func->ffs->hs_descs_count;
2169
2170	int ret;
2171
2172	/* Make it a single chunk, less management later on */
2173	struct {
2174		struct ffs_ep eps[ffs->eps_count];
2175		struct usb_descriptor_header
2176			*fs_descs[full ? ffs->fs_descs_count + 1 : 0];
2177		struct usb_descriptor_header
2178			*hs_descs[high ? ffs->hs_descs_count + 1 : 0];
2179		short inums[ffs->interfaces_count];
2180		char raw_descs[high ? ffs->raw_descs_length
2181				    : ffs->raw_fs_descs_length];
2182	} *data;
2183
2184	ENTER();
2185
2186	/* Only high speed but not supported by gadget? */
2187	if (unlikely(!(full | high)))
2188		return -ENOTSUPP;
2189
2190	/* Allocate */
2191	data = kmalloc(sizeof *data, GFP_KERNEL);
2192	if (unlikely(!data))
2193		return -ENOMEM;
2194
2195	/* Zero */
2196	memset(data->eps, 0, sizeof data->eps);
2197	memcpy(data->raw_descs, ffs->raw_descs + 16, sizeof data->raw_descs);
2198	memset(data->inums, 0xff, sizeof data->inums);
2199	for (ret = ffs->eps_count; ret; --ret)
2200		data->eps[ret].num = -1;
2201
2202	/* Save pointers */
2203	func->eps             = data->eps;
2204	func->interfaces_nums = data->inums;
2205
2206	/* Go throught all the endpoint descriptors and allocate
2207	 * endpoints first, so that later we can rewrite the endpoint
2208	 * numbers without worying that it may be described later on. */
2209	if (likely(full)) {
2210		func->function.descriptors = data->fs_descs;
2211		ret = ffs_do_descs(ffs->fs_descs_count,
2212				   data->raw_descs,
2213				   sizeof data->raw_descs,
2214				   __ffs_func_bind_do_descs, func);
2215		if (unlikely(ret < 0))
2216			goto error;
2217	} else {
2218		ret = 0;
2219	}
2220
2221	if (likely(high)) {
2222		func->function.hs_descriptors = data->hs_descs;
2223		ret = ffs_do_descs(ffs->hs_descs_count,
2224				   data->raw_descs + ret,
2225				   (sizeof data->raw_descs) - ret,
2226				   __ffs_func_bind_do_descs, func);
2227	}
2228
2229	/* Now handle interface numbers allocation and interface and
2230	 * enpoint numbers rewritting.  We can do that in one go
2231	 * now. */
2232	ret = ffs_do_descs(ffs->fs_descs_count +
2233			   (high ? ffs->hs_descs_count : 0),
2234			   data->raw_descs, sizeof data->raw_descs,
2235			   __ffs_func_bind_do_nums, func);
2236	if (unlikely(ret < 0))
2237		goto error;
2238
2239	/* And we're done */
2240	ffs_event_add(ffs, FUNCTIONFS_BIND);
2241	return 0;
2242
2243error:
2244	return ret;
2245}
2246
2247
2248/* Other USB function hooks *************************************************/
2249
2250static void ffs_func_unbind(struct usb_configuration *c,
2251			    struct usb_function *f)
2252{
2253	struct ffs_function *func = ffs_func_from_usb(f);
2254	struct ffs_data *ffs = func->ffs;
2255
2256	ENTER();
2257
2258	if (ffs->func == func) {
2259		ffs_func_eps_disable(func);
2260		ffs->func = NULL;
2261	}
2262
2263	ffs_event_add(ffs, FUNCTIONFS_UNBIND);
2264
2265	ffs_func_free(func);
2266}
2267
2268
2269static int ffs_func_set_alt(struct usb_function *f,
2270			    unsigned interface, unsigned alt)
2271{
2272	struct ffs_function *func = ffs_func_from_usb(f);
2273	struct ffs_data *ffs = func->ffs;
2274	int ret = 0, intf;
2275
2276	if (alt != (unsigned)-1) {
2277		intf = ffs_func_revmap_intf(func, interface);
2278		if (unlikely(intf < 0))
2279			return intf;
2280	}
2281
2282	if (ffs->func)
2283		ffs_func_eps_disable(ffs->func);
2284
2285	if (ffs->state != FFS_ACTIVE)
2286		return -ENODEV;
2287
2288	if (alt == (unsigned)-1) {
2289		ffs->func = NULL;
2290		ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2291		return 0;
2292	}
2293
2294	ffs->func = func;
2295	ret = ffs_func_eps_enable(func);
2296	if (likely(ret >= 0))
2297		ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2298	return ret;
2299}
2300
2301static void ffs_func_disable(struct usb_function *f)
2302{
2303	ffs_func_set_alt(f, 0, (unsigned)-1);
2304}
2305
2306static int ffs_func_setup(struct usb_function *f,
2307			  const struct usb_ctrlrequest *creq)
2308{
2309	struct ffs_function *func = ffs_func_from_usb(f);
2310	struct ffs_data *ffs = func->ffs;
2311	unsigned long flags;
2312	int ret;
2313
2314	ENTER();
2315
2316	FVDBG("creq->bRequestType = %02x", creq->bRequestType);
2317	FVDBG("creq->bRequest     = %02x", creq->bRequest);
2318	FVDBG("creq->wValue       = %04x", le16_to_cpu(creq->wValue));
2319	FVDBG("creq->wIndex       = %04x", le16_to_cpu(creq->wIndex));
2320	FVDBG("creq->wLength      = %04x", le16_to_cpu(creq->wLength));
2321
2322	/* Most requests directed to interface go throught here
2323	 * (notable exceptions are set/get interface) so we need to
2324	 * handle them.  All other either handled by composite or
2325	 * passed to usb_configuration->setup() (if one is set).  No
2326	 * matter, we will handle requests directed to endpoint here
2327	 * as well (as it's straightforward) but what to do with any
2328	 * other request? */
2329
2330	if (ffs->state != FFS_ACTIVE)
2331		return -ENODEV;
2332
2333	switch (creq->bRequestType & USB_RECIP_MASK) {
2334	case USB_RECIP_INTERFACE:
2335		ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2336		if (unlikely(ret < 0))
2337			return ret;
2338		break;
2339
2340	case USB_RECIP_ENDPOINT:
2341		ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2342		if (unlikely(ret < 0))
2343			return ret;
2344		break;
2345
2346	default:
2347		return -EOPNOTSUPP;
2348	}
2349
2350	spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2351	ffs->ev.setup = *creq;
2352	ffs->ev.setup.wIndex = cpu_to_le16(ret);
2353	__ffs_event_add(ffs, FUNCTIONFS_SETUP);
2354	spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2355
2356	return 0;
2357}
2358
2359static void ffs_func_suspend(struct usb_function *f)
2360{
2361	ENTER();
2362	ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2363}
2364
2365static void ffs_func_resume(struct usb_function *f)
2366{
2367	ENTER();
2368	ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2369}
2370
2371
2372
2373/* Enpoint and interface numbers reverse mapping ****************************/
2374
2375static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2376{
2377	num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2378	return num ? num : -EDOM;
2379}
2380
2381static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2382{
2383	short *nums = func->interfaces_nums;
2384	unsigned count = func->ffs->interfaces_count;
2385
2386	for (; count; --count, ++nums) {
2387		if (*nums >= 0 && *nums == intf)
2388			return nums - func->interfaces_nums;
2389	}
2390
2391	return -EDOM;
2392}
2393
2394
2395/* Misc helper functions ****************************************************/
2396
2397static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
2398{
2399	return nonblock
2400		? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
2401		: mutex_lock_interruptible(mutex);
2402}
2403
2404
2405static char *ffs_prepare_buffer(const char * __user buf, size_t len)
2406{
2407	char *data;
2408
2409	if (unlikely(!len))
2410		return NULL;
2411
2412	data = kmalloc(len, GFP_KERNEL);
2413	if (unlikely(!data))
2414		return ERR_PTR(-ENOMEM);
2415
2416	if (unlikely(__copy_from_user(data, buf, len))) {
2417		kfree(data);
2418		return ERR_PTR(-EFAULT);
2419	}
2420
2421	FVDBG("Buffer from user space:");
2422	ffs_dump_mem("", data, len);
2423
2424	return data;
2425}
2426