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