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