xref: /openbmc/linux/drivers/usb/core/devio.c (revision d0bd7f2a)
1 /*****************************************************************************/
2 
3 /*
4  *      devio.c  --  User space communication with USB devices.
5  *
6  *      Copyright (C) 1999-2000  Thomas Sailer (sailer@ife.ee.ethz.ch)
7  *
8  *      This program is free software; you can redistribute it and/or modify
9  *      it under the terms of the GNU General Public License as published by
10  *      the Free Software Foundation; either version 2 of the License, or
11  *      (at your option) any later version.
12  *
13  *      This program is distributed in the hope that it will be useful,
14  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *      GNU General Public License for more details.
17  *
18  *      You should have received a copy of the GNU General Public License
19  *      along with this program; if not, write to the Free Software
20  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  *
22  *  This file implements the usbfs/x/y files, where
23  *  x is the bus number and y the device number.
24  *
25  *  It allows user space programs/"drivers" to communicate directly
26  *  with USB devices without intervening kernel driver.
27  *
28  *  Revision history
29  *    22.12.1999   0.1   Initial release (split from proc_usb.c)
30  *    04.01.2000   0.2   Turned into its own filesystem
31  *    30.09.2005   0.3   Fix user-triggerable oops in async URB delivery
32  *    			 (CAN-2005-3055)
33  */
34 
35 /*****************************************************************************/
36 
37 #include <linux/fs.h>
38 #include <linux/mm.h>
39 #include <linux/slab.h>
40 #include <linux/signal.h>
41 #include <linux/poll.h>
42 #include <linux/module.h>
43 #include <linux/string.h>
44 #include <linux/usb.h>
45 #include <linux/usbdevice_fs.h>
46 #include <linux/usb/hcd.h>	/* for usbcore internals */
47 #include <linux/cdev.h>
48 #include <linux/notifier.h>
49 #include <linux/security.h>
50 #include <linux/user_namespace.h>
51 #include <linux/scatterlist.h>
52 #include <linux/uaccess.h>
53 #include <asm/byteorder.h>
54 #include <linux/moduleparam.h>
55 
56 #include "usb.h"
57 
58 #define USB_MAXBUS			64
59 #define USB_DEVICE_MAX			(USB_MAXBUS * 128)
60 #define USB_SG_SIZE			16384 /* split-size for large txs */
61 
62 /* Mutual exclusion for removal, open, and release */
63 DEFINE_MUTEX(usbfs_mutex);
64 
65 struct usb_dev_state {
66 	struct list_head list;      /* state list */
67 	struct usb_device *dev;
68 	struct file *file;
69 	spinlock_t lock;            /* protects the async urb lists */
70 	struct list_head async_pending;
71 	struct list_head async_completed;
72 	wait_queue_head_t wait;     /* wake up if a request completed */
73 	unsigned int discsignr;
74 	struct pid *disc_pid;
75 	const struct cred *cred;
76 	void __user *disccontext;
77 	unsigned long ifclaimed;
78 	u32 secid;
79 	u32 disabled_bulk_eps;
80 };
81 
82 struct async {
83 	struct list_head asynclist;
84 	struct usb_dev_state *ps;
85 	struct pid *pid;
86 	const struct cred *cred;
87 	unsigned int signr;
88 	unsigned int ifnum;
89 	void __user *userbuffer;
90 	void __user *userurb;
91 	struct urb *urb;
92 	unsigned int mem_usage;
93 	int status;
94 	u32 secid;
95 	u8 bulk_addr;
96 	u8 bulk_status;
97 };
98 
99 static bool usbfs_snoop;
100 module_param(usbfs_snoop, bool, S_IRUGO | S_IWUSR);
101 MODULE_PARM_DESC(usbfs_snoop, "true to log all usbfs traffic");
102 
103 #define snoop(dev, format, arg...)				\
104 	do {							\
105 		if (usbfs_snoop)				\
106 			dev_info(dev , format , ## arg);	\
107 	} while (0)
108 
109 enum snoop_when {
110 	SUBMIT, COMPLETE
111 };
112 
113 #define USB_DEVICE_DEV		MKDEV(USB_DEVICE_MAJOR, 0)
114 
115 /* Limit on the total amount of memory we can allocate for transfers */
116 static unsigned usbfs_memory_mb = 16;
117 module_param(usbfs_memory_mb, uint, 0644);
118 MODULE_PARM_DESC(usbfs_memory_mb,
119 		"maximum MB allowed for usbfs buffers (0 = no limit)");
120 
121 /* Hard limit, necessary to avoid arithmetic overflow */
122 #define USBFS_XFER_MAX		(UINT_MAX / 2 - 1000000)
123 
124 static atomic_t usbfs_memory_usage;	/* Total memory currently allocated */
125 
126 /* Check whether it's okay to allocate more memory for a transfer */
127 static int usbfs_increase_memory_usage(unsigned amount)
128 {
129 	unsigned lim;
130 
131 	/*
132 	 * Convert usbfs_memory_mb to bytes, avoiding overflows.
133 	 * 0 means use the hard limit (effectively unlimited).
134 	 */
135 	lim = ACCESS_ONCE(usbfs_memory_mb);
136 	if (lim == 0 || lim > (USBFS_XFER_MAX >> 20))
137 		lim = USBFS_XFER_MAX;
138 	else
139 		lim <<= 20;
140 
141 	atomic_add(amount, &usbfs_memory_usage);
142 	if (atomic_read(&usbfs_memory_usage) <= lim)
143 		return 0;
144 	atomic_sub(amount, &usbfs_memory_usage);
145 	return -ENOMEM;
146 }
147 
148 /* Memory for a transfer is being deallocated */
149 static void usbfs_decrease_memory_usage(unsigned amount)
150 {
151 	atomic_sub(amount, &usbfs_memory_usage);
152 }
153 
154 static int connected(struct usb_dev_state *ps)
155 {
156 	return (!list_empty(&ps->list) &&
157 			ps->dev->state != USB_STATE_NOTATTACHED);
158 }
159 
160 static loff_t usbdev_lseek(struct file *file, loff_t offset, int orig)
161 {
162 	loff_t ret;
163 
164 	mutex_lock(&file_inode(file)->i_mutex);
165 
166 	switch (orig) {
167 	case 0:
168 		file->f_pos = offset;
169 		ret = file->f_pos;
170 		break;
171 	case 1:
172 		file->f_pos += offset;
173 		ret = file->f_pos;
174 		break;
175 	case 2:
176 	default:
177 		ret = -EINVAL;
178 	}
179 
180 	mutex_unlock(&file_inode(file)->i_mutex);
181 	return ret;
182 }
183 
184 static ssize_t usbdev_read(struct file *file, char __user *buf, size_t nbytes,
185 			   loff_t *ppos)
186 {
187 	struct usb_dev_state *ps = file->private_data;
188 	struct usb_device *dev = ps->dev;
189 	ssize_t ret = 0;
190 	unsigned len;
191 	loff_t pos;
192 	int i;
193 
194 	pos = *ppos;
195 	usb_lock_device(dev);
196 	if (!connected(ps)) {
197 		ret = -ENODEV;
198 		goto err;
199 	} else if (pos < 0) {
200 		ret = -EINVAL;
201 		goto err;
202 	}
203 
204 	if (pos < sizeof(struct usb_device_descriptor)) {
205 		/* 18 bytes - fits on the stack */
206 		struct usb_device_descriptor temp_desc;
207 
208 		memcpy(&temp_desc, &dev->descriptor, sizeof(dev->descriptor));
209 		le16_to_cpus(&temp_desc.bcdUSB);
210 		le16_to_cpus(&temp_desc.idVendor);
211 		le16_to_cpus(&temp_desc.idProduct);
212 		le16_to_cpus(&temp_desc.bcdDevice);
213 
214 		len = sizeof(struct usb_device_descriptor) - pos;
215 		if (len > nbytes)
216 			len = nbytes;
217 		if (copy_to_user(buf, ((char *)&temp_desc) + pos, len)) {
218 			ret = -EFAULT;
219 			goto err;
220 		}
221 
222 		*ppos += len;
223 		buf += len;
224 		nbytes -= len;
225 		ret += len;
226 	}
227 
228 	pos = sizeof(struct usb_device_descriptor);
229 	for (i = 0; nbytes && i < dev->descriptor.bNumConfigurations; i++) {
230 		struct usb_config_descriptor *config =
231 			(struct usb_config_descriptor *)dev->rawdescriptors[i];
232 		unsigned int length = le16_to_cpu(config->wTotalLength);
233 
234 		if (*ppos < pos + length) {
235 
236 			/* The descriptor may claim to be longer than it
237 			 * really is.  Here is the actual allocated length. */
238 			unsigned alloclen =
239 				le16_to_cpu(dev->config[i].desc.wTotalLength);
240 
241 			len = length - (*ppos - pos);
242 			if (len > nbytes)
243 				len = nbytes;
244 
245 			/* Simply don't write (skip over) unallocated parts */
246 			if (alloclen > (*ppos - pos)) {
247 				alloclen -= (*ppos - pos);
248 				if (copy_to_user(buf,
249 				    dev->rawdescriptors[i] + (*ppos - pos),
250 				    min(len, alloclen))) {
251 					ret = -EFAULT;
252 					goto err;
253 				}
254 			}
255 
256 			*ppos += len;
257 			buf += len;
258 			nbytes -= len;
259 			ret += len;
260 		}
261 
262 		pos += length;
263 	}
264 
265 err:
266 	usb_unlock_device(dev);
267 	return ret;
268 }
269 
270 /*
271  * async list handling
272  */
273 
274 static struct async *alloc_async(unsigned int numisoframes)
275 {
276 	struct async *as;
277 
278 	as = kzalloc(sizeof(struct async), GFP_KERNEL);
279 	if (!as)
280 		return NULL;
281 	as->urb = usb_alloc_urb(numisoframes, GFP_KERNEL);
282 	if (!as->urb) {
283 		kfree(as);
284 		return NULL;
285 	}
286 	return as;
287 }
288 
289 static void free_async(struct async *as)
290 {
291 	int i;
292 
293 	put_pid(as->pid);
294 	if (as->cred)
295 		put_cred(as->cred);
296 	for (i = 0; i < as->urb->num_sgs; i++) {
297 		if (sg_page(&as->urb->sg[i]))
298 			kfree(sg_virt(&as->urb->sg[i]));
299 	}
300 	kfree(as->urb->sg);
301 	kfree(as->urb->transfer_buffer);
302 	kfree(as->urb->setup_packet);
303 	usb_free_urb(as->urb);
304 	usbfs_decrease_memory_usage(as->mem_usage);
305 	kfree(as);
306 }
307 
308 static void async_newpending(struct async *as)
309 {
310 	struct usb_dev_state *ps = as->ps;
311 	unsigned long flags;
312 
313 	spin_lock_irqsave(&ps->lock, flags);
314 	list_add_tail(&as->asynclist, &ps->async_pending);
315 	spin_unlock_irqrestore(&ps->lock, flags);
316 }
317 
318 static void async_removepending(struct async *as)
319 {
320 	struct usb_dev_state *ps = as->ps;
321 	unsigned long flags;
322 
323 	spin_lock_irqsave(&ps->lock, flags);
324 	list_del_init(&as->asynclist);
325 	spin_unlock_irqrestore(&ps->lock, flags);
326 }
327 
328 static struct async *async_getcompleted(struct usb_dev_state *ps)
329 {
330 	unsigned long flags;
331 	struct async *as = NULL;
332 
333 	spin_lock_irqsave(&ps->lock, flags);
334 	if (!list_empty(&ps->async_completed)) {
335 		as = list_entry(ps->async_completed.next, struct async,
336 				asynclist);
337 		list_del_init(&as->asynclist);
338 	}
339 	spin_unlock_irqrestore(&ps->lock, flags);
340 	return as;
341 }
342 
343 static struct async *async_getpending(struct usb_dev_state *ps,
344 					     void __user *userurb)
345 {
346 	struct async *as;
347 
348 	list_for_each_entry(as, &ps->async_pending, asynclist)
349 		if (as->userurb == userurb) {
350 			list_del_init(&as->asynclist);
351 			return as;
352 		}
353 
354 	return NULL;
355 }
356 
357 static void snoop_urb(struct usb_device *udev,
358 		void __user *userurb, int pipe, unsigned length,
359 		int timeout_or_status, enum snoop_when when,
360 		unsigned char *data, unsigned data_len)
361 {
362 	static const char *types[] = {"isoc", "int", "ctrl", "bulk"};
363 	static const char *dirs[] = {"out", "in"};
364 	int ep;
365 	const char *t, *d;
366 
367 	if (!usbfs_snoop)
368 		return;
369 
370 	ep = usb_pipeendpoint(pipe);
371 	t = types[usb_pipetype(pipe)];
372 	d = dirs[!!usb_pipein(pipe)];
373 
374 	if (userurb) {		/* Async */
375 		if (when == SUBMIT)
376 			dev_info(&udev->dev, "userurb %p, ep%d %s-%s, "
377 					"length %u\n",
378 					userurb, ep, t, d, length);
379 		else
380 			dev_info(&udev->dev, "userurb %p, ep%d %s-%s, "
381 					"actual_length %u status %d\n",
382 					userurb, ep, t, d, length,
383 					timeout_or_status);
384 	} else {
385 		if (when == SUBMIT)
386 			dev_info(&udev->dev, "ep%d %s-%s, length %u, "
387 					"timeout %d\n",
388 					ep, t, d, length, timeout_or_status);
389 		else
390 			dev_info(&udev->dev, "ep%d %s-%s, actual_length %u, "
391 					"status %d\n",
392 					ep, t, d, length, timeout_or_status);
393 	}
394 
395 	if (data && data_len > 0) {
396 		print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1,
397 			data, data_len, 1);
398 	}
399 }
400 
401 static void snoop_urb_data(struct urb *urb, unsigned len)
402 {
403 	int i, size;
404 
405 	if (!usbfs_snoop)
406 		return;
407 
408 	if (urb->num_sgs == 0) {
409 		print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1,
410 			urb->transfer_buffer, len, 1);
411 		return;
412 	}
413 
414 	for (i = 0; i < urb->num_sgs && len; i++) {
415 		size = (len > USB_SG_SIZE) ? USB_SG_SIZE : len;
416 		print_hex_dump(KERN_DEBUG, "data: ", DUMP_PREFIX_NONE, 32, 1,
417 			sg_virt(&urb->sg[i]), size, 1);
418 		len -= size;
419 	}
420 }
421 
422 static int copy_urb_data_to_user(u8 __user *userbuffer, struct urb *urb)
423 {
424 	unsigned i, len, size;
425 
426 	if (urb->number_of_packets > 0)		/* Isochronous */
427 		len = urb->transfer_buffer_length;
428 	else					/* Non-Isoc */
429 		len = urb->actual_length;
430 
431 	if (urb->num_sgs == 0) {
432 		if (copy_to_user(userbuffer, urb->transfer_buffer, len))
433 			return -EFAULT;
434 		return 0;
435 	}
436 
437 	for (i = 0; i < urb->num_sgs && len; i++) {
438 		size = (len > USB_SG_SIZE) ? USB_SG_SIZE : len;
439 		if (copy_to_user(userbuffer, sg_virt(&urb->sg[i]), size))
440 			return -EFAULT;
441 		userbuffer += size;
442 		len -= size;
443 	}
444 
445 	return 0;
446 }
447 
448 #define AS_CONTINUATION	1
449 #define AS_UNLINK	2
450 
451 static void cancel_bulk_urbs(struct usb_dev_state *ps, unsigned bulk_addr)
452 __releases(ps->lock)
453 __acquires(ps->lock)
454 {
455 	struct urb *urb;
456 	struct async *as;
457 
458 	/* Mark all the pending URBs that match bulk_addr, up to but not
459 	 * including the first one without AS_CONTINUATION.  If such an
460 	 * URB is encountered then a new transfer has already started so
461 	 * the endpoint doesn't need to be disabled; otherwise it does.
462 	 */
463 	list_for_each_entry(as, &ps->async_pending, asynclist) {
464 		if (as->bulk_addr == bulk_addr) {
465 			if (as->bulk_status != AS_CONTINUATION)
466 				goto rescan;
467 			as->bulk_status = AS_UNLINK;
468 			as->bulk_addr = 0;
469 		}
470 	}
471 	ps->disabled_bulk_eps |= (1 << bulk_addr);
472 
473 	/* Now carefully unlink all the marked pending URBs */
474  rescan:
475 	list_for_each_entry(as, &ps->async_pending, asynclist) {
476 		if (as->bulk_status == AS_UNLINK) {
477 			as->bulk_status = 0;		/* Only once */
478 			urb = as->urb;
479 			usb_get_urb(urb);
480 			spin_unlock(&ps->lock);		/* Allow completions */
481 			usb_unlink_urb(urb);
482 			usb_put_urb(urb);
483 			spin_lock(&ps->lock);
484 			goto rescan;
485 		}
486 	}
487 }
488 
489 static void async_completed(struct urb *urb)
490 {
491 	struct async *as = urb->context;
492 	struct usb_dev_state *ps = as->ps;
493 	struct siginfo sinfo;
494 	struct pid *pid = NULL;
495 	u32 secid = 0;
496 	const struct cred *cred = NULL;
497 	int signr;
498 
499 	spin_lock(&ps->lock);
500 	list_move_tail(&as->asynclist, &ps->async_completed);
501 	as->status = urb->status;
502 	signr = as->signr;
503 	if (signr) {
504 		memset(&sinfo, 0, sizeof(sinfo));
505 		sinfo.si_signo = as->signr;
506 		sinfo.si_errno = as->status;
507 		sinfo.si_code = SI_ASYNCIO;
508 		sinfo.si_addr = as->userurb;
509 		pid = get_pid(as->pid);
510 		cred = get_cred(as->cred);
511 		secid = as->secid;
512 	}
513 	snoop(&urb->dev->dev, "urb complete\n");
514 	snoop_urb(urb->dev, as->userurb, urb->pipe, urb->actual_length,
515 			as->status, COMPLETE, NULL, 0);
516 	if ((urb->transfer_flags & URB_DIR_MASK) == USB_DIR_IN)
517 		snoop_urb_data(urb, urb->actual_length);
518 
519 	if (as->status < 0 && as->bulk_addr && as->status != -ECONNRESET &&
520 			as->status != -ENOENT)
521 		cancel_bulk_urbs(ps, as->bulk_addr);
522 	spin_unlock(&ps->lock);
523 
524 	if (signr) {
525 		kill_pid_info_as_cred(sinfo.si_signo, &sinfo, pid, cred, secid);
526 		put_pid(pid);
527 		put_cred(cred);
528 	}
529 
530 	wake_up(&ps->wait);
531 }
532 
533 static void destroy_async(struct usb_dev_state *ps, struct list_head *list)
534 {
535 	struct urb *urb;
536 	struct async *as;
537 	unsigned long flags;
538 
539 	spin_lock_irqsave(&ps->lock, flags);
540 	while (!list_empty(list)) {
541 		as = list_entry(list->next, struct async, asynclist);
542 		list_del_init(&as->asynclist);
543 		urb = as->urb;
544 		usb_get_urb(urb);
545 
546 		/* drop the spinlock so the completion handler can run */
547 		spin_unlock_irqrestore(&ps->lock, flags);
548 		usb_kill_urb(urb);
549 		usb_put_urb(urb);
550 		spin_lock_irqsave(&ps->lock, flags);
551 	}
552 	spin_unlock_irqrestore(&ps->lock, flags);
553 }
554 
555 static void destroy_async_on_interface(struct usb_dev_state *ps,
556 				       unsigned int ifnum)
557 {
558 	struct list_head *p, *q, hitlist;
559 	unsigned long flags;
560 
561 	INIT_LIST_HEAD(&hitlist);
562 	spin_lock_irqsave(&ps->lock, flags);
563 	list_for_each_safe(p, q, &ps->async_pending)
564 		if (ifnum == list_entry(p, struct async, asynclist)->ifnum)
565 			list_move_tail(p, &hitlist);
566 	spin_unlock_irqrestore(&ps->lock, flags);
567 	destroy_async(ps, &hitlist);
568 }
569 
570 static void destroy_all_async(struct usb_dev_state *ps)
571 {
572 	destroy_async(ps, &ps->async_pending);
573 }
574 
575 /*
576  * interface claims are made only at the request of user level code,
577  * which can also release them (explicitly or by closing files).
578  * they're also undone when devices disconnect.
579  */
580 
581 static int driver_probe(struct usb_interface *intf,
582 			const struct usb_device_id *id)
583 {
584 	return -ENODEV;
585 }
586 
587 static void driver_disconnect(struct usb_interface *intf)
588 {
589 	struct usb_dev_state *ps = usb_get_intfdata(intf);
590 	unsigned int ifnum = intf->altsetting->desc.bInterfaceNumber;
591 
592 	if (!ps)
593 		return;
594 
595 	/* NOTE:  this relies on usbcore having canceled and completed
596 	 * all pending I/O requests; 2.6 does that.
597 	 */
598 
599 	if (likely(ifnum < 8*sizeof(ps->ifclaimed)))
600 		clear_bit(ifnum, &ps->ifclaimed);
601 	else
602 		dev_warn(&intf->dev, "interface number %u out of range\n",
603 			 ifnum);
604 
605 	usb_set_intfdata(intf, NULL);
606 
607 	/* force async requests to complete */
608 	destroy_async_on_interface(ps, ifnum);
609 }
610 
611 /* The following routines are merely placeholders.  There is no way
612  * to inform a user task about suspend or resumes.
613  */
614 static int driver_suspend(struct usb_interface *intf, pm_message_t msg)
615 {
616 	return 0;
617 }
618 
619 static int driver_resume(struct usb_interface *intf)
620 {
621 	return 0;
622 }
623 
624 struct usb_driver usbfs_driver = {
625 	.name =		"usbfs",
626 	.probe =	driver_probe,
627 	.disconnect =	driver_disconnect,
628 	.suspend =	driver_suspend,
629 	.resume =	driver_resume,
630 };
631 
632 static int claimintf(struct usb_dev_state *ps, unsigned int ifnum)
633 {
634 	struct usb_device *dev = ps->dev;
635 	struct usb_interface *intf;
636 	int err;
637 
638 	if (ifnum >= 8*sizeof(ps->ifclaimed))
639 		return -EINVAL;
640 	/* already claimed */
641 	if (test_bit(ifnum, &ps->ifclaimed))
642 		return 0;
643 
644 	intf = usb_ifnum_to_if(dev, ifnum);
645 	if (!intf)
646 		err = -ENOENT;
647 	else
648 		err = usb_driver_claim_interface(&usbfs_driver, intf, ps);
649 	if (err == 0)
650 		set_bit(ifnum, &ps->ifclaimed);
651 	return err;
652 }
653 
654 static int releaseintf(struct usb_dev_state *ps, unsigned int ifnum)
655 {
656 	struct usb_device *dev;
657 	struct usb_interface *intf;
658 	int err;
659 
660 	err = -EINVAL;
661 	if (ifnum >= 8*sizeof(ps->ifclaimed))
662 		return err;
663 	dev = ps->dev;
664 	intf = usb_ifnum_to_if(dev, ifnum);
665 	if (!intf)
666 		err = -ENOENT;
667 	else if (test_and_clear_bit(ifnum, &ps->ifclaimed)) {
668 		usb_driver_release_interface(&usbfs_driver, intf);
669 		err = 0;
670 	}
671 	return err;
672 }
673 
674 static int checkintf(struct usb_dev_state *ps, unsigned int ifnum)
675 {
676 	if (ps->dev->state != USB_STATE_CONFIGURED)
677 		return -EHOSTUNREACH;
678 	if (ifnum >= 8*sizeof(ps->ifclaimed))
679 		return -EINVAL;
680 	if (test_bit(ifnum, &ps->ifclaimed))
681 		return 0;
682 	/* if not yet claimed, claim it for the driver */
683 	dev_warn(&ps->dev->dev, "usbfs: process %d (%s) did not claim "
684 		 "interface %u before use\n", task_pid_nr(current),
685 		 current->comm, ifnum);
686 	return claimintf(ps, ifnum);
687 }
688 
689 static int findintfep(struct usb_device *dev, unsigned int ep)
690 {
691 	unsigned int i, j, e;
692 	struct usb_interface *intf;
693 	struct usb_host_interface *alts;
694 	struct usb_endpoint_descriptor *endpt;
695 
696 	if (ep & ~(USB_DIR_IN|0xf))
697 		return -EINVAL;
698 	if (!dev->actconfig)
699 		return -ESRCH;
700 	for (i = 0; i < dev->actconfig->desc.bNumInterfaces; i++) {
701 		intf = dev->actconfig->interface[i];
702 		for (j = 0; j < intf->num_altsetting; j++) {
703 			alts = &intf->altsetting[j];
704 			for (e = 0; e < alts->desc.bNumEndpoints; e++) {
705 				endpt = &alts->endpoint[e].desc;
706 				if (endpt->bEndpointAddress == ep)
707 					return alts->desc.bInterfaceNumber;
708 			}
709 		}
710 	}
711 	return -ENOENT;
712 }
713 
714 static int check_ctrlrecip(struct usb_dev_state *ps, unsigned int requesttype,
715 			   unsigned int request, unsigned int index)
716 {
717 	int ret = 0;
718 	struct usb_host_interface *alt_setting;
719 
720 	if (ps->dev->state != USB_STATE_UNAUTHENTICATED
721 	 && ps->dev->state != USB_STATE_ADDRESS
722 	 && ps->dev->state != USB_STATE_CONFIGURED)
723 		return -EHOSTUNREACH;
724 	if (USB_TYPE_VENDOR == (USB_TYPE_MASK & requesttype))
725 		return 0;
726 
727 	/*
728 	 * check for the special corner case 'get_device_id' in the printer
729 	 * class specification, which we always want to allow as it is used
730 	 * to query things like ink level, etc.
731 	 */
732 	if (requesttype == 0xa1 && request == 0) {
733 		alt_setting = usb_find_alt_setting(ps->dev->actconfig,
734 						   index >> 8, index & 0xff);
735 		if (alt_setting
736 		 && alt_setting->desc.bInterfaceClass == USB_CLASS_PRINTER)
737 			return 0;
738 	}
739 
740 	index &= 0xff;
741 	switch (requesttype & USB_RECIP_MASK) {
742 	case USB_RECIP_ENDPOINT:
743 		if ((index & ~USB_DIR_IN) == 0)
744 			return 0;
745 		ret = findintfep(ps->dev, index);
746 		if (ret < 0) {
747 			/*
748 			 * Some not fully compliant Win apps seem to get
749 			 * index wrong and have the endpoint number here
750 			 * rather than the endpoint address (with the
751 			 * correct direction). Win does let this through,
752 			 * so we'll not reject it here but leave it to
753 			 * the device to not break KVM. But we warn.
754 			 */
755 			ret = findintfep(ps->dev, index ^ 0x80);
756 			if (ret >= 0)
757 				dev_info(&ps->dev->dev,
758 					"%s: process %i (%s) requesting ep %02x but needs %02x\n",
759 					__func__, task_pid_nr(current),
760 					current->comm, index, index ^ 0x80);
761 		}
762 		if (ret >= 0)
763 			ret = checkintf(ps, ret);
764 		break;
765 
766 	case USB_RECIP_INTERFACE:
767 		ret = checkintf(ps, index);
768 		break;
769 	}
770 	return ret;
771 }
772 
773 static struct usb_host_endpoint *ep_to_host_endpoint(struct usb_device *dev,
774 						     unsigned char ep)
775 {
776 	if (ep & USB_ENDPOINT_DIR_MASK)
777 		return dev->ep_in[ep & USB_ENDPOINT_NUMBER_MASK];
778 	else
779 		return dev->ep_out[ep & USB_ENDPOINT_NUMBER_MASK];
780 }
781 
782 static int parse_usbdevfs_streams(struct usb_dev_state *ps,
783 				  struct usbdevfs_streams __user *streams,
784 				  unsigned int *num_streams_ret,
785 				  unsigned int *num_eps_ret,
786 				  struct usb_host_endpoint ***eps_ret,
787 				  struct usb_interface **intf_ret)
788 {
789 	unsigned int i, num_streams, num_eps;
790 	struct usb_host_endpoint **eps;
791 	struct usb_interface *intf = NULL;
792 	unsigned char ep;
793 	int ifnum, ret;
794 
795 	if (get_user(num_streams, &streams->num_streams) ||
796 	    get_user(num_eps, &streams->num_eps))
797 		return -EFAULT;
798 
799 	if (num_eps < 1 || num_eps > USB_MAXENDPOINTS)
800 		return -EINVAL;
801 
802 	/* The XHCI controller allows max 2 ^ 16 streams */
803 	if (num_streams_ret && (num_streams < 2 || num_streams > 65536))
804 		return -EINVAL;
805 
806 	eps = kmalloc(num_eps * sizeof(*eps), GFP_KERNEL);
807 	if (!eps)
808 		return -ENOMEM;
809 
810 	for (i = 0; i < num_eps; i++) {
811 		if (get_user(ep, &streams->eps[i])) {
812 			ret = -EFAULT;
813 			goto error;
814 		}
815 		eps[i] = ep_to_host_endpoint(ps->dev, ep);
816 		if (!eps[i]) {
817 			ret = -EINVAL;
818 			goto error;
819 		}
820 
821 		/* usb_alloc/free_streams operate on an usb_interface */
822 		ifnum = findintfep(ps->dev, ep);
823 		if (ifnum < 0) {
824 			ret = ifnum;
825 			goto error;
826 		}
827 
828 		if (i == 0) {
829 			ret = checkintf(ps, ifnum);
830 			if (ret < 0)
831 				goto error;
832 			intf = usb_ifnum_to_if(ps->dev, ifnum);
833 		} else {
834 			/* Verify all eps belong to the same interface */
835 			if (ifnum != intf->altsetting->desc.bInterfaceNumber) {
836 				ret = -EINVAL;
837 				goto error;
838 			}
839 		}
840 	}
841 
842 	if (num_streams_ret)
843 		*num_streams_ret = num_streams;
844 	*num_eps_ret = num_eps;
845 	*eps_ret = eps;
846 	*intf_ret = intf;
847 
848 	return 0;
849 
850 error:
851 	kfree(eps);
852 	return ret;
853 }
854 
855 static int match_devt(struct device *dev, void *data)
856 {
857 	return dev->devt == (dev_t) (unsigned long) data;
858 }
859 
860 static struct usb_device *usbdev_lookup_by_devt(dev_t devt)
861 {
862 	struct device *dev;
863 
864 	dev = bus_find_device(&usb_bus_type, NULL,
865 			      (void *) (unsigned long) devt, match_devt);
866 	if (!dev)
867 		return NULL;
868 	return container_of(dev, struct usb_device, dev);
869 }
870 
871 /*
872  * file operations
873  */
874 static int usbdev_open(struct inode *inode, struct file *file)
875 {
876 	struct usb_device *dev = NULL;
877 	struct usb_dev_state *ps;
878 	int ret;
879 
880 	ret = -ENOMEM;
881 	ps = kmalloc(sizeof(struct usb_dev_state), GFP_KERNEL);
882 	if (!ps)
883 		goto out_free_ps;
884 
885 	ret = -ENODEV;
886 
887 	/* Protect against simultaneous removal or release */
888 	mutex_lock(&usbfs_mutex);
889 
890 	/* usbdev device-node */
891 	if (imajor(inode) == USB_DEVICE_MAJOR)
892 		dev = usbdev_lookup_by_devt(inode->i_rdev);
893 
894 	mutex_unlock(&usbfs_mutex);
895 
896 	if (!dev)
897 		goto out_free_ps;
898 
899 	usb_lock_device(dev);
900 	if (dev->state == USB_STATE_NOTATTACHED)
901 		goto out_unlock_device;
902 
903 	ret = usb_autoresume_device(dev);
904 	if (ret)
905 		goto out_unlock_device;
906 
907 	ps->dev = dev;
908 	ps->file = file;
909 	spin_lock_init(&ps->lock);
910 	INIT_LIST_HEAD(&ps->list);
911 	INIT_LIST_HEAD(&ps->async_pending);
912 	INIT_LIST_HEAD(&ps->async_completed);
913 	init_waitqueue_head(&ps->wait);
914 	ps->discsignr = 0;
915 	ps->disc_pid = get_pid(task_pid(current));
916 	ps->cred = get_current_cred();
917 	ps->disccontext = NULL;
918 	ps->ifclaimed = 0;
919 	security_task_getsecid(current, &ps->secid);
920 	smp_wmb();
921 	list_add_tail(&ps->list, &dev->filelist);
922 	file->private_data = ps;
923 	usb_unlock_device(dev);
924 	snoop(&dev->dev, "opened by process %d: %s\n", task_pid_nr(current),
925 			current->comm);
926 	return ret;
927 
928  out_unlock_device:
929 	usb_unlock_device(dev);
930 	usb_put_dev(dev);
931  out_free_ps:
932 	kfree(ps);
933 	return ret;
934 }
935 
936 static int usbdev_release(struct inode *inode, struct file *file)
937 {
938 	struct usb_dev_state *ps = file->private_data;
939 	struct usb_device *dev = ps->dev;
940 	unsigned int ifnum;
941 	struct async *as;
942 
943 	usb_lock_device(dev);
944 	usb_hub_release_all_ports(dev, ps);
945 
946 	list_del_init(&ps->list);
947 
948 	for (ifnum = 0; ps->ifclaimed && ifnum < 8*sizeof(ps->ifclaimed);
949 			ifnum++) {
950 		if (test_bit(ifnum, &ps->ifclaimed))
951 			releaseintf(ps, ifnum);
952 	}
953 	destroy_all_async(ps);
954 	usb_autosuspend_device(dev);
955 	usb_unlock_device(dev);
956 	usb_put_dev(dev);
957 	put_pid(ps->disc_pid);
958 	put_cred(ps->cred);
959 
960 	as = async_getcompleted(ps);
961 	while (as) {
962 		free_async(as);
963 		as = async_getcompleted(ps);
964 	}
965 	kfree(ps);
966 	return 0;
967 }
968 
969 static int proc_control(struct usb_dev_state *ps, void __user *arg)
970 {
971 	struct usb_device *dev = ps->dev;
972 	struct usbdevfs_ctrltransfer ctrl;
973 	unsigned int tmo;
974 	unsigned char *tbuf;
975 	unsigned wLength;
976 	int i, pipe, ret;
977 
978 	if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
979 		return -EFAULT;
980 	ret = check_ctrlrecip(ps, ctrl.bRequestType, ctrl.bRequest,
981 			      ctrl.wIndex);
982 	if (ret)
983 		return ret;
984 	wLength = ctrl.wLength;		/* To suppress 64k PAGE_SIZE warning */
985 	if (wLength > PAGE_SIZE)
986 		return -EINVAL;
987 	ret = usbfs_increase_memory_usage(PAGE_SIZE + sizeof(struct urb) +
988 			sizeof(struct usb_ctrlrequest));
989 	if (ret)
990 		return ret;
991 	tbuf = (unsigned char *)__get_free_page(GFP_KERNEL);
992 	if (!tbuf) {
993 		ret = -ENOMEM;
994 		goto done;
995 	}
996 	tmo = ctrl.timeout;
997 	snoop(&dev->dev, "control urb: bRequestType=%02x "
998 		"bRequest=%02x wValue=%04x "
999 		"wIndex=%04x wLength=%04x\n",
1000 		ctrl.bRequestType, ctrl.bRequest, ctrl.wValue,
1001 		ctrl.wIndex, ctrl.wLength);
1002 	if (ctrl.bRequestType & 0x80) {
1003 		if (ctrl.wLength && !access_ok(VERIFY_WRITE, ctrl.data,
1004 					       ctrl.wLength)) {
1005 			ret = -EINVAL;
1006 			goto done;
1007 		}
1008 		pipe = usb_rcvctrlpipe(dev, 0);
1009 		snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT, NULL, 0);
1010 
1011 		usb_unlock_device(dev);
1012 		i = usb_control_msg(dev, pipe, ctrl.bRequest,
1013 				    ctrl.bRequestType, ctrl.wValue, ctrl.wIndex,
1014 				    tbuf, ctrl.wLength, tmo);
1015 		usb_lock_device(dev);
1016 		snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE,
1017 			  tbuf, max(i, 0));
1018 		if ((i > 0) && ctrl.wLength) {
1019 			if (copy_to_user(ctrl.data, tbuf, i)) {
1020 				ret = -EFAULT;
1021 				goto done;
1022 			}
1023 		}
1024 	} else {
1025 		if (ctrl.wLength) {
1026 			if (copy_from_user(tbuf, ctrl.data, ctrl.wLength)) {
1027 				ret = -EFAULT;
1028 				goto done;
1029 			}
1030 		}
1031 		pipe = usb_sndctrlpipe(dev, 0);
1032 		snoop_urb(dev, NULL, pipe, ctrl.wLength, tmo, SUBMIT,
1033 			tbuf, ctrl.wLength);
1034 
1035 		usb_unlock_device(dev);
1036 		i = usb_control_msg(dev, usb_sndctrlpipe(dev, 0), ctrl.bRequest,
1037 				    ctrl.bRequestType, ctrl.wValue, ctrl.wIndex,
1038 				    tbuf, ctrl.wLength, tmo);
1039 		usb_lock_device(dev);
1040 		snoop_urb(dev, NULL, pipe, max(i, 0), min(i, 0), COMPLETE, NULL, 0);
1041 	}
1042 	if (i < 0 && i != -EPIPE) {
1043 		dev_printk(KERN_DEBUG, &dev->dev, "usbfs: USBDEVFS_CONTROL "
1044 			   "failed cmd %s rqt %u rq %u len %u ret %d\n",
1045 			   current->comm, ctrl.bRequestType, ctrl.bRequest,
1046 			   ctrl.wLength, i);
1047 	}
1048 	ret = i;
1049  done:
1050 	free_page((unsigned long) tbuf);
1051 	usbfs_decrease_memory_usage(PAGE_SIZE + sizeof(struct urb) +
1052 			sizeof(struct usb_ctrlrequest));
1053 	return ret;
1054 }
1055 
1056 static int proc_bulk(struct usb_dev_state *ps, void __user *arg)
1057 {
1058 	struct usb_device *dev = ps->dev;
1059 	struct usbdevfs_bulktransfer bulk;
1060 	unsigned int tmo, len1, pipe;
1061 	int len2;
1062 	unsigned char *tbuf;
1063 	int i, ret;
1064 
1065 	if (copy_from_user(&bulk, arg, sizeof(bulk)))
1066 		return -EFAULT;
1067 	ret = findintfep(ps->dev, bulk.ep);
1068 	if (ret < 0)
1069 		return ret;
1070 	ret = checkintf(ps, ret);
1071 	if (ret)
1072 		return ret;
1073 	if (bulk.ep & USB_DIR_IN)
1074 		pipe = usb_rcvbulkpipe(dev, bulk.ep & 0x7f);
1075 	else
1076 		pipe = usb_sndbulkpipe(dev, bulk.ep & 0x7f);
1077 	if (!usb_maxpacket(dev, pipe, !(bulk.ep & USB_DIR_IN)))
1078 		return -EINVAL;
1079 	len1 = bulk.len;
1080 	if (len1 >= USBFS_XFER_MAX)
1081 		return -EINVAL;
1082 	ret = usbfs_increase_memory_usage(len1 + sizeof(struct urb));
1083 	if (ret)
1084 		return ret;
1085 	if (!(tbuf = kmalloc(len1, GFP_KERNEL))) {
1086 		ret = -ENOMEM;
1087 		goto done;
1088 	}
1089 	tmo = bulk.timeout;
1090 	if (bulk.ep & 0x80) {
1091 		if (len1 && !access_ok(VERIFY_WRITE, bulk.data, len1)) {
1092 			ret = -EINVAL;
1093 			goto done;
1094 		}
1095 		snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT, NULL, 0);
1096 
1097 		usb_unlock_device(dev);
1098 		i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo);
1099 		usb_lock_device(dev);
1100 		snoop_urb(dev, NULL, pipe, len2, i, COMPLETE, tbuf, len2);
1101 
1102 		if (!i && len2) {
1103 			if (copy_to_user(bulk.data, tbuf, len2)) {
1104 				ret = -EFAULT;
1105 				goto done;
1106 			}
1107 		}
1108 	} else {
1109 		if (len1) {
1110 			if (copy_from_user(tbuf, bulk.data, len1)) {
1111 				ret = -EFAULT;
1112 				goto done;
1113 			}
1114 		}
1115 		snoop_urb(dev, NULL, pipe, len1, tmo, SUBMIT, tbuf, len1);
1116 
1117 		usb_unlock_device(dev);
1118 		i = usb_bulk_msg(dev, pipe, tbuf, len1, &len2, tmo);
1119 		usb_lock_device(dev);
1120 		snoop_urb(dev, NULL, pipe, len2, i, COMPLETE, NULL, 0);
1121 	}
1122 	ret = (i < 0 ? i : len2);
1123  done:
1124 	kfree(tbuf);
1125 	usbfs_decrease_memory_usage(len1 + sizeof(struct urb));
1126 	return ret;
1127 }
1128 
1129 static void check_reset_of_active_ep(struct usb_device *udev,
1130 		unsigned int epnum, char *ioctl_name)
1131 {
1132 	struct usb_host_endpoint **eps;
1133 	struct usb_host_endpoint *ep;
1134 
1135 	eps = (epnum & USB_DIR_IN) ? udev->ep_in : udev->ep_out;
1136 	ep = eps[epnum & 0x0f];
1137 	if (ep && !list_empty(&ep->urb_list))
1138 		dev_warn(&udev->dev, "Process %d (%s) called USBDEVFS_%s for active endpoint 0x%02x\n",
1139 				task_pid_nr(current), current->comm,
1140 				ioctl_name, epnum);
1141 }
1142 
1143 static int proc_resetep(struct usb_dev_state *ps, void __user *arg)
1144 {
1145 	unsigned int ep;
1146 	int ret;
1147 
1148 	if (get_user(ep, (unsigned int __user *)arg))
1149 		return -EFAULT;
1150 	ret = findintfep(ps->dev, ep);
1151 	if (ret < 0)
1152 		return ret;
1153 	ret = checkintf(ps, ret);
1154 	if (ret)
1155 		return ret;
1156 	check_reset_of_active_ep(ps->dev, ep, "RESETEP");
1157 	usb_reset_endpoint(ps->dev, ep);
1158 	return 0;
1159 }
1160 
1161 static int proc_clearhalt(struct usb_dev_state *ps, void __user *arg)
1162 {
1163 	unsigned int ep;
1164 	int pipe;
1165 	int ret;
1166 
1167 	if (get_user(ep, (unsigned int __user *)arg))
1168 		return -EFAULT;
1169 	ret = findintfep(ps->dev, ep);
1170 	if (ret < 0)
1171 		return ret;
1172 	ret = checkintf(ps, ret);
1173 	if (ret)
1174 		return ret;
1175 	check_reset_of_active_ep(ps->dev, ep, "CLEAR_HALT");
1176 	if (ep & USB_DIR_IN)
1177 		pipe = usb_rcvbulkpipe(ps->dev, ep & 0x7f);
1178 	else
1179 		pipe = usb_sndbulkpipe(ps->dev, ep & 0x7f);
1180 
1181 	return usb_clear_halt(ps->dev, pipe);
1182 }
1183 
1184 static int proc_getdriver(struct usb_dev_state *ps, void __user *arg)
1185 {
1186 	struct usbdevfs_getdriver gd;
1187 	struct usb_interface *intf;
1188 	int ret;
1189 
1190 	if (copy_from_user(&gd, arg, sizeof(gd)))
1191 		return -EFAULT;
1192 	intf = usb_ifnum_to_if(ps->dev, gd.interface);
1193 	if (!intf || !intf->dev.driver)
1194 		ret = -ENODATA;
1195 	else {
1196 		strlcpy(gd.driver, intf->dev.driver->name,
1197 				sizeof(gd.driver));
1198 		ret = (copy_to_user(arg, &gd, sizeof(gd)) ? -EFAULT : 0);
1199 	}
1200 	return ret;
1201 }
1202 
1203 static int proc_connectinfo(struct usb_dev_state *ps, void __user *arg)
1204 {
1205 	struct usbdevfs_connectinfo ci = {
1206 		.devnum = ps->dev->devnum,
1207 		.slow = ps->dev->speed == USB_SPEED_LOW
1208 	};
1209 
1210 	if (copy_to_user(arg, &ci, sizeof(ci)))
1211 		return -EFAULT;
1212 	return 0;
1213 }
1214 
1215 static int proc_resetdevice(struct usb_dev_state *ps)
1216 {
1217 	return usb_reset_device(ps->dev);
1218 }
1219 
1220 static int proc_setintf(struct usb_dev_state *ps, void __user *arg)
1221 {
1222 	struct usbdevfs_setinterface setintf;
1223 	int ret;
1224 
1225 	if (copy_from_user(&setintf, arg, sizeof(setintf)))
1226 		return -EFAULT;
1227 	if ((ret = checkintf(ps, setintf.interface)))
1228 		return ret;
1229 
1230 	destroy_async_on_interface(ps, setintf.interface);
1231 
1232 	return usb_set_interface(ps->dev, setintf.interface,
1233 			setintf.altsetting);
1234 }
1235 
1236 static int proc_setconfig(struct usb_dev_state *ps, void __user *arg)
1237 {
1238 	int u;
1239 	int status = 0;
1240 	struct usb_host_config *actconfig;
1241 
1242 	if (get_user(u, (int __user *)arg))
1243 		return -EFAULT;
1244 
1245 	actconfig = ps->dev->actconfig;
1246 
1247 	/* Don't touch the device if any interfaces are claimed.
1248 	 * It could interfere with other drivers' operations, and if
1249 	 * an interface is claimed by usbfs it could easily deadlock.
1250 	 */
1251 	if (actconfig) {
1252 		int i;
1253 
1254 		for (i = 0; i < actconfig->desc.bNumInterfaces; ++i) {
1255 			if (usb_interface_claimed(actconfig->interface[i])) {
1256 				dev_warn(&ps->dev->dev,
1257 					"usbfs: interface %d claimed by %s "
1258 					"while '%s' sets config #%d\n",
1259 					actconfig->interface[i]
1260 						->cur_altsetting
1261 						->desc.bInterfaceNumber,
1262 					actconfig->interface[i]
1263 						->dev.driver->name,
1264 					current->comm, u);
1265 				status = -EBUSY;
1266 				break;
1267 			}
1268 		}
1269 	}
1270 
1271 	/* SET_CONFIGURATION is often abused as a "cheap" driver reset,
1272 	 * so avoid usb_set_configuration()'s kick to sysfs
1273 	 */
1274 	if (status == 0) {
1275 		if (actconfig && actconfig->desc.bConfigurationValue == u)
1276 			status = usb_reset_configuration(ps->dev);
1277 		else
1278 			status = usb_set_configuration(ps->dev, u);
1279 	}
1280 
1281 	return status;
1282 }
1283 
1284 static int proc_do_submiturb(struct usb_dev_state *ps, struct usbdevfs_urb *uurb,
1285 			struct usbdevfs_iso_packet_desc __user *iso_frame_desc,
1286 			void __user *arg)
1287 {
1288 	struct usbdevfs_iso_packet_desc *isopkt = NULL;
1289 	struct usb_host_endpoint *ep;
1290 	struct async *as = NULL;
1291 	struct usb_ctrlrequest *dr = NULL;
1292 	unsigned int u, totlen, isofrmlen;
1293 	int i, ret, is_in, num_sgs = 0, ifnum = -1;
1294 	int number_of_packets = 0;
1295 	unsigned int stream_id = 0;
1296 	void *buf;
1297 
1298 	if (uurb->flags & ~(USBDEVFS_URB_ISO_ASAP |
1299 				USBDEVFS_URB_SHORT_NOT_OK |
1300 				USBDEVFS_URB_BULK_CONTINUATION |
1301 				USBDEVFS_URB_NO_FSBR |
1302 				USBDEVFS_URB_ZERO_PACKET |
1303 				USBDEVFS_URB_NO_INTERRUPT))
1304 		return -EINVAL;
1305 	if (uurb->buffer_length > 0 && !uurb->buffer)
1306 		return -EINVAL;
1307 	if (!(uurb->type == USBDEVFS_URB_TYPE_CONTROL &&
1308 	    (uurb->endpoint & ~USB_ENDPOINT_DIR_MASK) == 0)) {
1309 		ifnum = findintfep(ps->dev, uurb->endpoint);
1310 		if (ifnum < 0)
1311 			return ifnum;
1312 		ret = checkintf(ps, ifnum);
1313 		if (ret)
1314 			return ret;
1315 	}
1316 	ep = ep_to_host_endpoint(ps->dev, uurb->endpoint);
1317 	if (!ep)
1318 		return -ENOENT;
1319 	is_in = (uurb->endpoint & USB_ENDPOINT_DIR_MASK) != 0;
1320 
1321 	u = 0;
1322 	switch(uurb->type) {
1323 	case USBDEVFS_URB_TYPE_CONTROL:
1324 		if (!usb_endpoint_xfer_control(&ep->desc))
1325 			return -EINVAL;
1326 		/* min 8 byte setup packet */
1327 		if (uurb->buffer_length < 8)
1328 			return -EINVAL;
1329 		dr = kmalloc(sizeof(struct usb_ctrlrequest), GFP_KERNEL);
1330 		if (!dr)
1331 			return -ENOMEM;
1332 		if (copy_from_user(dr, uurb->buffer, 8)) {
1333 			ret = -EFAULT;
1334 			goto error;
1335 		}
1336 		if (uurb->buffer_length < (le16_to_cpup(&dr->wLength) + 8)) {
1337 			ret = -EINVAL;
1338 			goto error;
1339 		}
1340 		ret = check_ctrlrecip(ps, dr->bRequestType, dr->bRequest,
1341 				      le16_to_cpup(&dr->wIndex));
1342 		if (ret)
1343 			goto error;
1344 		uurb->buffer_length = le16_to_cpup(&dr->wLength);
1345 		uurb->buffer += 8;
1346 		if ((dr->bRequestType & USB_DIR_IN) && uurb->buffer_length) {
1347 			is_in = 1;
1348 			uurb->endpoint |= USB_DIR_IN;
1349 		} else {
1350 			is_in = 0;
1351 			uurb->endpoint &= ~USB_DIR_IN;
1352 		}
1353 		snoop(&ps->dev->dev, "control urb: bRequestType=%02x "
1354 			"bRequest=%02x wValue=%04x "
1355 			"wIndex=%04x wLength=%04x\n",
1356 			dr->bRequestType, dr->bRequest,
1357 			__le16_to_cpup(&dr->wValue),
1358 			__le16_to_cpup(&dr->wIndex),
1359 			__le16_to_cpup(&dr->wLength));
1360 		u = sizeof(struct usb_ctrlrequest);
1361 		break;
1362 
1363 	case USBDEVFS_URB_TYPE_BULK:
1364 		switch (usb_endpoint_type(&ep->desc)) {
1365 		case USB_ENDPOINT_XFER_CONTROL:
1366 		case USB_ENDPOINT_XFER_ISOC:
1367 			return -EINVAL;
1368 		case USB_ENDPOINT_XFER_INT:
1369 			/* allow single-shot interrupt transfers */
1370 			uurb->type = USBDEVFS_URB_TYPE_INTERRUPT;
1371 			goto interrupt_urb;
1372 		}
1373 		num_sgs = DIV_ROUND_UP(uurb->buffer_length, USB_SG_SIZE);
1374 		if (num_sgs == 1 || num_sgs > ps->dev->bus->sg_tablesize)
1375 			num_sgs = 0;
1376 		if (ep->streams)
1377 			stream_id = uurb->stream_id;
1378 		break;
1379 
1380 	case USBDEVFS_URB_TYPE_INTERRUPT:
1381 		if (!usb_endpoint_xfer_int(&ep->desc))
1382 			return -EINVAL;
1383  interrupt_urb:
1384 		break;
1385 
1386 	case USBDEVFS_URB_TYPE_ISO:
1387 		/* arbitrary limit */
1388 		if (uurb->number_of_packets < 1 ||
1389 		    uurb->number_of_packets > 128)
1390 			return -EINVAL;
1391 		if (!usb_endpoint_xfer_isoc(&ep->desc))
1392 			return -EINVAL;
1393 		number_of_packets = uurb->number_of_packets;
1394 		isofrmlen = sizeof(struct usbdevfs_iso_packet_desc) *
1395 				   number_of_packets;
1396 		if (!(isopkt = kmalloc(isofrmlen, GFP_KERNEL)))
1397 			return -ENOMEM;
1398 		if (copy_from_user(isopkt, iso_frame_desc, isofrmlen)) {
1399 			ret = -EFAULT;
1400 			goto error;
1401 		}
1402 		for (totlen = u = 0; u < number_of_packets; u++) {
1403 			/*
1404 			 * arbitrary limit need for USB 3.0
1405 			 * bMaxBurst (0~15 allowed, 1~16 packets)
1406 			 * bmAttributes (bit 1:0, mult 0~2, 1~3 packets)
1407 			 * sizemax: 1024 * 16 * 3 = 49152
1408 			 */
1409 			if (isopkt[u].length > 49152) {
1410 				ret = -EINVAL;
1411 				goto error;
1412 			}
1413 			totlen += isopkt[u].length;
1414 		}
1415 		u *= sizeof(struct usb_iso_packet_descriptor);
1416 		uurb->buffer_length = totlen;
1417 		break;
1418 
1419 	default:
1420 		return -EINVAL;
1421 	}
1422 
1423 	if (uurb->buffer_length >= USBFS_XFER_MAX) {
1424 		ret = -EINVAL;
1425 		goto error;
1426 	}
1427 	if (uurb->buffer_length > 0 &&
1428 			!access_ok(is_in ? VERIFY_WRITE : VERIFY_READ,
1429 				uurb->buffer, uurb->buffer_length)) {
1430 		ret = -EFAULT;
1431 		goto error;
1432 	}
1433 	as = alloc_async(number_of_packets);
1434 	if (!as) {
1435 		ret = -ENOMEM;
1436 		goto error;
1437 	}
1438 
1439 	u += sizeof(struct async) + sizeof(struct urb) + uurb->buffer_length +
1440 	     num_sgs * sizeof(struct scatterlist);
1441 	ret = usbfs_increase_memory_usage(u);
1442 	if (ret)
1443 		goto error;
1444 	as->mem_usage = u;
1445 
1446 	if (num_sgs) {
1447 		as->urb->sg = kmalloc(num_sgs * sizeof(struct scatterlist),
1448 				      GFP_KERNEL);
1449 		if (!as->urb->sg) {
1450 			ret = -ENOMEM;
1451 			goto error;
1452 		}
1453 		as->urb->num_sgs = num_sgs;
1454 		sg_init_table(as->urb->sg, as->urb->num_sgs);
1455 
1456 		totlen = uurb->buffer_length;
1457 		for (i = 0; i < as->urb->num_sgs; i++) {
1458 			u = (totlen > USB_SG_SIZE) ? USB_SG_SIZE : totlen;
1459 			buf = kmalloc(u, GFP_KERNEL);
1460 			if (!buf) {
1461 				ret = -ENOMEM;
1462 				goto error;
1463 			}
1464 			sg_set_buf(&as->urb->sg[i], buf, u);
1465 
1466 			if (!is_in) {
1467 				if (copy_from_user(buf, uurb->buffer, u)) {
1468 					ret = -EFAULT;
1469 					goto error;
1470 				}
1471 				uurb->buffer += u;
1472 			}
1473 			totlen -= u;
1474 		}
1475 	} else if (uurb->buffer_length > 0) {
1476 		as->urb->transfer_buffer = kmalloc(uurb->buffer_length,
1477 				GFP_KERNEL);
1478 		if (!as->urb->transfer_buffer) {
1479 			ret = -ENOMEM;
1480 			goto error;
1481 		}
1482 
1483 		if (!is_in) {
1484 			if (copy_from_user(as->urb->transfer_buffer,
1485 					   uurb->buffer,
1486 					   uurb->buffer_length)) {
1487 				ret = -EFAULT;
1488 				goto error;
1489 			}
1490 		} else if (uurb->type == USBDEVFS_URB_TYPE_ISO) {
1491 			/*
1492 			 * Isochronous input data may end up being
1493 			 * discontiguous if some of the packets are short.
1494 			 * Clear the buffer so that the gaps don't leak
1495 			 * kernel data to userspace.
1496 			 */
1497 			memset(as->urb->transfer_buffer, 0,
1498 					uurb->buffer_length);
1499 		}
1500 	}
1501 	as->urb->dev = ps->dev;
1502 	as->urb->pipe = (uurb->type << 30) |
1503 			__create_pipe(ps->dev, uurb->endpoint & 0xf) |
1504 			(uurb->endpoint & USB_DIR_IN);
1505 
1506 	/* This tedious sequence is necessary because the URB_* flags
1507 	 * are internal to the kernel and subject to change, whereas
1508 	 * the USBDEVFS_URB_* flags are a user API and must not be changed.
1509 	 */
1510 	u = (is_in ? URB_DIR_IN : URB_DIR_OUT);
1511 	if (uurb->flags & USBDEVFS_URB_ISO_ASAP)
1512 		u |= URB_ISO_ASAP;
1513 	if (uurb->flags & USBDEVFS_URB_SHORT_NOT_OK && is_in)
1514 		u |= URB_SHORT_NOT_OK;
1515 	if (uurb->flags & USBDEVFS_URB_NO_FSBR)
1516 		u |= URB_NO_FSBR;
1517 	if (uurb->flags & USBDEVFS_URB_ZERO_PACKET)
1518 		u |= URB_ZERO_PACKET;
1519 	if (uurb->flags & USBDEVFS_URB_NO_INTERRUPT)
1520 		u |= URB_NO_INTERRUPT;
1521 	as->urb->transfer_flags = u;
1522 
1523 	as->urb->transfer_buffer_length = uurb->buffer_length;
1524 	as->urb->setup_packet = (unsigned char *)dr;
1525 	dr = NULL;
1526 	as->urb->start_frame = uurb->start_frame;
1527 	as->urb->number_of_packets = number_of_packets;
1528 	as->urb->stream_id = stream_id;
1529 	if (uurb->type == USBDEVFS_URB_TYPE_ISO ||
1530 			ps->dev->speed == USB_SPEED_HIGH)
1531 		as->urb->interval = 1 << min(15, ep->desc.bInterval - 1);
1532 	else
1533 		as->urb->interval = ep->desc.bInterval;
1534 	as->urb->context = as;
1535 	as->urb->complete = async_completed;
1536 	for (totlen = u = 0; u < number_of_packets; u++) {
1537 		as->urb->iso_frame_desc[u].offset = totlen;
1538 		as->urb->iso_frame_desc[u].length = isopkt[u].length;
1539 		totlen += isopkt[u].length;
1540 	}
1541 	kfree(isopkt);
1542 	isopkt = NULL;
1543 	as->ps = ps;
1544 	as->userurb = arg;
1545 	if (is_in && uurb->buffer_length > 0)
1546 		as->userbuffer = uurb->buffer;
1547 	else
1548 		as->userbuffer = NULL;
1549 	as->signr = uurb->signr;
1550 	as->ifnum = ifnum;
1551 	as->pid = get_pid(task_pid(current));
1552 	as->cred = get_current_cred();
1553 	security_task_getsecid(current, &as->secid);
1554 	snoop_urb(ps->dev, as->userurb, as->urb->pipe,
1555 			as->urb->transfer_buffer_length, 0, SUBMIT,
1556 			NULL, 0);
1557 	if (!is_in)
1558 		snoop_urb_data(as->urb, as->urb->transfer_buffer_length);
1559 
1560 	async_newpending(as);
1561 
1562 	if (usb_endpoint_xfer_bulk(&ep->desc)) {
1563 		spin_lock_irq(&ps->lock);
1564 
1565 		/* Not exactly the endpoint address; the direction bit is
1566 		 * shifted to the 0x10 position so that the value will be
1567 		 * between 0 and 31.
1568 		 */
1569 		as->bulk_addr = usb_endpoint_num(&ep->desc) |
1570 			((ep->desc.bEndpointAddress & USB_ENDPOINT_DIR_MASK)
1571 				>> 3);
1572 
1573 		/* If this bulk URB is the start of a new transfer, re-enable
1574 		 * the endpoint.  Otherwise mark it as a continuation URB.
1575 		 */
1576 		if (uurb->flags & USBDEVFS_URB_BULK_CONTINUATION)
1577 			as->bulk_status = AS_CONTINUATION;
1578 		else
1579 			ps->disabled_bulk_eps &= ~(1 << as->bulk_addr);
1580 
1581 		/* Don't accept continuation URBs if the endpoint is
1582 		 * disabled because of an earlier error.
1583 		 */
1584 		if (ps->disabled_bulk_eps & (1 << as->bulk_addr))
1585 			ret = -EREMOTEIO;
1586 		else
1587 			ret = usb_submit_urb(as->urb, GFP_ATOMIC);
1588 		spin_unlock_irq(&ps->lock);
1589 	} else {
1590 		ret = usb_submit_urb(as->urb, GFP_KERNEL);
1591 	}
1592 
1593 	if (ret) {
1594 		dev_printk(KERN_DEBUG, &ps->dev->dev,
1595 			   "usbfs: usb_submit_urb returned %d\n", ret);
1596 		snoop_urb(ps->dev, as->userurb, as->urb->pipe,
1597 				0, ret, COMPLETE, NULL, 0);
1598 		async_removepending(as);
1599 		goto error;
1600 	}
1601 	return 0;
1602 
1603  error:
1604 	kfree(isopkt);
1605 	kfree(dr);
1606 	if (as)
1607 		free_async(as);
1608 	return ret;
1609 }
1610 
1611 static int proc_submiturb(struct usb_dev_state *ps, void __user *arg)
1612 {
1613 	struct usbdevfs_urb uurb;
1614 
1615 	if (copy_from_user(&uurb, arg, sizeof(uurb)))
1616 		return -EFAULT;
1617 
1618 	return proc_do_submiturb(ps, &uurb,
1619 			(((struct usbdevfs_urb __user *)arg)->iso_frame_desc),
1620 			arg);
1621 }
1622 
1623 static int proc_unlinkurb(struct usb_dev_state *ps, void __user *arg)
1624 {
1625 	struct urb *urb;
1626 	struct async *as;
1627 	unsigned long flags;
1628 
1629 	spin_lock_irqsave(&ps->lock, flags);
1630 	as = async_getpending(ps, arg);
1631 	if (!as) {
1632 		spin_unlock_irqrestore(&ps->lock, flags);
1633 		return -EINVAL;
1634 	}
1635 
1636 	urb = as->urb;
1637 	usb_get_urb(urb);
1638 	spin_unlock_irqrestore(&ps->lock, flags);
1639 
1640 	usb_kill_urb(urb);
1641 	usb_put_urb(urb);
1642 
1643 	return 0;
1644 }
1645 
1646 static int processcompl(struct async *as, void __user * __user *arg)
1647 {
1648 	struct urb *urb = as->urb;
1649 	struct usbdevfs_urb __user *userurb = as->userurb;
1650 	void __user *addr = as->userurb;
1651 	unsigned int i;
1652 
1653 	if (as->userbuffer && urb->actual_length) {
1654 		if (copy_urb_data_to_user(as->userbuffer, urb))
1655 			goto err_out;
1656 	}
1657 	if (put_user(as->status, &userurb->status))
1658 		goto err_out;
1659 	if (put_user(urb->actual_length, &userurb->actual_length))
1660 		goto err_out;
1661 	if (put_user(urb->error_count, &userurb->error_count))
1662 		goto err_out;
1663 
1664 	if (usb_endpoint_xfer_isoc(&urb->ep->desc)) {
1665 		for (i = 0; i < urb->number_of_packets; i++) {
1666 			if (put_user(urb->iso_frame_desc[i].actual_length,
1667 				     &userurb->iso_frame_desc[i].actual_length))
1668 				goto err_out;
1669 			if (put_user(urb->iso_frame_desc[i].status,
1670 				     &userurb->iso_frame_desc[i].status))
1671 				goto err_out;
1672 		}
1673 	}
1674 
1675 	if (put_user(addr, (void __user * __user *)arg))
1676 		return -EFAULT;
1677 	return 0;
1678 
1679 err_out:
1680 	return -EFAULT;
1681 }
1682 
1683 static struct async *reap_as(struct usb_dev_state *ps)
1684 {
1685 	DECLARE_WAITQUEUE(wait, current);
1686 	struct async *as = NULL;
1687 	struct usb_device *dev = ps->dev;
1688 
1689 	add_wait_queue(&ps->wait, &wait);
1690 	for (;;) {
1691 		__set_current_state(TASK_INTERRUPTIBLE);
1692 		as = async_getcompleted(ps);
1693 		if (as || !connected(ps))
1694 			break;
1695 		if (signal_pending(current))
1696 			break;
1697 		usb_unlock_device(dev);
1698 		schedule();
1699 		usb_lock_device(dev);
1700 	}
1701 	remove_wait_queue(&ps->wait, &wait);
1702 	set_current_state(TASK_RUNNING);
1703 	return as;
1704 }
1705 
1706 static int proc_reapurb(struct usb_dev_state *ps, void __user *arg)
1707 {
1708 	struct async *as = reap_as(ps);
1709 	if (as) {
1710 		int retval = processcompl(as, (void __user * __user *)arg);
1711 		free_async(as);
1712 		return retval;
1713 	}
1714 	if (signal_pending(current))
1715 		return -EINTR;
1716 	return -ENODEV;
1717 }
1718 
1719 static int proc_reapurbnonblock(struct usb_dev_state *ps, void __user *arg)
1720 {
1721 	int retval;
1722 	struct async *as;
1723 
1724 	as = async_getcompleted(ps);
1725 	if (as) {
1726 		retval = processcompl(as, (void __user * __user *)arg);
1727 		free_async(as);
1728 	} else {
1729 		retval = (connected(ps) ? -EAGAIN : -ENODEV);
1730 	}
1731 	return retval;
1732 }
1733 
1734 #ifdef CONFIG_COMPAT
1735 static int proc_control_compat(struct usb_dev_state *ps,
1736 				struct usbdevfs_ctrltransfer32 __user *p32)
1737 {
1738 	struct usbdevfs_ctrltransfer __user *p;
1739 	__u32 udata;
1740 	p = compat_alloc_user_space(sizeof(*p));
1741 	if (copy_in_user(p, p32, (sizeof(*p32) - sizeof(compat_caddr_t))) ||
1742 	    get_user(udata, &p32->data) ||
1743 	    put_user(compat_ptr(udata), &p->data))
1744 		return -EFAULT;
1745 	return proc_control(ps, p);
1746 }
1747 
1748 static int proc_bulk_compat(struct usb_dev_state *ps,
1749 			struct usbdevfs_bulktransfer32 __user *p32)
1750 {
1751 	struct usbdevfs_bulktransfer __user *p;
1752 	compat_uint_t n;
1753 	compat_caddr_t addr;
1754 
1755 	p = compat_alloc_user_space(sizeof(*p));
1756 
1757 	if (get_user(n, &p32->ep) || put_user(n, &p->ep) ||
1758 	    get_user(n, &p32->len) || put_user(n, &p->len) ||
1759 	    get_user(n, &p32->timeout) || put_user(n, &p->timeout) ||
1760 	    get_user(addr, &p32->data) || put_user(compat_ptr(addr), &p->data))
1761 		return -EFAULT;
1762 
1763 	return proc_bulk(ps, p);
1764 }
1765 static int proc_disconnectsignal_compat(struct usb_dev_state *ps, void __user *arg)
1766 {
1767 	struct usbdevfs_disconnectsignal32 ds;
1768 
1769 	if (copy_from_user(&ds, arg, sizeof(ds)))
1770 		return -EFAULT;
1771 	ps->discsignr = ds.signr;
1772 	ps->disccontext = compat_ptr(ds.context);
1773 	return 0;
1774 }
1775 
1776 static int get_urb32(struct usbdevfs_urb *kurb,
1777 		     struct usbdevfs_urb32 __user *uurb)
1778 {
1779 	__u32  uptr;
1780 	if (!access_ok(VERIFY_READ, uurb, sizeof(*uurb)) ||
1781 	    __get_user(kurb->type, &uurb->type) ||
1782 	    __get_user(kurb->endpoint, &uurb->endpoint) ||
1783 	    __get_user(kurb->status, &uurb->status) ||
1784 	    __get_user(kurb->flags, &uurb->flags) ||
1785 	    __get_user(kurb->buffer_length, &uurb->buffer_length) ||
1786 	    __get_user(kurb->actual_length, &uurb->actual_length) ||
1787 	    __get_user(kurb->start_frame, &uurb->start_frame) ||
1788 	    __get_user(kurb->number_of_packets, &uurb->number_of_packets) ||
1789 	    __get_user(kurb->error_count, &uurb->error_count) ||
1790 	    __get_user(kurb->signr, &uurb->signr))
1791 		return -EFAULT;
1792 
1793 	if (__get_user(uptr, &uurb->buffer))
1794 		return -EFAULT;
1795 	kurb->buffer = compat_ptr(uptr);
1796 	if (__get_user(uptr, &uurb->usercontext))
1797 		return -EFAULT;
1798 	kurb->usercontext = compat_ptr(uptr);
1799 
1800 	return 0;
1801 }
1802 
1803 static int proc_submiturb_compat(struct usb_dev_state *ps, void __user *arg)
1804 {
1805 	struct usbdevfs_urb uurb;
1806 
1807 	if (get_urb32(&uurb, (struct usbdevfs_urb32 __user *)arg))
1808 		return -EFAULT;
1809 
1810 	return proc_do_submiturb(ps, &uurb,
1811 			((struct usbdevfs_urb32 __user *)arg)->iso_frame_desc,
1812 			arg);
1813 }
1814 
1815 static int processcompl_compat(struct async *as, void __user * __user *arg)
1816 {
1817 	struct urb *urb = as->urb;
1818 	struct usbdevfs_urb32 __user *userurb = as->userurb;
1819 	void __user *addr = as->userurb;
1820 	unsigned int i;
1821 
1822 	if (as->userbuffer && urb->actual_length) {
1823 		if (copy_urb_data_to_user(as->userbuffer, urb))
1824 			return -EFAULT;
1825 	}
1826 	if (put_user(as->status, &userurb->status))
1827 		return -EFAULT;
1828 	if (put_user(urb->actual_length, &userurb->actual_length))
1829 		return -EFAULT;
1830 	if (put_user(urb->error_count, &userurb->error_count))
1831 		return -EFAULT;
1832 
1833 	if (usb_endpoint_xfer_isoc(&urb->ep->desc)) {
1834 		for (i = 0; i < urb->number_of_packets; i++) {
1835 			if (put_user(urb->iso_frame_desc[i].actual_length,
1836 				     &userurb->iso_frame_desc[i].actual_length))
1837 				return -EFAULT;
1838 			if (put_user(urb->iso_frame_desc[i].status,
1839 				     &userurb->iso_frame_desc[i].status))
1840 				return -EFAULT;
1841 		}
1842 	}
1843 
1844 	if (put_user(ptr_to_compat(addr), (u32 __user *)arg))
1845 		return -EFAULT;
1846 	return 0;
1847 }
1848 
1849 static int proc_reapurb_compat(struct usb_dev_state *ps, void __user *arg)
1850 {
1851 	struct async *as = reap_as(ps);
1852 	if (as) {
1853 		int retval = processcompl_compat(as, (void __user * __user *)arg);
1854 		free_async(as);
1855 		return retval;
1856 	}
1857 	if (signal_pending(current))
1858 		return -EINTR;
1859 	return -ENODEV;
1860 }
1861 
1862 static int proc_reapurbnonblock_compat(struct usb_dev_state *ps, void __user *arg)
1863 {
1864 	int retval;
1865 	struct async *as;
1866 
1867 	as = async_getcompleted(ps);
1868 	if (as) {
1869 		retval = processcompl_compat(as, (void __user * __user *)arg);
1870 		free_async(as);
1871 	} else {
1872 		retval = (connected(ps) ? -EAGAIN : -ENODEV);
1873 	}
1874 	return retval;
1875 }
1876 
1877 
1878 #endif
1879 
1880 static int proc_disconnectsignal(struct usb_dev_state *ps, void __user *arg)
1881 {
1882 	struct usbdevfs_disconnectsignal ds;
1883 
1884 	if (copy_from_user(&ds, arg, sizeof(ds)))
1885 		return -EFAULT;
1886 	ps->discsignr = ds.signr;
1887 	ps->disccontext = ds.context;
1888 	return 0;
1889 }
1890 
1891 static int proc_claiminterface(struct usb_dev_state *ps, void __user *arg)
1892 {
1893 	unsigned int ifnum;
1894 
1895 	if (get_user(ifnum, (unsigned int __user *)arg))
1896 		return -EFAULT;
1897 	return claimintf(ps, ifnum);
1898 }
1899 
1900 static int proc_releaseinterface(struct usb_dev_state *ps, void __user *arg)
1901 {
1902 	unsigned int ifnum;
1903 	int ret;
1904 
1905 	if (get_user(ifnum, (unsigned int __user *)arg))
1906 		return -EFAULT;
1907 	if ((ret = releaseintf(ps, ifnum)) < 0)
1908 		return ret;
1909 	destroy_async_on_interface (ps, ifnum);
1910 	return 0;
1911 }
1912 
1913 static int proc_ioctl(struct usb_dev_state *ps, struct usbdevfs_ioctl *ctl)
1914 {
1915 	int			size;
1916 	void			*buf = NULL;
1917 	int			retval = 0;
1918 	struct usb_interface    *intf = NULL;
1919 	struct usb_driver       *driver = NULL;
1920 
1921 	/* alloc buffer */
1922 	if ((size = _IOC_SIZE(ctl->ioctl_code)) > 0) {
1923 		buf = kmalloc(size, GFP_KERNEL);
1924 		if (buf == NULL)
1925 			return -ENOMEM;
1926 		if ((_IOC_DIR(ctl->ioctl_code) & _IOC_WRITE)) {
1927 			if (copy_from_user(buf, ctl->data, size)) {
1928 				kfree(buf);
1929 				return -EFAULT;
1930 			}
1931 		} else {
1932 			memset(buf, 0, size);
1933 		}
1934 	}
1935 
1936 	if (!connected(ps)) {
1937 		kfree(buf);
1938 		return -ENODEV;
1939 	}
1940 
1941 	if (ps->dev->state != USB_STATE_CONFIGURED)
1942 		retval = -EHOSTUNREACH;
1943 	else if (!(intf = usb_ifnum_to_if(ps->dev, ctl->ifno)))
1944 		retval = -EINVAL;
1945 	else switch (ctl->ioctl_code) {
1946 
1947 	/* disconnect kernel driver from interface */
1948 	case USBDEVFS_DISCONNECT:
1949 		if (intf->dev.driver) {
1950 			driver = to_usb_driver(intf->dev.driver);
1951 			dev_dbg(&intf->dev, "disconnect by usbfs\n");
1952 			usb_driver_release_interface(driver, intf);
1953 		} else
1954 			retval = -ENODATA;
1955 		break;
1956 
1957 	/* let kernel drivers try to (re)bind to the interface */
1958 	case USBDEVFS_CONNECT:
1959 		if (!intf->dev.driver)
1960 			retval = device_attach(&intf->dev);
1961 		else
1962 			retval = -EBUSY;
1963 		break;
1964 
1965 	/* talk directly to the interface's driver */
1966 	default:
1967 		if (intf->dev.driver)
1968 			driver = to_usb_driver(intf->dev.driver);
1969 		if (driver == NULL || driver->unlocked_ioctl == NULL) {
1970 			retval = -ENOTTY;
1971 		} else {
1972 			retval = driver->unlocked_ioctl(intf, ctl->ioctl_code, buf);
1973 			if (retval == -ENOIOCTLCMD)
1974 				retval = -ENOTTY;
1975 		}
1976 	}
1977 
1978 	/* cleanup and return */
1979 	if (retval >= 0
1980 			&& (_IOC_DIR(ctl->ioctl_code) & _IOC_READ) != 0
1981 			&& size > 0
1982 			&& copy_to_user(ctl->data, buf, size) != 0)
1983 		retval = -EFAULT;
1984 
1985 	kfree(buf);
1986 	return retval;
1987 }
1988 
1989 static int proc_ioctl_default(struct usb_dev_state *ps, void __user *arg)
1990 {
1991 	struct usbdevfs_ioctl	ctrl;
1992 
1993 	if (copy_from_user(&ctrl, arg, sizeof(ctrl)))
1994 		return -EFAULT;
1995 	return proc_ioctl(ps, &ctrl);
1996 }
1997 
1998 #ifdef CONFIG_COMPAT
1999 static int proc_ioctl_compat(struct usb_dev_state *ps, compat_uptr_t arg)
2000 {
2001 	struct usbdevfs_ioctl32 __user *uioc;
2002 	struct usbdevfs_ioctl ctrl;
2003 	u32 udata;
2004 
2005 	uioc = compat_ptr((long)arg);
2006 	if (!access_ok(VERIFY_READ, uioc, sizeof(*uioc)) ||
2007 	    __get_user(ctrl.ifno, &uioc->ifno) ||
2008 	    __get_user(ctrl.ioctl_code, &uioc->ioctl_code) ||
2009 	    __get_user(udata, &uioc->data))
2010 		return -EFAULT;
2011 	ctrl.data = compat_ptr(udata);
2012 
2013 	return proc_ioctl(ps, &ctrl);
2014 }
2015 #endif
2016 
2017 static int proc_claim_port(struct usb_dev_state *ps, void __user *arg)
2018 {
2019 	unsigned portnum;
2020 	int rc;
2021 
2022 	if (get_user(portnum, (unsigned __user *) arg))
2023 		return -EFAULT;
2024 	rc = usb_hub_claim_port(ps->dev, portnum, ps);
2025 	if (rc == 0)
2026 		snoop(&ps->dev->dev, "port %d claimed by process %d: %s\n",
2027 			portnum, task_pid_nr(current), current->comm);
2028 	return rc;
2029 }
2030 
2031 static int proc_release_port(struct usb_dev_state *ps, void __user *arg)
2032 {
2033 	unsigned portnum;
2034 
2035 	if (get_user(portnum, (unsigned __user *) arg))
2036 		return -EFAULT;
2037 	return usb_hub_release_port(ps->dev, portnum, ps);
2038 }
2039 
2040 static int proc_get_capabilities(struct usb_dev_state *ps, void __user *arg)
2041 {
2042 	__u32 caps;
2043 
2044 	caps = USBDEVFS_CAP_ZERO_PACKET | USBDEVFS_CAP_NO_PACKET_SIZE_LIM |
2045 			USBDEVFS_CAP_REAP_AFTER_DISCONNECT;
2046 	if (!ps->dev->bus->no_stop_on_short)
2047 		caps |= USBDEVFS_CAP_BULK_CONTINUATION;
2048 	if (ps->dev->bus->sg_tablesize)
2049 		caps |= USBDEVFS_CAP_BULK_SCATTER_GATHER;
2050 
2051 	if (put_user(caps, (__u32 __user *)arg))
2052 		return -EFAULT;
2053 
2054 	return 0;
2055 }
2056 
2057 static int proc_disconnect_claim(struct usb_dev_state *ps, void __user *arg)
2058 {
2059 	struct usbdevfs_disconnect_claim dc;
2060 	struct usb_interface *intf;
2061 
2062 	if (copy_from_user(&dc, arg, sizeof(dc)))
2063 		return -EFAULT;
2064 
2065 	intf = usb_ifnum_to_if(ps->dev, dc.interface);
2066 	if (!intf)
2067 		return -EINVAL;
2068 
2069 	if (intf->dev.driver) {
2070 		struct usb_driver *driver = to_usb_driver(intf->dev.driver);
2071 
2072 		if ((dc.flags & USBDEVFS_DISCONNECT_CLAIM_IF_DRIVER) &&
2073 				strncmp(dc.driver, intf->dev.driver->name,
2074 					sizeof(dc.driver)) != 0)
2075 			return -EBUSY;
2076 
2077 		if ((dc.flags & USBDEVFS_DISCONNECT_CLAIM_EXCEPT_DRIVER) &&
2078 				strncmp(dc.driver, intf->dev.driver->name,
2079 					sizeof(dc.driver)) == 0)
2080 			return -EBUSY;
2081 
2082 		dev_dbg(&intf->dev, "disconnect by usbfs\n");
2083 		usb_driver_release_interface(driver, intf);
2084 	}
2085 
2086 	return claimintf(ps, dc.interface);
2087 }
2088 
2089 static int proc_alloc_streams(struct usb_dev_state *ps, void __user *arg)
2090 {
2091 	unsigned num_streams, num_eps;
2092 	struct usb_host_endpoint **eps;
2093 	struct usb_interface *intf;
2094 	int r;
2095 
2096 	r = parse_usbdevfs_streams(ps, arg, &num_streams, &num_eps,
2097 				   &eps, &intf);
2098 	if (r)
2099 		return r;
2100 
2101 	destroy_async_on_interface(ps,
2102 				   intf->altsetting[0].desc.bInterfaceNumber);
2103 
2104 	r = usb_alloc_streams(intf, eps, num_eps, num_streams, GFP_KERNEL);
2105 	kfree(eps);
2106 	return r;
2107 }
2108 
2109 static int proc_free_streams(struct usb_dev_state *ps, void __user *arg)
2110 {
2111 	unsigned num_eps;
2112 	struct usb_host_endpoint **eps;
2113 	struct usb_interface *intf;
2114 	int r;
2115 
2116 	r = parse_usbdevfs_streams(ps, arg, NULL, &num_eps, &eps, &intf);
2117 	if (r)
2118 		return r;
2119 
2120 	destroy_async_on_interface(ps,
2121 				   intf->altsetting[0].desc.bInterfaceNumber);
2122 
2123 	r = usb_free_streams(intf, eps, num_eps, GFP_KERNEL);
2124 	kfree(eps);
2125 	return r;
2126 }
2127 
2128 /*
2129  * NOTE:  All requests here that have interface numbers as parameters
2130  * are assuming that somehow the configuration has been prevented from
2131  * changing.  But there's no mechanism to ensure that...
2132  */
2133 static long usbdev_do_ioctl(struct file *file, unsigned int cmd,
2134 				void __user *p)
2135 {
2136 	struct usb_dev_state *ps = file->private_data;
2137 	struct inode *inode = file_inode(file);
2138 	struct usb_device *dev = ps->dev;
2139 	int ret = -ENOTTY;
2140 
2141 	if (!(file->f_mode & FMODE_WRITE))
2142 		return -EPERM;
2143 
2144 	usb_lock_device(dev);
2145 
2146 	/* Reap operations are allowed even after disconnection */
2147 	switch (cmd) {
2148 	case USBDEVFS_REAPURB:
2149 		snoop(&dev->dev, "%s: REAPURB\n", __func__);
2150 		ret = proc_reapurb(ps, p);
2151 		goto done;
2152 
2153 	case USBDEVFS_REAPURBNDELAY:
2154 		snoop(&dev->dev, "%s: REAPURBNDELAY\n", __func__);
2155 		ret = proc_reapurbnonblock(ps, p);
2156 		goto done;
2157 
2158 #ifdef CONFIG_COMPAT
2159 	case USBDEVFS_REAPURB32:
2160 		snoop(&dev->dev, "%s: REAPURB32\n", __func__);
2161 		ret = proc_reapurb_compat(ps, p);
2162 		goto done;
2163 
2164 	case USBDEVFS_REAPURBNDELAY32:
2165 		snoop(&dev->dev, "%s: REAPURBNDELAY32\n", __func__);
2166 		ret = proc_reapurbnonblock_compat(ps, p);
2167 		goto done;
2168 #endif
2169 	}
2170 
2171 	if (!connected(ps)) {
2172 		usb_unlock_device(dev);
2173 		return -ENODEV;
2174 	}
2175 
2176 	switch (cmd) {
2177 	case USBDEVFS_CONTROL:
2178 		snoop(&dev->dev, "%s: CONTROL\n", __func__);
2179 		ret = proc_control(ps, p);
2180 		if (ret >= 0)
2181 			inode->i_mtime = CURRENT_TIME;
2182 		break;
2183 
2184 	case USBDEVFS_BULK:
2185 		snoop(&dev->dev, "%s: BULK\n", __func__);
2186 		ret = proc_bulk(ps, p);
2187 		if (ret >= 0)
2188 			inode->i_mtime = CURRENT_TIME;
2189 		break;
2190 
2191 	case USBDEVFS_RESETEP:
2192 		snoop(&dev->dev, "%s: RESETEP\n", __func__);
2193 		ret = proc_resetep(ps, p);
2194 		if (ret >= 0)
2195 			inode->i_mtime = CURRENT_TIME;
2196 		break;
2197 
2198 	case USBDEVFS_RESET:
2199 		snoop(&dev->dev, "%s: RESET\n", __func__);
2200 		ret = proc_resetdevice(ps);
2201 		break;
2202 
2203 	case USBDEVFS_CLEAR_HALT:
2204 		snoop(&dev->dev, "%s: CLEAR_HALT\n", __func__);
2205 		ret = proc_clearhalt(ps, p);
2206 		if (ret >= 0)
2207 			inode->i_mtime = CURRENT_TIME;
2208 		break;
2209 
2210 	case USBDEVFS_GETDRIVER:
2211 		snoop(&dev->dev, "%s: GETDRIVER\n", __func__);
2212 		ret = proc_getdriver(ps, p);
2213 		break;
2214 
2215 	case USBDEVFS_CONNECTINFO:
2216 		snoop(&dev->dev, "%s: CONNECTINFO\n", __func__);
2217 		ret = proc_connectinfo(ps, p);
2218 		break;
2219 
2220 	case USBDEVFS_SETINTERFACE:
2221 		snoop(&dev->dev, "%s: SETINTERFACE\n", __func__);
2222 		ret = proc_setintf(ps, p);
2223 		break;
2224 
2225 	case USBDEVFS_SETCONFIGURATION:
2226 		snoop(&dev->dev, "%s: SETCONFIGURATION\n", __func__);
2227 		ret = proc_setconfig(ps, p);
2228 		break;
2229 
2230 	case USBDEVFS_SUBMITURB:
2231 		snoop(&dev->dev, "%s: SUBMITURB\n", __func__);
2232 		ret = proc_submiturb(ps, p);
2233 		if (ret >= 0)
2234 			inode->i_mtime = CURRENT_TIME;
2235 		break;
2236 
2237 #ifdef CONFIG_COMPAT
2238 	case USBDEVFS_CONTROL32:
2239 		snoop(&dev->dev, "%s: CONTROL32\n", __func__);
2240 		ret = proc_control_compat(ps, p);
2241 		if (ret >= 0)
2242 			inode->i_mtime = CURRENT_TIME;
2243 		break;
2244 
2245 	case USBDEVFS_BULK32:
2246 		snoop(&dev->dev, "%s: BULK32\n", __func__);
2247 		ret = proc_bulk_compat(ps, p);
2248 		if (ret >= 0)
2249 			inode->i_mtime = CURRENT_TIME;
2250 		break;
2251 
2252 	case USBDEVFS_DISCSIGNAL32:
2253 		snoop(&dev->dev, "%s: DISCSIGNAL32\n", __func__);
2254 		ret = proc_disconnectsignal_compat(ps, p);
2255 		break;
2256 
2257 	case USBDEVFS_SUBMITURB32:
2258 		snoop(&dev->dev, "%s: SUBMITURB32\n", __func__);
2259 		ret = proc_submiturb_compat(ps, p);
2260 		if (ret >= 0)
2261 			inode->i_mtime = CURRENT_TIME;
2262 		break;
2263 
2264 	case USBDEVFS_IOCTL32:
2265 		snoop(&dev->dev, "%s: IOCTL32\n", __func__);
2266 		ret = proc_ioctl_compat(ps, ptr_to_compat(p));
2267 		break;
2268 #endif
2269 
2270 	case USBDEVFS_DISCARDURB:
2271 		snoop(&dev->dev, "%s: DISCARDURB\n", __func__);
2272 		ret = proc_unlinkurb(ps, p);
2273 		break;
2274 
2275 	case USBDEVFS_DISCSIGNAL:
2276 		snoop(&dev->dev, "%s: DISCSIGNAL\n", __func__);
2277 		ret = proc_disconnectsignal(ps, p);
2278 		break;
2279 
2280 	case USBDEVFS_CLAIMINTERFACE:
2281 		snoop(&dev->dev, "%s: CLAIMINTERFACE\n", __func__);
2282 		ret = proc_claiminterface(ps, p);
2283 		break;
2284 
2285 	case USBDEVFS_RELEASEINTERFACE:
2286 		snoop(&dev->dev, "%s: RELEASEINTERFACE\n", __func__);
2287 		ret = proc_releaseinterface(ps, p);
2288 		break;
2289 
2290 	case USBDEVFS_IOCTL:
2291 		snoop(&dev->dev, "%s: IOCTL\n", __func__);
2292 		ret = proc_ioctl_default(ps, p);
2293 		break;
2294 
2295 	case USBDEVFS_CLAIM_PORT:
2296 		snoop(&dev->dev, "%s: CLAIM_PORT\n", __func__);
2297 		ret = proc_claim_port(ps, p);
2298 		break;
2299 
2300 	case USBDEVFS_RELEASE_PORT:
2301 		snoop(&dev->dev, "%s: RELEASE_PORT\n", __func__);
2302 		ret = proc_release_port(ps, p);
2303 		break;
2304 	case USBDEVFS_GET_CAPABILITIES:
2305 		ret = proc_get_capabilities(ps, p);
2306 		break;
2307 	case USBDEVFS_DISCONNECT_CLAIM:
2308 		ret = proc_disconnect_claim(ps, p);
2309 		break;
2310 	case USBDEVFS_ALLOC_STREAMS:
2311 		ret = proc_alloc_streams(ps, p);
2312 		break;
2313 	case USBDEVFS_FREE_STREAMS:
2314 		ret = proc_free_streams(ps, p);
2315 		break;
2316 	}
2317 
2318  done:
2319 	usb_unlock_device(dev);
2320 	if (ret >= 0)
2321 		inode->i_atime = CURRENT_TIME;
2322 	return ret;
2323 }
2324 
2325 static long usbdev_ioctl(struct file *file, unsigned int cmd,
2326 			unsigned long arg)
2327 {
2328 	int ret;
2329 
2330 	ret = usbdev_do_ioctl(file, cmd, (void __user *)arg);
2331 
2332 	return ret;
2333 }
2334 
2335 #ifdef CONFIG_COMPAT
2336 static long usbdev_compat_ioctl(struct file *file, unsigned int cmd,
2337 			unsigned long arg)
2338 {
2339 	int ret;
2340 
2341 	ret = usbdev_do_ioctl(file, cmd, compat_ptr(arg));
2342 
2343 	return ret;
2344 }
2345 #endif
2346 
2347 /* No kernel lock - fine */
2348 static unsigned int usbdev_poll(struct file *file,
2349 				struct poll_table_struct *wait)
2350 {
2351 	struct usb_dev_state *ps = file->private_data;
2352 	unsigned int mask = 0;
2353 
2354 	poll_wait(file, &ps->wait, wait);
2355 	if (file->f_mode & FMODE_WRITE && !list_empty(&ps->async_completed))
2356 		mask |= POLLOUT | POLLWRNORM;
2357 	if (!connected(ps))
2358 		mask |= POLLERR | POLLHUP;
2359 	return mask;
2360 }
2361 
2362 const struct file_operations usbdev_file_operations = {
2363 	.owner =	  THIS_MODULE,
2364 	.llseek =	  usbdev_lseek,
2365 	.read =		  usbdev_read,
2366 	.poll =		  usbdev_poll,
2367 	.unlocked_ioctl = usbdev_ioctl,
2368 #ifdef CONFIG_COMPAT
2369 	.compat_ioctl =   usbdev_compat_ioctl,
2370 #endif
2371 	.open =		  usbdev_open,
2372 	.release =	  usbdev_release,
2373 };
2374 
2375 static void usbdev_remove(struct usb_device *udev)
2376 {
2377 	struct usb_dev_state *ps;
2378 	struct siginfo sinfo;
2379 
2380 	while (!list_empty(&udev->filelist)) {
2381 		ps = list_entry(udev->filelist.next, struct usb_dev_state, list);
2382 		destroy_all_async(ps);
2383 		wake_up_all(&ps->wait);
2384 		list_del_init(&ps->list);
2385 		if (ps->discsignr) {
2386 			memset(&sinfo, 0, sizeof(sinfo));
2387 			sinfo.si_signo = ps->discsignr;
2388 			sinfo.si_errno = EPIPE;
2389 			sinfo.si_code = SI_ASYNCIO;
2390 			sinfo.si_addr = ps->disccontext;
2391 			kill_pid_info_as_cred(ps->discsignr, &sinfo,
2392 					ps->disc_pid, ps->cred, ps->secid);
2393 		}
2394 	}
2395 }
2396 
2397 static int usbdev_notify(struct notifier_block *self,
2398 			       unsigned long action, void *dev)
2399 {
2400 	switch (action) {
2401 	case USB_DEVICE_ADD:
2402 		break;
2403 	case USB_DEVICE_REMOVE:
2404 		usbdev_remove(dev);
2405 		break;
2406 	}
2407 	return NOTIFY_OK;
2408 }
2409 
2410 static struct notifier_block usbdev_nb = {
2411 	.notifier_call =	usbdev_notify,
2412 };
2413 
2414 static struct cdev usb_device_cdev;
2415 
2416 int __init usb_devio_init(void)
2417 {
2418 	int retval;
2419 
2420 	retval = register_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX,
2421 					"usb_device");
2422 	if (retval) {
2423 		printk(KERN_ERR "Unable to register minors for usb_device\n");
2424 		goto out;
2425 	}
2426 	cdev_init(&usb_device_cdev, &usbdev_file_operations);
2427 	retval = cdev_add(&usb_device_cdev, USB_DEVICE_DEV, USB_DEVICE_MAX);
2428 	if (retval) {
2429 		printk(KERN_ERR "Unable to get usb_device major %d\n",
2430 		       USB_DEVICE_MAJOR);
2431 		goto error_cdev;
2432 	}
2433 	usb_register_notify(&usbdev_nb);
2434 out:
2435 	return retval;
2436 
2437 error_cdev:
2438 	unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX);
2439 	goto out;
2440 }
2441 
2442 void usb_devio_cleanup(void)
2443 {
2444 	usb_unregister_notify(&usbdev_nb);
2445 	cdev_del(&usb_device_cdev);
2446 	unregister_chrdev_region(USB_DEVICE_DEV, USB_DEVICE_MAX);
2447 }
2448