xref: /freebsd/sys/compat/linuxkpi/common/src/linux_compat.c (revision 813c5b75e68073a724fdc032b24a12baeab8f6d9)
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-2021 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/refcount.h>
44 #include <sys/lock.h>
45 #include <sys/mutex.h>
46 #include <sys/bus.h>
47 #include <sys/eventhandler.h>
48 #include <sys/fcntl.h>
49 #include <sys/file.h>
50 #include <sys/filio.h>
51 #include <sys/rwlock.h>
52 #include <sys/mman.h>
53 #include <sys/stack.h>
54 #include <sys/sysent.h>
55 #include <sys/time.h>
56 #include <sys/user.h>
57 
58 #include <vm/vm.h>
59 #include <vm/pmap.h>
60 #include <vm/vm_object.h>
61 #include <vm/vm_page.h>
62 #include <vm/vm_pager.h>
63 
64 #include <machine/stdarg.h>
65 
66 #if defined(__i386__) || defined(__amd64__)
67 #include <machine/md_var.h>
68 #endif
69 
70 #include <linux/kobject.h>
71 #include <linux/cpu.h>
72 #include <linux/device.h>
73 #include <linux/slab.h>
74 #include <linux/module.h>
75 #include <linux/moduleparam.h>
76 #include <linux/cdev.h>
77 #include <linux/file.h>
78 #include <linux/sysfs.h>
79 #include <linux/mm.h>
80 #include <linux/io.h>
81 #include <linux/vmalloc.h>
82 #include <linux/netdevice.h>
83 #include <linux/timer.h>
84 #include <linux/interrupt.h>
85 #include <linux/uaccess.h>
86 #include <linux/list.h>
87 #include <linux/kthread.h>
88 #include <linux/kernel.h>
89 #include <linux/compat.h>
90 #include <linux/io-mapping.h>
91 #include <linux/poll.h>
92 #include <linux/smp.h>
93 #include <linux/wait_bit.h>
94 #include <linux/rcupdate.h>
95 #include <linux/interval_tree.h>
96 #include <linux/interval_tree_generic.h>
97 
98 #if defined(__i386__) || defined(__amd64__)
99 #include <asm/smp.h>
100 #include <asm/processor.h>
101 #endif
102 
103 SYSCTL_NODE(_compat, OID_AUTO, linuxkpi, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
104     "LinuxKPI parameters");
105 
106 int linuxkpi_debug;
107 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, debug, CTLFLAG_RWTUN,
108     &linuxkpi_debug, 0, "Set to enable pr_debug() prints. Clear to disable.");
109 
110 int linuxkpi_warn_dump_stack = 0;
111 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, warn_dump_stack, CTLFLAG_RWTUN,
112     &linuxkpi_warn_dump_stack, 0,
113     "Set to enable stack traces from WARN_ON(). Clear to disable.");
114 
115 static struct timeval lkpi_net_lastlog;
116 static int lkpi_net_curpps;
117 static int lkpi_net_maxpps = 99;
118 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, net_ratelimit, CTLFLAG_RWTUN,
119     &lkpi_net_maxpps, 0, "Limit number of LinuxKPI net messages per second.");
120 
121 MALLOC_DEFINE(M_KMALLOC, "lkpikmalloc", "Linux kmalloc compat");
122 
123 #include <linux/rbtree.h>
124 /* Undo Linux compat changes. */
125 #undef RB_ROOT
126 #undef file
127 #undef cdev
128 #define	RB_ROOT(head)	(head)->rbh_root
129 
130 static void linux_destroy_dev(struct linux_cdev *);
131 static void linux_cdev_deref(struct linux_cdev *ldev);
132 static struct vm_area_struct *linux_cdev_handle_find(void *handle);
133 
134 cpumask_t cpu_online_mask;
135 static cpumask_t static_single_cpu_mask[MAXCPU];
136 struct kobject linux_class_root;
137 struct device linux_root_device;
138 struct class linux_class_misc;
139 struct list_head pci_drivers;
140 struct list_head pci_devices;
141 spinlock_t pci_lock;
142 
143 unsigned long linux_timer_hz_mask;
144 
145 wait_queue_head_t linux_bit_waitq;
146 wait_queue_head_t linux_var_waitq;
147 
148 int
149 panic_cmp(struct rb_node *one, struct rb_node *two)
150 {
151 	panic("no cmp");
152 }
153 
154 RB_GENERATE(linux_root, rb_node, __entry, panic_cmp);
155 
156 #define	START(node)	((node)->start)
157 #define	LAST(node)	((node)->last)
158 
159 INTERVAL_TREE_DEFINE(struct interval_tree_node, rb, unsigned long,, START,
160     LAST,, lkpi_interval_tree)
161 
162 struct kobject *
163 kobject_create(void)
164 {
165 	struct kobject *kobj;
166 
167 	kobj = kzalloc(sizeof(*kobj), GFP_KERNEL);
168 	if (kobj == NULL)
169 		return (NULL);
170 	kobject_init(kobj, &linux_kfree_type);
171 
172 	return (kobj);
173 }
174 
175 
176 int
177 kobject_set_name_vargs(struct kobject *kobj, const char *fmt, va_list args)
178 {
179 	va_list tmp_va;
180 	int len;
181 	char *old;
182 	char *name;
183 	char dummy;
184 
185 	old = kobj->name;
186 
187 	if (old && fmt == NULL)
188 		return (0);
189 
190 	/* compute length of string */
191 	va_copy(tmp_va, args);
192 	len = vsnprintf(&dummy, 0, fmt, tmp_va);
193 	va_end(tmp_va);
194 
195 	/* account for zero termination */
196 	len++;
197 
198 	/* check for error */
199 	if (len < 1)
200 		return (-EINVAL);
201 
202 	/* allocate memory for string */
203 	name = kzalloc(len, GFP_KERNEL);
204 	if (name == NULL)
205 		return (-ENOMEM);
206 	vsnprintf(name, len, fmt, args);
207 	kobj->name = name;
208 
209 	/* free old string */
210 	kfree(old);
211 
212 	/* filter new string */
213 	for (; *name != '\0'; name++)
214 		if (*name == '/')
215 			*name = '!';
216 	return (0);
217 }
218 
219 int
220 kobject_set_name(struct kobject *kobj, const char *fmt, ...)
221 {
222 	va_list args;
223 	int error;
224 
225 	va_start(args, fmt);
226 	error = kobject_set_name_vargs(kobj, fmt, args);
227 	va_end(args);
228 
229 	return (error);
230 }
231 
232 static int
233 kobject_add_complete(struct kobject *kobj, struct kobject *parent)
234 {
235 	const struct kobj_type *t;
236 	int error;
237 
238 	kobj->parent = parent;
239 	error = sysfs_create_dir(kobj);
240 	if (error == 0 && kobj->ktype && kobj->ktype->default_attrs) {
241 		struct attribute **attr;
242 		t = kobj->ktype;
243 
244 		for (attr = t->default_attrs; *attr != NULL; attr++) {
245 			error = sysfs_create_file(kobj, *attr);
246 			if (error)
247 				break;
248 		}
249 		if (error)
250 			sysfs_remove_dir(kobj);
251 	}
252 	return (error);
253 }
254 
255 int
256 kobject_add(struct kobject *kobj, struct kobject *parent, const char *fmt, ...)
257 {
258 	va_list args;
259 	int error;
260 
261 	va_start(args, fmt);
262 	error = kobject_set_name_vargs(kobj, fmt, args);
263 	va_end(args);
264 	if (error)
265 		return (error);
266 
267 	return kobject_add_complete(kobj, parent);
268 }
269 
270 void
271 linux_kobject_release(struct kref *kref)
272 {
273 	struct kobject *kobj;
274 	char *name;
275 
276 	kobj = container_of(kref, struct kobject, kref);
277 	sysfs_remove_dir(kobj);
278 	name = kobj->name;
279 	if (kobj->ktype && kobj->ktype->release)
280 		kobj->ktype->release(kobj);
281 	kfree(name);
282 }
283 
284 static void
285 linux_kobject_kfree(struct kobject *kobj)
286 {
287 	kfree(kobj);
288 }
289 
290 static void
291 linux_kobject_kfree_name(struct kobject *kobj)
292 {
293 	if (kobj) {
294 		kfree(kobj->name);
295 	}
296 }
297 
298 const struct kobj_type linux_kfree_type = {
299 	.release = linux_kobject_kfree
300 };
301 
302 static ssize_t
303 lkpi_kobj_attr_show(struct kobject *kobj, struct attribute *attr, char *buf)
304 {
305 	struct kobj_attribute *ka =
306 	    container_of(attr, struct kobj_attribute, attr);
307 
308 	if (ka->show == NULL)
309 		return (-EIO);
310 
311 	return (ka->show(kobj, ka, buf));
312 }
313 
314 static ssize_t
315 lkpi_kobj_attr_store(struct kobject *kobj, struct attribute *attr,
316     const char *buf, size_t count)
317 {
318 	struct kobj_attribute *ka =
319 	    container_of(attr, struct kobj_attribute, attr);
320 
321 	if (ka->store == NULL)
322 		return (-EIO);
323 
324 	return (ka->store(kobj, ka, buf, count));
325 }
326 
327 const struct sysfs_ops kobj_sysfs_ops = {
328 	.show	= lkpi_kobj_attr_show,
329 	.store	= lkpi_kobj_attr_store,
330 };
331 
332 static void
333 linux_device_release(struct device *dev)
334 {
335 	pr_debug("linux_device_release: %s\n", dev_name(dev));
336 	kfree(dev);
337 }
338 
339 static ssize_t
340 linux_class_show(struct kobject *kobj, struct attribute *attr, char *buf)
341 {
342 	struct class_attribute *dattr;
343 	ssize_t error;
344 
345 	dattr = container_of(attr, struct class_attribute, attr);
346 	error = -EIO;
347 	if (dattr->show)
348 		error = dattr->show(container_of(kobj, struct class, kobj),
349 		    dattr, buf);
350 	return (error);
351 }
352 
353 static ssize_t
354 linux_class_store(struct kobject *kobj, struct attribute *attr, const char *buf,
355     size_t count)
356 {
357 	struct class_attribute *dattr;
358 	ssize_t error;
359 
360 	dattr = container_of(attr, struct class_attribute, attr);
361 	error = -EIO;
362 	if (dattr->store)
363 		error = dattr->store(container_of(kobj, struct class, kobj),
364 		    dattr, buf, count);
365 	return (error);
366 }
367 
368 static void
369 linux_class_release(struct kobject *kobj)
370 {
371 	struct class *class;
372 
373 	class = container_of(kobj, struct class, kobj);
374 	if (class->class_release)
375 		class->class_release(class);
376 }
377 
378 static const struct sysfs_ops linux_class_sysfs = {
379 	.show  = linux_class_show,
380 	.store = linux_class_store,
381 };
382 
383 const struct kobj_type linux_class_ktype = {
384 	.release = linux_class_release,
385 	.sysfs_ops = &linux_class_sysfs
386 };
387 
388 static void
389 linux_dev_release(struct kobject *kobj)
390 {
391 	struct device *dev;
392 
393 	dev = container_of(kobj, struct device, kobj);
394 	/* This is the precedence defined by linux. */
395 	if (dev->release)
396 		dev->release(dev);
397 	else if (dev->class && dev->class->dev_release)
398 		dev->class->dev_release(dev);
399 }
400 
401 static ssize_t
402 linux_dev_show(struct kobject *kobj, struct attribute *attr, char *buf)
403 {
404 	struct device_attribute *dattr;
405 	ssize_t error;
406 
407 	dattr = container_of(attr, struct device_attribute, attr);
408 	error = -EIO;
409 	if (dattr->show)
410 		error = dattr->show(container_of(kobj, struct device, kobj),
411 		    dattr, buf);
412 	return (error);
413 }
414 
415 static ssize_t
416 linux_dev_store(struct kobject *kobj, struct attribute *attr, const char *buf,
417     size_t count)
418 {
419 	struct device_attribute *dattr;
420 	ssize_t error;
421 
422 	dattr = container_of(attr, struct device_attribute, attr);
423 	error = -EIO;
424 	if (dattr->store)
425 		error = dattr->store(container_of(kobj, struct device, kobj),
426 		    dattr, buf, count);
427 	return (error);
428 }
429 
430 static const struct sysfs_ops linux_dev_sysfs = {
431 	.show  = linux_dev_show,
432 	.store = linux_dev_store,
433 };
434 
435 const struct kobj_type linux_dev_ktype = {
436 	.release = linux_dev_release,
437 	.sysfs_ops = &linux_dev_sysfs
438 };
439 
440 struct device *
441 device_create(struct class *class, struct device *parent, dev_t devt,
442     void *drvdata, const char *fmt, ...)
443 {
444 	struct device *dev;
445 	va_list args;
446 
447 	dev = kzalloc(sizeof(*dev), M_WAITOK);
448 	dev->parent = parent;
449 	dev->class = class;
450 	dev->devt = devt;
451 	dev->driver_data = drvdata;
452 	dev->release = linux_device_release;
453 	va_start(args, fmt);
454 	kobject_set_name_vargs(&dev->kobj, fmt, args);
455 	va_end(args);
456 	device_register(dev);
457 
458 	return (dev);
459 }
460 
461 struct device *
462 device_create_groups_vargs(struct class *class, struct device *parent,
463     dev_t devt, void *drvdata, const struct attribute_group **groups,
464     const char *fmt, va_list args)
465 {
466 	struct device *dev = NULL;
467 	int retval = -ENODEV;
468 
469 	if (class == NULL || IS_ERR(class))
470 		goto error;
471 
472 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
473 	if (!dev) {
474 		retval = -ENOMEM;
475 		goto error;
476 	}
477 
478 	dev->devt = devt;
479 	dev->class = class;
480 	dev->parent = parent;
481 	dev->groups = groups;
482 	dev->release = device_create_release;
483 	/* device_initialize() needs the class and parent to be set */
484 	device_initialize(dev);
485 	dev_set_drvdata(dev, drvdata);
486 
487 	retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
488 	if (retval)
489 		goto error;
490 
491 	retval = device_add(dev);
492 	if (retval)
493 		goto error;
494 
495 	return dev;
496 
497 error:
498 	put_device(dev);
499 	return ERR_PTR(retval);
500 }
501 
502 struct class *
503 class_create(struct module *owner, const char *name)
504 {
505 	struct class *class;
506 	int error;
507 
508 	class = kzalloc(sizeof(*class), M_WAITOK);
509 	class->owner = owner;
510 	class->name = name;
511 	class->class_release = linux_class_kfree;
512 	error = class_register(class);
513 	if (error) {
514 		kfree(class);
515 		return (NULL);
516 	}
517 
518 	return (class);
519 }
520 
521 int
522 kobject_init_and_add(struct kobject *kobj, const struct kobj_type *ktype,
523     struct kobject *parent, const char *fmt, ...)
524 {
525 	va_list args;
526 	int error;
527 
528 	kobject_init(kobj, ktype);
529 	kobj->ktype = ktype;
530 	kobj->parent = parent;
531 	kobj->name = NULL;
532 
533 	va_start(args, fmt);
534 	error = kobject_set_name_vargs(kobj, fmt, args);
535 	va_end(args);
536 	if (error)
537 		return (error);
538 	return kobject_add_complete(kobj, parent);
539 }
540 
541 static void
542 linux_kq_lock(void *arg)
543 {
544 	spinlock_t *s = arg;
545 
546 	spin_lock(s);
547 }
548 static void
549 linux_kq_unlock(void *arg)
550 {
551 	spinlock_t *s = arg;
552 
553 	spin_unlock(s);
554 }
555 
556 static void
557 linux_kq_assert_lock(void *arg, int what)
558 {
559 #ifdef INVARIANTS
560 	spinlock_t *s = arg;
561 
562 	if (what == LA_LOCKED)
563 		mtx_assert(&s->m, MA_OWNED);
564 	else
565 		mtx_assert(&s->m, MA_NOTOWNED);
566 #endif
567 }
568 
569 static void
570 linux_file_kqfilter_poll(struct linux_file *, int);
571 
572 struct linux_file *
573 linux_file_alloc(void)
574 {
575 	struct linux_file *filp;
576 
577 	filp = kzalloc(sizeof(*filp), GFP_KERNEL);
578 
579 	/* set initial refcount */
580 	filp->f_count = 1;
581 
582 	/* setup fields needed by kqueue support */
583 	spin_lock_init(&filp->f_kqlock);
584 	knlist_init(&filp->f_selinfo.si_note, &filp->f_kqlock,
585 	    linux_kq_lock, linux_kq_unlock, linux_kq_assert_lock);
586 
587 	return (filp);
588 }
589 
590 void
591 linux_file_free(struct linux_file *filp)
592 {
593 	if (filp->_file == NULL) {
594 		if (filp->f_op != NULL && filp->f_op->release != NULL)
595 			filp->f_op->release(filp->f_vnode, filp);
596 		if (filp->f_shmem != NULL)
597 			vm_object_deallocate(filp->f_shmem);
598 		kfree_rcu(filp, rcu);
599 	} else {
600 		/*
601 		 * The close method of the character device or file
602 		 * will free the linux_file structure:
603 		 */
604 		_fdrop(filp->_file, curthread);
605 	}
606 }
607 
608 struct linux_cdev *
609 cdev_alloc(void)
610 {
611 	struct linux_cdev *cdev;
612 
613 	cdev = kzalloc(sizeof(struct linux_cdev), M_WAITOK);
614 	kobject_init(&cdev->kobj, &linux_cdev_ktype);
615 	cdev->refs = 1;
616 	return (cdev);
617 }
618 
619 static int
620 linux_cdev_pager_fault(vm_object_t vm_obj, vm_ooffset_t offset, int prot,
621     vm_page_t *mres)
622 {
623 	struct vm_area_struct *vmap;
624 
625 	vmap = linux_cdev_handle_find(vm_obj->handle);
626 
627 	MPASS(vmap != NULL);
628 	MPASS(vmap->vm_private_data == vm_obj->handle);
629 
630 	if (likely(vmap->vm_ops != NULL && offset < vmap->vm_len)) {
631 		vm_paddr_t paddr = IDX_TO_OFF(vmap->vm_pfn) + offset;
632 		vm_page_t page;
633 
634 		if (((*mres)->flags & PG_FICTITIOUS) != 0) {
635 			/*
636 			 * If the passed in result page is a fake
637 			 * page, update it with the new physical
638 			 * address.
639 			 */
640 			page = *mres;
641 			vm_page_updatefake(page, paddr, vm_obj->memattr);
642 		} else {
643 			/*
644 			 * Replace the passed in "mres" page with our
645 			 * own fake page and free up the all of the
646 			 * original pages.
647 			 */
648 			VM_OBJECT_WUNLOCK(vm_obj);
649 			page = vm_page_getfake(paddr, vm_obj->memattr);
650 			VM_OBJECT_WLOCK(vm_obj);
651 
652 			vm_page_replace(page, vm_obj, (*mres)->pindex, *mres);
653 			*mres = page;
654 		}
655 		vm_page_valid(page);
656 		return (VM_PAGER_OK);
657 	}
658 	return (VM_PAGER_FAIL);
659 }
660 
661 static int
662 linux_cdev_pager_populate(vm_object_t vm_obj, vm_pindex_t pidx, int fault_type,
663     vm_prot_t max_prot, vm_pindex_t *first, vm_pindex_t *last)
664 {
665 	struct vm_area_struct *vmap;
666 	int err;
667 
668 	/* get VM area structure */
669 	vmap = linux_cdev_handle_find(vm_obj->handle);
670 	MPASS(vmap != NULL);
671 	MPASS(vmap->vm_private_data == vm_obj->handle);
672 
673 	VM_OBJECT_WUNLOCK(vm_obj);
674 
675 	linux_set_current(curthread);
676 
677 	down_write(&vmap->vm_mm->mmap_sem);
678 	if (unlikely(vmap->vm_ops == NULL)) {
679 		err = VM_FAULT_SIGBUS;
680 	} else {
681 		struct vm_fault vmf;
682 
683 		/* fill out VM fault structure */
684 		vmf.virtual_address = (void *)(uintptr_t)IDX_TO_OFF(pidx);
685 		vmf.flags = (fault_type & VM_PROT_WRITE) ? FAULT_FLAG_WRITE : 0;
686 		vmf.pgoff = 0;
687 		vmf.page = NULL;
688 		vmf.vma = vmap;
689 
690 		vmap->vm_pfn_count = 0;
691 		vmap->vm_pfn_pcount = &vmap->vm_pfn_count;
692 		vmap->vm_obj = vm_obj;
693 
694 		err = vmap->vm_ops->fault(&vmf);
695 
696 		while (vmap->vm_pfn_count == 0 && err == VM_FAULT_NOPAGE) {
697 			kern_yield(PRI_USER);
698 			err = vmap->vm_ops->fault(&vmf);
699 		}
700 	}
701 
702 	/* translate return code */
703 	switch (err) {
704 	case VM_FAULT_OOM:
705 		err = VM_PAGER_AGAIN;
706 		break;
707 	case VM_FAULT_SIGBUS:
708 		err = VM_PAGER_BAD;
709 		break;
710 	case VM_FAULT_NOPAGE:
711 		/*
712 		 * By contract the fault handler will return having
713 		 * busied all the pages itself. If pidx is already
714 		 * found in the object, it will simply xbusy the first
715 		 * page and return with vm_pfn_count set to 1.
716 		 */
717 		*first = vmap->vm_pfn_first;
718 		*last = *first + vmap->vm_pfn_count - 1;
719 		err = VM_PAGER_OK;
720 		break;
721 	default:
722 		err = VM_PAGER_ERROR;
723 		break;
724 	}
725 	up_write(&vmap->vm_mm->mmap_sem);
726 	VM_OBJECT_WLOCK(vm_obj);
727 	return (err);
728 }
729 
730 static struct rwlock linux_vma_lock;
731 static TAILQ_HEAD(, vm_area_struct) linux_vma_head =
732     TAILQ_HEAD_INITIALIZER(linux_vma_head);
733 
734 static void
735 linux_cdev_handle_free(struct vm_area_struct *vmap)
736 {
737 	/* Drop reference on vm_file */
738 	if (vmap->vm_file != NULL)
739 		fput(vmap->vm_file);
740 
741 	/* Drop reference on mm_struct */
742 	mmput(vmap->vm_mm);
743 
744 	kfree(vmap);
745 }
746 
747 static void
748 linux_cdev_handle_remove(struct vm_area_struct *vmap)
749 {
750 	rw_wlock(&linux_vma_lock);
751 	TAILQ_REMOVE(&linux_vma_head, vmap, vm_entry);
752 	rw_wunlock(&linux_vma_lock);
753 }
754 
755 static struct vm_area_struct *
756 linux_cdev_handle_find(void *handle)
757 {
758 	struct vm_area_struct *vmap;
759 
760 	rw_rlock(&linux_vma_lock);
761 	TAILQ_FOREACH(vmap, &linux_vma_head, vm_entry) {
762 		if (vmap->vm_private_data == handle)
763 			break;
764 	}
765 	rw_runlock(&linux_vma_lock);
766 	return (vmap);
767 }
768 
769 static int
770 linux_cdev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
771 		      vm_ooffset_t foff, struct ucred *cred, u_short *color)
772 {
773 
774 	MPASS(linux_cdev_handle_find(handle) != NULL);
775 	*color = 0;
776 	return (0);
777 }
778 
779 static void
780 linux_cdev_pager_dtor(void *handle)
781 {
782 	const struct vm_operations_struct *vm_ops;
783 	struct vm_area_struct *vmap;
784 
785 	vmap = linux_cdev_handle_find(handle);
786 	MPASS(vmap != NULL);
787 
788 	/*
789 	 * Remove handle before calling close operation to prevent
790 	 * other threads from reusing the handle pointer.
791 	 */
792 	linux_cdev_handle_remove(vmap);
793 
794 	down_write(&vmap->vm_mm->mmap_sem);
795 	vm_ops = vmap->vm_ops;
796 	if (likely(vm_ops != NULL))
797 		vm_ops->close(vmap);
798 	up_write(&vmap->vm_mm->mmap_sem);
799 
800 	linux_cdev_handle_free(vmap);
801 }
802 
803 static struct cdev_pager_ops linux_cdev_pager_ops[2] = {
804   {
805 	/* OBJT_MGTDEVICE */
806 	.cdev_pg_populate	= linux_cdev_pager_populate,
807 	.cdev_pg_ctor	= linux_cdev_pager_ctor,
808 	.cdev_pg_dtor	= linux_cdev_pager_dtor
809   },
810   {
811 	/* OBJT_DEVICE */
812 	.cdev_pg_fault	= linux_cdev_pager_fault,
813 	.cdev_pg_ctor	= linux_cdev_pager_ctor,
814 	.cdev_pg_dtor	= linux_cdev_pager_dtor
815   },
816 };
817 
818 int
819 zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
820     unsigned long size)
821 {
822 	vm_object_t obj;
823 	vm_page_t m;
824 
825 	obj = vma->vm_obj;
826 	if (obj == NULL || (obj->flags & OBJ_UNMANAGED) != 0)
827 		return (-ENOTSUP);
828 	VM_OBJECT_RLOCK(obj);
829 	for (m = vm_page_find_least(obj, OFF_TO_IDX(address));
830 	    m != NULL && m->pindex < OFF_TO_IDX(address + size);
831 	    m = TAILQ_NEXT(m, listq))
832 		pmap_remove_all(m);
833 	VM_OBJECT_RUNLOCK(obj);
834 	return (0);
835 }
836 
837 static struct file_operations dummy_ldev_ops = {
838 	/* XXXKIB */
839 };
840 
841 static struct linux_cdev dummy_ldev = {
842 	.ops = &dummy_ldev_ops,
843 };
844 
845 #define	LDEV_SI_DTR	0x0001
846 #define	LDEV_SI_REF	0x0002
847 
848 static void
849 linux_get_fop(struct linux_file *filp, const struct file_operations **fop,
850     struct linux_cdev **dev)
851 {
852 	struct linux_cdev *ldev;
853 	u_int siref;
854 
855 	ldev = filp->f_cdev;
856 	*fop = filp->f_op;
857 	if (ldev != NULL) {
858 		if (ldev->kobj.ktype == &linux_cdev_static_ktype) {
859 			refcount_acquire(&ldev->refs);
860 		} else {
861 			for (siref = ldev->siref;;) {
862 				if ((siref & LDEV_SI_DTR) != 0) {
863 					ldev = &dummy_ldev;
864 					*fop = ldev->ops;
865 					siref = ldev->siref;
866 					MPASS((ldev->siref & LDEV_SI_DTR) == 0);
867 				} else if (atomic_fcmpset_int(&ldev->siref,
868 				    &siref, siref + LDEV_SI_REF)) {
869 					break;
870 				}
871 			}
872 		}
873 	}
874 	*dev = ldev;
875 }
876 
877 static void
878 linux_drop_fop(struct linux_cdev *ldev)
879 {
880 
881 	if (ldev == NULL)
882 		return;
883 	if (ldev->kobj.ktype == &linux_cdev_static_ktype) {
884 		linux_cdev_deref(ldev);
885 	} else {
886 		MPASS(ldev->kobj.ktype == &linux_cdev_ktype);
887 		MPASS((ldev->siref & ~LDEV_SI_DTR) != 0);
888 		atomic_subtract_int(&ldev->siref, LDEV_SI_REF);
889 	}
890 }
891 
892 #define	OPW(fp,td,code) ({			\
893 	struct file *__fpop;			\
894 	__typeof(code) __retval;		\
895 						\
896 	__fpop = (td)->td_fpop;			\
897 	(td)->td_fpop = (fp);			\
898 	__retval = (code);			\
899 	(td)->td_fpop = __fpop;			\
900 	__retval;				\
901 })
902 
903 static int
904 linux_dev_fdopen(struct cdev *dev, int fflags, struct thread *td,
905     struct file *file)
906 {
907 	struct linux_cdev *ldev;
908 	struct linux_file *filp;
909 	const struct file_operations *fop;
910 	int error;
911 
912 	ldev = dev->si_drv1;
913 
914 	filp = linux_file_alloc();
915 	filp->f_dentry = &filp->f_dentry_store;
916 	filp->f_op = ldev->ops;
917 	filp->f_mode = file->f_flag;
918 	filp->f_flags = file->f_flag;
919 	filp->f_vnode = file->f_vnode;
920 	filp->_file = file;
921 	refcount_acquire(&ldev->refs);
922 	filp->f_cdev = ldev;
923 
924 	linux_set_current(td);
925 	linux_get_fop(filp, &fop, &ldev);
926 
927 	if (fop->open != NULL) {
928 		error = -fop->open(file->f_vnode, filp);
929 		if (error != 0) {
930 			linux_drop_fop(ldev);
931 			linux_cdev_deref(filp->f_cdev);
932 			kfree(filp);
933 			return (error);
934 		}
935 	}
936 
937 	/* hold on to the vnode - used for fstat() */
938 	vhold(filp->f_vnode);
939 
940 	/* release the file from devfs */
941 	finit(file, filp->f_mode, DTYPE_DEV, filp, &linuxfileops);
942 	linux_drop_fop(ldev);
943 	return (ENXIO);
944 }
945 
946 #define	LINUX_IOCTL_MIN_PTR 0x10000UL
947 #define	LINUX_IOCTL_MAX_PTR (LINUX_IOCTL_MIN_PTR + IOCPARM_MAX)
948 
949 static inline int
950 linux_remap_address(void **uaddr, size_t len)
951 {
952 	uintptr_t uaddr_val = (uintptr_t)(*uaddr);
953 
954 	if (unlikely(uaddr_val >= LINUX_IOCTL_MIN_PTR &&
955 	    uaddr_val < LINUX_IOCTL_MAX_PTR)) {
956 		struct task_struct *pts = current;
957 		if (pts == NULL) {
958 			*uaddr = NULL;
959 			return (1);
960 		}
961 
962 		/* compute data offset */
963 		uaddr_val -= LINUX_IOCTL_MIN_PTR;
964 
965 		/* check that length is within bounds */
966 		if ((len > IOCPARM_MAX) ||
967 		    (uaddr_val + len) > pts->bsd_ioctl_len) {
968 			*uaddr = NULL;
969 			return (1);
970 		}
971 
972 		/* re-add kernel buffer address */
973 		uaddr_val += (uintptr_t)pts->bsd_ioctl_data;
974 
975 		/* update address location */
976 		*uaddr = (void *)uaddr_val;
977 		return (1);
978 	}
979 	return (0);
980 }
981 
982 int
983 linux_copyin(const void *uaddr, void *kaddr, size_t len)
984 {
985 	if (linux_remap_address(__DECONST(void **, &uaddr), len)) {
986 		if (uaddr == NULL)
987 			return (-EFAULT);
988 		memcpy(kaddr, uaddr, len);
989 		return (0);
990 	}
991 	return (-copyin(uaddr, kaddr, len));
992 }
993 
994 int
995 linux_copyout(const void *kaddr, void *uaddr, size_t len)
996 {
997 	if (linux_remap_address(&uaddr, len)) {
998 		if (uaddr == NULL)
999 			return (-EFAULT);
1000 		memcpy(uaddr, kaddr, len);
1001 		return (0);
1002 	}
1003 	return (-copyout(kaddr, uaddr, len));
1004 }
1005 
1006 size_t
1007 linux_clear_user(void *_uaddr, size_t _len)
1008 {
1009 	uint8_t *uaddr = _uaddr;
1010 	size_t len = _len;
1011 
1012 	/* make sure uaddr is aligned before going into the fast loop */
1013 	while (((uintptr_t)uaddr & 7) != 0 && len > 7) {
1014 		if (subyte(uaddr, 0))
1015 			return (_len);
1016 		uaddr++;
1017 		len--;
1018 	}
1019 
1020 	/* zero 8 bytes at a time */
1021 	while (len > 7) {
1022 #ifdef __LP64__
1023 		if (suword64(uaddr, 0))
1024 			return (_len);
1025 #else
1026 		if (suword32(uaddr, 0))
1027 			return (_len);
1028 		if (suword32(uaddr + 4, 0))
1029 			return (_len);
1030 #endif
1031 		uaddr += 8;
1032 		len -= 8;
1033 	}
1034 
1035 	/* zero fill end, if any */
1036 	while (len > 0) {
1037 		if (subyte(uaddr, 0))
1038 			return (_len);
1039 		uaddr++;
1040 		len--;
1041 	}
1042 	return (0);
1043 }
1044 
1045 int
1046 linux_access_ok(const void *uaddr, size_t len)
1047 {
1048 	uintptr_t saddr;
1049 	uintptr_t eaddr;
1050 
1051 	/* get start and end address */
1052 	saddr = (uintptr_t)uaddr;
1053 	eaddr = (uintptr_t)uaddr + len;
1054 
1055 	/* verify addresses are valid for userspace */
1056 	return ((saddr == eaddr) ||
1057 	    (eaddr > saddr && eaddr <= VM_MAXUSER_ADDRESS));
1058 }
1059 
1060 /*
1061  * This function should return either EINTR or ERESTART depending on
1062  * the signal type sent to this thread:
1063  */
1064 static int
1065 linux_get_error(struct task_struct *task, int error)
1066 {
1067 	/* check for signal type interrupt code */
1068 	if (error == EINTR || error == ERESTARTSYS || error == ERESTART) {
1069 		error = -linux_schedule_get_interrupt_value(task);
1070 		if (error == 0)
1071 			error = EINTR;
1072 	}
1073 	return (error);
1074 }
1075 
1076 static int
1077 linux_file_ioctl_sub(struct file *fp, struct linux_file *filp,
1078     const struct file_operations *fop, u_long cmd, caddr_t data,
1079     struct thread *td)
1080 {
1081 	struct task_struct *task = current;
1082 	unsigned size;
1083 	int error;
1084 
1085 	size = IOCPARM_LEN(cmd);
1086 	/* refer to logic in sys_ioctl() */
1087 	if (size > 0) {
1088 		/*
1089 		 * Setup hint for linux_copyin() and linux_copyout().
1090 		 *
1091 		 * Background: Linux code expects a user-space address
1092 		 * while FreeBSD supplies a kernel-space address.
1093 		 */
1094 		task->bsd_ioctl_data = data;
1095 		task->bsd_ioctl_len = size;
1096 		data = (void *)LINUX_IOCTL_MIN_PTR;
1097 	} else {
1098 		/* fetch user-space pointer */
1099 		data = *(void **)data;
1100 	}
1101 #ifdef COMPAT_FREEBSD32
1102 	if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
1103 		/* try the compat IOCTL handler first */
1104 		if (fop->compat_ioctl != NULL) {
1105 			error = -OPW(fp, td, fop->compat_ioctl(filp,
1106 			    cmd, (u_long)data));
1107 		} else {
1108 			error = ENOTTY;
1109 		}
1110 
1111 		/* fallback to the regular IOCTL handler, if any */
1112 		if (error == ENOTTY && fop->unlocked_ioctl != NULL) {
1113 			error = -OPW(fp, td, fop->unlocked_ioctl(filp,
1114 			    cmd, (u_long)data));
1115 		}
1116 	} else
1117 #endif
1118 	{
1119 		if (fop->unlocked_ioctl != NULL) {
1120 			error = -OPW(fp, td, fop->unlocked_ioctl(filp,
1121 			    cmd, (u_long)data));
1122 		} else {
1123 			error = ENOTTY;
1124 		}
1125 	}
1126 	if (size > 0) {
1127 		task->bsd_ioctl_data = NULL;
1128 		task->bsd_ioctl_len = 0;
1129 	}
1130 
1131 	if (error == EWOULDBLOCK) {
1132 		/* update kqfilter status, if any */
1133 		linux_file_kqfilter_poll(filp,
1134 		    LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
1135 	} else {
1136 		error = linux_get_error(task, error);
1137 	}
1138 	return (error);
1139 }
1140 
1141 #define	LINUX_POLL_TABLE_NORMAL ((poll_table *)1)
1142 
1143 /*
1144  * This function atomically updates the poll wakeup state and returns
1145  * the previous state at the time of update.
1146  */
1147 static uint8_t
1148 linux_poll_wakeup_state(atomic_t *v, const uint8_t *pstate)
1149 {
1150 	int c, old;
1151 
1152 	c = v->counter;
1153 
1154 	while ((old = atomic_cmpxchg(v, c, pstate[c])) != c)
1155 		c = old;
1156 
1157 	return (c);
1158 }
1159 
1160 static int
1161 linux_poll_wakeup_callback(wait_queue_t *wq, unsigned int wq_state, int flags, void *key)
1162 {
1163 	static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1164 		[LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_INIT, /* NOP */
1165 		[LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_NOT_READY, /* NOP */
1166 		[LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_READY,
1167 		[LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_READY, /* NOP */
1168 	};
1169 	struct linux_file *filp = container_of(wq, struct linux_file, f_wait_queue.wq);
1170 
1171 	switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1172 	case LINUX_FWQ_STATE_QUEUED:
1173 		linux_poll_wakeup(filp);
1174 		return (1);
1175 	default:
1176 		return (0);
1177 	}
1178 }
1179 
1180 void
1181 linux_poll_wait(struct linux_file *filp, wait_queue_head_t *wqh, poll_table *p)
1182 {
1183 	static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1184 		[LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_NOT_READY,
1185 		[LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_NOT_READY, /* NOP */
1186 		[LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_QUEUED, /* NOP */
1187 		[LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_QUEUED,
1188 	};
1189 
1190 	/* check if we are called inside the select system call */
1191 	if (p == LINUX_POLL_TABLE_NORMAL)
1192 		selrecord(curthread, &filp->f_selinfo);
1193 
1194 	switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1195 	case LINUX_FWQ_STATE_INIT:
1196 		/* NOTE: file handles can only belong to one wait-queue */
1197 		filp->f_wait_queue.wqh = wqh;
1198 		filp->f_wait_queue.wq.func = &linux_poll_wakeup_callback;
1199 		add_wait_queue(wqh, &filp->f_wait_queue.wq);
1200 		atomic_set(&filp->f_wait_queue.state, LINUX_FWQ_STATE_QUEUED);
1201 		break;
1202 	default:
1203 		break;
1204 	}
1205 }
1206 
1207 static void
1208 linux_poll_wait_dequeue(struct linux_file *filp)
1209 {
1210 	static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1211 		[LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_INIT,	/* NOP */
1212 		[LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_INIT,
1213 		[LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_INIT,
1214 		[LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_INIT,
1215 	};
1216 
1217 	seldrain(&filp->f_selinfo);
1218 
1219 	switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1220 	case LINUX_FWQ_STATE_NOT_READY:
1221 	case LINUX_FWQ_STATE_QUEUED:
1222 	case LINUX_FWQ_STATE_READY:
1223 		remove_wait_queue(filp->f_wait_queue.wqh, &filp->f_wait_queue.wq);
1224 		break;
1225 	default:
1226 		break;
1227 	}
1228 }
1229 
1230 void
1231 linux_poll_wakeup(struct linux_file *filp)
1232 {
1233 	/* this function should be NULL-safe */
1234 	if (filp == NULL)
1235 		return;
1236 
1237 	selwakeup(&filp->f_selinfo);
1238 
1239 	spin_lock(&filp->f_kqlock);
1240 	filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ |
1241 	    LINUX_KQ_FLAG_NEED_WRITE;
1242 
1243 	/* make sure the "knote" gets woken up */
1244 	KNOTE_LOCKED(&filp->f_selinfo.si_note, 1);
1245 	spin_unlock(&filp->f_kqlock);
1246 }
1247 
1248 static void
1249 linux_file_kqfilter_detach(struct knote *kn)
1250 {
1251 	struct linux_file *filp = kn->kn_hook;
1252 
1253 	spin_lock(&filp->f_kqlock);
1254 	knlist_remove(&filp->f_selinfo.si_note, kn, 1);
1255 	spin_unlock(&filp->f_kqlock);
1256 }
1257 
1258 static int
1259 linux_file_kqfilter_read_event(struct knote *kn, long hint)
1260 {
1261 	struct linux_file *filp = kn->kn_hook;
1262 
1263 	mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1264 
1265 	return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_READ) ? 1 : 0);
1266 }
1267 
1268 static int
1269 linux_file_kqfilter_write_event(struct knote *kn, long hint)
1270 {
1271 	struct linux_file *filp = kn->kn_hook;
1272 
1273 	mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1274 
1275 	return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_WRITE) ? 1 : 0);
1276 }
1277 
1278 static struct filterops linux_dev_kqfiltops_read = {
1279 	.f_isfd = 1,
1280 	.f_detach = linux_file_kqfilter_detach,
1281 	.f_event = linux_file_kqfilter_read_event,
1282 };
1283 
1284 static struct filterops linux_dev_kqfiltops_write = {
1285 	.f_isfd = 1,
1286 	.f_detach = linux_file_kqfilter_detach,
1287 	.f_event = linux_file_kqfilter_write_event,
1288 };
1289 
1290 static void
1291 linux_file_kqfilter_poll(struct linux_file *filp, int kqflags)
1292 {
1293 	struct thread *td;
1294 	const struct file_operations *fop;
1295 	struct linux_cdev *ldev;
1296 	int temp;
1297 
1298 	if ((filp->f_kqflags & kqflags) == 0)
1299 		return;
1300 
1301 	td = curthread;
1302 
1303 	linux_get_fop(filp, &fop, &ldev);
1304 	/* get the latest polling state */
1305 	temp = OPW(filp->_file, td, fop->poll(filp, NULL));
1306 	linux_drop_fop(ldev);
1307 
1308 	spin_lock(&filp->f_kqlock);
1309 	/* clear kqflags */
1310 	filp->f_kqflags &= ~(LINUX_KQ_FLAG_NEED_READ |
1311 	    LINUX_KQ_FLAG_NEED_WRITE);
1312 	/* update kqflags */
1313 	if ((temp & (POLLIN | POLLOUT)) != 0) {
1314 		if ((temp & POLLIN) != 0)
1315 			filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ;
1316 		if ((temp & POLLOUT) != 0)
1317 			filp->f_kqflags |= LINUX_KQ_FLAG_NEED_WRITE;
1318 
1319 		/* make sure the "knote" gets woken up */
1320 		KNOTE_LOCKED(&filp->f_selinfo.si_note, 0);
1321 	}
1322 	spin_unlock(&filp->f_kqlock);
1323 }
1324 
1325 static int
1326 linux_file_kqfilter(struct file *file, struct knote *kn)
1327 {
1328 	struct linux_file *filp;
1329 	struct thread *td;
1330 	int error;
1331 
1332 	td = curthread;
1333 	filp = (struct linux_file *)file->f_data;
1334 	filp->f_flags = file->f_flag;
1335 	if (filp->f_op->poll == NULL)
1336 		return (EINVAL);
1337 
1338 	spin_lock(&filp->f_kqlock);
1339 	switch (kn->kn_filter) {
1340 	case EVFILT_READ:
1341 		filp->f_kqflags |= LINUX_KQ_FLAG_HAS_READ;
1342 		kn->kn_fop = &linux_dev_kqfiltops_read;
1343 		kn->kn_hook = filp;
1344 		knlist_add(&filp->f_selinfo.si_note, kn, 1);
1345 		error = 0;
1346 		break;
1347 	case EVFILT_WRITE:
1348 		filp->f_kqflags |= LINUX_KQ_FLAG_HAS_WRITE;
1349 		kn->kn_fop = &linux_dev_kqfiltops_write;
1350 		kn->kn_hook = filp;
1351 		knlist_add(&filp->f_selinfo.si_note, kn, 1);
1352 		error = 0;
1353 		break;
1354 	default:
1355 		error = EINVAL;
1356 		break;
1357 	}
1358 	spin_unlock(&filp->f_kqlock);
1359 
1360 	if (error == 0) {
1361 		linux_set_current(td);
1362 
1363 		/* update kqfilter status, if any */
1364 		linux_file_kqfilter_poll(filp,
1365 		    LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
1366 	}
1367 	return (error);
1368 }
1369 
1370 static int
1371 linux_file_mmap_single(struct file *fp, const struct file_operations *fop,
1372     vm_ooffset_t *offset, vm_size_t size, struct vm_object **object,
1373     int nprot, bool is_shared, struct thread *td)
1374 {
1375 	struct task_struct *task;
1376 	struct vm_area_struct *vmap;
1377 	struct mm_struct *mm;
1378 	struct linux_file *filp;
1379 	vm_memattr_t attr;
1380 	int error;
1381 
1382 	filp = (struct linux_file *)fp->f_data;
1383 	filp->f_flags = fp->f_flag;
1384 
1385 	if (fop->mmap == NULL)
1386 		return (EOPNOTSUPP);
1387 
1388 	linux_set_current(td);
1389 
1390 	/*
1391 	 * The same VM object might be shared by multiple processes
1392 	 * and the mm_struct is usually freed when a process exits.
1393 	 *
1394 	 * The atomic reference below makes sure the mm_struct is
1395 	 * available as long as the vmap is in the linux_vma_head.
1396 	 */
1397 	task = current;
1398 	mm = task->mm;
1399 	if (atomic_inc_not_zero(&mm->mm_users) == 0)
1400 		return (EINVAL);
1401 
1402 	vmap = kzalloc(sizeof(*vmap), GFP_KERNEL);
1403 	vmap->vm_start = 0;
1404 	vmap->vm_end = size;
1405 	vmap->vm_pgoff = *offset / PAGE_SIZE;
1406 	vmap->vm_pfn = 0;
1407 	vmap->vm_flags = vmap->vm_page_prot = (nprot & VM_PROT_ALL);
1408 	if (is_shared)
1409 		vmap->vm_flags |= VM_SHARED;
1410 	vmap->vm_ops = NULL;
1411 	vmap->vm_file = get_file(filp);
1412 	vmap->vm_mm = mm;
1413 
1414 	if (unlikely(down_write_killable(&vmap->vm_mm->mmap_sem))) {
1415 		error = linux_get_error(task, EINTR);
1416 	} else {
1417 		error = -OPW(fp, td, fop->mmap(filp, vmap));
1418 		error = linux_get_error(task, error);
1419 		up_write(&vmap->vm_mm->mmap_sem);
1420 	}
1421 
1422 	if (error != 0) {
1423 		linux_cdev_handle_free(vmap);
1424 		return (error);
1425 	}
1426 
1427 	attr = pgprot2cachemode(vmap->vm_page_prot);
1428 
1429 	if (vmap->vm_ops != NULL) {
1430 		struct vm_area_struct *ptr;
1431 		void *vm_private_data;
1432 		bool vm_no_fault;
1433 
1434 		if (vmap->vm_ops->open == NULL ||
1435 		    vmap->vm_ops->close == NULL ||
1436 		    vmap->vm_private_data == NULL) {
1437 			/* free allocated VM area struct */
1438 			linux_cdev_handle_free(vmap);
1439 			return (EINVAL);
1440 		}
1441 
1442 		vm_private_data = vmap->vm_private_data;
1443 
1444 		rw_wlock(&linux_vma_lock);
1445 		TAILQ_FOREACH(ptr, &linux_vma_head, vm_entry) {
1446 			if (ptr->vm_private_data == vm_private_data)
1447 				break;
1448 		}
1449 		/* check if there is an existing VM area struct */
1450 		if (ptr != NULL) {
1451 			/* check if the VM area structure is invalid */
1452 			if (ptr->vm_ops == NULL ||
1453 			    ptr->vm_ops->open == NULL ||
1454 			    ptr->vm_ops->close == NULL) {
1455 				error = ESTALE;
1456 				vm_no_fault = 1;
1457 			} else {
1458 				error = EEXIST;
1459 				vm_no_fault = (ptr->vm_ops->fault == NULL);
1460 			}
1461 		} else {
1462 			/* insert VM area structure into list */
1463 			TAILQ_INSERT_TAIL(&linux_vma_head, vmap, vm_entry);
1464 			error = 0;
1465 			vm_no_fault = (vmap->vm_ops->fault == NULL);
1466 		}
1467 		rw_wunlock(&linux_vma_lock);
1468 
1469 		if (error != 0) {
1470 			/* free allocated VM area struct */
1471 			linux_cdev_handle_free(vmap);
1472 			/* check for stale VM area struct */
1473 			if (error != EEXIST)
1474 				return (error);
1475 		}
1476 
1477 		/* check if there is no fault handler */
1478 		if (vm_no_fault) {
1479 			*object = cdev_pager_allocate(vm_private_data, OBJT_DEVICE,
1480 			    &linux_cdev_pager_ops[1], size, nprot, *offset,
1481 			    td->td_ucred);
1482 		} else {
1483 			*object = cdev_pager_allocate(vm_private_data, OBJT_MGTDEVICE,
1484 			    &linux_cdev_pager_ops[0], size, nprot, *offset,
1485 			    td->td_ucred);
1486 		}
1487 
1488 		/* check if allocating the VM object failed */
1489 		if (*object == NULL) {
1490 			if (error == 0) {
1491 				/* remove VM area struct from list */
1492 				linux_cdev_handle_remove(vmap);
1493 				/* free allocated VM area struct */
1494 				linux_cdev_handle_free(vmap);
1495 			}
1496 			return (EINVAL);
1497 		}
1498 	} else {
1499 		struct sglist *sg;
1500 
1501 		sg = sglist_alloc(1, M_WAITOK);
1502 		sglist_append_phys(sg,
1503 		    (vm_paddr_t)vmap->vm_pfn << PAGE_SHIFT, vmap->vm_len);
1504 
1505 		*object = vm_pager_allocate(OBJT_SG, sg, vmap->vm_len,
1506 		    nprot, 0, td->td_ucred);
1507 
1508 		linux_cdev_handle_free(vmap);
1509 
1510 		if (*object == NULL) {
1511 			sglist_free(sg);
1512 			return (EINVAL);
1513 		}
1514 	}
1515 
1516 	if (attr != VM_MEMATTR_DEFAULT) {
1517 		VM_OBJECT_WLOCK(*object);
1518 		vm_object_set_memattr(*object, attr);
1519 		VM_OBJECT_WUNLOCK(*object);
1520 	}
1521 	*offset = 0;
1522 	return (0);
1523 }
1524 
1525 struct cdevsw linuxcdevsw = {
1526 	.d_version = D_VERSION,
1527 	.d_fdopen = linux_dev_fdopen,
1528 	.d_name = "lkpidev",
1529 };
1530 
1531 static int
1532 linux_file_read(struct file *file, struct uio *uio, struct ucred *active_cred,
1533     int flags, struct thread *td)
1534 {
1535 	struct linux_file *filp;
1536 	const struct file_operations *fop;
1537 	struct linux_cdev *ldev;
1538 	ssize_t bytes;
1539 	int error;
1540 
1541 	error = 0;
1542 	filp = (struct linux_file *)file->f_data;
1543 	filp->f_flags = file->f_flag;
1544 	/* XXX no support for I/O vectors currently */
1545 	if (uio->uio_iovcnt != 1)
1546 		return (EOPNOTSUPP);
1547 	if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1548 		return (EINVAL);
1549 	linux_set_current(td);
1550 	linux_get_fop(filp, &fop, &ldev);
1551 	if (fop->read != NULL) {
1552 		bytes = OPW(file, td, fop->read(filp,
1553 		    uio->uio_iov->iov_base,
1554 		    uio->uio_iov->iov_len, &uio->uio_offset));
1555 		if (bytes >= 0) {
1556 			uio->uio_iov->iov_base =
1557 			    ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1558 			uio->uio_iov->iov_len -= bytes;
1559 			uio->uio_resid -= bytes;
1560 		} else {
1561 			error = linux_get_error(current, -bytes);
1562 		}
1563 	} else
1564 		error = ENXIO;
1565 
1566 	/* update kqfilter status, if any */
1567 	linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_READ);
1568 	linux_drop_fop(ldev);
1569 
1570 	return (error);
1571 }
1572 
1573 static int
1574 linux_file_write(struct file *file, struct uio *uio, struct ucred *active_cred,
1575     int flags, struct thread *td)
1576 {
1577 	struct linux_file *filp;
1578 	const struct file_operations *fop;
1579 	struct linux_cdev *ldev;
1580 	ssize_t bytes;
1581 	int error;
1582 
1583 	filp = (struct linux_file *)file->f_data;
1584 	filp->f_flags = file->f_flag;
1585 	/* XXX no support for I/O vectors currently */
1586 	if (uio->uio_iovcnt != 1)
1587 		return (EOPNOTSUPP);
1588 	if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1589 		return (EINVAL);
1590 	linux_set_current(td);
1591 	linux_get_fop(filp, &fop, &ldev);
1592 	if (fop->write != NULL) {
1593 		bytes = OPW(file, td, fop->write(filp,
1594 		    uio->uio_iov->iov_base,
1595 		    uio->uio_iov->iov_len, &uio->uio_offset));
1596 		if (bytes >= 0) {
1597 			uio->uio_iov->iov_base =
1598 			    ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1599 			uio->uio_iov->iov_len -= bytes;
1600 			uio->uio_resid -= bytes;
1601 			error = 0;
1602 		} else {
1603 			error = linux_get_error(current, -bytes);
1604 		}
1605 	} else
1606 		error = ENXIO;
1607 
1608 	/* update kqfilter status, if any */
1609 	linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_WRITE);
1610 
1611 	linux_drop_fop(ldev);
1612 
1613 	return (error);
1614 }
1615 
1616 static int
1617 linux_file_poll(struct file *file, int events, struct ucred *active_cred,
1618     struct thread *td)
1619 {
1620 	struct linux_file *filp;
1621 	const struct file_operations *fop;
1622 	struct linux_cdev *ldev;
1623 	int revents;
1624 
1625 	filp = (struct linux_file *)file->f_data;
1626 	filp->f_flags = file->f_flag;
1627 	linux_set_current(td);
1628 	linux_get_fop(filp, &fop, &ldev);
1629 	if (fop->poll != NULL) {
1630 		revents = OPW(file, td, fop->poll(filp,
1631 		    LINUX_POLL_TABLE_NORMAL)) & events;
1632 	} else {
1633 		revents = 0;
1634 	}
1635 	linux_drop_fop(ldev);
1636 	return (revents);
1637 }
1638 
1639 static int
1640 linux_file_close(struct file *file, struct thread *td)
1641 {
1642 	struct linux_file *filp;
1643 	int (*release)(struct inode *, struct linux_file *);
1644 	const struct file_operations *fop;
1645 	struct linux_cdev *ldev;
1646 	int error;
1647 
1648 	filp = (struct linux_file *)file->f_data;
1649 
1650 	KASSERT(file_count(filp) == 0,
1651 	    ("File refcount(%d) is not zero", file_count(filp)));
1652 
1653 	if (td == NULL)
1654 		td = curthread;
1655 
1656 	error = 0;
1657 	filp->f_flags = file->f_flag;
1658 	linux_set_current(td);
1659 	linux_poll_wait_dequeue(filp);
1660 	linux_get_fop(filp, &fop, &ldev);
1661 	/*
1662 	 * Always use the real release function, if any, to avoid
1663 	 * leaking device resources:
1664 	 */
1665 	release = filp->f_op->release;
1666 	if (release != NULL)
1667 		error = -OPW(file, td, release(filp->f_vnode, filp));
1668 	funsetown(&filp->f_sigio);
1669 	if (filp->f_vnode != NULL)
1670 		vdrop(filp->f_vnode);
1671 	linux_drop_fop(ldev);
1672 	ldev = filp->f_cdev;
1673 	if (ldev != NULL)
1674 		linux_cdev_deref(ldev);
1675 	linux_synchronize_rcu(RCU_TYPE_REGULAR);
1676 	kfree(filp);
1677 
1678 	return (error);
1679 }
1680 
1681 static int
1682 linux_file_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *cred,
1683     struct thread *td)
1684 {
1685 	struct linux_file *filp;
1686 	const struct file_operations *fop;
1687 	struct linux_cdev *ldev;
1688 	struct fiodgname_arg *fgn;
1689 	const char *p;
1690 	int error, i;
1691 
1692 	error = 0;
1693 	filp = (struct linux_file *)fp->f_data;
1694 	filp->f_flags = fp->f_flag;
1695 	linux_get_fop(filp, &fop, &ldev);
1696 
1697 	linux_set_current(td);
1698 	switch (cmd) {
1699 	case FIONBIO:
1700 		break;
1701 	case FIOASYNC:
1702 		if (fop->fasync == NULL)
1703 			break;
1704 		error = -OPW(fp, td, fop->fasync(0, filp, fp->f_flag & FASYNC));
1705 		break;
1706 	case FIOSETOWN:
1707 		error = fsetown(*(int *)data, &filp->f_sigio);
1708 		if (error == 0) {
1709 			if (fop->fasync == NULL)
1710 				break;
1711 			error = -OPW(fp, td, fop->fasync(0, filp,
1712 			    fp->f_flag & FASYNC));
1713 		}
1714 		break;
1715 	case FIOGETOWN:
1716 		*(int *)data = fgetown(&filp->f_sigio);
1717 		break;
1718 	case FIODGNAME:
1719 #ifdef	COMPAT_FREEBSD32
1720 	case FIODGNAME_32:
1721 #endif
1722 		if (filp->f_cdev == NULL || filp->f_cdev->cdev == NULL) {
1723 			error = ENXIO;
1724 			break;
1725 		}
1726 		fgn = data;
1727 		p = devtoname(filp->f_cdev->cdev);
1728 		i = strlen(p) + 1;
1729 		if (i > fgn->len) {
1730 			error = EINVAL;
1731 			break;
1732 		}
1733 		error = copyout(p, fiodgname_buf_get_ptr(fgn, cmd), i);
1734 		break;
1735 	default:
1736 		error = linux_file_ioctl_sub(fp, filp, fop, cmd, data, td);
1737 		break;
1738 	}
1739 	linux_drop_fop(ldev);
1740 	return (error);
1741 }
1742 
1743 static int
1744 linux_file_mmap_sub(struct thread *td, vm_size_t objsize, vm_prot_t prot,
1745     vm_prot_t maxprot, int flags, struct file *fp,
1746     vm_ooffset_t *foff, const struct file_operations *fop, vm_object_t *objp)
1747 {
1748 	/*
1749 	 * Character devices do not provide private mappings
1750 	 * of any kind:
1751 	 */
1752 	if ((maxprot & VM_PROT_WRITE) == 0 &&
1753 	    (prot & VM_PROT_WRITE) != 0)
1754 		return (EACCES);
1755 	if ((flags & (MAP_PRIVATE | MAP_COPY)) != 0)
1756 		return (EINVAL);
1757 
1758 	return (linux_file_mmap_single(fp, fop, foff, objsize, objp,
1759 	    (int)prot, (flags & MAP_SHARED) ? true : false, td));
1760 }
1761 
1762 static int
1763 linux_file_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
1764     vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
1765     struct thread *td)
1766 {
1767 	struct linux_file *filp;
1768 	const struct file_operations *fop;
1769 	struct linux_cdev *ldev;
1770 	struct mount *mp;
1771 	struct vnode *vp;
1772 	vm_object_t object;
1773 	vm_prot_t maxprot;
1774 	int error;
1775 
1776 	filp = (struct linux_file *)fp->f_data;
1777 
1778 	vp = filp->f_vnode;
1779 	if (vp == NULL)
1780 		return (EOPNOTSUPP);
1781 
1782 	/*
1783 	 * Ensure that file and memory protections are
1784 	 * compatible.
1785 	 */
1786 	mp = vp->v_mount;
1787 	if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
1788 		maxprot = VM_PROT_NONE;
1789 		if ((prot & VM_PROT_EXECUTE) != 0)
1790 			return (EACCES);
1791 	} else
1792 		maxprot = VM_PROT_EXECUTE;
1793 	if ((fp->f_flag & FREAD) != 0)
1794 		maxprot |= VM_PROT_READ;
1795 	else if ((prot & VM_PROT_READ) != 0)
1796 		return (EACCES);
1797 
1798 	/*
1799 	 * If we are sharing potential changes via MAP_SHARED and we
1800 	 * are trying to get write permission although we opened it
1801 	 * without asking for it, bail out.
1802 	 *
1803 	 * Note that most character devices always share mappings.
1804 	 *
1805 	 * Rely on linux_file_mmap_sub() to fail invalid MAP_PRIVATE
1806 	 * requests rather than doing it here.
1807 	 */
1808 	if ((flags & MAP_SHARED) != 0) {
1809 		if ((fp->f_flag & FWRITE) != 0)
1810 			maxprot |= VM_PROT_WRITE;
1811 		else if ((prot & VM_PROT_WRITE) != 0)
1812 			return (EACCES);
1813 	}
1814 	maxprot &= cap_maxprot;
1815 
1816 	linux_get_fop(filp, &fop, &ldev);
1817 	error = linux_file_mmap_sub(td, size, prot, maxprot, flags, fp,
1818 	    &foff, fop, &object);
1819 	if (error != 0)
1820 		goto out;
1821 
1822 	error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
1823 	    foff, FALSE, td);
1824 	if (error != 0)
1825 		vm_object_deallocate(object);
1826 out:
1827 	linux_drop_fop(ldev);
1828 	return (error);
1829 }
1830 
1831 static int
1832 linux_file_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
1833 {
1834 	struct linux_file *filp;
1835 	struct vnode *vp;
1836 	int error;
1837 
1838 	filp = (struct linux_file *)fp->f_data;
1839 	if (filp->f_vnode == NULL)
1840 		return (EOPNOTSUPP);
1841 
1842 	vp = filp->f_vnode;
1843 
1844 	vn_lock(vp, LK_SHARED | LK_RETRY);
1845 	error = VOP_STAT(vp, sb, curthread->td_ucred, NOCRED);
1846 	VOP_UNLOCK(vp);
1847 
1848 	return (error);
1849 }
1850 
1851 static int
1852 linux_file_fill_kinfo(struct file *fp, struct kinfo_file *kif,
1853     struct filedesc *fdp)
1854 {
1855 	struct linux_file *filp;
1856 	struct vnode *vp;
1857 	int error;
1858 
1859 	filp = fp->f_data;
1860 	vp = filp->f_vnode;
1861 	if (vp == NULL) {
1862 		error = 0;
1863 		kif->kf_type = KF_TYPE_DEV;
1864 	} else {
1865 		vref(vp);
1866 		FILEDESC_SUNLOCK(fdp);
1867 		error = vn_fill_kinfo_vnode(vp, kif);
1868 		vrele(vp);
1869 		kif->kf_type = KF_TYPE_VNODE;
1870 		FILEDESC_SLOCK(fdp);
1871 	}
1872 	return (error);
1873 }
1874 
1875 unsigned int
1876 linux_iminor(struct inode *inode)
1877 {
1878 	struct linux_cdev *ldev;
1879 
1880 	if (inode == NULL || inode->v_rdev == NULL ||
1881 	    inode->v_rdev->si_devsw != &linuxcdevsw)
1882 		return (-1U);
1883 	ldev = inode->v_rdev->si_drv1;
1884 	if (ldev == NULL)
1885 		return (-1U);
1886 
1887 	return (minor(ldev->dev));
1888 }
1889 
1890 struct fileops linuxfileops = {
1891 	.fo_read = linux_file_read,
1892 	.fo_write = linux_file_write,
1893 	.fo_truncate = invfo_truncate,
1894 	.fo_kqfilter = linux_file_kqfilter,
1895 	.fo_stat = linux_file_stat,
1896 	.fo_fill_kinfo = linux_file_fill_kinfo,
1897 	.fo_poll = linux_file_poll,
1898 	.fo_close = linux_file_close,
1899 	.fo_ioctl = linux_file_ioctl,
1900 	.fo_mmap = linux_file_mmap,
1901 	.fo_chmod = invfo_chmod,
1902 	.fo_chown = invfo_chown,
1903 	.fo_sendfile = invfo_sendfile,
1904 	.fo_flags = DFLAG_PASSABLE,
1905 };
1906 
1907 /*
1908  * Hash of vmmap addresses.  This is infrequently accessed and does not
1909  * need to be particularly large.  This is done because we must store the
1910  * caller's idea of the map size to properly unmap.
1911  */
1912 struct vmmap {
1913 	LIST_ENTRY(vmmap)	vm_next;
1914 	void 			*vm_addr;
1915 	unsigned long		vm_size;
1916 };
1917 
1918 struct vmmaphd {
1919 	struct vmmap *lh_first;
1920 };
1921 #define	VMMAP_HASH_SIZE	64
1922 #define	VMMAP_HASH_MASK	(VMMAP_HASH_SIZE - 1)
1923 #define	VM_HASH(addr)	((uintptr_t)(addr) >> PAGE_SHIFT) & VMMAP_HASH_MASK
1924 static struct vmmaphd vmmaphead[VMMAP_HASH_SIZE];
1925 static struct mtx vmmaplock;
1926 
1927 static void
1928 vmmap_add(void *addr, unsigned long size)
1929 {
1930 	struct vmmap *vmmap;
1931 
1932 	vmmap = kmalloc(sizeof(*vmmap), GFP_KERNEL);
1933 	mtx_lock(&vmmaplock);
1934 	vmmap->vm_size = size;
1935 	vmmap->vm_addr = addr;
1936 	LIST_INSERT_HEAD(&vmmaphead[VM_HASH(addr)], vmmap, vm_next);
1937 	mtx_unlock(&vmmaplock);
1938 }
1939 
1940 static struct vmmap *
1941 vmmap_remove(void *addr)
1942 {
1943 	struct vmmap *vmmap;
1944 
1945 	mtx_lock(&vmmaplock);
1946 	LIST_FOREACH(vmmap, &vmmaphead[VM_HASH(addr)], vm_next)
1947 		if (vmmap->vm_addr == addr)
1948 			break;
1949 	if (vmmap)
1950 		LIST_REMOVE(vmmap, vm_next);
1951 	mtx_unlock(&vmmaplock);
1952 
1953 	return (vmmap);
1954 }
1955 
1956 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__) || defined(__aarch64__) || defined(__riscv)
1957 void *
1958 _ioremap_attr(vm_paddr_t phys_addr, unsigned long size, int attr)
1959 {
1960 	void *addr;
1961 
1962 	addr = pmap_mapdev_attr(phys_addr, size, attr);
1963 	if (addr == NULL)
1964 		return (NULL);
1965 	vmmap_add(addr, size);
1966 
1967 	return (addr);
1968 }
1969 #endif
1970 
1971 void
1972 iounmap(void *addr)
1973 {
1974 	struct vmmap *vmmap;
1975 
1976 	vmmap = vmmap_remove(addr);
1977 	if (vmmap == NULL)
1978 		return;
1979 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__) || defined(__aarch64__) || defined(__riscv)
1980 	pmap_unmapdev(addr, vmmap->vm_size);
1981 #endif
1982 	kfree(vmmap);
1983 }
1984 
1985 void *
1986 vmap(struct page **pages, unsigned int count, unsigned long flags, int prot)
1987 {
1988 	vm_offset_t off;
1989 	size_t size;
1990 
1991 	size = count * PAGE_SIZE;
1992 	off = kva_alloc(size);
1993 	if (off == 0)
1994 		return (NULL);
1995 	vmmap_add((void *)off, size);
1996 	pmap_qenter(off, pages, count);
1997 
1998 	return ((void *)off);
1999 }
2000 
2001 void
2002 vunmap(void *addr)
2003 {
2004 	struct vmmap *vmmap;
2005 
2006 	vmmap = vmmap_remove(addr);
2007 	if (vmmap == NULL)
2008 		return;
2009 	pmap_qremove((vm_offset_t)addr, vmmap->vm_size / PAGE_SIZE);
2010 	kva_free((vm_offset_t)addr, vmmap->vm_size);
2011 	kfree(vmmap);
2012 }
2013 
2014 static char *
2015 devm_kvasprintf(struct device *dev, gfp_t gfp, const char *fmt, va_list ap)
2016 {
2017 	unsigned int len;
2018 	char *p;
2019 	va_list aq;
2020 
2021 	va_copy(aq, ap);
2022 	len = vsnprintf(NULL, 0, fmt, aq);
2023 	va_end(aq);
2024 
2025 	if (dev != NULL)
2026 		p = devm_kmalloc(dev, len + 1, gfp);
2027 	else
2028 		p = kmalloc(len + 1, gfp);
2029 	if (p != NULL)
2030 		vsnprintf(p, len + 1, fmt, ap);
2031 
2032 	return (p);
2033 }
2034 
2035 char *
2036 kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
2037 {
2038 
2039 	return (devm_kvasprintf(NULL, gfp, fmt, ap));
2040 }
2041 
2042 char *
2043 lkpi_devm_kasprintf(struct device *dev, gfp_t gfp, const char *fmt, ...)
2044 {
2045 	va_list ap;
2046 	char *p;
2047 
2048 	va_start(ap, fmt);
2049 	p = devm_kvasprintf(dev, gfp, fmt, ap);
2050 	va_end(ap);
2051 
2052 	return (p);
2053 }
2054 
2055 char *
2056 kasprintf(gfp_t gfp, const char *fmt, ...)
2057 {
2058 	va_list ap;
2059 	char *p;
2060 
2061 	va_start(ap, fmt);
2062 	p = kvasprintf(gfp, fmt, ap);
2063 	va_end(ap);
2064 
2065 	return (p);
2066 }
2067 
2068 static void
2069 linux_timer_callback_wrapper(void *context)
2070 {
2071 	struct timer_list *timer;
2072 
2073 	timer = context;
2074 
2075 	if (linux_set_current_flags(curthread, M_NOWAIT)) {
2076 		/* try again later */
2077 		callout_reset(&timer->callout, 1,
2078 		    &linux_timer_callback_wrapper, timer);
2079 		return;
2080 	}
2081 
2082 	timer->function(timer->data);
2083 }
2084 
2085 int
2086 mod_timer(struct timer_list *timer, int expires)
2087 {
2088 	int ret;
2089 
2090 	timer->expires = expires;
2091 	ret = callout_reset(&timer->callout,
2092 	    linux_timer_jiffies_until(expires),
2093 	    &linux_timer_callback_wrapper, timer);
2094 
2095 	MPASS(ret == 0 || ret == 1);
2096 
2097 	return (ret == 1);
2098 }
2099 
2100 void
2101 add_timer(struct timer_list *timer)
2102 {
2103 
2104 	callout_reset(&timer->callout,
2105 	    linux_timer_jiffies_until(timer->expires),
2106 	    &linux_timer_callback_wrapper, timer);
2107 }
2108 
2109 void
2110 add_timer_on(struct timer_list *timer, int cpu)
2111 {
2112 
2113 	callout_reset_on(&timer->callout,
2114 	    linux_timer_jiffies_until(timer->expires),
2115 	    &linux_timer_callback_wrapper, timer, cpu);
2116 }
2117 
2118 int
2119 del_timer(struct timer_list *timer)
2120 {
2121 
2122 	if (callout_stop(&(timer)->callout) == -1)
2123 		return (0);
2124 	return (1);
2125 }
2126 
2127 int
2128 del_timer_sync(struct timer_list *timer)
2129 {
2130 
2131 	if (callout_drain(&(timer)->callout) == -1)
2132 		return (0);
2133 	return (1);
2134 }
2135 
2136 /* greatest common divisor, Euclid equation */
2137 static uint64_t
2138 lkpi_gcd_64(uint64_t a, uint64_t b)
2139 {
2140 	uint64_t an;
2141 	uint64_t bn;
2142 
2143 	while (b != 0) {
2144 		an = b;
2145 		bn = a % b;
2146 		a = an;
2147 		b = bn;
2148 	}
2149 	return (a);
2150 }
2151 
2152 uint64_t lkpi_nsec2hz_rem;
2153 uint64_t lkpi_nsec2hz_div = 1000000000ULL;
2154 uint64_t lkpi_nsec2hz_max;
2155 
2156 uint64_t lkpi_usec2hz_rem;
2157 uint64_t lkpi_usec2hz_div = 1000000ULL;
2158 uint64_t lkpi_usec2hz_max;
2159 
2160 uint64_t lkpi_msec2hz_rem;
2161 uint64_t lkpi_msec2hz_div = 1000ULL;
2162 uint64_t lkpi_msec2hz_max;
2163 
2164 static void
2165 linux_timer_init(void *arg)
2166 {
2167 	uint64_t gcd;
2168 
2169 	/*
2170 	 * Compute an internal HZ value which can divide 2**32 to
2171 	 * avoid timer rounding problems when the tick value wraps
2172 	 * around 2**32:
2173 	 */
2174 	linux_timer_hz_mask = 1;
2175 	while (linux_timer_hz_mask < (unsigned long)hz)
2176 		linux_timer_hz_mask *= 2;
2177 	linux_timer_hz_mask--;
2178 
2179 	/* compute some internal constants */
2180 
2181 	lkpi_nsec2hz_rem = hz;
2182 	lkpi_usec2hz_rem = hz;
2183 	lkpi_msec2hz_rem = hz;
2184 
2185 	gcd = lkpi_gcd_64(lkpi_nsec2hz_rem, lkpi_nsec2hz_div);
2186 	lkpi_nsec2hz_rem /= gcd;
2187 	lkpi_nsec2hz_div /= gcd;
2188 	lkpi_nsec2hz_max = -1ULL / lkpi_nsec2hz_rem;
2189 
2190 	gcd = lkpi_gcd_64(lkpi_usec2hz_rem, lkpi_usec2hz_div);
2191 	lkpi_usec2hz_rem /= gcd;
2192 	lkpi_usec2hz_div /= gcd;
2193 	lkpi_usec2hz_max = -1ULL / lkpi_usec2hz_rem;
2194 
2195 	gcd = lkpi_gcd_64(lkpi_msec2hz_rem, lkpi_msec2hz_div);
2196 	lkpi_msec2hz_rem /= gcd;
2197 	lkpi_msec2hz_div /= gcd;
2198 	lkpi_msec2hz_max = -1ULL / lkpi_msec2hz_rem;
2199 }
2200 SYSINIT(linux_timer, SI_SUB_DRIVERS, SI_ORDER_FIRST, linux_timer_init, NULL);
2201 
2202 void
2203 linux_complete_common(struct completion *c, int all)
2204 {
2205 	int wakeup_swapper;
2206 
2207 	sleepq_lock(c);
2208 	if (all) {
2209 		c->done = UINT_MAX;
2210 		wakeup_swapper = sleepq_broadcast(c, SLEEPQ_SLEEP, 0, 0);
2211 	} else {
2212 		if (c->done != UINT_MAX)
2213 			c->done++;
2214 		wakeup_swapper = sleepq_signal(c, SLEEPQ_SLEEP, 0, 0);
2215 	}
2216 	sleepq_release(c);
2217 	if (wakeup_swapper)
2218 		kick_proc0();
2219 }
2220 
2221 /*
2222  * Indefinite wait for done != 0 with or without signals.
2223  */
2224 int
2225 linux_wait_for_common(struct completion *c, int flags)
2226 {
2227 	struct task_struct *task;
2228 	int error;
2229 
2230 	if (SCHEDULER_STOPPED())
2231 		return (0);
2232 
2233 	task = current;
2234 
2235 	if (flags != 0)
2236 		flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
2237 	else
2238 		flags = SLEEPQ_SLEEP;
2239 	error = 0;
2240 	for (;;) {
2241 		sleepq_lock(c);
2242 		if (c->done)
2243 			break;
2244 		sleepq_add(c, NULL, "completion", flags, 0);
2245 		if (flags & SLEEPQ_INTERRUPTIBLE) {
2246 			DROP_GIANT();
2247 			error = -sleepq_wait_sig(c, 0);
2248 			PICKUP_GIANT();
2249 			if (error != 0) {
2250 				linux_schedule_save_interrupt_value(task, error);
2251 				error = -ERESTARTSYS;
2252 				goto intr;
2253 			}
2254 		} else {
2255 			DROP_GIANT();
2256 			sleepq_wait(c, 0);
2257 			PICKUP_GIANT();
2258 		}
2259 	}
2260 	if (c->done != UINT_MAX)
2261 		c->done--;
2262 	sleepq_release(c);
2263 
2264 intr:
2265 	return (error);
2266 }
2267 
2268 /*
2269  * Time limited wait for done != 0 with or without signals.
2270  */
2271 int
2272 linux_wait_for_timeout_common(struct completion *c, int timeout, int flags)
2273 {
2274 	struct task_struct *task;
2275 	int end = jiffies + timeout;
2276 	int error;
2277 
2278 	if (SCHEDULER_STOPPED())
2279 		return (0);
2280 
2281 	task = current;
2282 
2283 	if (flags != 0)
2284 		flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
2285 	else
2286 		flags = SLEEPQ_SLEEP;
2287 
2288 	for (;;) {
2289 		sleepq_lock(c);
2290 		if (c->done)
2291 			break;
2292 		sleepq_add(c, NULL, "completion", flags, 0);
2293 		sleepq_set_timeout(c, linux_timer_jiffies_until(end));
2294 
2295 		DROP_GIANT();
2296 		if (flags & SLEEPQ_INTERRUPTIBLE)
2297 			error = -sleepq_timedwait_sig(c, 0);
2298 		else
2299 			error = -sleepq_timedwait(c, 0);
2300 		PICKUP_GIANT();
2301 
2302 		if (error != 0) {
2303 			/* check for timeout */
2304 			if (error == -EWOULDBLOCK) {
2305 				error = 0;	/* timeout */
2306 			} else {
2307 				/* signal happened */
2308 				linux_schedule_save_interrupt_value(task, error);
2309 				error = -ERESTARTSYS;
2310 			}
2311 			goto done;
2312 		}
2313 	}
2314 	if (c->done != UINT_MAX)
2315 		c->done--;
2316 	sleepq_release(c);
2317 
2318 	/* return how many jiffies are left */
2319 	error = linux_timer_jiffies_until(end);
2320 done:
2321 	return (error);
2322 }
2323 
2324 int
2325 linux_try_wait_for_completion(struct completion *c)
2326 {
2327 	int isdone;
2328 
2329 	sleepq_lock(c);
2330 	isdone = (c->done != 0);
2331 	if (c->done != 0 && c->done != UINT_MAX)
2332 		c->done--;
2333 	sleepq_release(c);
2334 	return (isdone);
2335 }
2336 
2337 int
2338 linux_completion_done(struct completion *c)
2339 {
2340 	int isdone;
2341 
2342 	sleepq_lock(c);
2343 	isdone = (c->done != 0);
2344 	sleepq_release(c);
2345 	return (isdone);
2346 }
2347 
2348 static void
2349 linux_cdev_deref(struct linux_cdev *ldev)
2350 {
2351 	if (refcount_release(&ldev->refs) &&
2352 	    ldev->kobj.ktype == &linux_cdev_ktype)
2353 		kfree(ldev);
2354 }
2355 
2356 static void
2357 linux_cdev_release(struct kobject *kobj)
2358 {
2359 	struct linux_cdev *cdev;
2360 	struct kobject *parent;
2361 
2362 	cdev = container_of(kobj, struct linux_cdev, kobj);
2363 	parent = kobj->parent;
2364 	linux_destroy_dev(cdev);
2365 	linux_cdev_deref(cdev);
2366 	kobject_put(parent);
2367 }
2368 
2369 static void
2370 linux_cdev_static_release(struct kobject *kobj)
2371 {
2372 	struct cdev *cdev;
2373 	struct linux_cdev *ldev;
2374 
2375 	ldev = container_of(kobj, struct linux_cdev, kobj);
2376 	cdev = ldev->cdev;
2377 	if (cdev != NULL) {
2378 		destroy_dev(cdev);
2379 		ldev->cdev = NULL;
2380 	}
2381 	kobject_put(kobj->parent);
2382 }
2383 
2384 int
2385 linux_cdev_device_add(struct linux_cdev *ldev, struct device *dev)
2386 {
2387 	int ret;
2388 
2389 	if (dev->devt != 0) {
2390 		/* Set parent kernel object. */
2391 		ldev->kobj.parent = &dev->kobj;
2392 
2393 		/*
2394 		 * Unlike Linux we require the kobject of the
2395 		 * character device structure to have a valid name
2396 		 * before calling this function:
2397 		 */
2398 		if (ldev->kobj.name == NULL)
2399 			return (-EINVAL);
2400 
2401 		ret = cdev_add(ldev, dev->devt, 1);
2402 		if (ret)
2403 			return (ret);
2404 	}
2405 	ret = device_add(dev);
2406 	if (ret != 0 && dev->devt != 0)
2407 		cdev_del(ldev);
2408 	return (ret);
2409 }
2410 
2411 void
2412 linux_cdev_device_del(struct linux_cdev *ldev, struct device *dev)
2413 {
2414 	device_del(dev);
2415 
2416 	if (dev->devt != 0)
2417 		cdev_del(ldev);
2418 }
2419 
2420 static void
2421 linux_destroy_dev(struct linux_cdev *ldev)
2422 {
2423 
2424 	if (ldev->cdev == NULL)
2425 		return;
2426 
2427 	MPASS((ldev->siref & LDEV_SI_DTR) == 0);
2428 	MPASS(ldev->kobj.ktype == &linux_cdev_ktype);
2429 
2430 	atomic_set_int(&ldev->siref, LDEV_SI_DTR);
2431 	while ((atomic_load_int(&ldev->siref) & ~LDEV_SI_DTR) != 0)
2432 		pause("ldevdtr", hz / 4);
2433 
2434 	destroy_dev(ldev->cdev);
2435 	ldev->cdev = NULL;
2436 }
2437 
2438 const struct kobj_type linux_cdev_ktype = {
2439 	.release = linux_cdev_release,
2440 };
2441 
2442 const struct kobj_type linux_cdev_static_ktype = {
2443 	.release = linux_cdev_static_release,
2444 };
2445 
2446 static void
2447 linux_handle_ifnet_link_event(void *arg, struct ifnet *ifp, int linkstate)
2448 {
2449 	struct notifier_block *nb;
2450 	struct netdev_notifier_info ni;
2451 
2452 	nb = arg;
2453 	ni.ifp = ifp;
2454 	ni.dev = (struct net_device *)ifp;
2455 	if (linkstate == LINK_STATE_UP)
2456 		nb->notifier_call(nb, NETDEV_UP, &ni);
2457 	else
2458 		nb->notifier_call(nb, NETDEV_DOWN, &ni);
2459 }
2460 
2461 static void
2462 linux_handle_ifnet_arrival_event(void *arg, struct ifnet *ifp)
2463 {
2464 	struct notifier_block *nb;
2465 	struct netdev_notifier_info ni;
2466 
2467 	nb = arg;
2468 	ni.ifp = ifp;
2469 	ni.dev = (struct net_device *)ifp;
2470 	nb->notifier_call(nb, NETDEV_REGISTER, &ni);
2471 }
2472 
2473 static void
2474 linux_handle_ifnet_departure_event(void *arg, struct ifnet *ifp)
2475 {
2476 	struct notifier_block *nb;
2477 	struct netdev_notifier_info ni;
2478 
2479 	nb = arg;
2480 	ni.ifp = ifp;
2481 	ni.dev = (struct net_device *)ifp;
2482 	nb->notifier_call(nb, NETDEV_UNREGISTER, &ni);
2483 }
2484 
2485 static void
2486 linux_handle_iflladdr_event(void *arg, struct ifnet *ifp)
2487 {
2488 	struct notifier_block *nb;
2489 	struct netdev_notifier_info ni;
2490 
2491 	nb = arg;
2492 	ni.ifp = ifp;
2493 	ni.dev = (struct net_device *)ifp;
2494 	nb->notifier_call(nb, NETDEV_CHANGEADDR, &ni);
2495 }
2496 
2497 static void
2498 linux_handle_ifaddr_event(void *arg, struct ifnet *ifp)
2499 {
2500 	struct notifier_block *nb;
2501 	struct netdev_notifier_info ni;
2502 
2503 	nb = arg;
2504 	ni.ifp = ifp;
2505 	ni.dev = (struct net_device *)ifp;
2506 	nb->notifier_call(nb, NETDEV_CHANGEIFADDR, &ni);
2507 }
2508 
2509 int
2510 register_netdevice_notifier(struct notifier_block *nb)
2511 {
2512 
2513 	nb->tags[NETDEV_UP] = EVENTHANDLER_REGISTER(
2514 	    ifnet_link_event, linux_handle_ifnet_link_event, nb, 0);
2515 	nb->tags[NETDEV_REGISTER] = EVENTHANDLER_REGISTER(
2516 	    ifnet_arrival_event, linux_handle_ifnet_arrival_event, nb, 0);
2517 	nb->tags[NETDEV_UNREGISTER] = EVENTHANDLER_REGISTER(
2518 	    ifnet_departure_event, linux_handle_ifnet_departure_event, nb, 0);
2519 	nb->tags[NETDEV_CHANGEADDR] = EVENTHANDLER_REGISTER(
2520 	    iflladdr_event, linux_handle_iflladdr_event, nb, 0);
2521 
2522 	return (0);
2523 }
2524 
2525 int
2526 register_inetaddr_notifier(struct notifier_block *nb)
2527 {
2528 
2529 	nb->tags[NETDEV_CHANGEIFADDR] = EVENTHANDLER_REGISTER(
2530 	    ifaddr_event, linux_handle_ifaddr_event, nb, 0);
2531 	return (0);
2532 }
2533 
2534 int
2535 unregister_netdevice_notifier(struct notifier_block *nb)
2536 {
2537 
2538 	EVENTHANDLER_DEREGISTER(ifnet_link_event,
2539 	    nb->tags[NETDEV_UP]);
2540 	EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
2541 	    nb->tags[NETDEV_REGISTER]);
2542 	EVENTHANDLER_DEREGISTER(ifnet_departure_event,
2543 	    nb->tags[NETDEV_UNREGISTER]);
2544 	EVENTHANDLER_DEREGISTER(iflladdr_event,
2545 	    nb->tags[NETDEV_CHANGEADDR]);
2546 
2547 	return (0);
2548 }
2549 
2550 int
2551 unregister_inetaddr_notifier(struct notifier_block *nb)
2552 {
2553 
2554 	EVENTHANDLER_DEREGISTER(ifaddr_event,
2555 	    nb->tags[NETDEV_CHANGEIFADDR]);
2556 
2557 	return (0);
2558 }
2559 
2560 struct list_sort_thunk {
2561 	int (*cmp)(void *, struct list_head *, struct list_head *);
2562 	void *priv;
2563 };
2564 
2565 static inline int
2566 linux_le_cmp(const void *d1, const void *d2, void *priv)
2567 {
2568 	struct list_head *le1, *le2;
2569 	struct list_sort_thunk *thunk;
2570 
2571 	thunk = priv;
2572 	le1 = *(__DECONST(struct list_head **, d1));
2573 	le2 = *(__DECONST(struct list_head **, d2));
2574 	return ((thunk->cmp)(thunk->priv, le1, le2));
2575 }
2576 
2577 void
2578 list_sort(void *priv, struct list_head *head, int (*cmp)(void *priv,
2579     struct list_head *a, struct list_head *b))
2580 {
2581 	struct list_sort_thunk thunk;
2582 	struct list_head **ar, *le;
2583 	size_t count, i;
2584 
2585 	count = 0;
2586 	list_for_each(le, head)
2587 		count++;
2588 	ar = malloc(sizeof(struct list_head *) * count, M_KMALLOC, M_WAITOK);
2589 	i = 0;
2590 	list_for_each(le, head)
2591 		ar[i++] = le;
2592 	thunk.cmp = cmp;
2593 	thunk.priv = priv;
2594 	qsort_r(ar, count, sizeof(struct list_head *), linux_le_cmp, &thunk);
2595 	INIT_LIST_HEAD(head);
2596 	for (i = 0; i < count; i++)
2597 		list_add_tail(ar[i], head);
2598 	free(ar, M_KMALLOC);
2599 }
2600 
2601 #if defined(__i386__) || defined(__amd64__)
2602 int
2603 linux_wbinvd_on_all_cpus(void)
2604 {
2605 
2606 	pmap_invalidate_cache();
2607 	return (0);
2608 }
2609 #endif
2610 
2611 int
2612 linux_on_each_cpu(void callback(void *), void *data)
2613 {
2614 
2615 	smp_rendezvous(smp_no_rendezvous_barrier, callback,
2616 	    smp_no_rendezvous_barrier, data);
2617 	return (0);
2618 }
2619 
2620 int
2621 linux_in_atomic(void)
2622 {
2623 
2624 	return ((curthread->td_pflags & TDP_NOFAULTING) != 0);
2625 }
2626 
2627 struct linux_cdev *
2628 linux_find_cdev(const char *name, unsigned major, unsigned minor)
2629 {
2630 	dev_t dev = MKDEV(major, minor);
2631 	struct cdev *cdev;
2632 
2633 	dev_lock();
2634 	LIST_FOREACH(cdev, &linuxcdevsw.d_devs, si_list) {
2635 		struct linux_cdev *ldev = cdev->si_drv1;
2636 		if (ldev->dev == dev &&
2637 		    strcmp(kobject_name(&ldev->kobj), name) == 0) {
2638 			break;
2639 		}
2640 	}
2641 	dev_unlock();
2642 
2643 	return (cdev != NULL ? cdev->si_drv1 : NULL);
2644 }
2645 
2646 int
2647 __register_chrdev(unsigned int major, unsigned int baseminor,
2648     unsigned int count, const char *name,
2649     const struct file_operations *fops)
2650 {
2651 	struct linux_cdev *cdev;
2652 	int ret = 0;
2653 	int i;
2654 
2655 	for (i = baseminor; i < baseminor + count; i++) {
2656 		cdev = cdev_alloc();
2657 		cdev->ops = fops;
2658 		kobject_set_name(&cdev->kobj, name);
2659 
2660 		ret = cdev_add(cdev, makedev(major, i), 1);
2661 		if (ret != 0)
2662 			break;
2663 	}
2664 	return (ret);
2665 }
2666 
2667 int
2668 __register_chrdev_p(unsigned int major, unsigned int baseminor,
2669     unsigned int count, const char *name,
2670     const struct file_operations *fops, uid_t uid,
2671     gid_t gid, int mode)
2672 {
2673 	struct linux_cdev *cdev;
2674 	int ret = 0;
2675 	int i;
2676 
2677 	for (i = baseminor; i < baseminor + count; i++) {
2678 		cdev = cdev_alloc();
2679 		cdev->ops = fops;
2680 		kobject_set_name(&cdev->kobj, name);
2681 
2682 		ret = cdev_add_ext(cdev, makedev(major, i), uid, gid, mode);
2683 		if (ret != 0)
2684 			break;
2685 	}
2686 	return (ret);
2687 }
2688 
2689 void
2690 __unregister_chrdev(unsigned int major, unsigned int baseminor,
2691     unsigned int count, const char *name)
2692 {
2693 	struct linux_cdev *cdevp;
2694 	int i;
2695 
2696 	for (i = baseminor; i < baseminor + count; i++) {
2697 		cdevp = linux_find_cdev(name, major, i);
2698 		if (cdevp != NULL)
2699 			cdev_del(cdevp);
2700 	}
2701 }
2702 
2703 void
2704 linux_dump_stack(void)
2705 {
2706 #ifdef STACK
2707 	struct stack st;
2708 
2709 	stack_save(&st);
2710 	stack_print(&st);
2711 #endif
2712 }
2713 
2714 int
2715 linuxkpi_net_ratelimit(void)
2716 {
2717 
2718 	return (ppsratecheck(&lkpi_net_lastlog, &lkpi_net_curpps,
2719 	   lkpi_net_maxpps));
2720 }
2721 
2722 struct io_mapping *
2723 io_mapping_create_wc(resource_size_t base, unsigned long size)
2724 {
2725 	struct io_mapping *mapping;
2726 
2727 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2728 	if (mapping == NULL)
2729 		return (NULL);
2730 	return (io_mapping_init_wc(mapping, base, size));
2731 }
2732 
2733 #if defined(__i386__) || defined(__amd64__)
2734 bool linux_cpu_has_clflush;
2735 struct cpuinfo_x86 boot_cpu_data;
2736 #endif
2737 
2738 cpumask_t *
2739 lkpi_get_static_single_cpu_mask(int cpuid)
2740 {
2741 
2742 	KASSERT((cpuid >= 0 && cpuid < MAXCPU), ("%s: invalid cpuid %d\n",
2743 	    __func__, cpuid));
2744 
2745 	return (&static_single_cpu_mask[cpuid]);
2746 }
2747 
2748 static void
2749 linux_compat_init(void *arg)
2750 {
2751 	struct sysctl_oid *rootoid;
2752 	int i;
2753 
2754 #if defined(__i386__) || defined(__amd64__)
2755 	linux_cpu_has_clflush = (cpu_feature & CPUID_CLFSH);
2756 	boot_cpu_data.x86_clflush_size = cpu_clflush_line_size;
2757 	boot_cpu_data.x86 = ((cpu_id & 0xf0000) >> 12) | ((cpu_id & 0xf0) >> 4);
2758 #endif
2759 	rw_init(&linux_vma_lock, "lkpi-vma-lock");
2760 
2761 	rootoid = SYSCTL_ADD_ROOT_NODE(NULL,
2762 	    OID_AUTO, "sys", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "sys");
2763 	kobject_init(&linux_class_root, &linux_class_ktype);
2764 	kobject_set_name(&linux_class_root, "class");
2765 	linux_class_root.oidp = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(rootoid),
2766 	    OID_AUTO, "class", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "class");
2767 	kobject_init(&linux_root_device.kobj, &linux_dev_ktype);
2768 	kobject_set_name(&linux_root_device.kobj, "device");
2769 	linux_root_device.kobj.oidp = SYSCTL_ADD_NODE(NULL,
2770 	    SYSCTL_CHILDREN(rootoid), OID_AUTO, "device",
2771 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "device");
2772 	linux_root_device.bsddev = root_bus;
2773 	linux_class_misc.name = "misc";
2774 	class_register(&linux_class_misc);
2775 	INIT_LIST_HEAD(&pci_drivers);
2776 	INIT_LIST_HEAD(&pci_devices);
2777 	spin_lock_init(&pci_lock);
2778 	mtx_init(&vmmaplock, "IO Map lock", NULL, MTX_DEF);
2779 	for (i = 0; i < VMMAP_HASH_SIZE; i++)
2780 		LIST_INIT(&vmmaphead[i]);
2781 	init_waitqueue_head(&linux_bit_waitq);
2782 	init_waitqueue_head(&linux_var_waitq);
2783 
2784 	CPU_COPY(&all_cpus, &cpu_online_mask);
2785 	/*
2786 	 * Generate a single-CPU cpumask_t for each CPU (possibly) in the system.
2787 	 * CPUs are indexed from 0..(MAXCPU-1).  The entry for cpuid 0 will only
2788 	 * have itself in the cpumask, cupid 1 only itself on entry 1, and so on.
2789 	 * This is used by cpumask_of() (and possibly others in the future) for,
2790 	 * e.g., drivers to pass hints to irq_set_affinity_hint().
2791 	 */
2792 	for (i = 0; i < MAXCPU; i++)
2793 		CPU_SET(i, &static_single_cpu_mask[i]);
2794 }
2795 SYSINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_init, NULL);
2796 
2797 static void
2798 linux_compat_uninit(void *arg)
2799 {
2800 	linux_kobject_kfree_name(&linux_class_root);
2801 	linux_kobject_kfree_name(&linux_root_device.kobj);
2802 	linux_kobject_kfree_name(&linux_class_misc.kobj);
2803 
2804 	mtx_destroy(&vmmaplock);
2805 	spin_lock_destroy(&pci_lock);
2806 	rw_destroy(&linux_vma_lock);
2807 }
2808 SYSUNINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_uninit, NULL);
2809 
2810 /*
2811  * NOTE: Linux frequently uses "unsigned long" for pointer to integer
2812  * conversion and vice versa, where in FreeBSD "uintptr_t" would be
2813  * used. Assert these types have the same size, else some parts of the
2814  * LinuxKPI may not work like expected:
2815  */
2816 CTASSERT(sizeof(unsigned long) == sizeof(uintptr_t));
2817