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