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