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