]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/compat/linuxkpi/common/src/linux_compat.c
MFC r342627:
[FreeBSD/FreeBSD.git] / sys / compat / linuxkpi / common / src / linux_compat.c
1 /*-
2  * Copyright (c) 2010 Isilon Systems, Inc.
3  * Copyright (c) 2010 iX Systems, Inc.
4  * Copyright (c) 2010 Panasas, Inc.
5  * Copyright (c) 2013-2018 Mellanox Technologies, Ltd.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice unmodified, this list of conditions, and the following
13  *    disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include "opt_stack.h"
34
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/malloc.h>
38 #include <sys/kernel.h>
39 #include <sys/sysctl.h>
40 #include <sys/proc.h>
41 #include <sys/sglist.h>
42 #include <sys/sleepqueue.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/bus.h>
46 #include <sys/fcntl.h>
47 #include <sys/file.h>
48 #include <sys/filio.h>
49 #include <sys/rwlock.h>
50 #include <sys/mman.h>
51 #include <sys/stack.h>
52 #include <sys/user.h>
53
54 #include <vm/vm.h>
55 #include <vm/pmap.h>
56 #include <vm/vm_object.h>
57 #include <vm/vm_page.h>
58 #include <vm/vm_pager.h>
59
60 #include <machine/stdarg.h>
61
62 #if defined(__i386__) || defined(__amd64__)
63 #include <machine/md_var.h>
64 #endif
65
66 #include <linux/kobject.h>
67 #include <linux/device.h>
68 #include <linux/slab.h>
69 #include <linux/module.h>
70 #include <linux/moduleparam.h>
71 #include <linux/cdev.h>
72 #include <linux/file.h>
73 #include <linux/sysfs.h>
74 #include <linux/mm.h>
75 #include <linux/io.h>
76 #include <linux/vmalloc.h>
77 #include <linux/netdevice.h>
78 #include <linux/timer.h>
79 #include <linux/interrupt.h>
80 #include <linux/uaccess.h>
81 #include <linux/list.h>
82 #include <linux/kthread.h>
83 #include <linux/kernel.h>
84 #include <linux/compat.h>
85 #include <linux/poll.h>
86 #include <linux/smp.h>
87
88 #if defined(__i386__) || defined(__amd64__)
89 #include <asm/smp.h>
90 #endif
91
92 SYSCTL_NODE(_compat, OID_AUTO, linuxkpi, CTLFLAG_RW, 0, "LinuxKPI parameters");
93
94 MALLOC_DEFINE(M_KMALLOC, "linux", "Linux kmalloc compat");
95
96 #include <linux/rbtree.h>
97 /* Undo Linux compat changes. */
98 #undef RB_ROOT
99 #undef file
100 #undef cdev
101 #define RB_ROOT(head)   (head)->rbh_root
102
103 static struct vm_area_struct *linux_cdev_handle_find(void *handle);
104
105 struct kobject linux_class_root;
106 struct device linux_root_device;
107 struct class linux_class_misc;
108 struct list_head pci_drivers;
109 struct list_head pci_devices;
110 spinlock_t pci_lock;
111
112 unsigned long linux_timer_hz_mask;
113
114 int
115 panic_cmp(struct rb_node *one, struct rb_node *two)
116 {
117         panic("no cmp");
118 }
119
120 RB_GENERATE(linux_root, rb_node, __entry, panic_cmp);
121
122 int
123 kobject_set_name_vargs(struct kobject *kobj, const char *fmt, va_list args)
124 {
125         va_list tmp_va;
126         int len;
127         char *old;
128         char *name;
129         char dummy;
130
131         old = kobj->name;
132
133         if (old && fmt == NULL)
134                 return (0);
135
136         /* compute length of string */
137         va_copy(tmp_va, args);
138         len = vsnprintf(&dummy, 0, fmt, tmp_va);
139         va_end(tmp_va);
140
141         /* account for zero termination */
142         len++;
143
144         /* check for error */
145         if (len < 1)
146                 return (-EINVAL);
147
148         /* allocate memory for string */
149         name = kzalloc(len, GFP_KERNEL);
150         if (name == NULL)
151                 return (-ENOMEM);
152         vsnprintf(name, len, fmt, args);
153         kobj->name = name;
154
155         /* free old string */
156         kfree(old);
157
158         /* filter new string */
159         for (; *name != '\0'; name++)
160                 if (*name == '/')
161                         *name = '!';
162         return (0);
163 }
164
165 int
166 kobject_set_name(struct kobject *kobj, const char *fmt, ...)
167 {
168         va_list args;
169         int error;
170
171         va_start(args, fmt);
172         error = kobject_set_name_vargs(kobj, fmt, args);
173         va_end(args);
174
175         return (error);
176 }
177
178 static int
179 kobject_add_complete(struct kobject *kobj, struct kobject *parent)
180 {
181         const struct kobj_type *t;
182         int error;
183
184         kobj->parent = parent;
185         error = sysfs_create_dir(kobj);
186         if (error == 0 && kobj->ktype && kobj->ktype->default_attrs) {
187                 struct attribute **attr;
188                 t = kobj->ktype;
189
190                 for (attr = t->default_attrs; *attr != NULL; attr++) {
191                         error = sysfs_create_file(kobj, *attr);
192                         if (error)
193                                 break;
194                 }
195                 if (error)
196                         sysfs_remove_dir(kobj);
197
198         }
199         return (error);
200 }
201
202 int
203 kobject_add(struct kobject *kobj, struct kobject *parent, const char *fmt, ...)
204 {
205         va_list args;
206         int error;
207
208         va_start(args, fmt);
209         error = kobject_set_name_vargs(kobj, fmt, args);
210         va_end(args);
211         if (error)
212                 return (error);
213
214         return kobject_add_complete(kobj, parent);
215 }
216
217 void
218 linux_kobject_release(struct kref *kref)
219 {
220         struct kobject *kobj;
221         char *name;
222
223         kobj = container_of(kref, struct kobject, kref);
224         sysfs_remove_dir(kobj);
225         name = kobj->name;
226         if (kobj->ktype && kobj->ktype->release)
227                 kobj->ktype->release(kobj);
228         kfree(name);
229 }
230
231 static void
232 linux_kobject_kfree(struct kobject *kobj)
233 {
234         kfree(kobj);
235 }
236
237 static void
238 linux_kobject_kfree_name(struct kobject *kobj)
239 {
240         if (kobj) {
241                 kfree(kobj->name);
242         }
243 }
244
245 const struct kobj_type linux_kfree_type = {
246         .release = linux_kobject_kfree
247 };
248
249 static void
250 linux_device_release(struct device *dev)
251 {
252         pr_debug("linux_device_release: %s\n", dev_name(dev));
253         kfree(dev);
254 }
255
256 static ssize_t
257 linux_class_show(struct kobject *kobj, struct attribute *attr, char *buf)
258 {
259         struct class_attribute *dattr;
260         ssize_t error;
261
262         dattr = container_of(attr, struct class_attribute, attr);
263         error = -EIO;
264         if (dattr->show)
265                 error = dattr->show(container_of(kobj, struct class, kobj),
266                     dattr, buf);
267         return (error);
268 }
269
270 static ssize_t
271 linux_class_store(struct kobject *kobj, struct attribute *attr, const char *buf,
272     size_t count)
273 {
274         struct class_attribute *dattr;
275         ssize_t error;
276
277         dattr = container_of(attr, struct class_attribute, attr);
278         error = -EIO;
279         if (dattr->store)
280                 error = dattr->store(container_of(kobj, struct class, kobj),
281                     dattr, buf, count);
282         return (error);
283 }
284
285 static void
286 linux_class_release(struct kobject *kobj)
287 {
288         struct class *class;
289
290         class = container_of(kobj, struct class, kobj);
291         if (class->class_release)
292                 class->class_release(class);
293 }
294
295 static const struct sysfs_ops linux_class_sysfs = {
296         .show  = linux_class_show,
297         .store = linux_class_store,
298 };
299
300 const struct kobj_type linux_class_ktype = {
301         .release = linux_class_release,
302         .sysfs_ops = &linux_class_sysfs
303 };
304
305 static void
306 linux_dev_release(struct kobject *kobj)
307 {
308         struct device *dev;
309
310         dev = container_of(kobj, struct device, kobj);
311         /* This is the precedence defined by linux. */
312         if (dev->release)
313                 dev->release(dev);
314         else if (dev->class && dev->class->dev_release)
315                 dev->class->dev_release(dev);
316 }
317
318 static ssize_t
319 linux_dev_show(struct kobject *kobj, struct attribute *attr, char *buf)
320 {
321         struct device_attribute *dattr;
322         ssize_t error;
323
324         dattr = container_of(attr, struct device_attribute, attr);
325         error = -EIO;
326         if (dattr->show)
327                 error = dattr->show(container_of(kobj, struct device, kobj),
328                     dattr, buf);
329         return (error);
330 }
331
332 static ssize_t
333 linux_dev_store(struct kobject *kobj, struct attribute *attr, const char *buf,
334     size_t count)
335 {
336         struct device_attribute *dattr;
337         ssize_t error;
338
339         dattr = container_of(attr, struct device_attribute, attr);
340         error = -EIO;
341         if (dattr->store)
342                 error = dattr->store(container_of(kobj, struct device, kobj),
343                     dattr, buf, count);
344         return (error);
345 }
346
347 static const struct sysfs_ops linux_dev_sysfs = {
348         .show  = linux_dev_show,
349         .store = linux_dev_store,
350 };
351
352 const struct kobj_type linux_dev_ktype = {
353         .release = linux_dev_release,
354         .sysfs_ops = &linux_dev_sysfs
355 };
356
357 struct device *
358 device_create(struct class *class, struct device *parent, dev_t devt,
359     void *drvdata, const char *fmt, ...)
360 {
361         struct device *dev;
362         va_list args;
363
364         dev = kzalloc(sizeof(*dev), M_WAITOK);
365         dev->parent = parent;
366         dev->class = class;
367         dev->devt = devt;
368         dev->driver_data = drvdata;
369         dev->release = linux_device_release;
370         va_start(args, fmt);
371         kobject_set_name_vargs(&dev->kobj, fmt, args);
372         va_end(args);
373         device_register(dev);
374
375         return (dev);
376 }
377
378 int
379 kobject_init_and_add(struct kobject *kobj, const struct kobj_type *ktype,
380     struct kobject *parent, const char *fmt, ...)
381 {
382         va_list args;
383         int error;
384
385         kobject_init(kobj, ktype);
386         kobj->ktype = ktype;
387         kobj->parent = parent;
388         kobj->name = NULL;
389
390         va_start(args, fmt);
391         error = kobject_set_name_vargs(kobj, fmt, args);
392         va_end(args);
393         if (error)
394                 return (error);
395         return kobject_add_complete(kobj, parent);
396 }
397
398 static void
399 linux_kq_lock(void *arg)
400 {
401         spinlock_t *s = arg;
402
403         spin_lock(s);
404 }
405 static void
406 linux_kq_unlock(void *arg)
407 {
408         spinlock_t *s = arg;
409
410         spin_unlock(s);
411 }
412
413 static void
414 linux_kq_lock_owned(void *arg)
415 {
416 #ifdef INVARIANTS
417         spinlock_t *s = arg;
418
419         mtx_assert(&s->m, MA_OWNED);
420 #endif
421 }
422
423 static void
424 linux_kq_lock_unowned(void *arg)
425 {
426 #ifdef INVARIANTS
427         spinlock_t *s = arg;
428
429         mtx_assert(&s->m, MA_NOTOWNED);
430 #endif
431 }
432
433 static void
434 linux_file_kqfilter_poll(struct linux_file *, int);
435
436 struct linux_file *
437 linux_file_alloc(void)
438 {
439         struct linux_file *filp;
440
441         filp = kzalloc(sizeof(*filp), GFP_KERNEL);
442
443         /* set initial refcount */
444         filp->f_count = 1;
445
446         /* setup fields needed by kqueue support */
447         spin_lock_init(&filp->f_kqlock);
448         knlist_init(&filp->f_selinfo.si_note, &filp->f_kqlock,
449             linux_kq_lock, linux_kq_unlock,
450             linux_kq_lock_owned, linux_kq_lock_unowned);
451
452         return (filp);
453 }
454
455 void
456 linux_file_free(struct linux_file *filp)
457 {
458         if (filp->_file == NULL) {
459                 if (filp->f_shmem != NULL)
460                         vm_object_deallocate(filp->f_shmem);
461                 kfree(filp);
462         } else {
463                 /*
464                  * The close method of the character device or file
465                  * will free the linux_file structure:
466                  */
467                 _fdrop(filp->_file, curthread);
468         }
469 }
470
471 static int
472 linux_cdev_pager_fault(vm_object_t vm_obj, vm_ooffset_t offset, int prot,
473     vm_page_t *mres)
474 {
475         struct vm_area_struct *vmap;
476
477         vmap = linux_cdev_handle_find(vm_obj->handle);
478
479         MPASS(vmap != NULL);
480         MPASS(vmap->vm_private_data == vm_obj->handle);
481
482         if (likely(vmap->vm_ops != NULL && offset < vmap->vm_len)) {
483                 vm_paddr_t paddr = IDX_TO_OFF(vmap->vm_pfn) + offset;
484                 vm_page_t page;
485
486                 if (((*mres)->flags & PG_FICTITIOUS) != 0) {
487                         /*
488                          * If the passed in result page is a fake
489                          * page, update it with the new physical
490                          * address.
491                          */
492                         page = *mres;
493                         vm_page_updatefake(page, paddr, vm_obj->memattr);
494                 } else {
495                         /*
496                          * Replace the passed in "mres" page with our
497                          * own fake page and free up the all of the
498                          * original pages.
499                          */
500                         VM_OBJECT_WUNLOCK(vm_obj);
501                         page = vm_page_getfake(paddr, vm_obj->memattr);
502                         VM_OBJECT_WLOCK(vm_obj);
503
504                         vm_page_replace_checked(page, vm_obj,
505                             (*mres)->pindex, *mres);
506
507                         vm_page_lock(*mres);
508                         vm_page_free(*mres);
509                         vm_page_unlock(*mres);
510                         *mres = page;
511                 }
512                 page->valid = VM_PAGE_BITS_ALL;
513                 return (VM_PAGER_OK);
514         }
515         return (VM_PAGER_FAIL);
516 }
517
518 static int
519 linux_cdev_pager_populate(vm_object_t vm_obj, vm_pindex_t pidx, int fault_type,
520     vm_prot_t max_prot, vm_pindex_t *first, vm_pindex_t *last)
521 {
522         struct vm_area_struct *vmap;
523         int err;
524
525         linux_set_current(curthread);
526
527         /* get VM area structure */
528         vmap = linux_cdev_handle_find(vm_obj->handle);
529         MPASS(vmap != NULL);
530         MPASS(vmap->vm_private_data == vm_obj->handle);
531
532         VM_OBJECT_WUNLOCK(vm_obj);
533
534         down_write(&vmap->vm_mm->mmap_sem);
535         if (unlikely(vmap->vm_ops == NULL)) {
536                 err = VM_FAULT_SIGBUS;
537         } else {
538                 struct vm_fault vmf;
539
540                 /* fill out VM fault structure */
541                 vmf.virtual_address = (void *)(uintptr_t)IDX_TO_OFF(pidx);
542                 vmf.flags = (fault_type & VM_PROT_WRITE) ? FAULT_FLAG_WRITE : 0;
543                 vmf.pgoff = 0;
544                 vmf.page = NULL;
545                 vmf.vma = vmap;
546
547                 vmap->vm_pfn_count = 0;
548                 vmap->vm_pfn_pcount = &vmap->vm_pfn_count;
549                 vmap->vm_obj = vm_obj;
550
551                 err = vmap->vm_ops->fault(vmap, &vmf);
552
553                 while (vmap->vm_pfn_count == 0 && err == VM_FAULT_NOPAGE) {
554                         kern_yield(PRI_USER);
555                         err = vmap->vm_ops->fault(vmap, &vmf);
556                 }
557         }
558
559         /* translate return code */
560         switch (err) {
561         case VM_FAULT_OOM:
562                 err = VM_PAGER_AGAIN;
563                 break;
564         case VM_FAULT_SIGBUS:
565                 err = VM_PAGER_BAD;
566                 break;
567         case VM_FAULT_NOPAGE:
568                 /*
569                  * By contract the fault handler will return having
570                  * busied all the pages itself. If pidx is already
571                  * found in the object, it will simply xbusy the first
572                  * page and return with vm_pfn_count set to 1.
573                  */
574                 *first = vmap->vm_pfn_first;
575                 *last = *first + vmap->vm_pfn_count - 1;
576                 err = VM_PAGER_OK;
577                 break;
578         default:
579                 err = VM_PAGER_ERROR;
580                 break;
581         }
582         up_write(&vmap->vm_mm->mmap_sem);
583         VM_OBJECT_WLOCK(vm_obj);
584         return (err);
585 }
586
587 static struct rwlock linux_vma_lock;
588 static TAILQ_HEAD(, vm_area_struct) linux_vma_head =
589     TAILQ_HEAD_INITIALIZER(linux_vma_head);
590
591 static void
592 linux_cdev_handle_free(struct vm_area_struct *vmap)
593 {
594         /* Drop reference on vm_file */
595         if (vmap->vm_file != NULL)
596                 fput(vmap->vm_file);
597
598         /* Drop reference on mm_struct */
599         mmput(vmap->vm_mm);
600
601         kfree(vmap);
602 }
603
604 static void
605 linux_cdev_handle_remove(struct vm_area_struct *vmap)
606 {
607         rw_wlock(&linux_vma_lock);
608         TAILQ_REMOVE(&linux_vma_head, vmap, vm_entry);
609         rw_wunlock(&linux_vma_lock);
610 }
611
612 static struct vm_area_struct *
613 linux_cdev_handle_find(void *handle)
614 {
615         struct vm_area_struct *vmap;
616
617         rw_rlock(&linux_vma_lock);
618         TAILQ_FOREACH(vmap, &linux_vma_head, vm_entry) {
619                 if (vmap->vm_private_data == handle)
620                         break;
621         }
622         rw_runlock(&linux_vma_lock);
623         return (vmap);
624 }
625
626 static int
627 linux_cdev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
628                       vm_ooffset_t foff, struct ucred *cred, u_short *color)
629 {
630
631         MPASS(linux_cdev_handle_find(handle) != NULL);
632         *color = 0;
633         return (0);
634 }
635
636 static void
637 linux_cdev_pager_dtor(void *handle)
638 {
639         const struct vm_operations_struct *vm_ops;
640         struct vm_area_struct *vmap;
641
642         vmap = linux_cdev_handle_find(handle);
643         MPASS(vmap != NULL);
644
645         /*
646          * Remove handle before calling close operation to prevent
647          * other threads from reusing the handle pointer.
648          */
649         linux_cdev_handle_remove(vmap);
650
651         down_write(&vmap->vm_mm->mmap_sem);
652         vm_ops = vmap->vm_ops;
653         if (likely(vm_ops != NULL))
654                 vm_ops->close(vmap);
655         up_write(&vmap->vm_mm->mmap_sem);
656
657         linux_cdev_handle_free(vmap);
658 }
659
660 static struct cdev_pager_ops linux_cdev_pager_ops[2] = {
661   {
662         /* OBJT_MGTDEVICE */
663         .cdev_pg_populate       = linux_cdev_pager_populate,
664         .cdev_pg_ctor   = linux_cdev_pager_ctor,
665         .cdev_pg_dtor   = linux_cdev_pager_dtor
666   },
667   {
668         /* OBJT_DEVICE */
669         .cdev_pg_fault  = linux_cdev_pager_fault,
670         .cdev_pg_ctor   = linux_cdev_pager_ctor,
671         .cdev_pg_dtor   = linux_cdev_pager_dtor
672   },
673 };
674
675 int
676 zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
677     unsigned long size)
678 {
679         vm_object_t obj;
680         vm_page_t m;
681
682         obj = vma->vm_obj;
683         if (obj == NULL || (obj->flags & OBJ_UNMANAGED) != 0)
684                 return (-ENOTSUP);
685         VM_OBJECT_RLOCK(obj);
686         for (m = vm_page_find_least(obj, OFF_TO_IDX(address));
687             m != NULL && m->pindex < OFF_TO_IDX(address + size);
688             m = TAILQ_NEXT(m, listq))
689                 pmap_remove_all(m);
690         VM_OBJECT_RUNLOCK(obj);
691         return (0);
692 }
693
694 #define OPW(fp,td,code) ({                      \
695         struct file *__fpop;                    \
696         __typeof(code) __retval;                \
697                                                 \
698         __fpop = (td)->td_fpop;                 \
699         (td)->td_fpop = (fp);                   \
700         __retval = (code);                      \
701         (td)->td_fpop = __fpop;                 \
702         __retval;                               \
703 })
704
705 static int
706 linux_dev_fdopen(struct cdev *dev, int fflags, struct thread *td, struct file *file)
707 {
708         struct linux_cdev *ldev;
709         struct linux_file *filp;
710         int error;
711
712         ldev = dev->si_drv1;
713
714         filp = linux_file_alloc();
715         filp->f_dentry = &filp->f_dentry_store;
716         filp->f_op = ldev->ops;
717         filp->f_mode = file->f_flag;
718         filp->f_flags = file->f_flag;
719         filp->f_vnode = file->f_vnode;
720         filp->_file = file;
721         filp->f_cdev = ldev;
722
723         linux_set_current(td);
724
725         /* get a reference on the Linux character device */
726         if (atomic_long_add_unless(&ldev->refs, 1, -1L) == 0) {
727                 kfree(filp);
728                 return (EINVAL);
729         }
730
731         if (filp->f_op->open) {
732                 error = -filp->f_op->open(file->f_vnode, filp);
733                 if (error) {
734                         atomic_long_dec(&ldev->refs);
735                         kfree(filp);
736                         return (error);
737                 }
738         }
739
740         /* hold on to the vnode - used for fstat() */
741         vhold(filp->f_vnode);
742
743         /* release the file from devfs */
744         finit(file, filp->f_mode, DTYPE_DEV, filp, &linuxfileops);
745         return (ENXIO);
746 }
747
748 #define LINUX_IOCTL_MIN_PTR 0x10000UL
749 #define LINUX_IOCTL_MAX_PTR (LINUX_IOCTL_MIN_PTR + IOCPARM_MAX)
750
751 static inline int
752 linux_remap_address(void **uaddr, size_t len)
753 {
754         uintptr_t uaddr_val = (uintptr_t)(*uaddr);
755
756         if (unlikely(uaddr_val >= LINUX_IOCTL_MIN_PTR &&
757             uaddr_val < LINUX_IOCTL_MAX_PTR)) {
758                 struct task_struct *pts = current;
759                 if (pts == NULL) {
760                         *uaddr = NULL;
761                         return (1);
762                 }
763
764                 /* compute data offset */
765                 uaddr_val -= LINUX_IOCTL_MIN_PTR;
766
767                 /* check that length is within bounds */
768                 if ((len > IOCPARM_MAX) ||
769                     (uaddr_val + len) > pts->bsd_ioctl_len) {
770                         *uaddr = NULL;
771                         return (1);
772                 }
773
774                 /* re-add kernel buffer address */
775                 uaddr_val += (uintptr_t)pts->bsd_ioctl_data;
776
777                 /* update address location */
778                 *uaddr = (void *)uaddr_val;
779                 return (1);
780         }
781         return (0);
782 }
783
784 int
785 linux_copyin(const void *uaddr, void *kaddr, size_t len)
786 {
787         if (linux_remap_address(__DECONST(void **, &uaddr), len)) {
788                 if (uaddr == NULL)
789                         return (-EFAULT);
790                 memcpy(kaddr, uaddr, len);
791                 return (0);
792         }
793         return (-copyin(uaddr, kaddr, len));
794 }
795
796 int
797 linux_copyout(const void *kaddr, void *uaddr, size_t len)
798 {
799         if (linux_remap_address(&uaddr, len)) {
800                 if (uaddr == NULL)
801                         return (-EFAULT);
802                 memcpy(uaddr, kaddr, len);
803                 return (0);
804         }
805         return (-copyout(kaddr, uaddr, len));
806 }
807
808 size_t
809 linux_clear_user(void *_uaddr, size_t _len)
810 {
811         uint8_t *uaddr = _uaddr;
812         size_t len = _len;
813
814         /* make sure uaddr is aligned before going into the fast loop */
815         while (((uintptr_t)uaddr & 7) != 0 && len > 7) {
816                 if (subyte(uaddr, 0))
817                         return (_len);
818                 uaddr++;
819                 len--;
820         }
821
822         /* zero 8 bytes at a time */
823         while (len > 7) {
824 #ifdef __LP64__
825                 if (suword64(uaddr, 0))
826                         return (_len);
827 #else
828                 if (suword32(uaddr, 0))
829                         return (_len);
830                 if (suword32(uaddr + 4, 0))
831                         return (_len);
832 #endif
833                 uaddr += 8;
834                 len -= 8;
835         }
836
837         /* zero fill end, if any */
838         while (len > 0) {
839                 if (subyte(uaddr, 0))
840                         return (_len);
841                 uaddr++;
842                 len--;
843         }
844         return (0);
845 }
846
847 int
848 linux_access_ok(int rw, const void *uaddr, size_t len)
849 {
850         uintptr_t saddr;
851         uintptr_t eaddr;
852
853         /* get start and end address */
854         saddr = (uintptr_t)uaddr;
855         eaddr = (uintptr_t)uaddr + len;
856
857         /* verify addresses are valid for userspace */
858         return ((saddr == eaddr) ||
859             (eaddr > saddr && eaddr <= VM_MAXUSER_ADDRESS));
860 }
861
862 /*
863  * This function should return either EINTR or ERESTART depending on
864  * the signal type sent to this thread:
865  */
866 static int
867 linux_get_error(struct task_struct *task, int error)
868 {
869         /* check for signal type interrupt code */
870         if (error == EINTR || error == ERESTARTSYS || error == ERESTART) {
871                 error = -linux_schedule_get_interrupt_value(task);
872                 if (error == 0)
873                         error = EINTR;
874         }
875         return (error);
876 }
877
878 static int
879 linux_file_ioctl_sub(struct file *fp, struct linux_file *filp,
880     u_long cmd, caddr_t data, struct thread *td)
881 {
882         struct task_struct *task = current;
883         unsigned size;
884         int error;
885
886         size = IOCPARM_LEN(cmd);
887         /* refer to logic in sys_ioctl() */
888         if (size > 0) {
889                 /*
890                  * Setup hint for linux_copyin() and linux_copyout().
891                  *
892                  * Background: Linux code expects a user-space address
893                  * while FreeBSD supplies a kernel-space address.
894                  */
895                 task->bsd_ioctl_data = data;
896                 task->bsd_ioctl_len = size;
897                 data = (void *)LINUX_IOCTL_MIN_PTR;
898         } else {
899                 /* fetch user-space pointer */
900                 data = *(void **)data;
901         }
902 #if defined(__amd64__)
903         if (td->td_proc->p_elf_machine == EM_386) {
904                 /* try the compat IOCTL handler first */
905                 if (filp->f_op->compat_ioctl != NULL)
906                         error = -OPW(fp, td, filp->f_op->compat_ioctl(filp, cmd, (u_long)data));
907                 else
908                         error = ENOTTY;
909
910                 /* fallback to the regular IOCTL handler, if any */
911                 if (error == ENOTTY && filp->f_op->unlocked_ioctl != NULL)
912                         error = -OPW(fp, td, filp->f_op->unlocked_ioctl(filp, cmd, (u_long)data));
913         } else
914 #endif
915         if (filp->f_op->unlocked_ioctl != NULL)
916                 error = -OPW(fp, td, filp->f_op->unlocked_ioctl(filp, cmd, (u_long)data));
917         else
918                 error = ENOTTY;
919         if (size > 0) {
920                 task->bsd_ioctl_data = NULL;
921                 task->bsd_ioctl_len = 0;
922         }
923
924         if (error == EWOULDBLOCK) {
925                 /* update kqfilter status, if any */
926                 linux_file_kqfilter_poll(filp,
927                     LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
928         } else {
929                 error = linux_get_error(task, error);
930         }
931         return (error);
932 }
933
934 #define LINUX_POLL_TABLE_NORMAL ((poll_table *)1)
935
936 /*
937  * This function atomically updates the poll wakeup state and returns
938  * the previous state at the time of update.
939  */
940 static uint8_t
941 linux_poll_wakeup_state(atomic_t *v, const uint8_t *pstate)
942 {
943         int c, old;
944
945         c = v->counter;
946
947         while ((old = atomic_cmpxchg(v, c, pstate[c])) != c)
948                 c = old;
949
950         return (c);
951 }
952
953
954 static int
955 linux_poll_wakeup_callback(wait_queue_t *wq, unsigned int wq_state, int flags, void *key)
956 {
957         static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
958                 [LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_INIT, /* NOP */
959                 [LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_NOT_READY, /* NOP */
960                 [LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_READY,
961                 [LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_READY, /* NOP */
962         };
963         struct linux_file *filp = container_of(wq, struct linux_file, f_wait_queue.wq);
964
965         switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
966         case LINUX_FWQ_STATE_QUEUED:
967                 linux_poll_wakeup(filp);
968                 return (1);
969         default:
970                 return (0);
971         }
972 }
973
974 void
975 linux_poll_wait(struct linux_file *filp, wait_queue_head_t *wqh, poll_table *p)
976 {
977         static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
978                 [LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_NOT_READY,
979                 [LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_NOT_READY, /* NOP */
980                 [LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_QUEUED, /* NOP */
981                 [LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_QUEUED,
982         };
983
984         /* check if we are called inside the select system call */
985         if (p == LINUX_POLL_TABLE_NORMAL)
986                 selrecord(curthread, &filp->f_selinfo);
987
988         switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
989         case LINUX_FWQ_STATE_INIT:
990                 /* NOTE: file handles can only belong to one wait-queue */
991                 filp->f_wait_queue.wqh = wqh;
992                 filp->f_wait_queue.wq.func = &linux_poll_wakeup_callback;
993                 add_wait_queue(wqh, &filp->f_wait_queue.wq);
994                 atomic_set(&filp->f_wait_queue.state, LINUX_FWQ_STATE_QUEUED);
995                 break;
996         default:
997                 break;
998         }
999 }
1000
1001 static void
1002 linux_poll_wait_dequeue(struct linux_file *filp)
1003 {
1004         static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1005                 [LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_INIT,  /* NOP */
1006                 [LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_INIT,
1007                 [LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_INIT,
1008                 [LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_INIT,
1009         };
1010
1011         seldrain(&filp->f_selinfo);
1012
1013         switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1014         case LINUX_FWQ_STATE_NOT_READY:
1015         case LINUX_FWQ_STATE_QUEUED:
1016         case LINUX_FWQ_STATE_READY:
1017                 remove_wait_queue(filp->f_wait_queue.wqh, &filp->f_wait_queue.wq);
1018                 break;
1019         default:
1020                 break;
1021         }
1022 }
1023
1024 void
1025 linux_poll_wakeup(struct linux_file *filp)
1026 {
1027         /* this function should be NULL-safe */
1028         if (filp == NULL)
1029                 return;
1030
1031         selwakeup(&filp->f_selinfo);
1032
1033         spin_lock(&filp->f_kqlock);
1034         filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ |
1035             LINUX_KQ_FLAG_NEED_WRITE;
1036
1037         /* make sure the "knote" gets woken up */
1038         KNOTE_LOCKED(&filp->f_selinfo.si_note, 1);
1039         spin_unlock(&filp->f_kqlock);
1040 }
1041
1042 static void
1043 linux_file_kqfilter_detach(struct knote *kn)
1044 {
1045         struct linux_file *filp = kn->kn_hook;
1046
1047         spin_lock(&filp->f_kqlock);
1048         knlist_remove(&filp->f_selinfo.si_note, kn, 1);
1049         spin_unlock(&filp->f_kqlock);
1050 }
1051
1052 static int
1053 linux_file_kqfilter_read_event(struct knote *kn, long hint)
1054 {
1055         struct linux_file *filp = kn->kn_hook;
1056
1057         mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1058
1059         return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_READ) ? 1 : 0);
1060 }
1061
1062 static int
1063 linux_file_kqfilter_write_event(struct knote *kn, long hint)
1064 {
1065         struct linux_file *filp = kn->kn_hook;
1066
1067         mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1068
1069         return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_WRITE) ? 1 : 0);
1070 }
1071
1072 static struct filterops linux_dev_kqfiltops_read = {
1073         .f_isfd = 1,
1074         .f_detach = linux_file_kqfilter_detach,
1075         .f_event = linux_file_kqfilter_read_event,
1076 };
1077
1078 static struct filterops linux_dev_kqfiltops_write = {
1079         .f_isfd = 1,
1080         .f_detach = linux_file_kqfilter_detach,
1081         .f_event = linux_file_kqfilter_write_event,
1082 };
1083
1084 static void
1085 linux_file_kqfilter_poll(struct linux_file *filp, int kqflags)
1086 {
1087         int temp;
1088
1089         if (filp->f_kqflags & kqflags) {
1090                 struct thread *td = curthread;
1091
1092                 /* get the latest polling state */
1093                 temp = OPW(filp->_file, td, filp->f_op->poll(filp, NULL));
1094
1095                 spin_lock(&filp->f_kqlock);
1096                 /* clear kqflags */
1097                 filp->f_kqflags &= ~(LINUX_KQ_FLAG_NEED_READ |
1098                     LINUX_KQ_FLAG_NEED_WRITE);
1099                 /* update kqflags */
1100                 if (temp & (POLLIN | POLLOUT)) {
1101                         if (temp & POLLIN)
1102                                 filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ;
1103                         if (temp & POLLOUT)
1104                                 filp->f_kqflags |= LINUX_KQ_FLAG_NEED_WRITE;
1105
1106                         /* make sure the "knote" gets woken up */
1107                         KNOTE_LOCKED(&filp->f_selinfo.si_note, 0);
1108                 }
1109                 spin_unlock(&filp->f_kqlock);
1110         }
1111 }
1112
1113 static int
1114 linux_file_kqfilter(struct file *file, struct knote *kn)
1115 {
1116         struct linux_file *filp;
1117         struct thread *td;
1118         int error;
1119
1120         td = curthread;
1121         filp = (struct linux_file *)file->f_data;
1122         filp->f_flags = file->f_flag;
1123         if (filp->f_op->poll == NULL)
1124                 return (EINVAL);
1125
1126         spin_lock(&filp->f_kqlock);
1127         switch (kn->kn_filter) {
1128         case EVFILT_READ:
1129                 filp->f_kqflags |= LINUX_KQ_FLAG_HAS_READ;
1130                 kn->kn_fop = &linux_dev_kqfiltops_read;
1131                 kn->kn_hook = filp;
1132                 knlist_add(&filp->f_selinfo.si_note, kn, 1);
1133                 error = 0;
1134                 break;
1135         case EVFILT_WRITE:
1136                 filp->f_kqflags |= LINUX_KQ_FLAG_HAS_WRITE;
1137                 kn->kn_fop = &linux_dev_kqfiltops_write;
1138                 kn->kn_hook = filp;
1139                 knlist_add(&filp->f_selinfo.si_note, kn, 1);
1140                 error = 0;
1141                 break;
1142         default:
1143                 error = EINVAL;
1144                 break;
1145         }
1146         spin_unlock(&filp->f_kqlock);
1147
1148         if (error == 0) {
1149                 linux_set_current(td);
1150
1151                 /* update kqfilter status, if any */
1152                 linux_file_kqfilter_poll(filp,
1153                     LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
1154         }
1155         return (error);
1156 }
1157
1158 static int
1159 linux_file_mmap_single(struct file *fp, vm_ooffset_t *offset,
1160     vm_size_t size, struct vm_object **object, int nprot,
1161     struct thread *td)
1162 {
1163         struct task_struct *task;
1164         struct vm_area_struct *vmap;
1165         struct mm_struct *mm;
1166         struct linux_file *filp;
1167         vm_memattr_t attr;
1168         int error;
1169
1170         filp = (struct linux_file *)fp->f_data;
1171         filp->f_flags = fp->f_flag;
1172
1173         if (filp->f_op->mmap == NULL)
1174                 return (EOPNOTSUPP);
1175
1176         linux_set_current(td);
1177
1178         /*
1179          * The same VM object might be shared by multiple processes
1180          * and the mm_struct is usually freed when a process exits.
1181          *
1182          * The atomic reference below makes sure the mm_struct is
1183          * available as long as the vmap is in the linux_vma_head.
1184          */
1185         task = current;
1186         mm = task->mm;
1187         if (atomic_inc_not_zero(&mm->mm_users) == 0)
1188                 return (EINVAL);
1189
1190         vmap = kzalloc(sizeof(*vmap), GFP_KERNEL);
1191         vmap->vm_start = 0;
1192         vmap->vm_end = size;
1193         vmap->vm_pgoff = *offset / PAGE_SIZE;
1194         vmap->vm_pfn = 0;
1195         vmap->vm_flags = vmap->vm_page_prot = (nprot & VM_PROT_ALL);
1196         vmap->vm_ops = NULL;
1197         vmap->vm_file = get_file(filp);
1198         vmap->vm_mm = mm;
1199
1200         if (unlikely(down_write_killable(&vmap->vm_mm->mmap_sem))) {
1201                 error = linux_get_error(task, EINTR);
1202         } else {
1203                 error = -OPW(fp, td, filp->f_op->mmap(filp, vmap));
1204                 error = linux_get_error(task, error);
1205                 up_write(&vmap->vm_mm->mmap_sem);
1206         }
1207
1208         if (error != 0) {
1209                 linux_cdev_handle_free(vmap);
1210                 return (error);
1211         }
1212
1213         attr = pgprot2cachemode(vmap->vm_page_prot);
1214
1215         if (vmap->vm_ops != NULL) {
1216                 struct vm_area_struct *ptr;
1217                 void *vm_private_data;
1218                 bool vm_no_fault;
1219
1220                 if (vmap->vm_ops->open == NULL ||
1221                     vmap->vm_ops->close == NULL ||
1222                     vmap->vm_private_data == NULL) {
1223                         /* free allocated VM area struct */
1224                         linux_cdev_handle_free(vmap);
1225                         return (EINVAL);
1226                 }
1227
1228                 vm_private_data = vmap->vm_private_data;
1229
1230                 rw_wlock(&linux_vma_lock);
1231                 TAILQ_FOREACH(ptr, &linux_vma_head, vm_entry) {
1232                         if (ptr->vm_private_data == vm_private_data)
1233                                 break;
1234                 }
1235                 /* check if there is an existing VM area struct */
1236                 if (ptr != NULL) {
1237                         /* check if the VM area structure is invalid */
1238                         if (ptr->vm_ops == NULL ||
1239                             ptr->vm_ops->open == NULL ||
1240                             ptr->vm_ops->close == NULL) {
1241                                 error = ESTALE;
1242                                 vm_no_fault = 1;
1243                         } else {
1244                                 error = EEXIST;
1245                                 vm_no_fault = (ptr->vm_ops->fault == NULL);
1246                         }
1247                 } else {
1248                         /* insert VM area structure into list */
1249                         TAILQ_INSERT_TAIL(&linux_vma_head, vmap, vm_entry);
1250                         error = 0;
1251                         vm_no_fault = (vmap->vm_ops->fault == NULL);
1252                 }
1253                 rw_wunlock(&linux_vma_lock);
1254
1255                 if (error != 0) {
1256                         /* free allocated VM area struct */
1257                         linux_cdev_handle_free(vmap);
1258                         /* check for stale VM area struct */
1259                         if (error != EEXIST)
1260                                 return (error);
1261                 }
1262
1263                 /* check if there is no fault handler */
1264                 if (vm_no_fault) {
1265                         *object = cdev_pager_allocate(vm_private_data, OBJT_DEVICE,
1266                             &linux_cdev_pager_ops[1], size, nprot, *offset,
1267                             td->td_ucred);
1268                 } else {
1269                         *object = cdev_pager_allocate(vm_private_data, OBJT_MGTDEVICE,
1270                             &linux_cdev_pager_ops[0], size, nprot, *offset,
1271                             td->td_ucred);
1272                 }
1273
1274                 /* check if allocating the VM object failed */
1275                 if (*object == NULL) {
1276                         if (error == 0) {
1277                                 /* remove VM area struct from list */
1278                                 linux_cdev_handle_remove(vmap);
1279                                 /* free allocated VM area struct */
1280                                 linux_cdev_handle_free(vmap);
1281                         }
1282                         return (EINVAL);
1283                 }
1284         } else {
1285                 struct sglist *sg;
1286
1287                 sg = sglist_alloc(1, M_WAITOK);
1288                 sglist_append_phys(sg,
1289                     (vm_paddr_t)vmap->vm_pfn << PAGE_SHIFT, vmap->vm_len);
1290
1291                 *object = vm_pager_allocate(OBJT_SG, sg, vmap->vm_len,
1292                     nprot, 0, td->td_ucred);
1293
1294                 linux_cdev_handle_free(vmap);
1295
1296                 if (*object == NULL) {
1297                         sglist_free(sg);
1298                         return (EINVAL);
1299                 }
1300         }
1301
1302         if (attr != VM_MEMATTR_DEFAULT) {
1303                 VM_OBJECT_WLOCK(*object);
1304                 vm_object_set_memattr(*object, attr);
1305                 VM_OBJECT_WUNLOCK(*object);
1306         }
1307         *offset = 0;
1308         return (0);
1309 }
1310
1311 struct cdevsw linuxcdevsw = {
1312         .d_version = D_VERSION,
1313         .d_fdopen = linux_dev_fdopen,
1314         .d_name = "lkpidev",
1315 };
1316
1317 static int
1318 linux_file_read(struct file *file, struct uio *uio, struct ucred *active_cred,
1319     int flags, struct thread *td)
1320 {
1321         struct linux_file *filp;
1322         ssize_t bytes;
1323         int error;
1324
1325         error = 0;
1326         filp = (struct linux_file *)file->f_data;
1327         filp->f_flags = file->f_flag;
1328         /* XXX no support for I/O vectors currently */
1329         if (uio->uio_iovcnt != 1)
1330                 return (EOPNOTSUPP);
1331         if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1332                 return (EINVAL);
1333         linux_set_current(td);
1334         if (filp->f_op->read) {
1335                 bytes = OPW(file, td, filp->f_op->read(filp, uio->uio_iov->iov_base,
1336                     uio->uio_iov->iov_len, &uio->uio_offset));
1337                 if (bytes >= 0) {
1338                         uio->uio_iov->iov_base =
1339                             ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1340                         uio->uio_iov->iov_len -= bytes;
1341                         uio->uio_resid -= bytes;
1342                 } else {
1343                         error = linux_get_error(current, -bytes);
1344                 }
1345         } else
1346                 error = ENXIO;
1347
1348         /* update kqfilter status, if any */
1349         linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_READ);
1350
1351         return (error);
1352 }
1353
1354 static int
1355 linux_file_write(struct file *file, struct uio *uio, struct ucred *active_cred,
1356     int flags, struct thread *td)
1357 {
1358         struct linux_file *filp;
1359         ssize_t bytes;
1360         int error;
1361
1362         error = 0;
1363         filp = (struct linux_file *)file->f_data;
1364         filp->f_flags = file->f_flag;
1365         /* XXX no support for I/O vectors currently */
1366         if (uio->uio_iovcnt != 1)
1367                 return (EOPNOTSUPP);
1368         if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1369                 return (EINVAL);
1370         linux_set_current(td);
1371         if (filp->f_op->write) {
1372                 bytes = OPW(file, td, filp->f_op->write(filp, uio->uio_iov->iov_base,
1373                     uio->uio_iov->iov_len, &uio->uio_offset));
1374                 if (bytes >= 0) {
1375                         uio->uio_iov->iov_base =
1376                             ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1377                         uio->uio_iov->iov_len -= bytes;
1378                         uio->uio_resid -= bytes;
1379                 } else {
1380                         error = linux_get_error(current, -bytes);
1381                 }
1382         } else
1383                 error = ENXIO;
1384
1385         /* update kqfilter status, if any */
1386         linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_WRITE);
1387
1388         return (error);
1389 }
1390
1391 static int
1392 linux_file_poll(struct file *file, int events, struct ucred *active_cred,
1393     struct thread *td)
1394 {
1395         struct linux_file *filp;
1396         int revents;
1397
1398         filp = (struct linux_file *)file->f_data;
1399         filp->f_flags = file->f_flag;
1400         linux_set_current(td);
1401         if (filp->f_op->poll != NULL)
1402                 revents = OPW(file, td, filp->f_op->poll(filp, LINUX_POLL_TABLE_NORMAL)) & events;
1403         else
1404                 revents = 0;
1405
1406         return (revents);
1407 }
1408
1409 static int
1410 linux_file_close(struct file *file, struct thread *td)
1411 {
1412         struct linux_file *filp;
1413         int error;
1414
1415         filp = (struct linux_file *)file->f_data;
1416
1417         KASSERT(file_count(filp) == 0, ("File refcount(%d) is not zero", file_count(filp)));
1418
1419         filp->f_flags = file->f_flag;
1420         linux_set_current(td);
1421         linux_poll_wait_dequeue(filp);
1422         error = -OPW(file, td, filp->f_op->release(filp->f_vnode, filp));
1423         funsetown(&filp->f_sigio);
1424         if (filp->f_vnode != NULL)
1425                 vdrop(filp->f_vnode);
1426         if (filp->f_cdev != NULL) {
1427                 /* put a reference on the Linux character device */
1428                 atomic_long_dec(&filp->f_cdev->refs);
1429         }
1430         kfree(filp);
1431
1432         return (error);
1433 }
1434
1435 static int
1436 linux_file_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *cred,
1437     struct thread *td)
1438 {
1439         struct linux_file *filp;
1440         int error;
1441
1442         filp = (struct linux_file *)fp->f_data;
1443         filp->f_flags = fp->f_flag;
1444         error = 0;
1445
1446         linux_set_current(td);
1447         switch (cmd) {
1448         case FIONBIO:
1449                 break;
1450         case FIOASYNC:
1451                 if (filp->f_op->fasync == NULL)
1452                         break;
1453                 error = -OPW(fp, td, filp->f_op->fasync(0, filp, fp->f_flag & FASYNC));
1454                 break;
1455         case FIOSETOWN:
1456                 error = fsetown(*(int *)data, &filp->f_sigio);
1457                 if (error == 0) {
1458                         if (filp->f_op->fasync == NULL)
1459                                 break;
1460                         error = -OPW(fp, td, filp->f_op->fasync(0, filp,
1461                             fp->f_flag & FASYNC));
1462                 }
1463                 break;
1464         case FIOGETOWN:
1465                 *(int *)data = fgetown(&filp->f_sigio);
1466                 break;
1467         default:
1468                 error = linux_file_ioctl_sub(fp, filp, cmd, data, td);
1469                 break;
1470         }
1471         return (error);
1472 }
1473
1474 static int
1475 linux_file_mmap_sub(struct thread *td, vm_size_t objsize, vm_prot_t prot,
1476     vm_prot_t *maxprotp, int *flagsp, struct file *fp,
1477     vm_ooffset_t *foff, vm_object_t *objp)
1478 {
1479         /*
1480          * Character devices do not provide private mappings
1481          * of any kind:
1482          */
1483         if ((*maxprotp & VM_PROT_WRITE) == 0 &&
1484             (prot & VM_PROT_WRITE) != 0)
1485                 return (EACCES);
1486         if ((*flagsp & (MAP_PRIVATE | MAP_COPY)) != 0)
1487                 return (EINVAL);
1488
1489         return (linux_file_mmap_single(fp, foff, objsize, objp, (int)prot, td));
1490 }
1491
1492 static int
1493 linux_file_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
1494     vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
1495     struct thread *td)
1496 {
1497         struct linux_file *filp;
1498         struct mount *mp;
1499         struct vnode *vp;
1500         vm_object_t object;
1501         vm_prot_t maxprot;
1502         int error;
1503
1504         filp = (struct linux_file *)fp->f_data;
1505
1506         vp = filp->f_vnode;
1507         if (vp == NULL)
1508                 return (EOPNOTSUPP);
1509
1510         /*
1511          * Ensure that file and memory protections are
1512          * compatible.
1513          */
1514         mp = vp->v_mount;
1515         if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
1516                 maxprot = VM_PROT_NONE;
1517                 if ((prot & VM_PROT_EXECUTE) != 0)
1518                         return (EACCES);
1519         } else
1520                 maxprot = VM_PROT_EXECUTE;
1521         if ((fp->f_flag & FREAD) != 0)
1522                 maxprot |= VM_PROT_READ;
1523         else if ((prot & VM_PROT_READ) != 0)
1524                 return (EACCES);
1525
1526         /*
1527          * If we are sharing potential changes via MAP_SHARED and we
1528          * are trying to get write permission although we opened it
1529          * without asking for it, bail out.
1530          *
1531          * Note that most character devices always share mappings.
1532          *
1533          * Rely on linux_file_mmap_sub() to fail invalid MAP_PRIVATE
1534          * requests rather than doing it here.
1535          */
1536         if ((flags & MAP_SHARED) != 0) {
1537                 if ((fp->f_flag & FWRITE) != 0)
1538                         maxprot |= VM_PROT_WRITE;
1539                 else if ((prot & VM_PROT_WRITE) != 0)
1540                         return (EACCES);
1541         }
1542         maxprot &= cap_maxprot;
1543
1544         error = linux_file_mmap_sub(td, size, prot, &maxprot, &flags, fp, &foff,
1545             &object);
1546         if (error != 0)
1547                 return (error);
1548
1549         error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
1550             foff, FALSE, td);
1551         if (error != 0)
1552                 vm_object_deallocate(object);
1553         return (error);
1554 }
1555
1556 static int
1557 linux_file_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
1558     struct thread *td)
1559 {
1560         struct linux_file *filp;
1561         struct vnode *vp;
1562         int error;
1563
1564         filp = (struct linux_file *)fp->f_data;
1565         if (filp->f_vnode == NULL)
1566                 return (EOPNOTSUPP);
1567
1568         vp = filp->f_vnode;
1569
1570         vn_lock(vp, LK_SHARED | LK_RETRY);
1571         error = vn_stat(vp, sb, td->td_ucred, NOCRED, td);
1572         VOP_UNLOCK(vp, 0);
1573
1574         return (error);
1575 }
1576
1577 static int
1578 linux_file_fill_kinfo(struct file *fp, struct kinfo_file *kif,
1579     struct filedesc *fdp)
1580 {
1581         struct linux_file *filp;
1582         struct vnode *vp;
1583         int error;
1584
1585         filp = fp->f_data;
1586         vp = filp->f_vnode;
1587         if (vp == NULL) {
1588                 error = 0;
1589                 kif->kf_type = KF_TYPE_DEV;
1590         } else {
1591                 vref(vp);
1592                 FILEDESC_SUNLOCK(fdp);
1593                 error = vn_fill_kinfo_vnode(vp, kif);
1594                 vrele(vp);
1595                 kif->kf_type = KF_TYPE_VNODE;
1596                 FILEDESC_SLOCK(fdp);
1597         }
1598         return (error);
1599 }
1600
1601 unsigned int
1602 linux_iminor(struct inode *inode)
1603 {
1604         struct linux_cdev *ldev;
1605
1606         if (inode == NULL || inode->v_rdev == NULL ||
1607             inode->v_rdev->si_devsw != &linuxcdevsw)
1608                 return (-1U);
1609         ldev = inode->v_rdev->si_drv1;
1610         if (ldev == NULL)
1611                 return (-1U);
1612
1613         return (minor(ldev->dev));
1614 }
1615
1616 struct fileops linuxfileops = {
1617         .fo_read = linux_file_read,
1618         .fo_write = linux_file_write,
1619         .fo_truncate = invfo_truncate,
1620         .fo_kqfilter = linux_file_kqfilter,
1621         .fo_stat = linux_file_stat,
1622         .fo_fill_kinfo = linux_file_fill_kinfo,
1623         .fo_poll = linux_file_poll,
1624         .fo_close = linux_file_close,
1625         .fo_ioctl = linux_file_ioctl,
1626         .fo_mmap = linux_file_mmap,
1627         .fo_chmod = invfo_chmod,
1628         .fo_chown = invfo_chown,
1629         .fo_sendfile = invfo_sendfile,
1630         .fo_flags = DFLAG_PASSABLE,
1631 };
1632
1633 /*
1634  * Hash of vmmap addresses.  This is infrequently accessed and does not
1635  * need to be particularly large.  This is done because we must store the
1636  * caller's idea of the map size to properly unmap.
1637  */
1638 struct vmmap {
1639         LIST_ENTRY(vmmap)       vm_next;
1640         void                    *vm_addr;
1641         unsigned long           vm_size;
1642 };
1643
1644 struct vmmaphd {
1645         struct vmmap *lh_first;
1646 };
1647 #define VMMAP_HASH_SIZE 64
1648 #define VMMAP_HASH_MASK (VMMAP_HASH_SIZE - 1)
1649 #define VM_HASH(addr)   ((uintptr_t)(addr) >> PAGE_SHIFT) & VMMAP_HASH_MASK
1650 static struct vmmaphd vmmaphead[VMMAP_HASH_SIZE];
1651 static struct mtx vmmaplock;
1652
1653 static void
1654 vmmap_add(void *addr, unsigned long size)
1655 {
1656         struct vmmap *vmmap;
1657
1658         vmmap = kmalloc(sizeof(*vmmap), GFP_KERNEL);
1659         mtx_lock(&vmmaplock);
1660         vmmap->vm_size = size;
1661         vmmap->vm_addr = addr;
1662         LIST_INSERT_HEAD(&vmmaphead[VM_HASH(addr)], vmmap, vm_next);
1663         mtx_unlock(&vmmaplock);
1664 }
1665
1666 static struct vmmap *
1667 vmmap_remove(void *addr)
1668 {
1669         struct vmmap *vmmap;
1670
1671         mtx_lock(&vmmaplock);
1672         LIST_FOREACH(vmmap, &vmmaphead[VM_HASH(addr)], vm_next)
1673                 if (vmmap->vm_addr == addr)
1674                         break;
1675         if (vmmap)
1676                 LIST_REMOVE(vmmap, vm_next);
1677         mtx_unlock(&vmmaplock);
1678
1679         return (vmmap);
1680 }
1681
1682 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
1683 void *
1684 _ioremap_attr(vm_paddr_t phys_addr, unsigned long size, int attr)
1685 {
1686         void *addr;
1687
1688         addr = pmap_mapdev_attr(phys_addr, size, attr);
1689         if (addr == NULL)
1690                 return (NULL);
1691         vmmap_add(addr, size);
1692
1693         return (addr);
1694 }
1695 #endif
1696
1697 void
1698 iounmap(void *addr)
1699 {
1700         struct vmmap *vmmap;
1701
1702         vmmap = vmmap_remove(addr);
1703         if (vmmap == NULL)
1704                 return;
1705 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
1706         pmap_unmapdev((vm_offset_t)addr, vmmap->vm_size);
1707 #endif
1708         kfree(vmmap);
1709 }
1710
1711
1712 void *
1713 vmap(struct page **pages, unsigned int count, unsigned long flags, int prot)
1714 {
1715         vm_offset_t off;
1716         size_t size;
1717
1718         size = count * PAGE_SIZE;
1719         off = kva_alloc(size);
1720         if (off == 0)
1721                 return (NULL);
1722         vmmap_add((void *)off, size);
1723         pmap_qenter(off, pages, count);
1724
1725         return ((void *)off);
1726 }
1727
1728 void
1729 vunmap(void *addr)
1730 {
1731         struct vmmap *vmmap;
1732
1733         vmmap = vmmap_remove(addr);
1734         if (vmmap == NULL)
1735                 return;
1736         pmap_qremove((vm_offset_t)addr, vmmap->vm_size / PAGE_SIZE);
1737         kva_free((vm_offset_t)addr, vmmap->vm_size);
1738         kfree(vmmap);
1739 }
1740
1741 char *
1742 kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
1743 {
1744         unsigned int len;
1745         char *p;
1746         va_list aq;
1747
1748         va_copy(aq, ap);
1749         len = vsnprintf(NULL, 0, fmt, aq);
1750         va_end(aq);
1751
1752         p = kmalloc(len + 1, gfp);
1753         if (p != NULL)
1754                 vsnprintf(p, len + 1, fmt, ap);
1755
1756         return (p);
1757 }
1758
1759 char *
1760 kasprintf(gfp_t gfp, const char *fmt, ...)
1761 {
1762         va_list ap;
1763         char *p;
1764
1765         va_start(ap, fmt);
1766         p = kvasprintf(gfp, fmt, ap);
1767         va_end(ap);
1768
1769         return (p);
1770 }
1771
1772 static void
1773 linux_timer_callback_wrapper(void *context)
1774 {
1775         struct timer_list *timer;
1776
1777         linux_set_current(curthread);
1778
1779         timer = context;
1780         timer->function(timer->data);
1781 }
1782
1783 void
1784 mod_timer(struct timer_list *timer, int expires)
1785 {
1786
1787         timer->expires = expires;
1788         callout_reset(&timer->callout,
1789             linux_timer_jiffies_until(expires),
1790             &linux_timer_callback_wrapper, timer);
1791 }
1792
1793 void
1794 add_timer(struct timer_list *timer)
1795 {
1796
1797         callout_reset(&timer->callout,
1798             linux_timer_jiffies_until(timer->expires),
1799             &linux_timer_callback_wrapper, timer);
1800 }
1801
1802 void
1803 add_timer_on(struct timer_list *timer, int cpu)
1804 {
1805
1806         callout_reset_on(&timer->callout,
1807             linux_timer_jiffies_until(timer->expires),
1808             &linux_timer_callback_wrapper, timer, cpu);
1809 }
1810
1811 static void
1812 linux_timer_init(void *arg)
1813 {
1814
1815         /*
1816          * Compute an internal HZ value which can divide 2**32 to
1817          * avoid timer rounding problems when the tick value wraps
1818          * around 2**32:
1819          */
1820         linux_timer_hz_mask = 1;
1821         while (linux_timer_hz_mask < (unsigned long)hz)
1822                 linux_timer_hz_mask *= 2;
1823         linux_timer_hz_mask--;
1824 }
1825 SYSINIT(linux_timer, SI_SUB_DRIVERS, SI_ORDER_FIRST, linux_timer_init, NULL);
1826
1827 void
1828 linux_complete_common(struct completion *c, int all)
1829 {
1830         int wakeup_swapper;
1831
1832         sleepq_lock(c);
1833         if (all) {
1834                 c->done = UINT_MAX;
1835                 wakeup_swapper = sleepq_broadcast(c, SLEEPQ_SLEEP, 0, 0);
1836         } else {
1837                 if (c->done != UINT_MAX)
1838                         c->done++;
1839                 wakeup_swapper = sleepq_signal(c, SLEEPQ_SLEEP, 0, 0);
1840         }
1841         sleepq_release(c);
1842         if (wakeup_swapper)
1843                 kick_proc0();
1844 }
1845
1846 /*
1847  * Indefinite wait for done != 0 with or without signals.
1848  */
1849 int
1850 linux_wait_for_common(struct completion *c, int flags)
1851 {
1852         struct task_struct *task;
1853         int error;
1854
1855         if (SCHEDULER_STOPPED())
1856                 return (0);
1857
1858         task = current;
1859
1860         if (flags != 0)
1861                 flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
1862         else
1863                 flags = SLEEPQ_SLEEP;
1864         error = 0;
1865         for (;;) {
1866                 sleepq_lock(c);
1867                 if (c->done)
1868                         break;
1869                 sleepq_add(c, NULL, "completion", flags, 0);
1870                 if (flags & SLEEPQ_INTERRUPTIBLE) {
1871                         DROP_GIANT();
1872                         error = -sleepq_wait_sig(c, 0);
1873                         PICKUP_GIANT();
1874                         if (error != 0) {
1875                                 linux_schedule_save_interrupt_value(task, error);
1876                                 error = -ERESTARTSYS;
1877                                 goto intr;
1878                         }
1879                 } else {
1880                         DROP_GIANT();
1881                         sleepq_wait(c, 0);
1882                         PICKUP_GIANT();
1883                 }
1884         }
1885         if (c->done != UINT_MAX)
1886                 c->done--;
1887         sleepq_release(c);
1888
1889 intr:
1890         return (error);
1891 }
1892
1893 /*
1894  * Time limited wait for done != 0 with or without signals.
1895  */
1896 int
1897 linux_wait_for_timeout_common(struct completion *c, int timeout, int flags)
1898 {
1899         struct task_struct *task;
1900         int end = jiffies + timeout;
1901         int error;
1902
1903         if (SCHEDULER_STOPPED())
1904                 return (0);
1905
1906         task = current;
1907
1908         if (flags != 0)
1909                 flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
1910         else
1911                 flags = SLEEPQ_SLEEP;
1912
1913         for (;;) {
1914                 sleepq_lock(c);
1915                 if (c->done)
1916                         break;
1917                 sleepq_add(c, NULL, "completion", flags, 0);
1918                 sleepq_set_timeout(c, linux_timer_jiffies_until(end));
1919
1920                 DROP_GIANT();
1921                 if (flags & SLEEPQ_INTERRUPTIBLE)
1922                         error = -sleepq_timedwait_sig(c, 0);
1923                 else
1924                         error = -sleepq_timedwait(c, 0);
1925                 PICKUP_GIANT();
1926
1927                 if (error != 0) {
1928                         /* check for timeout */
1929                         if (error == -EWOULDBLOCK) {
1930                                 error = 0;      /* timeout */
1931                         } else {
1932                                 /* signal happened */
1933                                 linux_schedule_save_interrupt_value(task, error);
1934                                 error = -ERESTARTSYS;
1935                         }
1936                         goto done;
1937                 }
1938         }
1939         if (c->done != UINT_MAX)
1940                 c->done--;
1941         sleepq_release(c);
1942
1943         /* return how many jiffies are left */
1944         error = linux_timer_jiffies_until(end);
1945 done:
1946         return (error);
1947 }
1948
1949 int
1950 linux_try_wait_for_completion(struct completion *c)
1951 {
1952         int isdone;
1953
1954         sleepq_lock(c);
1955         isdone = (c->done != 0);
1956         if (c->done != 0 && c->done != UINT_MAX)
1957                 c->done--;
1958         sleepq_release(c);
1959         return (isdone);
1960 }
1961
1962 int
1963 linux_completion_done(struct completion *c)
1964 {
1965         int isdone;
1966
1967         sleepq_lock(c);
1968         isdone = (c->done != 0);
1969         sleepq_release(c);
1970         return (isdone);
1971 }
1972
1973 static void
1974 linux_cdev_release(struct kobject *kobj)
1975 {
1976         struct linux_cdev *cdev;
1977         struct kobject *parent;
1978
1979         cdev = container_of(kobj, struct linux_cdev, kobj);
1980         parent = kobj->parent;
1981         linux_destroy_dev(cdev);
1982         kfree(cdev);
1983         kobject_put(parent);
1984 }
1985
1986 static void
1987 linux_cdev_static_release(struct kobject *kobj)
1988 {
1989         struct linux_cdev *cdev;
1990         struct kobject *parent;
1991
1992         cdev = container_of(kobj, struct linux_cdev, kobj);
1993         parent = kobj->parent;
1994         linux_destroy_dev(cdev);
1995         kobject_put(parent);
1996 }
1997
1998 void
1999 linux_destroy_dev(struct linux_cdev *cdev)
2000 {
2001
2002         if (cdev->cdev == NULL)
2003                 return;
2004
2005         atomic_long_dec(&cdev->refs);
2006
2007         /* wait for all open files to be closed */
2008         while (atomic_long_read(&cdev->refs) != -1L)
2009                 pause("ldevdrn", hz);
2010
2011         destroy_dev(cdev->cdev);
2012         cdev->cdev = NULL;
2013 }
2014
2015 const struct kobj_type linux_cdev_ktype = {
2016         .release = linux_cdev_release,
2017 };
2018
2019 const struct kobj_type linux_cdev_static_ktype = {
2020         .release = linux_cdev_static_release,
2021 };
2022
2023 static void
2024 linux_handle_ifnet_link_event(void *arg, struct ifnet *ifp, int linkstate)
2025 {
2026         struct notifier_block *nb;
2027
2028         nb = arg;
2029         if (linkstate == LINK_STATE_UP)
2030                 nb->notifier_call(nb, NETDEV_UP, ifp);
2031         else
2032                 nb->notifier_call(nb, NETDEV_DOWN, ifp);
2033 }
2034
2035 static void
2036 linux_handle_ifnet_arrival_event(void *arg, struct ifnet *ifp)
2037 {
2038         struct notifier_block *nb;
2039
2040         nb = arg;
2041         nb->notifier_call(nb, NETDEV_REGISTER, ifp);
2042 }
2043
2044 static void
2045 linux_handle_ifnet_departure_event(void *arg, struct ifnet *ifp)
2046 {
2047         struct notifier_block *nb;
2048
2049         nb = arg;
2050         nb->notifier_call(nb, NETDEV_UNREGISTER, ifp);
2051 }
2052
2053 static void
2054 linux_handle_iflladdr_event(void *arg, struct ifnet *ifp)
2055 {
2056         struct notifier_block *nb;
2057
2058         nb = arg;
2059         nb->notifier_call(nb, NETDEV_CHANGEADDR, ifp);
2060 }
2061
2062 static void
2063 linux_handle_ifaddr_event(void *arg, struct ifnet *ifp)
2064 {
2065         struct notifier_block *nb;
2066
2067         nb = arg;
2068         nb->notifier_call(nb, NETDEV_CHANGEIFADDR, ifp);
2069 }
2070
2071 int
2072 register_netdevice_notifier(struct notifier_block *nb)
2073 {
2074
2075         nb->tags[NETDEV_UP] = EVENTHANDLER_REGISTER(
2076             ifnet_link_event, linux_handle_ifnet_link_event, nb, 0);
2077         nb->tags[NETDEV_REGISTER] = EVENTHANDLER_REGISTER(
2078             ifnet_arrival_event, linux_handle_ifnet_arrival_event, nb, 0);
2079         nb->tags[NETDEV_UNREGISTER] = EVENTHANDLER_REGISTER(
2080             ifnet_departure_event, linux_handle_ifnet_departure_event, nb, 0);
2081         nb->tags[NETDEV_CHANGEADDR] = EVENTHANDLER_REGISTER(
2082             iflladdr_event, linux_handle_iflladdr_event, nb, 0);
2083
2084         return (0);
2085 }
2086
2087 int
2088 register_inetaddr_notifier(struct notifier_block *nb)
2089 {
2090
2091         nb->tags[NETDEV_CHANGEIFADDR] = EVENTHANDLER_REGISTER(
2092             ifaddr_event, linux_handle_ifaddr_event, nb, 0);
2093         return (0);
2094 }
2095
2096 int
2097 unregister_netdevice_notifier(struct notifier_block *nb)
2098 {
2099
2100         EVENTHANDLER_DEREGISTER(ifnet_link_event,
2101             nb->tags[NETDEV_UP]);
2102         EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
2103             nb->tags[NETDEV_REGISTER]);
2104         EVENTHANDLER_DEREGISTER(ifnet_departure_event,
2105             nb->tags[NETDEV_UNREGISTER]);
2106         EVENTHANDLER_DEREGISTER(iflladdr_event,
2107             nb->tags[NETDEV_CHANGEADDR]);
2108
2109         return (0);
2110 }
2111
2112 int
2113 unregister_inetaddr_notifier(struct notifier_block *nb)
2114 {
2115
2116         EVENTHANDLER_DEREGISTER(ifaddr_event,
2117             nb->tags[NETDEV_CHANGEIFADDR]);
2118
2119         return (0);
2120 }
2121
2122 struct list_sort_thunk {
2123         int (*cmp)(void *, struct list_head *, struct list_head *);
2124         void *priv;
2125 };
2126
2127 static inline int
2128 linux_le_cmp(void *priv, const void *d1, const void *d2)
2129 {
2130         struct list_head *le1, *le2;
2131         struct list_sort_thunk *thunk;
2132
2133         thunk = priv;
2134         le1 = *(__DECONST(struct list_head **, d1));
2135         le2 = *(__DECONST(struct list_head **, d2));
2136         return ((thunk->cmp)(thunk->priv, le1, le2));
2137 }
2138
2139 void
2140 list_sort(void *priv, struct list_head *head, int (*cmp)(void *priv,
2141     struct list_head *a, struct list_head *b))
2142 {
2143         struct list_sort_thunk thunk;
2144         struct list_head **ar, *le;
2145         size_t count, i;
2146
2147         count = 0;
2148         list_for_each(le, head)
2149                 count++;
2150         ar = malloc(sizeof(struct list_head *) * count, M_KMALLOC, M_WAITOK);
2151         i = 0;
2152         list_for_each(le, head)
2153                 ar[i++] = le;
2154         thunk.cmp = cmp;
2155         thunk.priv = priv;
2156         qsort_r(ar, count, sizeof(struct list_head *), &thunk, linux_le_cmp);
2157         INIT_LIST_HEAD(head);
2158         for (i = 0; i < count; i++)
2159                 list_add_tail(ar[i], head);
2160         free(ar, M_KMALLOC);
2161 }
2162
2163 void
2164 linux_irq_handler(void *ent)
2165 {
2166         struct irq_ent *irqe;
2167
2168         linux_set_current(curthread);
2169
2170         irqe = ent;
2171         irqe->handler(irqe->irq, irqe->arg);
2172 }
2173
2174 #if defined(__i386__) || defined(__amd64__)
2175 int
2176 linux_wbinvd_on_all_cpus(void)
2177 {
2178
2179         pmap_invalidate_cache();
2180         return (0);
2181 }
2182 #endif
2183
2184 int
2185 linux_on_each_cpu(void callback(void *), void *data)
2186 {
2187
2188         smp_rendezvous(smp_no_rendezvous_barrier, callback,
2189             smp_no_rendezvous_barrier, data);
2190         return (0);
2191 }
2192
2193 int
2194 linux_in_atomic(void)
2195 {
2196
2197         return ((curthread->td_pflags & TDP_NOFAULTING) != 0);
2198 }
2199
2200 struct linux_cdev *
2201 linux_find_cdev(const char *name, unsigned major, unsigned minor)
2202 {
2203         dev_t dev = MKDEV(major, minor);
2204         struct cdev *cdev;
2205
2206         dev_lock();
2207         LIST_FOREACH(cdev, &linuxcdevsw.d_devs, si_list) {
2208                 struct linux_cdev *ldev = cdev->si_drv1;
2209                 if (ldev->dev == dev &&
2210                     strcmp(kobject_name(&ldev->kobj), name) == 0) {
2211                         break;
2212                 }
2213         }
2214         dev_unlock();
2215
2216         return (cdev != NULL ? cdev->si_drv1 : NULL);
2217 }
2218
2219 int
2220 __register_chrdev(unsigned int major, unsigned int baseminor,
2221     unsigned int count, const char *name,
2222     const struct file_operations *fops)
2223 {
2224         struct linux_cdev *cdev;
2225         int ret = 0;
2226         int i;
2227
2228         for (i = baseminor; i < baseminor + count; i++) {
2229                 cdev = cdev_alloc();
2230                 cdev_init(cdev, fops);
2231                 kobject_set_name(&cdev->kobj, name);
2232
2233                 ret = cdev_add(cdev, makedev(major, i), 1);
2234                 if (ret != 0)
2235                         break;
2236         }
2237         return (ret);
2238 }
2239
2240 int
2241 __register_chrdev_p(unsigned int major, unsigned int baseminor,
2242     unsigned int count, const char *name,
2243     const struct file_operations *fops, uid_t uid,
2244     gid_t gid, int mode)
2245 {
2246         struct linux_cdev *cdev;
2247         int ret = 0;
2248         int i;
2249
2250         for (i = baseminor; i < baseminor + count; i++) {
2251                 cdev = cdev_alloc();
2252                 cdev_init(cdev, fops);
2253                 kobject_set_name(&cdev->kobj, name);
2254
2255                 ret = cdev_add_ext(cdev, makedev(major, i), uid, gid, mode);
2256                 if (ret != 0)
2257                         break;
2258         }
2259         return (ret);
2260 }
2261
2262 void
2263 __unregister_chrdev(unsigned int major, unsigned int baseminor,
2264     unsigned int count, const char *name)
2265 {
2266         struct linux_cdev *cdevp;
2267         int i;
2268
2269         for (i = baseminor; i < baseminor + count; i++) {
2270                 cdevp = linux_find_cdev(name, major, i);
2271                 if (cdevp != NULL)
2272                         cdev_del(cdevp);
2273         }
2274 }
2275
2276 void
2277 linux_dump_stack(void)
2278 {
2279 #ifdef STACK
2280         struct stack st;
2281
2282         stack_zero(&st);
2283         stack_save(&st);
2284         stack_print(&st);
2285 #endif
2286 }
2287
2288 #if defined(__i386__) || defined(__amd64__)
2289 bool linux_cpu_has_clflush;
2290 #endif
2291
2292 static void
2293 linux_compat_init(void *arg)
2294 {
2295         struct sysctl_oid *rootoid;
2296         int i;
2297
2298 #if defined(__i386__) || defined(__amd64__)
2299         linux_cpu_has_clflush = (cpu_feature & CPUID_CLFSH);
2300 #endif
2301         rw_init(&linux_vma_lock, "lkpi-vma-lock");
2302
2303         rootoid = SYSCTL_ADD_ROOT_NODE(NULL,
2304             OID_AUTO, "sys", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "sys");
2305         kobject_init(&linux_class_root, &linux_class_ktype);
2306         kobject_set_name(&linux_class_root, "class");
2307         linux_class_root.oidp = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(rootoid),
2308             OID_AUTO, "class", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "class");
2309         kobject_init(&linux_root_device.kobj, &linux_dev_ktype);
2310         kobject_set_name(&linux_root_device.kobj, "device");
2311         linux_root_device.kobj.oidp = SYSCTL_ADD_NODE(NULL,
2312             SYSCTL_CHILDREN(rootoid), OID_AUTO, "device", CTLFLAG_RD, NULL,
2313             "device");
2314         linux_root_device.bsddev = root_bus;
2315         linux_class_misc.name = "misc";
2316         class_register(&linux_class_misc);
2317         INIT_LIST_HEAD(&pci_drivers);
2318         INIT_LIST_HEAD(&pci_devices);
2319         spin_lock_init(&pci_lock);
2320         mtx_init(&vmmaplock, "IO Map lock", NULL, MTX_DEF);
2321         for (i = 0; i < VMMAP_HASH_SIZE; i++)
2322                 LIST_INIT(&vmmaphead[i]);
2323 }
2324 SYSINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_init, NULL);
2325
2326 static void
2327 linux_compat_uninit(void *arg)
2328 {
2329         linux_kobject_kfree_name(&linux_class_root);
2330         linux_kobject_kfree_name(&linux_root_device.kobj);
2331         linux_kobject_kfree_name(&linux_class_misc.kobj);
2332
2333         mtx_destroy(&vmmaplock);
2334         spin_lock_destroy(&pci_lock);
2335         rw_destroy(&linux_vma_lock);
2336 }
2337 SYSUNINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_uninit, NULL);
2338
2339 /*
2340  * NOTE: Linux frequently uses "unsigned long" for pointer to integer
2341  * conversion and vice versa, where in FreeBSD "uintptr_t" would be
2342  * used. Assert these types have the same size, else some parts of the
2343  * LinuxKPI may not work like expected:
2344  */
2345 CTASSERT(sizeof(unsigned long) == sizeof(uintptr_t));