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
403	value = -ENOMEM;
404	kbuf = kmalloc (len, GFP_KERNEL);
405	if (unlikely (!kbuf))
406		goto free1;
407
408	value = ep_io (data, kbuf, len);
409	VDEBUG (data->dev, "%s read %zu OUT, status %d\n",
410		data->name, len, (int) value);
411	if (value >= 0 && copy_to_user (buf, kbuf, value))
412		value = -EFAULT;
413
414free1:
415	up (&data->lock);
416	kfree (kbuf);
417	return value;
418}
419
420/* handle a synchronous IN bulk/intr/iso transfer */
421static ssize_t
422ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
423{
424	struct ep_data		*data = fd->private_data;
425	void			*kbuf;
426	ssize_t			value;
427
428	if ((value = get_ready_ep (fd->f_flags, data)) < 0)
429		return value;
430
431	/* halt any endpoint by doing a "wrong direction" i/o call */
432	if (!(data->desc.bEndpointAddress & USB_DIR_IN)) {
433		if ((data->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
434				== USB_ENDPOINT_XFER_ISOC)
435			return -EINVAL;
436		DBG (data->dev, "%s halt\n", data->name);
437		spin_lock_irq (&data->dev->lock);
438		if (likely (data->ep != NULL))
439			usb_ep_set_halt (data->ep);
440		spin_unlock_irq (&data->dev->lock);
441		up (&data->lock);
442		return -EBADMSG;
443	}
444
445
446	value = -ENOMEM;
447	kbuf = kmalloc (len, GFP_KERNEL);
448	if (!kbuf)
449		goto free1;
450	if (copy_from_user (kbuf, buf, len)) {
451		value = -EFAULT;
452		goto free1;
453	}
454
455	value = ep_io (data, kbuf, len);
456	VDEBUG (data->dev, "%s write %zu IN, status %d\n",
457		data->name, len, (int) value);
458free1:
459	up (&data->lock);
460	kfree (kbuf);
461	return value;
462}
463
464static int
465ep_release (struct inode *inode, struct file *fd)
466{
467	struct ep_data		*data = fd->private_data;
468	int value;
469
470	if ((value = down_interruptible(&data->lock)) < 0)
471		return value;
472
473	/* clean up if this can be reopened */
474	if (data->state != STATE_EP_UNBOUND) {
475		data->state = STATE_EP_DISABLED;
476		data->desc.bDescriptorType = 0;
477		data->hs_desc.bDescriptorType = 0;
478		usb_ep_disable(data->ep);
479	}
480	up (&data->lock);
481	put_ep (data);
482	return 0;
483}
484
485static int ep_ioctl (struct inode *inode, struct file *fd,
486		unsigned code, unsigned long value)
487{
488	struct ep_data		*data = fd->private_data;
489	int			status;
490
491	if ((status = get_ready_ep (fd->f_flags, data)) < 0)
492		return status;
493
494	spin_lock_irq (&data->dev->lock);
495	if (likely (data->ep != NULL)) {
496		switch (code) {
497		case GADGETFS_FIFO_STATUS:
498			status = usb_ep_fifo_status (data->ep);
499			break;
500		case GADGETFS_FIFO_FLUSH:
501			usb_ep_fifo_flush (data->ep);
502			break;
503		case GADGETFS_CLEAR_HALT:
504			status = usb_ep_clear_halt (data->ep);
505			break;
506		default:
507			status = -ENOTTY;
508		}
509	} else
510		status = -ENODEV;
511	spin_unlock_irq (&data->dev->lock);
512	up (&data->lock);
513	return status;
514}
515
516/*----------------------------------------------------------------------*/
517
518/* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */
519
520struct kiocb_priv {
521	struct usb_request	*req;
522	struct ep_data		*epdata;
523	void			*buf;
524	const struct iovec	*iv;
525	unsigned long		nr_segs;
526	unsigned		actual;
527};
528
529static int ep_aio_cancel(struct kiocb *iocb, struct io_event *e)
530{
531	struct kiocb_priv	*priv = iocb->private;
532	struct ep_data		*epdata;
533	int			value;
534
535	local_irq_disable();
536	epdata = priv->epdata;
537	// spin_lock(&epdata->dev->lock);
538	kiocbSetCancelled(iocb);
539	if (likely(epdata && epdata->ep && priv->req))
540		value = usb_ep_dequeue (epdata->ep, priv->req);
541	else
542		value = -EINVAL;
543	// spin_unlock(&epdata->dev->lock);
544	local_irq_enable();
545
546	aio_put_req(iocb);
547	return value;
548}
549
550static ssize_t ep_aio_read_retry(struct kiocb *iocb)
551{
552	struct kiocb_priv	*priv = iocb->private;
553	ssize_t			len, total;
554	void			*to_copy;
555	int			i;
556
557	/* we "retry" to get the right mm context for this: */
558
559	/* copy stuff into user buffers */
560	total = priv->actual;
561	len = 0;
562	to_copy = priv->buf;
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, to_copy, this)) {
567			if (len == 0)
568				len = -EFAULT;
569			break;
570		}
571
572		total -= this;
573		len += this;
574		to_copy += this;
575		if (total == 0)
576			break;
577	}
578	kfree(priv->buf);
579	kfree(priv);
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
594	/* if this was a write or a read returning no data then we
595	 * don't need to copy anything to userspace, so we can
596	 * complete the aio request immediately.
597	 */
598	if (priv->iv == NULL || unlikely(req->actual == 0)) {
599		kfree(req->buf);
600		kfree(priv);
601		iocb->private = NULL;
602		/* aio_complete() reports bytes-transferred _and_ faults */
603		aio_complete(iocb, req->actual ? req->actual : req->status,
604				req->status);
605	} else {
606		/* retry() won't report both; so we hide some faults */
607		if (unlikely(0 != req->status))
608			DBG(epdata->dev, "%s fault %d len %d\n",
609				ep->name, req->status, req->actual);
610
611		priv->buf = req->buf;
612		priv->actual = req->actual;
613		kick_iocb(iocb);
614	}
615	spin_unlock(&epdata->dev->lock);
616
617	usb_ep_free_request(ep, req);
618	put_ep(epdata);
619}
620
621static ssize_t
622ep_aio_rwtail(
623	struct kiocb	*iocb,
624	char		*buf,
625	size_t		len,
626	struct ep_data	*epdata,
627	const struct iovec *iv,
628	unsigned long	nr_segs
629)
630{
631	struct kiocb_priv	*priv;
632	struct usb_request	*req;
633	ssize_t			value;
634
635	priv = kmalloc(sizeof *priv, GFP_KERNEL);
636	if (!priv) {
637		value = -ENOMEM;
638fail:
639		kfree(buf);
640		return value;
641	}
642	iocb->private = priv;
643	priv->iv = iv;
644	priv->nr_segs = nr_segs;
645
646	value = get_ready_ep(iocb->ki_filp->f_flags, epdata);
647	if (unlikely(value < 0)) {
648		kfree(priv);
649		goto fail;
650	}
651
652	iocb->ki_cancel = ep_aio_cancel;
653	get_ep(epdata);
654	priv->epdata = epdata;
655	priv->actual = 0;
656
657	/* each kiocb is coupled to one usb_request, but we can't
658	 * allocate or submit those if the host disconnected.
659	 */
660	spin_lock_irq(&epdata->dev->lock);
661	if (likely(epdata->ep)) {
662		req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC);
663		if (likely(req)) {
664			priv->req = req;
665			req->buf = buf;
666			req->length = len;
667			req->complete = ep_aio_complete;
668			req->context = iocb;
669			value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC);
670			if (unlikely(0 != value))
671				usb_ep_free_request(epdata->ep, req);
672		} else
673			value = -EAGAIN;
674	} else
675		value = -ENODEV;
676	spin_unlock_irq(&epdata->dev->lock);
677
678	up(&epdata->lock);
679
680	if (unlikely(value)) {
681		kfree(priv);
682		put_ep(epdata);
683	} else
684		value = (iv ? -EIOCBRETRY : -EIOCBQUEUED);
685	return value;
686}
687
688static ssize_t
689ep_aio_read(struct kiocb *iocb, const struct iovec *iov,
690		unsigned long nr_segs, loff_t o)
691{
692	struct ep_data		*epdata = iocb->ki_filp->private_data;
693	char			*buf;
694
695	if (unlikely(epdata->desc.bEndpointAddress & USB_DIR_IN))
696		return -EINVAL;
697
698	buf = kmalloc(iocb->ki_left, GFP_KERNEL);
699	if (unlikely(!buf))
700		return -ENOMEM;
701
702	iocb->ki_retry = ep_aio_read_retry;
703	return ep_aio_rwtail(iocb, buf, iocb->ki_left, epdata, iov, nr_segs);
704}
705
706static ssize_t
707ep_aio_write(struct kiocb *iocb, const struct iovec *iov,
708		unsigned long nr_segs, loff_t o)
709{
710	struct ep_data		*epdata = iocb->ki_filp->private_data;
711	char			*buf;
712	size_t			len = 0;
713	int			i = 0;
714
715	if (unlikely(!(epdata->desc.bEndpointAddress & USB_DIR_IN)))
716		return -EINVAL;
717
718	buf = kmalloc(iocb->ki_left, GFP_KERNEL);
719	if (unlikely(!buf))
720		return -ENOMEM;
721
722	for (i=0; i < nr_segs; i++) {
723		if (unlikely(copy_from_user(&buf[len], iov[i].iov_base,
724				iov[i].iov_len) != 0)) {
725			kfree(buf);
726			return -EFAULT;
727		}
728		len += iov[i].iov_len;
729	}
730	return ep_aio_rwtail(iocb, buf, len, epdata, NULL, 0);
731}
732
733/*----------------------------------------------------------------------*/
734
735/* used after endpoint configuration */
736static const struct file_operations ep_io_operations = {
737	.owner =	THIS_MODULE,
738	.llseek =	no_llseek,
739
740	.read =		ep_read,
741	.write =	ep_write,
742	.ioctl =	ep_ioctl,
743	.release =	ep_release,
744
745	.aio_read =	ep_aio_read,
746	.aio_write =	ep_aio_write,
747};
748
749/* ENDPOINT INITIALIZATION
750 *
751 *     fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
752 *     status = write (fd, descriptors, sizeof descriptors)
753 *
754 * That write establishes the endpoint configuration, configuring
755 * the controller to process bulk, interrupt, or isochronous transfers
756 * at the right maxpacket size, and so on.
757 *
758 * The descriptors are message type 1, identified by a host order u32
759 * at the beginning of what's written.  Descriptor order is: full/low
760 * speed descriptor, then optional high speed descriptor.
761 */
762static ssize_t
763ep_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
764{
765	struct ep_data		*data = fd->private_data;
766	struct usb_ep		*ep;
767	u32			tag;
768	int			value, length = len;
769
770	if ((value = down_interruptible (&data->lock)) < 0)
771		return value;
772
773	if (data->state != STATE_EP_READY) {
774		value = -EL2HLT;
775		goto fail;
776	}
777
778	value = len;
779	if (len < USB_DT_ENDPOINT_SIZE + 4)
780		goto fail0;
781
782	/* we might need to change message format someday */
783	if (copy_from_user (&tag, buf, 4)) {
784		goto fail1;
785	}
786	if (tag != 1) {
787		DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
788		goto fail0;
789	}
790	buf += 4;
791	len -= 4;
792
793	/* NOTE:  audio endpoint extensions not accepted here;
794	 * just don't include the extra bytes.
795	 */
796
797	/* full/low speed descriptor, then high speed */
798	if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
799		goto fail1;
800	}
801	if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
802			|| data->desc.bDescriptorType != USB_DT_ENDPOINT)
803		goto fail0;
804	if (len != USB_DT_ENDPOINT_SIZE) {
805		if (len != 2 * USB_DT_ENDPOINT_SIZE)
806			goto fail0;
807		if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
808					USB_DT_ENDPOINT_SIZE)) {
809			goto fail1;
810		}
811		if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
812				|| data->hs_desc.bDescriptorType
813					!= USB_DT_ENDPOINT) {
814			DBG(data->dev, "config %s, bad hs length or type\n",
815					data->name);
816			goto fail0;
817		}
818	}
819
820	spin_lock_irq (&data->dev->lock);
821	if (data->dev->state == STATE_DEV_UNBOUND) {
822		value = -ENOENT;
823		goto gone;
824	} else if ((ep = data->ep) == NULL) {
825		value = -ENODEV;
826		goto gone;
827	}
828	switch (data->dev->gadget->speed) {
829	case USB_SPEED_LOW:
830	case USB_SPEED_FULL:
831		value = usb_ep_enable (ep, &data->desc);
832		if (value == 0)
833			data->state = STATE_EP_ENABLED;
834		break;
835#ifdef	CONFIG_USB_GADGET_DUALSPEED
836	case USB_SPEED_HIGH:
837		/* fails if caller didn't provide that descriptor... */
838		value = usb_ep_enable (ep, &data->hs_desc);
839		if (value == 0)
840			data->state = STATE_EP_ENABLED;
841		break;
842#endif
843	default:
844		DBG(data->dev, "unconnected, %s init abandoned\n",
845				data->name);
846		value = -EINVAL;
847	}
848	if (value == 0) {
849		fd->f_op = &ep_io_operations;
850		value = length;
851	}
852gone:
853	spin_unlock_irq (&data->dev->lock);
854	if (value < 0) {
855fail:
856		data->desc.bDescriptorType = 0;
857		data->hs_desc.bDescriptorType = 0;
858	}
859	up (&data->lock);
860	return value;
861fail0:
862	value = -EINVAL;
863	goto fail;
864fail1:
865	value = -EFAULT;
866	goto fail;
867}
868
869static int
870ep_open (struct inode *inode, struct file *fd)
871{
872	struct ep_data		*data = inode->i_private;
873	int			value = -EBUSY;
874
875	if (down_interruptible (&data->lock) != 0)
876		return -EINTR;
877	spin_lock_irq (&data->dev->lock);
878	if (data->dev->state == STATE_DEV_UNBOUND)
879		value = -ENOENT;
880	else if (data->state == STATE_EP_DISABLED) {
881		value = 0;
882		data->state = STATE_EP_READY;
883		get_ep (data);
884		fd->private_data = data;
885		VDEBUG (data->dev, "%s ready\n", data->name);
886	} else
887		DBG (data->dev, "%s state %d\n",
888			data->name, data->state);
889	spin_unlock_irq (&data->dev->lock);
890	up (&data->lock);
891	return value;
892}
893
894/* used before endpoint configuration */
895static const struct file_operations ep_config_operations = {
896	.owner =	THIS_MODULE,
897	.llseek =	no_llseek,
898
899	.open =		ep_open,
900	.write =	ep_config,
901	.release =	ep_release,
902};
903
904/*----------------------------------------------------------------------*/
905
906/* EP0 IMPLEMENTATION can be partly in userspace.
907 *
908 * Drivers that use this facility receive various events, including
909 * control requests the kernel doesn't handle.  Drivers that don't
910 * use this facility may be too simple-minded for real applications.
911 */
912
913static inline void ep0_readable (struct dev_data *dev)
914{
915	wake_up (&dev->wait);
916	kill_fasync (&dev->fasync, SIGIO, POLL_IN);
917}
918
919static void clean_req (struct usb_ep *ep, struct usb_request *req)
920{
921	struct dev_data		*dev = ep->driver_data;
922
923	if (req->buf != dev->rbuf) {
924		usb_ep_free_buffer (ep, req->buf, req->dma, req->length);
925		req->buf = dev->rbuf;
926		req->dma = DMA_ADDR_INVALID;
927	}
928	req->complete = epio_complete;
929	dev->setup_out_ready = 0;
930}
931
932static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
933{
934	struct dev_data		*dev = ep->driver_data;
935	unsigned long		flags;
936	int			free = 1;
937
938	/* for control OUT, data must still get to userspace */
939	spin_lock_irqsave(&dev->lock, flags);
940	if (!dev->setup_in) {
941		dev->setup_out_error = (req->status != 0);
942		if (!dev->setup_out_error)
943			free = 0;
944		dev->setup_out_ready = 1;
945		ep0_readable (dev);
946	}
947
948	/* clean up as appropriate */
949	if (free && req->buf != &dev->rbuf)
950		clean_req (ep, req);
951	req->complete = epio_complete;
952	spin_unlock_irqrestore(&dev->lock, flags);
953}
954
955static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
956{
957	struct dev_data	*dev = ep->driver_data;
958
959	if (dev->setup_out_ready) {
960		DBG (dev, "ep0 request busy!\n");
961		return -EBUSY;
962	}
963	if (len > sizeof (dev->rbuf))
964		req->buf = usb_ep_alloc_buffer (ep, len, &req->dma, GFP_ATOMIC);
965	if (req->buf == 0) {
966		req->buf = dev->rbuf;
967		return -ENOMEM;
968	}
969	req->complete = ep0_complete;
970	req->length = len;
971	req->zero = 0;
972	return 0;
973}
974
975static ssize_t
976ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
977{
978	struct dev_data			*dev = fd->private_data;
979	ssize_t				retval;
980	enum ep0_state			state;
981
982	spin_lock_irq (&dev->lock);
983
984	/* report fd mode change before acting on it */
985	if (dev->setup_abort) {
986		dev->setup_abort = 0;
987		retval = -EIDRM;
988		goto done;
989	}
990
991	/* control DATA stage */
992	if ((state = dev->state) == STATE_DEV_SETUP) {
993
994		if (dev->setup_in) {		/* stall IN */
995			VDEBUG(dev, "ep0in stall\n");
996			(void) usb_ep_set_halt (dev->gadget->ep0);
997			retval = -EL2HLT;
998			dev->state = STATE_DEV_CONNECTED;
999
1000		} else if (len == 0) {		/* ack SET_CONFIGURATION etc */
1001			struct usb_ep		*ep = dev->gadget->ep0;
1002			struct usb_request	*req = dev->req;
1003
1004			if ((retval = setup_req (ep, req, 0)) == 0)
1005				retval = usb_ep_queue (ep, req, GFP_ATOMIC);
1006			dev->state = STATE_DEV_CONNECTED;
1007
1008			/* assume that was SET_CONFIGURATION */
1009			if (dev->current_config) {
1010				unsigned power;
1011#ifdef	CONFIG_USB_GADGET_DUALSPEED
1012				if (dev->gadget->speed == USB_SPEED_HIGH)
1013					power = dev->hs_config->bMaxPower;
1014				else
1015#endif
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", __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				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", __FUNCTION__, 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", __FUNCTION__, 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	fasync_helper (-1, fd, 0, &dev->fasync);
1253	kfree (dev->buf);
1254	dev->buf = NULL;
1255	put_dev (dev);
1256
1257	/* other endpoints were all decoupled from this device */
1258	spin_lock_irq(&dev->lock);
1259	dev->state = STATE_DEV_DISABLED;
1260	spin_unlock_irq(&dev->lock);
1261	return 0;
1262}
1263
1264static unsigned int
1265ep0_poll (struct file *fd, poll_table *wait)
1266{
1267       struct dev_data         *dev = fd->private_data;
1268       int                     mask = 0;
1269
1270       poll_wait(fd, &dev->wait, wait);
1271
1272       spin_lock_irq (&dev->lock);
1273
1274       /* report fd mode change before acting on it */
1275       if (dev->setup_abort) {
1276               dev->setup_abort = 0;
1277               mask = POLLHUP;
1278               goto out;
1279       }
1280
1281       if (dev->state == STATE_DEV_SETUP) {
1282               if (dev->setup_in || dev->setup_can_stall)
1283                       mask = POLLOUT;
1284       } else {
1285               if (dev->ev_next != 0)
1286                       mask = POLLIN;
1287       }
1288out:
1289       spin_unlock_irq(&dev->lock);
1290       return mask;
1291}
1292
1293static int dev_ioctl (struct inode *inode, struct file *fd,
1294		unsigned code, unsigned long value)
1295{
1296	struct dev_data		*dev = fd->private_data;
1297	struct usb_gadget	*gadget = dev->gadget;
1298
1299	if (gadget->ops->ioctl)
1300		return gadget->ops->ioctl (gadget, code, value);
1301	return -ENOTTY;
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	.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 = __constant_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#ifdef CONFIG_USB_GADGET_DUALSPEED
1355	int		hs;
1356#endif
1357
1358	/* only one configuration */
1359	if (index > 0)
1360		return -EINVAL;
1361
1362#ifdef CONFIG_USB_GADGET_DUALSPEED
1363	hs = (dev->gadget->speed == USB_SPEED_HIGH);
1364	if (type == USB_DT_OTHER_SPEED_CONFIG)
1365		hs = !hs;
1366	if (hs) {
1367		dev->req->buf = dev->hs_config;
1368		len = le16_to_cpu(dev->hs_config->wTotalLength);
1369	} else
1370#endif
1371	{
1372		dev->req->buf = dev->config;
1373		len = le16_to_cpu(dev->config->wTotalLength);
1374	}
1375	((u8 *)dev->req->buf) [1] = type;
1376	return len;
1377}
1378
1379static int
1380gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1381{
1382	struct dev_data			*dev = get_gadget_data (gadget);
1383	struct usb_request		*req = dev->req;
1384	int				value = -EOPNOTSUPP;
1385	struct usb_gadgetfs_event	*event;
1386	u16				w_value = le16_to_cpu(ctrl->wValue);
1387	u16				w_length = le16_to_cpu(ctrl->wLength);
1388
1389	spin_lock (&dev->lock);
1390	dev->setup_abort = 0;
1391	if (dev->state == STATE_DEV_UNCONNECTED) {
1392#ifdef	CONFIG_USB_GADGET_DUALSPEED
1393		if (gadget->speed == USB_SPEED_HIGH && dev->hs_config == 0) {
1394			spin_unlock(&dev->lock);
1395			ERROR (dev, "no high speed config??\n");
1396			return -EINVAL;
1397		}
1398#endif	/* CONFIG_USB_GADGET_DUALSPEED */
1399
1400		dev->state = STATE_DEV_CONNECTED;
1401		dev->dev->bMaxPacketSize0 = gadget->ep0->maxpacket;
1402
1403		INFO (dev, "connected\n");
1404		event = next_event (dev, GADGETFS_CONNECT);
1405		event->u.speed = gadget->speed;
1406		ep0_readable (dev);
1407
1408	/* host may have given up waiting for response.  we can miss control
1409	 * requests handled lower down (device/endpoint status and features);
1410	 * then ep0_{read,write} will report the wrong status. controller
1411	 * driver will have aborted pending i/o.
1412	 */
1413	} else if (dev->state == STATE_DEV_SETUP)
1414		dev->setup_abort = 1;
1415
1416	req->buf = dev->rbuf;
1417	req->dma = DMA_ADDR_INVALID;
1418	req->context = NULL;
1419	value = -EOPNOTSUPP;
1420	switch (ctrl->bRequest) {
1421
1422	case USB_REQ_GET_DESCRIPTOR:
1423		if (ctrl->bRequestType != USB_DIR_IN)
1424			goto unrecognized;
1425		switch (w_value >> 8) {
1426
1427		case USB_DT_DEVICE:
1428			value = min (w_length, (u16) sizeof *dev->dev);
1429			req->buf = dev->dev;
1430			break;
1431#ifdef	CONFIG_USB_GADGET_DUALSPEED
1432		case USB_DT_DEVICE_QUALIFIER:
1433			if (!dev->hs_config)
1434				break;
1435			value = min (w_length, (u16)
1436				sizeof (struct usb_qualifier_descriptor));
1437			make_qualifier (dev);
1438			break;
1439		case USB_DT_OTHER_SPEED_CONFIG:
1440			// FALLTHROUGH
1441#endif
1442		case USB_DT_CONFIG:
1443			value = config_buf (dev,
1444					w_value >> 8,
1445					w_value & 0xff);
1446			if (value >= 0)
1447				value = min (w_length, (u16) value);
1448			break;
1449		case USB_DT_STRING:
1450			goto unrecognized;
1451
1452		default:		// all others are errors
1453			break;
1454		}
1455		break;
1456
1457	/* currently one config, two speeds */
1458	case USB_REQ_SET_CONFIGURATION:
1459		if (ctrl->bRequestType != 0)
1460			break;
1461		if (0 == (u8) w_value) {
1462			value = 0;
1463			dev->current_config = 0;
1464			usb_gadget_vbus_draw(gadget, 8 /* mA */ );
1465			// user mode expected to disable endpoints
1466		} else {
1467			u8	config, power;
1468#ifdef	CONFIG_USB_GADGET_DUALSPEED
1469			if (gadget->speed == USB_SPEED_HIGH) {
1470				config = dev->hs_config->bConfigurationValue;
1471				power = dev->hs_config->bMaxPower;
1472			} else
1473#endif
1474			{
1475				config = dev->config->bConfigurationValue;
1476				power = dev->config->bMaxPower;
1477			}
1478
1479			if (config == (u8) w_value) {
1480				value = 0;
1481				dev->current_config = config;
1482				usb_gadget_vbus_draw(gadget, 2 * power);
1483			}
1484		}
1485
1486		/* report SET_CONFIGURATION like any other control request,
1487		 * except that usermode may not stall this.  the next
1488		 * request mustn't be allowed start until this finishes:
1489		 * endpoints and threads set up, etc.
1490		 *
1491		 * NOTE:  older PXA hardware (before PXA 255: without UDCCFR)
1492		 * has bad/racey automagic that prevents synchronizing here.
1493		 * even kernel mode drivers often miss them.
1494		 */
1495		if (value == 0) {
1496			INFO (dev, "configuration #%d\n", dev->current_config);
1497			if (dev->usermode_setup) {
1498				dev->setup_can_stall = 0;
1499				goto delegate;
1500			}
1501		}
1502		break;
1503
1504#ifndef	CONFIG_USB_GADGETFS_PXA2XX
1505	/* PXA automagically handles this request too */
1506	case USB_REQ_GET_CONFIGURATION:
1507		if (ctrl->bRequestType != 0x80)
1508			break;
1509		*(u8 *)req->buf = dev->current_config;
1510		value = min (w_length, (u16) 1);
1511		break;
1512#endif
1513
1514	default:
1515unrecognized:
1516		VDEBUG (dev, "%s req%02x.%02x v%04x i%04x l%d\n",
1517			dev->usermode_setup ? "delegate" : "fail",
1518			ctrl->bRequestType, ctrl->bRequest,
1519			w_value, le16_to_cpu(ctrl->wIndex), w_length);
1520
1521		/* if there's an ep0 reader, don't stall */
1522		if (dev->usermode_setup) {
1523			dev->setup_can_stall = 1;
1524delegate:
1525			dev->setup_in = (ctrl->bRequestType & USB_DIR_IN)
1526						? 1 : 0;
1527			dev->setup_wLength = w_length;
1528			dev->setup_out_ready = 0;
1529			dev->setup_out_error = 0;
1530			value = 0;
1531
1532			/* read DATA stage for OUT right away */
1533			if (unlikely (!dev->setup_in && w_length)) {
1534				value = setup_req (gadget->ep0, dev->req,
1535							w_length);
1536				if (value < 0)
1537					break;
1538				value = usb_ep_queue (gadget->ep0, dev->req,
1539							GFP_ATOMIC);
1540				if (value < 0) {
1541					clean_req (gadget->ep0, dev->req);
1542					break;
1543				}
1544
1545				/* we can't currently stall these */
1546				dev->setup_can_stall = 0;
1547			}
1548
1549			/* state changes when reader collects event */
1550			event = next_event (dev, GADGETFS_SETUP);
1551			event->u.setup = *ctrl;
1552			ep0_readable (dev);
1553			spin_unlock (&dev->lock);
1554			return 0;
1555		}
1556	}
1557
1558	/* proceed with data transfer and status phases? */
1559	if (value >= 0 && dev->state != STATE_DEV_SETUP) {
1560		req->length = value;
1561		req->zero = value < w_length;
1562		value = usb_ep_queue (gadget->ep0, req, GFP_ATOMIC);
1563		if (value < 0) {
1564			DBG (dev, "ep_queue --> %d\n", value);
1565			req->status = 0;
1566		}
1567	}
1568
1569	/* device stalls when value < 0 */
1570	spin_unlock (&dev->lock);
1571	return value;
1572}
1573
1574static void destroy_ep_files (struct dev_data *dev)
1575{
1576	struct list_head	*entry, *tmp;
1577
1578	DBG (dev, "%s %d\n", __FUNCTION__, dev->state);
1579
1580	/* dev->state must prevent interference */
1581restart:
1582	spin_lock_irq (&dev->lock);
1583	list_for_each_safe (entry, tmp, &dev->epfiles) {
1584		struct ep_data	*ep;
1585		struct inode	*parent;
1586		struct dentry	*dentry;
1587
1588		/* break link to FS */
1589		ep = list_entry (entry, struct ep_data, epfiles);
1590		list_del_init (&ep->epfiles);
1591		dentry = ep->dentry;
1592		ep->dentry = NULL;
1593		parent = dentry->d_parent->d_inode;
1594
1595		/* break link to controller */
1596		if (ep->state == STATE_EP_ENABLED)
1597			(void) usb_ep_disable (ep->ep);
1598		ep->state = STATE_EP_UNBOUND;
1599		usb_ep_free_request (ep->ep, ep->req);
1600		ep->ep = NULL;
1601		wake_up (&ep->wait);
1602		put_ep (ep);
1603
1604		spin_unlock_irq (&dev->lock);
1605
1606		/* break link to dcache */
1607		mutex_lock (&parent->i_mutex);
1608		d_delete (dentry);
1609		dput (dentry);
1610		mutex_unlock (&parent->i_mutex);
1611
1612		/* fds may still be open */
1613		goto restart;
1614	}
1615	spin_unlock_irq (&dev->lock);
1616}
1617
1618
1619static struct inode *
1620gadgetfs_create_file (struct super_block *sb, char const *name,
1621		void *data, const struct file_operations *fops,
1622		struct dentry **dentry_p);
1623
1624static int activate_ep_files (struct dev_data *dev)
1625{
1626	struct usb_ep	*ep;
1627	struct ep_data	*data;
1628
1629	gadget_for_each_ep (ep, dev->gadget) {
1630
1631		data = kzalloc(sizeof(*data), GFP_KERNEL);
1632		if (!data)
1633			goto enomem0;
1634		data->state = STATE_EP_DISABLED;
1635		init_MUTEX (&data->lock);
1636		init_waitqueue_head (&data->wait);
1637
1638		strncpy (data->name, ep->name, sizeof (data->name) - 1);
1639		atomic_set (&data->count, 1);
1640		data->dev = dev;
1641		get_dev (dev);
1642
1643		data->ep = ep;
1644		ep->driver_data = data;
1645
1646		data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1647		if (!data->req)
1648			goto enomem1;
1649
1650		data->inode = gadgetfs_create_file (dev->sb, data->name,
1651				data, &ep_config_operations,
1652				&data->dentry);
1653		if (!data->inode)
1654			goto enomem2;
1655		list_add_tail (&data->epfiles, &dev->epfiles);
1656	}
1657	return 0;
1658
1659enomem2:
1660	usb_ep_free_request (ep, data->req);
1661enomem1:
1662	put_dev (dev);
1663	kfree (data);
1664enomem0:
1665	DBG (dev, "%s enomem\n", __FUNCTION__);
1666	destroy_ep_files (dev);
1667	return -ENOMEM;
1668}
1669
1670static void
1671gadgetfs_unbind (struct usb_gadget *gadget)
1672{
1673	struct dev_data		*dev = get_gadget_data (gadget);
1674
1675	DBG (dev, "%s\n", __FUNCTION__);
1676
1677	spin_lock_irq (&dev->lock);
1678	dev->state = STATE_DEV_UNBOUND;
1679	spin_unlock_irq (&dev->lock);
1680
1681	destroy_ep_files (dev);
1682	gadget->ep0->driver_data = NULL;
1683	set_gadget_data (gadget, NULL);
1684
1685	/* we've already been disconnected ... no i/o is active */
1686	if (dev->req)
1687		usb_ep_free_request (gadget->ep0, dev->req);
1688	DBG (dev, "%s done\n", __FUNCTION__);
1689	put_dev (dev);
1690}
1691
1692static struct dev_data		*the_device;
1693
1694static int
1695gadgetfs_bind (struct usb_gadget *gadget)
1696{
1697	struct dev_data		*dev = the_device;
1698
1699	if (!dev)
1700		return -ESRCH;
1701	if (0 != strcmp (CHIP, gadget->name)) {
1702		printk (KERN_ERR "%s expected %s controller not %s\n",
1703			shortname, CHIP, gadget->name);
1704		return -ENODEV;
1705	}
1706
1707	set_gadget_data (gadget, dev);
1708	dev->gadget = gadget;
1709	gadget->ep0->driver_data = dev;
1710	dev->dev->bMaxPacketSize0 = gadget->ep0->maxpacket;
1711
1712	/* preallocate control response and buffer */
1713	dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1714	if (!dev->req)
1715		goto enomem;
1716	dev->req->context = NULL;
1717	dev->req->complete = epio_complete;
1718
1719	if (activate_ep_files (dev) < 0)
1720		goto enomem;
1721
1722	INFO (dev, "bound to %s driver\n", gadget->name);
1723	spin_lock_irq(&dev->lock);
1724	dev->state = STATE_DEV_UNCONNECTED;
1725	spin_unlock_irq(&dev->lock);
1726	get_dev (dev);
1727	return 0;
1728
1729enomem:
1730	gadgetfs_unbind (gadget);
1731	return -ENOMEM;
1732}
1733
1734static void
1735gadgetfs_disconnect (struct usb_gadget *gadget)
1736{
1737	struct dev_data		*dev = get_gadget_data (gadget);
1738
1739	spin_lock (&dev->lock);
1740	if (dev->state == STATE_DEV_UNCONNECTED)
1741		goto exit;
1742	dev->state = STATE_DEV_UNCONNECTED;
1743
1744	INFO (dev, "disconnected\n");
1745	next_event (dev, GADGETFS_DISCONNECT);
1746	ep0_readable (dev);
1747exit:
1748	spin_unlock (&dev->lock);
1749}
1750
1751static void
1752gadgetfs_suspend (struct usb_gadget *gadget)
1753{
1754	struct dev_data		*dev = get_gadget_data (gadget);
1755
1756	INFO (dev, "suspended from state %d\n", dev->state);
1757	spin_lock (&dev->lock);
1758	switch (dev->state) {
1759	case STATE_DEV_SETUP:		// VERY odd... host died??
1760	case STATE_DEV_CONNECTED:
1761	case STATE_DEV_UNCONNECTED:
1762		next_event (dev, GADGETFS_SUSPEND);
1763		ep0_readable (dev);
1764		/* FALLTHROUGH */
1765	default:
1766		break;
1767	}
1768	spin_unlock (&dev->lock);
1769}
1770
1771static struct usb_gadget_driver gadgetfs_driver = {
1772#ifdef	CONFIG_USB_GADGET_DUALSPEED
1773	.speed		= USB_SPEED_HIGH,
1774#else
1775	.speed		= USB_SPEED_FULL,
1776#endif
1777	.function	= (char *) driver_desc,
1778	.bind		= gadgetfs_bind,
1779	.unbind		= gadgetfs_unbind,
1780	.setup		= gadgetfs_setup,
1781	.disconnect	= gadgetfs_disconnect,
1782	.suspend	= gadgetfs_suspend,
1783
1784	.driver	= {
1785		.name		= (char *) shortname,
1786	},
1787};
1788
1789/*----------------------------------------------------------------------*/
1790
1791static void gadgetfs_nop(struct usb_gadget *arg) { }
1792
1793static int gadgetfs_probe (struct usb_gadget *gadget)
1794{
1795	CHIP = gadget->name;
1796	return -EISNAM;
1797}
1798
1799static struct usb_gadget_driver probe_driver = {
1800	.speed		= USB_SPEED_HIGH,
1801	.bind		= gadgetfs_probe,
1802	.unbind		= gadgetfs_nop,
1803	.setup		= (void *)gadgetfs_nop,
1804	.disconnect	= gadgetfs_nop,
1805	.driver	= {
1806		.name		= "nop",
1807	},
1808};
1809
1810
1811/* DEVICE INITIALIZATION
1812 *
1813 *     fd = open ("/dev/gadget/$CHIP", O_RDWR)
1814 *     status = write (fd, descriptors, sizeof descriptors)
1815 *
1816 * That write establishes the device configuration, so the kernel can
1817 * bind to the controller ... guaranteeing it can handle enumeration
1818 * at all necessary speeds.  Descriptor order is:
1819 *
1820 * . message tag (u32, host order) ... for now, must be zero; it
1821 *	would change to support features like multi-config devices
1822 * . full/low speed config ... all wTotalLength bytes (with interface,
1823 *	class, altsetting, endpoint, and other descriptors)
1824 * . high speed config ... all descriptors, for high speed operation;
1825 *	this one's optional except for high-speed hardware
1826 * . device descriptor
1827 *
1828 * Endpoints are not yet enabled. Drivers must wait until device
1829 * configuration and interface altsetting changes create
1830 * the need to configure (or unconfigure) them.
1831 *
1832 * After initialization, the device stays active for as long as that
1833 * $CHIP file is open.  Events must then be read from that descriptor,
1834 * such as configuration notifications.
1835 */
1836
1837static int is_valid_config (struct usb_config_descriptor *config)
1838{
1839	return config->bDescriptorType == USB_DT_CONFIG
1840		&& config->bLength == USB_DT_CONFIG_SIZE
1841		&& config->bConfigurationValue != 0
1842		&& (config->bmAttributes & USB_CONFIG_ATT_ONE) != 0
1843		&& (config->bmAttributes & USB_CONFIG_ATT_WAKEUP) == 0;
1844}
1845
1846static ssize_t
1847dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1848{
1849	struct dev_data		*dev = fd->private_data;
1850	ssize_t			value = len, length = len;
1851	unsigned		total;
1852	u32			tag;
1853	char			*kbuf;
1854
1855	if (len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4))
1856		return -EINVAL;
1857
1858	/* we might need to change message format someday */
1859	if (copy_from_user (&tag, buf, 4))
1860		return -EFAULT;
1861	if (tag != 0)
1862		return -EINVAL;
1863	buf += 4;
1864	length -= 4;
1865
1866	kbuf = kmalloc (length, GFP_KERNEL);
1867	if (!kbuf)
1868		return -ENOMEM;
1869	if (copy_from_user (kbuf, buf, length)) {
1870		kfree (kbuf);
1871		return -EFAULT;
1872	}
1873
1874	spin_lock_irq (&dev->lock);
1875	value = -EINVAL;
1876	if (dev->buf)
1877		goto fail;
1878	dev->buf = kbuf;
1879
1880	/* full or low speed config */
1881	dev->config = (void *) kbuf;
1882	total = le16_to_cpu(dev->config->wTotalLength);
1883	if (!is_valid_config (dev->config) || total >= length)
1884		goto fail;
1885	kbuf += total;
1886	length -= total;
1887
1888	/* optional high speed config */
1889	if (kbuf [1] == USB_DT_CONFIG) {
1890		dev->hs_config = (void *) kbuf;
1891		total = le16_to_cpu(dev->hs_config->wTotalLength);
1892		if (!is_valid_config (dev->hs_config) || total >= length)
1893			goto fail;
1894		kbuf += total;
1895		length -= total;
1896	}
1897
1898	/* could support multiple configs, using another encoding! */
1899
1900	/* device descriptor (tweaked for paranoia) */
1901	if (length != USB_DT_DEVICE_SIZE)
1902		goto fail;
1903	dev->dev = (void *)kbuf;
1904	if (dev->dev->bLength != USB_DT_DEVICE_SIZE
1905			|| dev->dev->bDescriptorType != USB_DT_DEVICE
1906			|| dev->dev->bNumConfigurations != 1)
1907		goto fail;
1908	dev->dev->bNumConfigurations = 1;
1909	dev->dev->bcdUSB = __constant_cpu_to_le16 (0x0200);
1910
1911	/* triggers gadgetfs_bind(); then we can enumerate. */
1912	spin_unlock_irq (&dev->lock);
1913	value = usb_gadget_register_driver (&gadgetfs_driver);
1914	if (value != 0) {
1915		kfree (dev->buf);
1916		dev->buf = NULL;
1917	} else {
1918		/* at this point "good" hardware has for the first time
1919		 * let the USB the host see us.  alternatively, if users
1920		 * unplug/replug that will clear all the error state.
1921		 *
1922		 * note:  everything running before here was guaranteed
1923		 * to choke driver model style diagnostics.  from here
1924		 * on, they can work ... except in cleanup paths that
1925		 * kick in after the ep0 descriptor is closed.
1926		 */
1927		fd->f_op = &ep0_io_operations;
1928		value = len;
1929	}
1930	return value;
1931
1932fail:
1933	spin_unlock_irq (&dev->lock);
1934	pr_debug ("%s: %s fail %Zd, %p\n", shortname, __FUNCTION__, value, dev);
1935	kfree (dev->buf);
1936	dev->buf = NULL;
1937	return value;
1938}
1939
1940static int
1941dev_open (struct inode *inode, struct file *fd)
1942{
1943	struct dev_data		*dev = inode->i_private;
1944	int			value = -EBUSY;
1945
1946	spin_lock_irq(&dev->lock);
1947	if (dev->state == STATE_DEV_DISABLED) {
1948		dev->ev_next = 0;
1949		dev->state = STATE_DEV_OPENED;
1950		fd->private_data = dev;
1951		get_dev (dev);
1952		value = 0;
1953	}
1954	spin_unlock_irq(&dev->lock);
1955	return value;
1956}
1957
1958static const struct file_operations dev_init_operations = {
1959	.owner =	THIS_MODULE,
1960	.llseek =	no_llseek,
1961
1962	.open =		dev_open,
1963	.write =	dev_config,
1964	.fasync =	ep0_fasync,
1965	.ioctl =	dev_ioctl,
1966	.release =	dev_release,
1967};
1968
1969/*----------------------------------------------------------------------*/
1970
1971/* FILESYSTEM AND SUPERBLOCK OPERATIONS
1972 *
1973 * Mounting the filesystem creates a controller file, used first for
1974 * device configuration then later for event monitoring.
1975 */
1976
1977
1978
1979static unsigned default_uid;
1980static unsigned default_gid;
1981static unsigned default_perm = S_IRUSR | S_IWUSR;
1982
1983module_param (default_uid, uint, 0644);
1984module_param (default_gid, uint, 0644);
1985module_param (default_perm, uint, 0644);
1986
1987
1988static struct inode *
1989gadgetfs_make_inode (struct super_block *sb,
1990		void *data, const struct file_operations *fops,
1991		int mode)
1992{
1993	struct inode *inode = new_inode (sb);
1994
1995	if (inode) {
1996		inode->i_mode = mode;
1997		inode->i_uid = default_uid;
1998		inode->i_gid = default_gid;
1999		inode->i_blocks = 0;
2000		inode->i_atime = inode->i_mtime = inode->i_ctime
2001				= CURRENT_TIME;
2002		inode->i_private = data;
2003		inode->i_fop = fops;
2004	}
2005	return inode;
2006}
2007
2008/* creates in fs root directory, so non-renamable and non-linkable.
2009 * so inode and dentry are paired, until device reconfig.
2010 */
2011static struct inode *
2012gadgetfs_create_file (struct super_block *sb, char const *name,
2013		void *data, const struct file_operations *fops,
2014		struct dentry **dentry_p)
2015{
2016	struct dentry	*dentry;
2017	struct inode	*inode;
2018
2019	dentry = d_alloc_name(sb->s_root, name);
2020	if (!dentry)
2021		return NULL;
2022
2023	inode = gadgetfs_make_inode (sb, data, fops,
2024			S_IFREG | (default_perm & S_IRWXUGO));
2025	if (!inode) {
2026		dput(dentry);
2027		return NULL;
2028	}
2029	d_add (dentry, inode);
2030	*dentry_p = dentry;
2031	return inode;
2032}
2033
2034static struct super_operations gadget_fs_operations = {
2035	.statfs =	simple_statfs,
2036	.drop_inode =	generic_delete_inode,
2037};
2038
2039static int
2040gadgetfs_fill_super (struct super_block *sb, void *opts, int silent)
2041{
2042	struct inode	*inode;
2043	struct dentry	*d;
2044	struct dev_data	*dev;
2045
2046	if (the_device)
2047		return -ESRCH;
2048
2049	/* fake probe to determine $CHIP */
2050	(void) usb_gadget_register_driver (&probe_driver);
2051	if (!CHIP)
2052		return -ENODEV;
2053
2054	/* superblock */
2055	sb->s_blocksize = PAGE_CACHE_SIZE;
2056	sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
2057	sb->s_magic = GADGETFS_MAGIC;
2058	sb->s_op = &gadget_fs_operations;
2059	sb->s_time_gran = 1;
2060
2061	/* root inode */
2062	inode = gadgetfs_make_inode (sb,
2063			NULL, &simple_dir_operations,
2064			S_IFDIR | S_IRUGO | S_IXUGO);
2065	if (!inode)
2066		goto enomem0;
2067	inode->i_op = &simple_dir_inode_operations;
2068	if (!(d = d_alloc_root (inode)))
2069		goto enomem1;
2070	sb->s_root = d;
2071
2072	/* the ep0 file is named after the controller we expect;
2073	 * user mode code can use it for sanity checks, like we do.
2074	 */
2075	dev = dev_new ();
2076	if (!dev)
2077		goto enomem2;
2078
2079	dev->sb = sb;
2080	if (!gadgetfs_create_file (sb, CHIP,
2081				dev, &dev_init_operations,
2082				&dev->dentry))
2083		goto enomem3;
2084
2085	/* other endpoint files are available after hardware setup,
2086	 * from binding to a controller.
2087	 */
2088	the_device = dev;
2089	return 0;
2090
2091enomem3:
2092	put_dev (dev);
2093enomem2:
2094	dput (d);
2095enomem1:
2096	iput (inode);
2097enomem0:
2098	return -ENOMEM;
2099}
2100
2101/* "mount -t gadgetfs path /dev/gadget" ends up here */
2102static int
2103gadgetfs_get_sb (struct file_system_type *t, int flags,
2104		const char *path, void *opts, struct vfsmount *mnt)
2105{
2106	return get_sb_single (t, flags, opts, gadgetfs_fill_super, mnt);
2107}
2108
2109static void
2110gadgetfs_kill_sb (struct super_block *sb)
2111{
2112	kill_litter_super (sb);
2113	if (the_device) {
2114		put_dev (the_device);
2115		the_device = NULL;
2116	}
2117}
2118
2119/*----------------------------------------------------------------------*/
2120
2121static struct file_system_type gadgetfs_type = {
2122	.owner		= THIS_MODULE,
2123	.name		= shortname,
2124	.get_sb		= gadgetfs_get_sb,
2125	.kill_sb	= gadgetfs_kill_sb,
2126};
2127
2128/*----------------------------------------------------------------------*/
2129
2130static int __init init (void)
2131{
2132	int status;
2133
2134	status = register_filesystem (&gadgetfs_type);
2135	if (status == 0)
2136		pr_info ("%s: %s, version " DRIVER_VERSION "\n",
2137			shortname, driver_desc);
2138	return status;
2139}
2140module_init (init);
2141
2142static void __exit cleanup (void)
2143{
2144	pr_debug ("unregister %s\n", shortname);
2145	unregister_filesystem (&gadgetfs_type);
2146}
2147module_exit (cleanup);
2148