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