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