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