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