• 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/drivers/usb/gadget/
1/*
2 * inode.c -- user mode filesystem api for usb gadget controllers
3 *
4 * Copyright (C) 2003-2004 David Brownell
5 * Copyright (C) 2003 Agilent Technologies
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 */
21
22
23/* #define VERBOSE_DEBUG */
24
25#include <linux/init.h>
26#include <linux/module.h>
27#include <linux/fs.h>
28#include <linux/pagemap.h>
29#include <linux/uts.h>
30#include <linux/wait.h>
31#include <linux/compiler.h>
32#include <asm/uaccess.h>
33#include <linux/sched.h>
34#include <linux/slab.h>
35#include <linux/poll.h>
36#include <linux/smp_lock.h>
37
38#include <linux/device.h>
39#include <linux/moduleparam.h>
40
41#include <linux/usb/gadgetfs.h>
42#include <linux/usb/gadget.h>
43
44
45/*
46 * The gadgetfs API maps each endpoint to a file descriptor so that you
47 * can use standard synchronous read/write calls for I/O.  There's some
48 * O_NONBLOCK and O_ASYNC/FASYNC style i/o support.  Example usermode
49 * drivers show how this works in practice.  You can also use AIO to
50 * eliminate I/O gaps between requests, to help when streaming data.
51 *
52 * Key parts that must be USB-specific are protocols defining how the
53 * read/write operations relate to the hardware state machines.  There
54 * are two types of files.  One type is for the device, implementing ep0.
55 * The other type is for each IN or OUT endpoint.  In both cases, the
56 * user mode driver must configure the hardware before using it.
57 *
58 * - First, dev_config() is called when /dev/gadget/$CHIP is configured
59 *   (by writing configuration and device descriptors).  Afterwards it
60 *   may serve as a source of device events, used to handle all control
61 *   requests other than basic enumeration.
62 *
63 * - Then, after a SET_CONFIGURATION control request, ep_config() is
64 *   called when each /dev/gadget/ep* file is configured (by writing
65 *   endpoint descriptors).  Afterwards these files are used to write()
66 *   IN data or to read() OUT data.  To halt the endpoint, a "wrong
67 *   direction" request is issued (like reading an IN endpoint).
68 *
69 * Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe
70 * not possible on all hardware.  For example, precise fault handling with
71 * respect to data left in endpoint fifos after aborted operations; or
72 * selective clearing of endpoint halts, to implement SET_INTERFACE.
73 */
74
75#define	DRIVER_DESC	"USB Gadget filesystem"
76#define	DRIVER_VERSION	"24 Aug 2004"
77
78static const char driver_desc [] = DRIVER_DESC;
79static const char shortname [] = "gadgetfs";
80
81MODULE_DESCRIPTION (DRIVER_DESC);
82MODULE_AUTHOR ("David Brownell");
83MODULE_LICENSE ("GPL");
84
85
86/*----------------------------------------------------------------------*/
87
88#define GADGETFS_MAGIC		0xaee71ee7
89#define DMA_ADDR_INVALID	(~(dma_addr_t)0)
90
91/* /dev/gadget/$CHIP represents ep0 and the whole device */
92enum ep0_state {
93	/* DISBLED is the initial state.
94	 */
95	STATE_DEV_DISABLED = 0,
96
97	/* Only one open() of /dev/gadget/$CHIP; only one file tracks
98	 * ep0/device i/o modes and binding to the controller.  Driver
99	 * must always write descriptors to initialize the device, then
100	 * the device becomes UNCONNECTED until enumeration.
101	 */
102	STATE_DEV_OPENED,
103
104	/* From then on, ep0 fd is in either of two basic modes:
105	 * - (UN)CONNECTED: read usb_gadgetfs_event(s) from it
106	 * - SETUP: read/write will transfer control data and succeed;
107	 *   or if "wrong direction", performs protocol stall
108	 */
109	STATE_DEV_UNCONNECTED,
110	STATE_DEV_CONNECTED,
111	STATE_DEV_SETUP,
112
113	/* UNBOUND means the driver closed ep0, so the device won't be
114	 * accessible again (DEV_DISABLED) until all fds are closed.
115	 */
116	STATE_DEV_UNBOUND,
117};
118
119/* enough for the whole queue: most events invalidate others */
120#define	N_EVENT			5
121
122struct dev_data {
123	spinlock_t			lock;
124	atomic_t			count;
125	enum ep0_state			state;		/* P: lock */
126	struct usb_gadgetfs_event	event [N_EVENT];
127	unsigned			ev_next;
128	struct fasync_struct		*fasync;
129	u8				current_config;
130
131	/* drivers reading ep0 MUST handle control requests (SETUP)
132	 * reported that way; else the host will time out.
133	 */
134	unsigned			usermode_setup : 1,
135					setup_in : 1,
136					setup_can_stall : 1,
137					setup_out_ready : 1,
138					setup_out_error : 1,
139					setup_abort : 1;
140	unsigned			setup_wLength;
141
142	/* the rest is basically write-once */
143	struct usb_config_descriptor	*config, *hs_config;
144	struct usb_device_descriptor	*dev;
145	struct usb_request		*req;
146	struct usb_gadget		*gadget;
147	struct list_head		epfiles;
148	void				*buf;
149	wait_queue_head_t		wait;
150	struct super_block		*sb;
151	struct dentry			*dentry;
152
153	/* except this scratch i/o buffer for ep0 */
154	u8				rbuf [256];
155};
156
157static inline void get_dev (struct dev_data *data)
158{
159	atomic_inc (&data->count);
160}
161
162static void put_dev (struct dev_data *data)
163{
164	if (likely (!atomic_dec_and_test (&data->count)))
165		return;
166	/* needs no more cleanup */
167	BUG_ON (waitqueue_active (&data->wait));
168	kfree (data);
169}
170
171static struct dev_data *dev_new (void)
172{
173	struct dev_data		*dev;
174
175	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
176	if (!dev)
177		return NULL;
178	dev->state = STATE_DEV_DISABLED;
179	atomic_set (&dev->count, 1);
180	spin_lock_init (&dev->lock);
181	INIT_LIST_HEAD (&dev->epfiles);
182	init_waitqueue_head (&dev->wait);
183	return dev;
184}
185
186/*----------------------------------------------------------------------*/
187
188/* other /dev/gadget/$ENDPOINT files represent endpoints */
189enum ep_state {
190	STATE_EP_DISABLED = 0,
191	STATE_EP_READY,
192	STATE_EP_ENABLED,
193	STATE_EP_UNBOUND,
194};
195
196struct ep_data {
197	struct mutex			lock;
198	enum ep_state			state;
199	atomic_t			count;
200	struct dev_data			*dev;
201	/* must hold dev->lock before accessing ep or req */
202	struct usb_ep			*ep;
203	struct usb_request		*req;
204	ssize_t				status;
205	char				name [16];
206	struct usb_endpoint_descriptor	desc, hs_desc;
207	struct list_head		epfiles;
208	wait_queue_head_t		wait;
209	struct dentry			*dentry;
210	struct inode			*inode;
211};
212
213static inline void get_ep (struct ep_data *data)
214{
215	atomic_inc (&data->count);
216}
217
218static void put_ep (struct ep_data *data)
219{
220	if (likely (!atomic_dec_and_test (&data->count)))
221		return;
222	put_dev (data->dev);
223	/* needs no more cleanup */
224	BUG_ON (!list_empty (&data->epfiles));
225	BUG_ON (waitqueue_active (&data->wait));
226	kfree (data);
227}
228
229/*----------------------------------------------------------------------*/
230
231/* most "how to use the hardware" policy choices are in userspace:
232 * mapping endpoint roles (which the driver needs) to the capabilities
233 * which the usb controller has.  most of those capabilities are exposed
234 * implicitly, starting with the driver name and then endpoint names.
235 */
236
237static const char *CHIP;
238
239/*----------------------------------------------------------------------*/
240
241/* NOTE:  don't use dev_printk calls before binding to the gadget
242 * at the end of ep0 configuration, or after unbind.
243 */
244
245/* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */
246#define xprintk(d,level,fmt,args...) \
247	printk(level "%s: " fmt , shortname , ## args)
248
249#ifdef DEBUG
250#define DBG(dev,fmt,args...) \
251	xprintk(dev , KERN_DEBUG , fmt , ## args)
252#else
253#define DBG(dev,fmt,args...) \
254	do { } while (0)
255#endif /* DEBUG */
256
257#ifdef VERBOSE_DEBUG
258#define VDEBUG	DBG
259#else
260#define VDEBUG(dev,fmt,args...) \
261	do { } while (0)
262#endif /* DEBUG */
263
264#define ERROR(dev,fmt,args...) \
265	xprintk(dev , KERN_ERR , fmt , ## args)
266#define INFO(dev,fmt,args...) \
267	xprintk(dev , KERN_INFO , fmt , ## args)
268
269
270/*----------------------------------------------------------------------*/
271
272/* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
273 *
274 * After opening, configure non-control endpoints.  Then use normal
275 * stream read() and write() requests; and maybe ioctl() to get more
276 * precise FIFO status when recovering from cancellation.
277 */
278
279static void epio_complete (struct usb_ep *ep, struct usb_request *req)
280{
281	struct ep_data	*epdata = ep->driver_data;
282
283	if (!req->context)
284		return;
285	if (req->status)
286		epdata->status = req->status;
287	else
288		epdata->status = req->actual;
289	complete ((struct completion *)req->context);
290}
291
292/* tasklock endpoint, returning when it's connected.
293 * still need dev->lock to use epdata->ep.
294 */
295static int
296get_ready_ep (unsigned f_flags, struct ep_data *epdata)
297{
298	int	val;
299
300	if (f_flags & O_NONBLOCK) {
301		if (!mutex_trylock(&epdata->lock))
302			goto nonblock;
303		if (epdata->state != STATE_EP_ENABLED) {
304			mutex_unlock(&epdata->lock);
305nonblock:
306			val = -EAGAIN;
307		} else
308			val = 0;
309		return val;
310	}
311
312	val = mutex_lock_interruptible(&epdata->lock);
313	if (val < 0)
314		return val;
315
316	switch (epdata->state) {
317	case STATE_EP_ENABLED:
318		break;
319	// case STATE_EP_DISABLED:		/* "can't happen" */
320	// case STATE_EP_READY:			/* "can't happen" */
321	default:				/* error! */
322		pr_debug ("%s: ep %p not available, state %d\n",
323				shortname, epdata, epdata->state);
324		// FALLTHROUGH
325	case STATE_EP_UNBOUND:			/* clean disconnect */
326		val = -ENODEV;
327		mutex_unlock(&epdata->lock);
328	}
329	return val;
330}
331
332static ssize_t
333ep_io (struct ep_data *epdata, void *buf, unsigned len)
334{
335	DECLARE_COMPLETION_ONSTACK (done);
336	int value;
337
338	spin_lock_irq (&epdata->dev->lock);
339	if (likely (epdata->ep != NULL)) {
340		struct usb_request	*req = epdata->req;
341
342		req->context = &done;
343		req->complete = epio_complete;
344		req->buf = buf;
345		req->length = len;
346		value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
347	} else
348		value = -ENODEV;
349	spin_unlock_irq (&epdata->dev->lock);
350
351	if (likely (value == 0)) {
352		value = wait_event_interruptible (done.wait, done.done);
353		if (value != 0) {
354			spin_lock_irq (&epdata->dev->lock);
355			if (likely (epdata->ep != NULL)) {
356				DBG (epdata->dev, "%s i/o interrupted\n",
357						epdata->name);
358				usb_ep_dequeue (epdata->ep, epdata->req);
359				spin_unlock_irq (&epdata->dev->lock);
360
361				wait_event (done.wait, done.done);
362				if (epdata->status == -ECONNRESET)
363					epdata->status = -EINTR;
364			} else {
365				spin_unlock_irq (&epdata->dev->lock);
366
367				DBG (epdata->dev, "endpoint gone\n");
368				epdata->status = -ENODEV;
369			}
370		}
371		return epdata->status;
372	}
373	return value;
374}
375
376
377/* handle a synchronous OUT bulk/intr/iso transfer */
378static ssize_t
379ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
380{
381	struct ep_data		*data = fd->private_data;
382	void			*kbuf;
383	ssize_t			value;
384
385	if ((value = get_ready_ep (fd->f_flags, data)) < 0)
386		return value;
387
388	/* halt any endpoint by doing a "wrong direction" i/o call */
389	if (usb_endpoint_dir_in(&data->desc)) {
390		if (usb_endpoint_xfer_isoc(&data->desc))
391			return -EINVAL;
392		DBG (data->dev, "%s halt\n", data->name);
393		spin_lock_irq (&data->dev->lock);
394		if (likely (data->ep != NULL))
395			usb_ep_set_halt (data->ep);
396		spin_unlock_irq (&data->dev->lock);
397		mutex_unlock(&data->lock);
398		return -EBADMSG;
399	}
400
401
402	value = -ENOMEM;
403	kbuf = kmalloc (len, GFP_KERNEL);
404	if (unlikely (!kbuf))
405		goto free1;
406
407	value = ep_io (data, kbuf, len);
408	VDEBUG (data->dev, "%s read %zu OUT, status %d\n",
409		data->name, len, (int) value);
410	if (value >= 0 && copy_to_user (buf, kbuf, value))
411		value = -EFAULT;
412
413free1:
414	mutex_unlock(&data->lock);
415	kfree (kbuf);
416	return value;
417}
418
419/* handle a synchronous IN bulk/intr/iso transfer */
420static ssize_t
421ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
422{
423	struct ep_data		*data = fd->private_data;
424	void			*kbuf;
425	ssize_t			value;
426
427	if ((value = get_ready_ep (fd->f_flags, data)) < 0)
428		return value;
429
430	/* halt any endpoint by doing a "wrong direction" i/o call */
431	if (!usb_endpoint_dir_in(&data->desc)) {
432		if (usb_endpoint_xfer_isoc(&data->desc))
433			return -EINVAL;
434		DBG (data->dev, "%s halt\n", data->name);
435		spin_lock_irq (&data->dev->lock);
436		if (likely (data->ep != NULL))
437			usb_ep_set_halt (data->ep);
438		spin_unlock_irq (&data->dev->lock);
439		mutex_unlock(&data->lock);
440		return -EBADMSG;
441	}
442
443
444	value = -ENOMEM;
445	kbuf = kmalloc (len, GFP_KERNEL);
446	if (!kbuf)
447		goto free1;
448	if (copy_from_user (kbuf, buf, len)) {
449		value = -EFAULT;
450		goto free1;
451	}
452
453	value = ep_io (data, kbuf, len);
454	VDEBUG (data->dev, "%s write %zu IN, status %d\n",
455		data->name, len, (int) value);
456free1:
457	mutex_unlock(&data->lock);
458	kfree (kbuf);
459	return value;
460}
461
462static int
463ep_release (struct inode *inode, struct file *fd)
464{
465	struct ep_data		*data = fd->private_data;
466	int value;
467
468	value = mutex_lock_interruptible(&data->lock);
469	if (value < 0)
470		return value;
471
472	/* clean up if this can be reopened */
473	if (data->state != STATE_EP_UNBOUND) {
474		data->state = STATE_EP_DISABLED;
475		data->desc.bDescriptorType = 0;
476		data->hs_desc.bDescriptorType = 0;
477		usb_ep_disable(data->ep);
478	}
479	mutex_unlock(&data->lock);
480	put_ep (data);
481	return 0;
482}
483
484static long ep_ioctl(struct file *fd, unsigned code, unsigned long value)
485{
486	struct ep_data		*data = fd->private_data;
487	int			status;
488
489	if ((status = get_ready_ep (fd->f_flags, data)) < 0)
490		return status;
491
492	spin_lock_irq (&data->dev->lock);
493	if (likely (data->ep != NULL)) {
494		switch (code) {
495		case GADGETFS_FIFO_STATUS:
496			status = usb_ep_fifo_status (data->ep);
497			break;
498		case GADGETFS_FIFO_FLUSH:
499			usb_ep_fifo_flush (data->ep);
500			break;
501		case GADGETFS_CLEAR_HALT:
502			status = usb_ep_clear_halt (data->ep);
503			break;
504		default:
505			status = -ENOTTY;
506		}
507	} else
508		status = -ENODEV;
509	spin_unlock_irq (&data->dev->lock);
510	mutex_unlock(&data->lock);
511	return status;
512}
513
514/*----------------------------------------------------------------------*/
515
516/* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */
517
518struct kiocb_priv {
519	struct usb_request	*req;
520	struct ep_data		*epdata;
521	void			*buf;
522	const struct iovec	*iv;
523	unsigned long		nr_segs;
524	unsigned		actual;
525};
526
527static int ep_aio_cancel(struct kiocb *iocb, struct io_event *e)
528{
529	struct kiocb_priv	*priv = iocb->private;
530	struct ep_data		*epdata;
531	int			value;
532
533	local_irq_disable();
534	epdata = priv->epdata;
535	// spin_lock(&epdata->dev->lock);
536	kiocbSetCancelled(iocb);
537	if (likely(epdata && epdata->ep && priv->req))
538		value = usb_ep_dequeue (epdata->ep, priv->req);
539	else
540		value = -EINVAL;
541	// spin_unlock(&epdata->dev->lock);
542	local_irq_enable();
543
544	aio_put_req(iocb);
545	return value;
546}
547
548static ssize_t ep_aio_read_retry(struct kiocb *iocb)
549{
550	struct kiocb_priv	*priv = iocb->private;
551	ssize_t			len, total;
552	void			*to_copy;
553	int			i;
554
555	/* we "retry" to get the right mm context for this: */
556
557	/* copy stuff into user buffers */
558	total = priv->actual;
559	len = 0;
560	to_copy = priv->buf;
561	for (i=0; i < priv->nr_segs; i++) {
562		ssize_t this = min((ssize_t)(priv->iv[i].iov_len), total);
563
564		if (copy_to_user(priv->iv[i].iov_base, to_copy, this)) {
565			if (len == 0)
566				len = -EFAULT;
567			break;
568		}
569
570		total -= this;
571		len += this;
572		to_copy += this;
573		if (total == 0)
574			break;
575	}
576	kfree(priv->buf);
577	kfree(priv);
578	return len;
579}
580
581static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req)
582{
583	struct kiocb		*iocb = req->context;
584	struct kiocb_priv	*priv = iocb->private;
585	struct ep_data		*epdata = priv->epdata;
586
587	/* lock against disconnect (and ideally, cancel) */
588	spin_lock(&epdata->dev->lock);
589	priv->req = NULL;
590	priv->epdata = NULL;
591
592	/* if this was a write or a read returning no data then we
593	 * don't need to copy anything to userspace, so we can
594	 * complete the aio request immediately.
595	 */
596	if (priv->iv == NULL || unlikely(req->actual == 0)) {
597		kfree(req->buf);
598		kfree(priv);
599		iocb->private = NULL;
600		/* aio_complete() reports bytes-transferred _and_ faults */
601		aio_complete(iocb, req->actual ? req->actual : req->status,
602				req->status);
603	} else {
604		/* retry() won't report both; so we hide some faults */
605		if (unlikely(0 != req->status))
606			DBG(epdata->dev, "%s fault %d len %d\n",
607				ep->name, req->status, req->actual);
608
609		priv->buf = req->buf;
610		priv->actual = req->actual;
611		kick_iocb(iocb);
612	}
613	spin_unlock(&epdata->dev->lock);
614
615	usb_ep_free_request(ep, req);
616	put_ep(epdata);
617}
618
619static ssize_t
620ep_aio_rwtail(
621	struct kiocb	*iocb,
622	char		*buf,
623	size_t		len,
624	struct ep_data	*epdata,
625	const struct iovec *iv,
626	unsigned long	nr_segs
627)
628{
629	struct kiocb_priv	*priv;
630	struct usb_request	*req;
631	ssize_t			value;
632
633	priv = kmalloc(sizeof *priv, GFP_KERNEL);
634	if (!priv) {
635		value = -ENOMEM;
636fail:
637		kfree(buf);
638		return value;
639	}
640	iocb->private = priv;
641	priv->iv = iv;
642	priv->nr_segs = nr_segs;
643
644	value = get_ready_ep(iocb->ki_filp->f_flags, epdata);
645	if (unlikely(value < 0)) {
646		kfree(priv);
647		goto fail;
648	}
649
650	iocb->ki_cancel = ep_aio_cancel;
651	get_ep(epdata);
652	priv->epdata = epdata;
653	priv->actual = 0;
654
655	/* each kiocb is coupled to one usb_request, but we can't
656	 * allocate or submit those if the host disconnected.
657	 */
658	spin_lock_irq(&epdata->dev->lock);
659	if (likely(epdata->ep)) {
660		req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC);
661		if (likely(req)) {
662			priv->req = req;
663			req->buf = buf;
664			req->length = len;
665			req->complete = ep_aio_complete;
666			req->context = iocb;
667			value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC);
668			if (unlikely(0 != value))
669				usb_ep_free_request(epdata->ep, req);
670		} else
671			value = -EAGAIN;
672	} else
673		value = -ENODEV;
674	spin_unlock_irq(&epdata->dev->lock);
675
676	mutex_unlock(&epdata->lock);
677
678	if (unlikely(value)) {
679		kfree(priv);
680		put_ep(epdata);
681	} else
682		value = (iv ? -EIOCBRETRY : -EIOCBQUEUED);
683	return value;
684}
685
686static ssize_t
687ep_aio_read(struct kiocb *iocb, const struct iovec *iov,
688		unsigned long nr_segs, loff_t o)
689{
690	struct ep_data		*epdata = iocb->ki_filp->private_data;
691	char			*buf;
692
693	if (unlikely(usb_endpoint_dir_in(&epdata->desc)))
694		return -EINVAL;
695
696	buf = kmalloc(iocb->ki_left, GFP_KERNEL);
697	if (unlikely(!buf))
698		return -ENOMEM;
699
700	iocb->ki_retry = ep_aio_read_retry;
701	return ep_aio_rwtail(iocb, buf, iocb->ki_left, epdata, iov, nr_segs);
702}
703
704static ssize_t
705ep_aio_write(struct kiocb *iocb, const struct iovec *iov,
706		unsigned long nr_segs, loff_t o)
707{
708	struct ep_data		*epdata = iocb->ki_filp->private_data;
709	char			*buf;
710	size_t			len = 0;
711	int			i = 0;
712
713	if (unlikely(!usb_endpoint_dir_in(&epdata->desc)))
714		return -EINVAL;
715
716	buf = kmalloc(iocb->ki_left, GFP_KERNEL);
717	if (unlikely(!buf))
718		return -ENOMEM;
719
720	for (i=0; i < nr_segs; i++) {
721		if (unlikely(copy_from_user(&buf[len], iov[i].iov_base,
722				iov[i].iov_len) != 0)) {
723			kfree(buf);
724			return -EFAULT;
725		}
726		len += iov[i].iov_len;
727	}
728	return ep_aio_rwtail(iocb, buf, len, epdata, NULL, 0);
729}
730
731/*----------------------------------------------------------------------*/
732
733/* used after endpoint configuration */
734static const struct file_operations ep_io_operations = {
735	.owner =	THIS_MODULE,
736	.llseek =	no_llseek,
737
738	.read =		ep_read,
739	.write =	ep_write,
740	.unlocked_ioctl = ep_ioctl,
741	.release =	ep_release,
742
743	.aio_read =	ep_aio_read,
744	.aio_write =	ep_aio_write,
745};
746
747/* ENDPOINT INITIALIZATION
748 *
749 *     fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
750 *     status = write (fd, descriptors, sizeof descriptors)
751 *
752 * That write establishes the endpoint configuration, configuring
753 * the controller to process bulk, interrupt, or isochronous transfers
754 * at the right maxpacket size, and so on.
755 *
756 * The descriptors are message type 1, identified by a host order u32
757 * at the beginning of what's written.  Descriptor order is: full/low
758 * speed descriptor, then optional high speed descriptor.
759 */
760static ssize_t
761ep_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
762{
763	struct ep_data		*data = fd->private_data;
764	struct usb_ep		*ep;
765	u32			tag;
766	int			value, length = len;
767
768	value = mutex_lock_interruptible(&data->lock);
769	if (value < 0)
770		return value;
771
772	if (data->state != STATE_EP_READY) {
773		value = -EL2HLT;
774		goto fail;
775	}
776
777	value = len;
778	if (len < USB_DT_ENDPOINT_SIZE + 4)
779		goto fail0;
780
781	/* we might need to change message format someday */
782	if (copy_from_user (&tag, buf, 4)) {
783		goto fail1;
784	}
785	if (tag != 1) {
786		DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
787		goto fail0;
788	}
789	buf += 4;
790	len -= 4;
791
792	/* NOTE:  audio endpoint extensions not accepted here;
793	 * just don't include the extra bytes.
794	 */
795
796	/* full/low speed descriptor, then high speed */
797	if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
798		goto fail1;
799	}
800	if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
801			|| data->desc.bDescriptorType != USB_DT_ENDPOINT)
802		goto fail0;
803	if (len != USB_DT_ENDPOINT_SIZE) {
804		if (len != 2 * USB_DT_ENDPOINT_SIZE)
805			goto fail0;
806		if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
807					USB_DT_ENDPOINT_SIZE)) {
808			goto fail1;
809		}
810		if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
811				|| data->hs_desc.bDescriptorType
812					!= USB_DT_ENDPOINT) {
813			DBG(data->dev, "config %s, bad hs length or type\n",
814					data->name);
815			goto fail0;
816		}
817	}
818
819	spin_lock_irq (&data->dev->lock);
820	if (data->dev->state == STATE_DEV_UNBOUND) {
821		value = -ENOENT;
822		goto gone;
823	} else if ((ep = data->ep) == NULL) {
824		value = -ENODEV;
825		goto gone;
826	}
827	switch (data->dev->gadget->speed) {
828	case USB_SPEED_LOW:
829	case USB_SPEED_FULL:
830		value = usb_ep_enable (ep, &data->desc);
831		if (value == 0)
832			data->state = STATE_EP_ENABLED;
833		break;
834#ifdef	CONFIG_USB_GADGET_DUALSPEED
835	case USB_SPEED_HIGH:
836		/* fails if caller didn't provide that descriptor... */
837		value = usb_ep_enable (ep, &data->hs_desc);
838		if (value == 0)
839			data->state = STATE_EP_ENABLED;
840		break;
841#endif
842	default:
843		DBG(data->dev, "unconnected, %s init abandoned\n",
844				data->name);
845		value = -EINVAL;
846	}
847	if (value == 0) {
848		fd->f_op = &ep_io_operations;
849		value = length;
850	}
851gone:
852	spin_unlock_irq (&data->dev->lock);
853	if (value < 0) {
854fail:
855		data->desc.bDescriptorType = 0;
856		data->hs_desc.bDescriptorType = 0;
857	}
858	mutex_unlock(&data->lock);
859	return value;
860fail0:
861	value = -EINVAL;
862	goto fail;
863fail1:
864	value = -EFAULT;
865	goto fail;
866}
867
868static int
869ep_open (struct inode *inode, struct file *fd)
870{
871	struct ep_data		*data = inode->i_private;
872	int			value = -EBUSY;
873
874	if (mutex_lock_interruptible(&data->lock) != 0)
875		return -EINTR;
876	spin_lock_irq (&data->dev->lock);
877	if (data->dev->state == STATE_DEV_UNBOUND)
878		value = -ENOENT;
879	else if (data->state == STATE_EP_DISABLED) {
880		value = 0;
881		data->state = STATE_EP_READY;
882		get_ep (data);
883		fd->private_data = data;
884		VDEBUG (data->dev, "%s ready\n", data->name);
885	} else
886		DBG (data->dev, "%s state %d\n",
887			data->name, data->state);
888	spin_unlock_irq (&data->dev->lock);
889	mutex_unlock(&data->lock);
890	return value;
891}
892
893/* used before endpoint configuration */
894static const struct file_operations ep_config_operations = {
895	.owner =	THIS_MODULE,
896	.llseek =	no_llseek,
897
898	.open =		ep_open,
899	.write =	ep_config,
900	.release =	ep_release,
901};
902
903/*----------------------------------------------------------------------*/
904
905/* EP0 IMPLEMENTATION can be partly in userspace.
906 *
907 * Drivers that use this facility receive various events, including
908 * control requests the kernel doesn't handle.  Drivers that don't
909 * use this facility may be too simple-minded for real applications.
910 */
911
912static inline void ep0_readable (struct dev_data *dev)
913{
914	wake_up (&dev->wait);
915	kill_fasync (&dev->fasync, SIGIO, POLL_IN);
916}
917
918static void clean_req (struct usb_ep *ep, struct usb_request *req)
919{
920	struct dev_data		*dev = ep->driver_data;
921
922	if (req->buf != dev->rbuf) {
923		kfree(req->buf);
924		req->buf = dev->rbuf;
925		req->dma = DMA_ADDR_INVALID;
926	}
927	req->complete = epio_complete;
928	dev->setup_out_ready = 0;
929}
930
931static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
932{
933	struct dev_data		*dev = ep->driver_data;
934	unsigned long		flags;
935	int			free = 1;
936
937	/* for control OUT, data must still get to userspace */
938	spin_lock_irqsave(&dev->lock, flags);
939	if (!dev->setup_in) {
940		dev->setup_out_error = (req->status != 0);
941		if (!dev->setup_out_error)
942			free = 0;
943		dev->setup_out_ready = 1;
944		ep0_readable (dev);
945	}
946
947	/* clean up as appropriate */
948	if (free && req->buf != &dev->rbuf)
949		clean_req (ep, req);
950	req->complete = epio_complete;
951	spin_unlock_irqrestore(&dev->lock, flags);
952}
953
954static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
955{
956	struct dev_data	*dev = ep->driver_data;
957
958	if (dev->setup_out_ready) {
959		DBG (dev, "ep0 request busy!\n");
960		return -EBUSY;
961	}
962	if (len > sizeof (dev->rbuf))
963		req->buf = kmalloc(len, GFP_ATOMIC);
964	if (req->buf == NULL) {
965		req->buf = dev->rbuf;
966		return -ENOMEM;
967	}
968	req->complete = ep0_complete;
969	req->length = len;
970	req->zero = 0;
971	return 0;
972}
973
974static ssize_t
975ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
976{
977	struct dev_data			*dev = fd->private_data;
978	ssize_t				retval;
979	enum ep0_state			state;
980
981	spin_lock_irq (&dev->lock);
982
983	/* report fd mode change before acting on it */
984	if (dev->setup_abort) {
985		dev->setup_abort = 0;
986		retval = -EIDRM;
987		goto done;
988	}
989
990	/* control DATA stage */
991	if ((state = dev->state) == STATE_DEV_SETUP) {
992
993		if (dev->setup_in) {		/* stall IN */
994			VDEBUG(dev, "ep0in stall\n");
995			(void) usb_ep_set_halt (dev->gadget->ep0);
996			retval = -EL2HLT;
997			dev->state = STATE_DEV_CONNECTED;
998
999		} else if (len == 0) {		/* ack SET_CONFIGURATION etc */
1000			struct usb_ep		*ep = dev->gadget->ep0;
1001			struct usb_request	*req = dev->req;
1002
1003			if ((retval = setup_req (ep, req, 0)) == 0)
1004				retval = usb_ep_queue (ep, req, GFP_ATOMIC);
1005			dev->state = STATE_DEV_CONNECTED;
1006
1007			/* assume that was SET_CONFIGURATION */
1008			if (dev->current_config) {
1009				unsigned power;
1010
1011				if (gadget_is_dualspeed(dev->gadget)
1012						&& (dev->gadget->speed
1013							== USB_SPEED_HIGH))
1014					power = dev->hs_config->bMaxPower;
1015				else
1016					power = dev->config->bMaxPower;
1017				usb_gadget_vbus_draw(dev->gadget, 2 * power);
1018			}
1019
1020		} else {			/* collect OUT data */
1021			if ((fd->f_flags & O_NONBLOCK) != 0
1022					&& !dev->setup_out_ready) {
1023				retval = -EAGAIN;
1024				goto done;
1025			}
1026			spin_unlock_irq (&dev->lock);
1027			retval = wait_event_interruptible (dev->wait,
1028					dev->setup_out_ready != 0);
1029
1030			spin_lock_irq (&dev->lock);
1031			if (retval)
1032				goto done;
1033
1034			if (dev->state != STATE_DEV_SETUP) {
1035				retval = -ECANCELED;
1036				goto done;
1037			}
1038			dev->state = STATE_DEV_CONNECTED;
1039
1040			if (dev->setup_out_error)
1041				retval = -EIO;
1042			else {
1043				len = min (len, (size_t)dev->req->actual);
1044				if (copy_to_user (buf, dev->req->buf, len))
1045					retval = -EFAULT;
1046				clean_req (dev->gadget->ep0, dev->req);
1047				/* NOTE userspace can't yet choose to stall */
1048			}
1049		}
1050		goto done;
1051	}
1052
1053	/* else normal: return event data */
1054	if (len < sizeof dev->event [0]) {
1055		retval = -EINVAL;
1056		goto done;
1057	}
1058	len -= len % sizeof (struct usb_gadgetfs_event);
1059	dev->usermode_setup = 1;
1060
1061scan:
1062	/* return queued events right away */
1063	if (dev->ev_next != 0) {
1064		unsigned		i, n;
1065
1066		n = len / sizeof (struct usb_gadgetfs_event);
1067		if (dev->ev_next < n)
1068			n = dev->ev_next;
1069
1070		/* ep0 i/o has special semantics during STATE_DEV_SETUP */
1071		for (i = 0; i < n; i++) {
1072			if (dev->event [i].type == GADGETFS_SETUP) {
1073				dev->state = STATE_DEV_SETUP;
1074				n = i + 1;
1075				break;
1076			}
1077		}
1078		spin_unlock_irq (&dev->lock);
1079		len = n * sizeof (struct usb_gadgetfs_event);
1080		if (copy_to_user (buf, &dev->event, len))
1081			retval = -EFAULT;
1082		else
1083			retval = len;
1084		if (len > 0) {
1085			/* NOTE this doesn't guard against broken drivers;
1086			 * concurrent ep0 readers may lose events.
1087			 */
1088			spin_lock_irq (&dev->lock);
1089			if (dev->ev_next > n) {
1090				memmove(&dev->event[0], &dev->event[n],
1091					sizeof (struct usb_gadgetfs_event)
1092						* (dev->ev_next - n));
1093			}
1094			dev->ev_next -= n;
1095			spin_unlock_irq (&dev->lock);
1096		}
1097		return retval;
1098	}
1099	if (fd->f_flags & O_NONBLOCK) {
1100		retval = -EAGAIN;
1101		goto done;
1102	}
1103
1104	switch (state) {
1105	default:
1106		DBG (dev, "fail %s, state %d\n", __func__, state);
1107		retval = -ESRCH;
1108		break;
1109	case STATE_DEV_UNCONNECTED:
1110	case STATE_DEV_CONNECTED:
1111		spin_unlock_irq (&dev->lock);
1112		DBG (dev, "%s wait\n", __func__);
1113
1114		/* wait for events */
1115		retval = wait_event_interruptible (dev->wait,
1116				dev->ev_next != 0);
1117		if (retval < 0)
1118			return retval;
1119		spin_lock_irq (&dev->lock);
1120		goto scan;
1121	}
1122
1123done:
1124	spin_unlock_irq (&dev->lock);
1125	return retval;
1126}
1127
1128static struct usb_gadgetfs_event *
1129next_event (struct dev_data *dev, enum usb_gadgetfs_event_type type)
1130{
1131	struct usb_gadgetfs_event	*event;
1132	unsigned			i;
1133
1134	switch (type) {
1135	/* these events purge the queue */
1136	case GADGETFS_DISCONNECT:
1137		if (dev->state == STATE_DEV_SETUP)
1138			dev->setup_abort = 1;
1139		// FALL THROUGH
1140	case GADGETFS_CONNECT:
1141		dev->ev_next = 0;
1142		break;
1143	case GADGETFS_SETUP:		/* previous request timed out */
1144	case GADGETFS_SUSPEND:		/* same effect */
1145		/* these events can't be repeated */
1146		for (i = 0; i != dev->ev_next; i++) {
1147			if (dev->event [i].type != type)
1148				continue;
1149			DBG(dev, "discard old event[%d] %d\n", i, type);
1150			dev->ev_next--;
1151			if (i == dev->ev_next)
1152				break;
1153			/* indices start at zero, for simplicity */
1154			memmove (&dev->event [i], &dev->event [i + 1],
1155				sizeof (struct usb_gadgetfs_event)
1156					* (dev->ev_next - i));
1157		}
1158		break;
1159	default:
1160		BUG ();
1161	}
1162	VDEBUG(dev, "event[%d] = %d\n", dev->ev_next, type);
1163	event = &dev->event [dev->ev_next++];
1164	BUG_ON (dev->ev_next > N_EVENT);
1165	memset (event, 0, sizeof *event);
1166	event->type = type;
1167	return event;
1168}
1169
1170static ssize_t
1171ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1172{
1173	struct dev_data		*dev = fd->private_data;
1174	ssize_t			retval = -ESRCH;
1175
1176	spin_lock_irq (&dev->lock);
1177
1178	/* report fd mode change before acting on it */
1179	if (dev->setup_abort) {
1180		dev->setup_abort = 0;
1181		retval = -EIDRM;
1182
1183	/* data and/or status stage for control request */
1184	} else if (dev->state == STATE_DEV_SETUP) {
1185
1186		/* IN DATA+STATUS caller makes len <= wLength */
1187		if (dev->setup_in) {
1188			retval = setup_req (dev->gadget->ep0, dev->req, len);
1189			if (retval == 0) {
1190				dev->state = STATE_DEV_CONNECTED;
1191				spin_unlock_irq (&dev->lock);
1192				if (copy_from_user (dev->req->buf, buf, len))
1193					retval = -EFAULT;
1194				else {
1195					if (len < dev->setup_wLength)
1196						dev->req->zero = 1;
1197					retval = usb_ep_queue (
1198						dev->gadget->ep0, dev->req,
1199						GFP_KERNEL);
1200				}
1201				if (retval < 0) {
1202					spin_lock_irq (&dev->lock);
1203					clean_req (dev->gadget->ep0, dev->req);
1204					spin_unlock_irq (&dev->lock);
1205				} else
1206					retval = len;
1207
1208				return retval;
1209			}
1210
1211		/* can stall some OUT transfers */
1212		} else if (dev->setup_can_stall) {
1213			VDEBUG(dev, "ep0out stall\n");
1214			(void) usb_ep_set_halt (dev->gadget->ep0);
1215			retval = -EL2HLT;
1216			dev->state = STATE_DEV_CONNECTED;
1217		} else {
1218			DBG(dev, "bogus ep0out stall!\n");
1219		}
1220	} else
1221		DBG (dev, "fail %s, state %d\n", __func__, dev->state);
1222
1223	spin_unlock_irq (&dev->lock);
1224	return retval;
1225}
1226
1227static int
1228ep0_fasync (int f, struct file *fd, int on)
1229{
1230	struct dev_data		*dev = fd->private_data;
1231	// caller must F_SETOWN before signal delivery happens
1232	VDEBUG (dev, "%s %s\n", __func__, on ? "on" : "off");
1233	return fasync_helper (f, fd, on, &dev->fasync);
1234}
1235
1236static struct usb_gadget_driver gadgetfs_driver;
1237
1238static int
1239dev_release (struct inode *inode, struct file *fd)
1240{
1241	struct dev_data		*dev = fd->private_data;
1242
1243	/* closing ep0 === shutdown all */
1244
1245	usb_gadget_unregister_driver (&gadgetfs_driver);
1246
1247	/* at this point "good" hardware has disconnected the
1248	 * device from USB; the host won't see it any more.
1249	 * alternatively, all host requests will time out.
1250	 */
1251
1252	kfree (dev->buf);
1253	dev->buf = NULL;
1254	put_dev (dev);
1255
1256	/* other endpoints were all decoupled from this device */
1257	spin_lock_irq(&dev->lock);
1258	dev->state = STATE_DEV_DISABLED;
1259	spin_unlock_irq(&dev->lock);
1260	return 0;
1261}
1262
1263static unsigned int
1264ep0_poll (struct file *fd, poll_table *wait)
1265{
1266       struct dev_data         *dev = fd->private_data;
1267       int                     mask = 0;
1268
1269       poll_wait(fd, &dev->wait, wait);
1270
1271       spin_lock_irq (&dev->lock);
1272
1273       /* report fd mode change before acting on it */
1274       if (dev->setup_abort) {
1275               dev->setup_abort = 0;
1276               mask = POLLHUP;
1277               goto out;
1278       }
1279
1280       if (dev->state == STATE_DEV_SETUP) {
1281               if (dev->setup_in || dev->setup_can_stall)
1282                       mask = POLLOUT;
1283       } else {
1284               if (dev->ev_next != 0)
1285                       mask = POLLIN;
1286       }
1287out:
1288       spin_unlock_irq(&dev->lock);
1289       return mask;
1290}
1291
1292static long dev_ioctl (struct file *fd, unsigned code, unsigned long value)
1293{
1294	struct dev_data		*dev = fd->private_data;
1295	struct usb_gadget	*gadget = dev->gadget;
1296	long ret = -ENOTTY;
1297
1298	if (gadget->ops->ioctl)
1299		ret = gadget->ops->ioctl (gadget, code, value);
1300
1301	return ret;
1302}
1303
1304/* used after device configuration */
1305static const struct file_operations ep0_io_operations = {
1306	.owner =	THIS_MODULE,
1307	.llseek =	no_llseek,
1308
1309	.read =		ep0_read,
1310	.write =	ep0_write,
1311	.fasync =	ep0_fasync,
1312	.poll =		ep0_poll,
1313	.unlocked_ioctl =	dev_ioctl,
1314	.release =	dev_release,
1315};
1316
1317/*----------------------------------------------------------------------*/
1318
1319/* The in-kernel gadget driver handles most ep0 issues, in particular
1320 * enumerating the single configuration (as provided from user space).
1321 *
1322 * Unrecognized ep0 requests may be handled in user space.
1323 */
1324
1325#ifdef	CONFIG_USB_GADGET_DUALSPEED
1326static void make_qualifier (struct dev_data *dev)
1327{
1328	struct usb_qualifier_descriptor		qual;
1329	struct usb_device_descriptor		*desc;
1330
1331	qual.bLength = sizeof qual;
1332	qual.bDescriptorType = USB_DT_DEVICE_QUALIFIER;
1333	qual.bcdUSB = cpu_to_le16 (0x0200);
1334
1335	desc = dev->dev;
1336	qual.bDeviceClass = desc->bDeviceClass;
1337	qual.bDeviceSubClass = desc->bDeviceSubClass;
1338	qual.bDeviceProtocol = desc->bDeviceProtocol;
1339
1340	/* assumes ep0 uses the same value for both speeds ... */
1341	qual.bMaxPacketSize0 = desc->bMaxPacketSize0;
1342
1343	qual.bNumConfigurations = 1;
1344	qual.bRESERVED = 0;
1345
1346	memcpy (dev->rbuf, &qual, sizeof qual);
1347}
1348#endif
1349
1350static int
1351config_buf (struct dev_data *dev, u8 type, unsigned index)
1352{
1353	int		len;
1354	int		hs = 0;
1355
1356	/* only one configuration */
1357	if (index > 0)
1358		return -EINVAL;
1359
1360	if (gadget_is_dualspeed(dev->gadget)) {
1361		hs = (dev->gadget->speed == USB_SPEED_HIGH);
1362		if (type == USB_DT_OTHER_SPEED_CONFIG)
1363			hs = !hs;
1364	}
1365	if (hs) {
1366		dev->req->buf = dev->hs_config;
1367		len = le16_to_cpu(dev->hs_config->wTotalLength);
1368	} else {
1369		dev->req->buf = dev->config;
1370		len = le16_to_cpu(dev->config->wTotalLength);
1371	}
1372	((u8 *)dev->req->buf) [1] = type;
1373	return len;
1374}
1375
1376static int
1377gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1378{
1379	struct dev_data			*dev = get_gadget_data (gadget);
1380	struct usb_request		*req = dev->req;
1381	int				value = -EOPNOTSUPP;
1382	struct usb_gadgetfs_event	*event;
1383	u16				w_value = le16_to_cpu(ctrl->wValue);
1384	u16				w_length = le16_to_cpu(ctrl->wLength);
1385
1386	spin_lock (&dev->lock);
1387	dev->setup_abort = 0;
1388	if (dev->state == STATE_DEV_UNCONNECTED) {
1389		if (gadget_is_dualspeed(gadget)
1390				&& gadget->speed == USB_SPEED_HIGH
1391				&& dev->hs_config == NULL) {
1392			spin_unlock(&dev->lock);
1393			ERROR (dev, "no high speed config??\n");
1394			return -EINVAL;
1395		}
1396
1397		dev->state = STATE_DEV_CONNECTED;
1398		dev->dev->bMaxPacketSize0 = gadget->ep0->maxpacket;
1399
1400		INFO (dev, "connected\n");
1401		event = next_event (dev, GADGETFS_CONNECT);
1402		event->u.speed = gadget->speed;
1403		ep0_readable (dev);
1404
1405	/* host may have given up waiting for response.  we can miss control
1406	 * requests handled lower down (device/endpoint status and features);
1407	 * then ep0_{read,write} will report the wrong status. controller
1408	 * driver will have aborted pending i/o.
1409	 */
1410	} else if (dev->state == STATE_DEV_SETUP)
1411		dev->setup_abort = 1;
1412
1413	req->buf = dev->rbuf;
1414	req->dma = DMA_ADDR_INVALID;
1415	req->context = NULL;
1416	value = -EOPNOTSUPP;
1417	switch (ctrl->bRequest) {
1418
1419	case USB_REQ_GET_DESCRIPTOR:
1420		if (ctrl->bRequestType != USB_DIR_IN)
1421			goto unrecognized;
1422		switch (w_value >> 8) {
1423
1424		case USB_DT_DEVICE:
1425			value = min (w_length, (u16) sizeof *dev->dev);
1426			req->buf = dev->dev;
1427			break;
1428#ifdef	CONFIG_USB_GADGET_DUALSPEED
1429		case USB_DT_DEVICE_QUALIFIER:
1430			if (!dev->hs_config)
1431				break;
1432			value = min (w_length, (u16)
1433				sizeof (struct usb_qualifier_descriptor));
1434			make_qualifier (dev);
1435			break;
1436		case USB_DT_OTHER_SPEED_CONFIG:
1437			// FALLTHROUGH
1438#endif
1439		case USB_DT_CONFIG:
1440			value = config_buf (dev,
1441					w_value >> 8,
1442					w_value & 0xff);
1443			if (value >= 0)
1444				value = min (w_length, (u16) value);
1445			break;
1446		case USB_DT_STRING:
1447			goto unrecognized;
1448
1449		default:		// all others are errors
1450			break;
1451		}
1452		break;
1453
1454	/* currently one config, two speeds */
1455	case USB_REQ_SET_CONFIGURATION:
1456		if (ctrl->bRequestType != 0)
1457			goto unrecognized;
1458		if (0 == (u8) w_value) {
1459			value = 0;
1460			dev->current_config = 0;
1461			usb_gadget_vbus_draw(gadget, 8 /* mA */ );
1462			// user mode expected to disable endpoints
1463		} else {
1464			u8	config, power;
1465
1466			if (gadget_is_dualspeed(gadget)
1467					&& gadget->speed == USB_SPEED_HIGH) {
1468				config = dev->hs_config->bConfigurationValue;
1469				power = dev->hs_config->bMaxPower;
1470			} else {
1471				config = dev->config->bConfigurationValue;
1472				power = dev->config->bMaxPower;
1473			}
1474
1475			if (config == (u8) w_value) {
1476				value = 0;
1477				dev->current_config = config;
1478				usb_gadget_vbus_draw(gadget, 2 * power);
1479			}
1480		}
1481
1482		/* report SET_CONFIGURATION like any other control request,
1483		 * except that usermode may not stall this.  the next
1484		 * request mustn't be allowed start until this finishes:
1485		 * endpoints and threads set up, etc.
1486		 *
1487		 * NOTE:  older PXA hardware (before PXA 255: without UDCCFR)
1488		 * has bad/racey automagic that prevents synchronizing here.
1489		 * even kernel mode drivers often miss them.
1490		 */
1491		if (value == 0) {
1492			INFO (dev, "configuration #%d\n", dev->current_config);
1493			if (dev->usermode_setup) {
1494				dev->setup_can_stall = 0;
1495				goto delegate;
1496			}
1497		}
1498		break;
1499
1500#ifndef	CONFIG_USB_GADGET_PXA25X
1501	/* PXA automagically handles this request too */
1502	case USB_REQ_GET_CONFIGURATION:
1503		if (ctrl->bRequestType != 0x80)
1504			goto unrecognized;
1505		*(u8 *)req->buf = dev->current_config;
1506		value = min (w_length, (u16) 1);
1507		break;
1508#endif
1509
1510	default:
1511unrecognized:
1512		VDEBUG (dev, "%s req%02x.%02x v%04x i%04x l%d\n",
1513			dev->usermode_setup ? "delegate" : "fail",
1514			ctrl->bRequestType, ctrl->bRequest,
1515			w_value, le16_to_cpu(ctrl->wIndex), w_length);
1516
1517		/* if there's an ep0 reader, don't stall */
1518		if (dev->usermode_setup) {
1519			dev->setup_can_stall = 1;
1520delegate:
1521			dev->setup_in = (ctrl->bRequestType & USB_DIR_IN)
1522						? 1 : 0;
1523			dev->setup_wLength = w_length;
1524			dev->setup_out_ready = 0;
1525			dev->setup_out_error = 0;
1526			value = 0;
1527
1528			/* read DATA stage for OUT right away */
1529			if (unlikely (!dev->setup_in && w_length)) {
1530				value = setup_req (gadget->ep0, dev->req,
1531							w_length);
1532				if (value < 0)
1533					break;
1534				value = usb_ep_queue (gadget->ep0, dev->req,
1535							GFP_ATOMIC);
1536				if (value < 0) {
1537					clean_req (gadget->ep0, dev->req);
1538					break;
1539				}
1540
1541				/* we can't currently stall these */
1542				dev->setup_can_stall = 0;
1543			}
1544
1545			/* state changes when reader collects event */
1546			event = next_event (dev, GADGETFS_SETUP);
1547			event->u.setup = *ctrl;
1548			ep0_readable (dev);
1549			spin_unlock (&dev->lock);
1550			return 0;
1551		}
1552	}
1553
1554	/* proceed with data transfer and status phases? */
1555	if (value >= 0 && dev->state != STATE_DEV_SETUP) {
1556		req->length = value;
1557		req->zero = value < w_length;
1558		value = usb_ep_queue (gadget->ep0, req, GFP_ATOMIC);
1559		if (value < 0) {
1560			DBG (dev, "ep_queue --> %d\n", value);
1561			req->status = 0;
1562		}
1563	}
1564
1565	/* device stalls when value < 0 */
1566	spin_unlock (&dev->lock);
1567	return value;
1568}
1569
1570static void destroy_ep_files (struct dev_data *dev)
1571{
1572	struct list_head	*entry, *tmp;
1573
1574	DBG (dev, "%s %d\n", __func__, dev->state);
1575
1576	/* dev->state must prevent interference */
1577restart:
1578	spin_lock_irq (&dev->lock);
1579	list_for_each_safe (entry, tmp, &dev->epfiles) {
1580		struct ep_data	*ep;
1581		struct inode	*parent;
1582		struct dentry	*dentry;
1583
1584		/* break link to FS */
1585		ep = list_entry (entry, struct ep_data, epfiles);
1586		list_del_init (&ep->epfiles);
1587		dentry = ep->dentry;
1588		ep->dentry = NULL;
1589		parent = dentry->d_parent->d_inode;
1590
1591		/* break link to controller */
1592		if (ep->state == STATE_EP_ENABLED)
1593			(void) usb_ep_disable (ep->ep);
1594		ep->state = STATE_EP_UNBOUND;
1595		usb_ep_free_request (ep->ep, ep->req);
1596		ep->ep = NULL;
1597		wake_up (&ep->wait);
1598		put_ep (ep);
1599
1600		spin_unlock_irq (&dev->lock);
1601
1602		/* break link to dcache */
1603		mutex_lock (&parent->i_mutex);
1604		d_delete (dentry);
1605		dput (dentry);
1606		mutex_unlock (&parent->i_mutex);
1607
1608		/* fds may still be open */
1609		goto restart;
1610	}
1611	spin_unlock_irq (&dev->lock);
1612}
1613
1614
1615static struct inode *
1616gadgetfs_create_file (struct super_block *sb, char const *name,
1617		void *data, const struct file_operations *fops,
1618		struct dentry **dentry_p);
1619
1620static int activate_ep_files (struct dev_data *dev)
1621{
1622	struct usb_ep	*ep;
1623	struct ep_data	*data;
1624
1625	gadget_for_each_ep (ep, dev->gadget) {
1626
1627		data = kzalloc(sizeof(*data), GFP_KERNEL);
1628		if (!data)
1629			goto enomem0;
1630		data->state = STATE_EP_DISABLED;
1631		mutex_init(&data->lock);
1632		init_waitqueue_head (&data->wait);
1633
1634		strncpy (data->name, ep->name, sizeof (data->name) - 1);
1635		atomic_set (&data->count, 1);
1636		data->dev = dev;
1637		get_dev (dev);
1638
1639		data->ep = ep;
1640		ep->driver_data = data;
1641
1642		data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1643		if (!data->req)
1644			goto enomem1;
1645
1646		data->inode = gadgetfs_create_file (dev->sb, data->name,
1647				data, &ep_config_operations,
1648				&data->dentry);
1649		if (!data->inode)
1650			goto enomem2;
1651		list_add_tail (&data->epfiles, &dev->epfiles);
1652	}
1653	return 0;
1654
1655enomem2:
1656	usb_ep_free_request (ep, data->req);
1657enomem1:
1658	put_dev (dev);
1659	kfree (data);
1660enomem0:
1661	DBG (dev, "%s enomem\n", __func__);
1662	destroy_ep_files (dev);
1663	return -ENOMEM;
1664}
1665
1666static void
1667gadgetfs_unbind (struct usb_gadget *gadget)
1668{
1669	struct dev_data		*dev = get_gadget_data (gadget);
1670
1671	DBG (dev, "%s\n", __func__);
1672
1673	spin_lock_irq (&dev->lock);
1674	dev->state = STATE_DEV_UNBOUND;
1675	spin_unlock_irq (&dev->lock);
1676
1677	destroy_ep_files (dev);
1678	gadget->ep0->driver_data = NULL;
1679	set_gadget_data (gadget, NULL);
1680
1681	/* we've already been disconnected ... no i/o is active */
1682	if (dev->req)
1683		usb_ep_free_request (gadget->ep0, dev->req);
1684	DBG (dev, "%s done\n", __func__);
1685	put_dev (dev);
1686}
1687
1688static struct dev_data		*the_device;
1689
1690static int
1691gadgetfs_bind (struct usb_gadget *gadget)
1692{
1693	struct dev_data		*dev = the_device;
1694
1695	if (!dev)
1696		return -ESRCH;
1697	if (0 != strcmp (CHIP, gadget->name)) {
1698		pr_err("%s expected %s controller not %s\n",
1699			shortname, CHIP, gadget->name);
1700		return -ENODEV;
1701	}
1702
1703	set_gadget_data (gadget, dev);
1704	dev->gadget = gadget;
1705	gadget->ep0->driver_data = dev;
1706	dev->dev->bMaxPacketSize0 = gadget->ep0->maxpacket;
1707
1708	/* preallocate control response and buffer */
1709	dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1710	if (!dev->req)
1711		goto enomem;
1712	dev->req->context = NULL;
1713	dev->req->complete = epio_complete;
1714
1715	if (activate_ep_files (dev) < 0)
1716		goto enomem;
1717
1718	INFO (dev, "bound to %s driver\n", gadget->name);
1719	spin_lock_irq(&dev->lock);
1720	dev->state = STATE_DEV_UNCONNECTED;
1721	spin_unlock_irq(&dev->lock);
1722	get_dev (dev);
1723	return 0;
1724
1725enomem:
1726	gadgetfs_unbind (gadget);
1727	return -ENOMEM;
1728}
1729
1730static void
1731gadgetfs_disconnect (struct usb_gadget *gadget)
1732{
1733	struct dev_data		*dev = get_gadget_data (gadget);
1734
1735	spin_lock (&dev->lock);
1736	if (dev->state == STATE_DEV_UNCONNECTED)
1737		goto exit;
1738	dev->state = STATE_DEV_UNCONNECTED;
1739
1740	INFO (dev, "disconnected\n");
1741	next_event (dev, GADGETFS_DISCONNECT);
1742	ep0_readable (dev);
1743exit:
1744	spin_unlock (&dev->lock);
1745}
1746
1747static void
1748gadgetfs_suspend (struct usb_gadget *gadget)
1749{
1750	struct dev_data		*dev = get_gadget_data (gadget);
1751
1752	INFO (dev, "suspended from state %d\n", dev->state);
1753	spin_lock (&dev->lock);
1754	switch (dev->state) {
1755	case STATE_DEV_SETUP:		// VERY odd... host died??
1756	case STATE_DEV_CONNECTED:
1757	case STATE_DEV_UNCONNECTED:
1758		next_event (dev, GADGETFS_SUSPEND);
1759		ep0_readable (dev);
1760		/* FALLTHROUGH */
1761	default:
1762		break;
1763	}
1764	spin_unlock (&dev->lock);
1765}
1766
1767static struct usb_gadget_driver gadgetfs_driver = {
1768#ifdef	CONFIG_USB_GADGET_DUALSPEED
1769	.speed		= USB_SPEED_HIGH,
1770#else
1771	.speed		= USB_SPEED_FULL,
1772#endif
1773	.function	= (char *) driver_desc,
1774	.bind		= gadgetfs_bind,
1775	.unbind		= gadgetfs_unbind,
1776	.setup		= gadgetfs_setup,
1777	.disconnect	= gadgetfs_disconnect,
1778	.suspend	= gadgetfs_suspend,
1779
1780	.driver	= {
1781		.name		= (char *) shortname,
1782	},
1783};
1784
1785/*----------------------------------------------------------------------*/
1786
1787static void gadgetfs_nop(struct usb_gadget *arg) { }
1788
1789static int gadgetfs_probe (struct usb_gadget *gadget)
1790{
1791	CHIP = gadget->name;
1792	return -EISNAM;
1793}
1794
1795static struct usb_gadget_driver probe_driver = {
1796	.speed		= USB_SPEED_HIGH,
1797	.bind		= gadgetfs_probe,
1798	.unbind		= gadgetfs_nop,
1799	.setup		= (void *)gadgetfs_nop,
1800	.disconnect	= gadgetfs_nop,
1801	.driver	= {
1802		.name		= "nop",
1803	},
1804};
1805
1806
1807/* DEVICE INITIALIZATION
1808 *
1809 *     fd = open ("/dev/gadget/$CHIP", O_RDWR)
1810 *     status = write (fd, descriptors, sizeof descriptors)
1811 *
1812 * That write establishes the device configuration, so the kernel can
1813 * bind to the controller ... guaranteeing it can handle enumeration
1814 * at all necessary speeds.  Descriptor order is:
1815 *
1816 * . message tag (u32, host order) ... for now, must be zero; it
1817 *	would change to support features like multi-config devices
1818 * . full/low speed config ... all wTotalLength bytes (with interface,
1819 *	class, altsetting, endpoint, and other descriptors)
1820 * . high speed config ... all descriptors, for high speed operation;
1821 *	this one's optional except for high-speed hardware
1822 * . device descriptor
1823 *
1824 * Endpoints are not yet enabled. Drivers must wait until device
1825 * configuration and interface altsetting changes create
1826 * the need to configure (or unconfigure) them.
1827 *
1828 * After initialization, the device stays active for as long as that
1829 * $CHIP file is open.  Events must then be read from that descriptor,
1830 * such as configuration notifications.
1831 */
1832
1833static int is_valid_config (struct usb_config_descriptor *config)
1834{
1835	return config->bDescriptorType == USB_DT_CONFIG
1836		&& config->bLength == USB_DT_CONFIG_SIZE
1837		&& config->bConfigurationValue != 0
1838		&& (config->bmAttributes & USB_CONFIG_ATT_ONE) != 0
1839		&& (config->bmAttributes & USB_CONFIG_ATT_WAKEUP) == 0;
1840}
1841
1842static ssize_t
1843dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1844{
1845	struct dev_data		*dev = fd->private_data;
1846	ssize_t			value = len, length = len;
1847	unsigned		total;
1848	u32			tag;
1849	char			*kbuf;
1850
1851	if (len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4))
1852		return -EINVAL;
1853
1854	/* we might need to change message format someday */
1855	if (copy_from_user (&tag, buf, 4))
1856		return -EFAULT;
1857	if (tag != 0)
1858		return -EINVAL;
1859	buf += 4;
1860	length -= 4;
1861
1862	kbuf = memdup_user(buf, length);
1863	if (IS_ERR(kbuf))
1864		return PTR_ERR(kbuf);
1865
1866	spin_lock_irq (&dev->lock);
1867	value = -EINVAL;
1868	if (dev->buf)
1869		goto fail;
1870	dev->buf = kbuf;
1871
1872	/* full or low speed config */
1873	dev->config = (void *) kbuf;
1874	total = le16_to_cpu(dev->config->wTotalLength);
1875	if (!is_valid_config (dev->config) || total >= length)
1876		goto fail;
1877	kbuf += total;
1878	length -= total;
1879
1880	/* optional high speed config */
1881	if (kbuf [1] == USB_DT_CONFIG) {
1882		dev->hs_config = (void *) kbuf;
1883		total = le16_to_cpu(dev->hs_config->wTotalLength);
1884		if (!is_valid_config (dev->hs_config) || total >= length)
1885			goto fail;
1886		kbuf += total;
1887		length -= total;
1888	}
1889
1890	/* could support multiple configs, using another encoding! */
1891
1892	/* device descriptor (tweaked for paranoia) */
1893	if (length != USB_DT_DEVICE_SIZE)
1894		goto fail;
1895	dev->dev = (void *)kbuf;
1896	if (dev->dev->bLength != USB_DT_DEVICE_SIZE
1897			|| dev->dev->bDescriptorType != USB_DT_DEVICE
1898			|| dev->dev->bNumConfigurations != 1)
1899		goto fail;
1900	dev->dev->bNumConfigurations = 1;
1901	dev->dev->bcdUSB = cpu_to_le16 (0x0200);
1902
1903	/* triggers gadgetfs_bind(); then we can enumerate. */
1904	spin_unlock_irq (&dev->lock);
1905	value = usb_gadget_register_driver (&gadgetfs_driver);
1906	if (value != 0) {
1907		kfree (dev->buf);
1908		dev->buf = NULL;
1909	} else {
1910		/* at this point "good" hardware has for the first time
1911		 * let the USB the host see us.  alternatively, if users
1912		 * unplug/replug that will clear all the error state.
1913		 *
1914		 * note:  everything running before here was guaranteed
1915		 * to choke driver model style diagnostics.  from here
1916		 * on, they can work ... except in cleanup paths that
1917		 * kick in after the ep0 descriptor is closed.
1918		 */
1919		fd->f_op = &ep0_io_operations;
1920		value = len;
1921	}
1922	return value;
1923
1924fail:
1925	spin_unlock_irq (&dev->lock);
1926	pr_debug ("%s: %s fail %Zd, %p\n", shortname, __func__, value, dev);
1927	kfree (dev->buf);
1928	dev->buf = NULL;
1929	return value;
1930}
1931
1932static int
1933dev_open (struct inode *inode, struct file *fd)
1934{
1935	struct dev_data		*dev = inode->i_private;
1936	int			value = -EBUSY;
1937
1938	spin_lock_irq(&dev->lock);
1939	if (dev->state == STATE_DEV_DISABLED) {
1940		dev->ev_next = 0;
1941		dev->state = STATE_DEV_OPENED;
1942		fd->private_data = dev;
1943		get_dev (dev);
1944		value = 0;
1945	}
1946	spin_unlock_irq(&dev->lock);
1947	return value;
1948}
1949
1950static const struct file_operations dev_init_operations = {
1951	.owner =	THIS_MODULE,
1952	.llseek =	no_llseek,
1953
1954	.open =		dev_open,
1955	.write =	dev_config,
1956	.fasync =	ep0_fasync,
1957	.unlocked_ioctl = dev_ioctl,
1958	.release =	dev_release,
1959};
1960
1961/*----------------------------------------------------------------------*/
1962
1963/* FILESYSTEM AND SUPERBLOCK OPERATIONS
1964 *
1965 * Mounting the filesystem creates a controller file, used first for
1966 * device configuration then later for event monitoring.
1967 */
1968
1969
1970
1971static unsigned default_uid;
1972static unsigned default_gid;
1973static unsigned default_perm = S_IRUSR | S_IWUSR;
1974
1975module_param (default_uid, uint, 0644);
1976module_param (default_gid, uint, 0644);
1977module_param (default_perm, uint, 0644);
1978
1979
1980static struct inode *
1981gadgetfs_make_inode (struct super_block *sb,
1982		void *data, const struct file_operations *fops,
1983		int mode)
1984{
1985	struct inode *inode = new_inode (sb);
1986
1987	if (inode) {
1988		inode->i_mode = mode;
1989		inode->i_uid = default_uid;
1990		inode->i_gid = default_gid;
1991		inode->i_atime = inode->i_mtime = inode->i_ctime
1992				= CURRENT_TIME;
1993		inode->i_private = data;
1994		inode->i_fop = fops;
1995	}
1996	return inode;
1997}
1998
1999/* creates in fs root directory, so non-renamable and non-linkable.
2000 * so inode and dentry are paired, until device reconfig.
2001 */
2002static struct inode *
2003gadgetfs_create_file (struct super_block *sb, char const *name,
2004		void *data, const struct file_operations *fops,
2005		struct dentry **dentry_p)
2006{
2007	struct dentry	*dentry;
2008	struct inode	*inode;
2009
2010	dentry = d_alloc_name(sb->s_root, name);
2011	if (!dentry)
2012		return NULL;
2013
2014	inode = gadgetfs_make_inode (sb, data, fops,
2015			S_IFREG | (default_perm & S_IRWXUGO));
2016	if (!inode) {
2017		dput(dentry);
2018		return NULL;
2019	}
2020	d_add (dentry, inode);
2021	*dentry_p = dentry;
2022	return inode;
2023}
2024
2025static const struct super_operations gadget_fs_operations = {
2026	.statfs =	simple_statfs,
2027	.drop_inode =	generic_delete_inode,
2028};
2029
2030static int
2031gadgetfs_fill_super (struct super_block *sb, void *opts, int silent)
2032{
2033	struct inode	*inode;
2034	struct dentry	*d;
2035	struct dev_data	*dev;
2036
2037	if (the_device)
2038		return -ESRCH;
2039
2040	/* fake probe to determine $CHIP */
2041	(void) usb_gadget_register_driver (&probe_driver);
2042	if (!CHIP)
2043		return -ENODEV;
2044
2045	/* superblock */
2046	sb->s_blocksize = PAGE_CACHE_SIZE;
2047	sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
2048	sb->s_magic = GADGETFS_MAGIC;
2049	sb->s_op = &gadget_fs_operations;
2050	sb->s_time_gran = 1;
2051
2052	/* root inode */
2053	inode = gadgetfs_make_inode (sb,
2054			NULL, &simple_dir_operations,
2055			S_IFDIR | S_IRUGO | S_IXUGO);
2056	if (!inode)
2057		goto enomem0;
2058	inode->i_op = &simple_dir_inode_operations;
2059	if (!(d = d_alloc_root (inode)))
2060		goto enomem1;
2061	sb->s_root = d;
2062
2063	/* the ep0 file is named after the controller we expect;
2064	 * user mode code can use it for sanity checks, like we do.
2065	 */
2066	dev = dev_new ();
2067	if (!dev)
2068		goto enomem2;
2069
2070	dev->sb = sb;
2071	if (!gadgetfs_create_file (sb, CHIP,
2072				dev, &dev_init_operations,
2073				&dev->dentry))
2074		goto enomem3;
2075
2076	/* other endpoint files are available after hardware setup,
2077	 * from binding to a controller.
2078	 */
2079	the_device = dev;
2080	return 0;
2081
2082enomem3:
2083	put_dev (dev);
2084enomem2:
2085	dput (d);
2086enomem1:
2087	iput (inode);
2088enomem0:
2089	return -ENOMEM;
2090}
2091
2092/* "mount -t gadgetfs path /dev/gadget" ends up here */
2093static int
2094gadgetfs_get_sb (struct file_system_type *t, int flags,
2095		const char *path, void *opts, struct vfsmount *mnt)
2096{
2097	return get_sb_single (t, flags, opts, gadgetfs_fill_super, mnt);
2098}
2099
2100static void
2101gadgetfs_kill_sb (struct super_block *sb)
2102{
2103	kill_litter_super (sb);
2104	if (the_device) {
2105		put_dev (the_device);
2106		the_device = NULL;
2107	}
2108}
2109
2110/*----------------------------------------------------------------------*/
2111
2112static struct file_system_type gadgetfs_type = {
2113	.owner		= THIS_MODULE,
2114	.name		= shortname,
2115	.get_sb		= gadgetfs_get_sb,
2116	.kill_sb	= gadgetfs_kill_sb,
2117};
2118
2119/*----------------------------------------------------------------------*/
2120
2121static int __init init (void)
2122{
2123	int status;
2124
2125	status = register_filesystem (&gadgetfs_type);
2126	if (status == 0)
2127		pr_info ("%s: %s, version " DRIVER_VERSION "\n",
2128			shortname, driver_desc);
2129	return status;
2130}
2131module_init (init);
2132
2133static void __exit cleanup (void)
2134{
2135	pr_debug ("unregister %s\n", shortname);
2136	unregister_filesystem (&gadgetfs_type);
2137}
2138module_exit (cleanup);
2139