xref: /freebsd/sys/compat/linuxkpi/common/src/linux_compat.c (revision d9a42747950146bf03cda7f6e25d219253f8a57a)
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 void
838 vma_set_file(struct vm_area_struct *vma, struct linux_file *file)
839 {
840 	struct linux_file *tmp;
841 
842 	/* Changing an anonymous vma with this is illegal */
843 	get_file(file);
844 	tmp = vma->vm_file;
845 	vma->vm_file = file;
846 	fput(tmp);
847 }
848 
849 static struct file_operations dummy_ldev_ops = {
850 	/* XXXKIB */
851 };
852 
853 static struct linux_cdev dummy_ldev = {
854 	.ops = &dummy_ldev_ops,
855 };
856 
857 #define	LDEV_SI_DTR	0x0001
858 #define	LDEV_SI_REF	0x0002
859 
860 static void
861 linux_get_fop(struct linux_file *filp, const struct file_operations **fop,
862     struct linux_cdev **dev)
863 {
864 	struct linux_cdev *ldev;
865 	u_int siref;
866 
867 	ldev = filp->f_cdev;
868 	*fop = filp->f_op;
869 	if (ldev != NULL) {
870 		if (ldev->kobj.ktype == &linux_cdev_static_ktype) {
871 			refcount_acquire(&ldev->refs);
872 		} else {
873 			for (siref = ldev->siref;;) {
874 				if ((siref & LDEV_SI_DTR) != 0) {
875 					ldev = &dummy_ldev;
876 					*fop = ldev->ops;
877 					siref = ldev->siref;
878 					MPASS((ldev->siref & LDEV_SI_DTR) == 0);
879 				} else if (atomic_fcmpset_int(&ldev->siref,
880 				    &siref, siref + LDEV_SI_REF)) {
881 					break;
882 				}
883 			}
884 		}
885 	}
886 	*dev = ldev;
887 }
888 
889 static void
890 linux_drop_fop(struct linux_cdev *ldev)
891 {
892 
893 	if (ldev == NULL)
894 		return;
895 	if (ldev->kobj.ktype == &linux_cdev_static_ktype) {
896 		linux_cdev_deref(ldev);
897 	} else {
898 		MPASS(ldev->kobj.ktype == &linux_cdev_ktype);
899 		MPASS((ldev->siref & ~LDEV_SI_DTR) != 0);
900 		atomic_subtract_int(&ldev->siref, LDEV_SI_REF);
901 	}
902 }
903 
904 #define	OPW(fp,td,code) ({			\
905 	struct file *__fpop;			\
906 	__typeof(code) __retval;		\
907 						\
908 	__fpop = (td)->td_fpop;			\
909 	(td)->td_fpop = (fp);			\
910 	__retval = (code);			\
911 	(td)->td_fpop = __fpop;			\
912 	__retval;				\
913 })
914 
915 static int
916 linux_dev_fdopen(struct cdev *dev, int fflags, struct thread *td,
917     struct file *file)
918 {
919 	struct linux_cdev *ldev;
920 	struct linux_file *filp;
921 	const struct file_operations *fop;
922 	int error;
923 
924 	ldev = dev->si_drv1;
925 
926 	filp = linux_file_alloc();
927 	filp->f_dentry = &filp->f_dentry_store;
928 	filp->f_op = ldev->ops;
929 	filp->f_mode = file->f_flag;
930 	filp->f_flags = file->f_flag;
931 	filp->f_vnode = file->f_vnode;
932 	filp->_file = file;
933 	refcount_acquire(&ldev->refs);
934 	filp->f_cdev = ldev;
935 
936 	linux_set_current(td);
937 	linux_get_fop(filp, &fop, &ldev);
938 
939 	if (fop->open != NULL) {
940 		error = -fop->open(file->f_vnode, filp);
941 		if (error != 0) {
942 			linux_drop_fop(ldev);
943 			linux_cdev_deref(filp->f_cdev);
944 			kfree(filp);
945 			return (error);
946 		}
947 	}
948 
949 	/* hold on to the vnode - used for fstat() */
950 	vhold(filp->f_vnode);
951 
952 	/* release the file from devfs */
953 	finit(file, filp->f_mode, DTYPE_DEV, filp, &linuxfileops);
954 	linux_drop_fop(ldev);
955 	return (ENXIO);
956 }
957 
958 #define	LINUX_IOCTL_MIN_PTR 0x10000UL
959 #define	LINUX_IOCTL_MAX_PTR (LINUX_IOCTL_MIN_PTR + IOCPARM_MAX)
960 
961 static inline int
962 linux_remap_address(void **uaddr, size_t len)
963 {
964 	uintptr_t uaddr_val = (uintptr_t)(*uaddr);
965 
966 	if (unlikely(uaddr_val >= LINUX_IOCTL_MIN_PTR &&
967 	    uaddr_val < LINUX_IOCTL_MAX_PTR)) {
968 		struct task_struct *pts = current;
969 		if (pts == NULL) {
970 			*uaddr = NULL;
971 			return (1);
972 		}
973 
974 		/* compute data offset */
975 		uaddr_val -= LINUX_IOCTL_MIN_PTR;
976 
977 		/* check that length is within bounds */
978 		if ((len > IOCPARM_MAX) ||
979 		    (uaddr_val + len) > pts->bsd_ioctl_len) {
980 			*uaddr = NULL;
981 			return (1);
982 		}
983 
984 		/* re-add kernel buffer address */
985 		uaddr_val += (uintptr_t)pts->bsd_ioctl_data;
986 
987 		/* update address location */
988 		*uaddr = (void *)uaddr_val;
989 		return (1);
990 	}
991 	return (0);
992 }
993 
994 int
995 linux_copyin(const void *uaddr, void *kaddr, size_t len)
996 {
997 	if (linux_remap_address(__DECONST(void **, &uaddr), len)) {
998 		if (uaddr == NULL)
999 			return (-EFAULT);
1000 		memcpy(kaddr, uaddr, len);
1001 		return (0);
1002 	}
1003 	return (-copyin(uaddr, kaddr, len));
1004 }
1005 
1006 int
1007 linux_copyout(const void *kaddr, void *uaddr, size_t len)
1008 {
1009 	if (linux_remap_address(&uaddr, len)) {
1010 		if (uaddr == NULL)
1011 			return (-EFAULT);
1012 		memcpy(uaddr, kaddr, len);
1013 		return (0);
1014 	}
1015 	return (-copyout(kaddr, uaddr, len));
1016 }
1017 
1018 size_t
1019 linux_clear_user(void *_uaddr, size_t _len)
1020 {
1021 	uint8_t *uaddr = _uaddr;
1022 	size_t len = _len;
1023 
1024 	/* make sure uaddr is aligned before going into the fast loop */
1025 	while (((uintptr_t)uaddr & 7) != 0 && len > 7) {
1026 		if (subyte(uaddr, 0))
1027 			return (_len);
1028 		uaddr++;
1029 		len--;
1030 	}
1031 
1032 	/* zero 8 bytes at a time */
1033 	while (len > 7) {
1034 #ifdef __LP64__
1035 		if (suword64(uaddr, 0))
1036 			return (_len);
1037 #else
1038 		if (suword32(uaddr, 0))
1039 			return (_len);
1040 		if (suword32(uaddr + 4, 0))
1041 			return (_len);
1042 #endif
1043 		uaddr += 8;
1044 		len -= 8;
1045 	}
1046 
1047 	/* zero fill end, if any */
1048 	while (len > 0) {
1049 		if (subyte(uaddr, 0))
1050 			return (_len);
1051 		uaddr++;
1052 		len--;
1053 	}
1054 	return (0);
1055 }
1056 
1057 int
1058 linux_access_ok(const void *uaddr, size_t len)
1059 {
1060 	uintptr_t saddr;
1061 	uintptr_t eaddr;
1062 
1063 	/* get start and end address */
1064 	saddr = (uintptr_t)uaddr;
1065 	eaddr = (uintptr_t)uaddr + len;
1066 
1067 	/* verify addresses are valid for userspace */
1068 	return ((saddr == eaddr) ||
1069 	    (eaddr > saddr && eaddr <= VM_MAXUSER_ADDRESS));
1070 }
1071 
1072 /*
1073  * This function should return either EINTR or ERESTART depending on
1074  * the signal type sent to this thread:
1075  */
1076 static int
1077 linux_get_error(struct task_struct *task, int error)
1078 {
1079 	/* check for signal type interrupt code */
1080 	if (error == EINTR || error == ERESTARTSYS || error == ERESTART) {
1081 		error = -linux_schedule_get_interrupt_value(task);
1082 		if (error == 0)
1083 			error = EINTR;
1084 	}
1085 	return (error);
1086 }
1087 
1088 static int
1089 linux_file_ioctl_sub(struct file *fp, struct linux_file *filp,
1090     const struct file_operations *fop, u_long cmd, caddr_t data,
1091     struct thread *td)
1092 {
1093 	struct task_struct *task = current;
1094 	unsigned size;
1095 	int error;
1096 
1097 	size = IOCPARM_LEN(cmd);
1098 	/* refer to logic in sys_ioctl() */
1099 	if (size > 0) {
1100 		/*
1101 		 * Setup hint for linux_copyin() and linux_copyout().
1102 		 *
1103 		 * Background: Linux code expects a user-space address
1104 		 * while FreeBSD supplies a kernel-space address.
1105 		 */
1106 		task->bsd_ioctl_data = data;
1107 		task->bsd_ioctl_len = size;
1108 		data = (void *)LINUX_IOCTL_MIN_PTR;
1109 	} else {
1110 		/* fetch user-space pointer */
1111 		data = *(void **)data;
1112 	}
1113 #ifdef COMPAT_FREEBSD32
1114 	if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
1115 		/* try the compat IOCTL handler first */
1116 		if (fop->compat_ioctl != NULL) {
1117 			error = -OPW(fp, td, fop->compat_ioctl(filp,
1118 			    cmd, (u_long)data));
1119 		} else {
1120 			error = ENOTTY;
1121 		}
1122 
1123 		/* fallback to the regular IOCTL handler, if any */
1124 		if (error == ENOTTY && fop->unlocked_ioctl != NULL) {
1125 			error = -OPW(fp, td, fop->unlocked_ioctl(filp,
1126 			    cmd, (u_long)data));
1127 		}
1128 	} else
1129 #endif
1130 	{
1131 		if (fop->unlocked_ioctl != NULL) {
1132 			error = -OPW(fp, td, fop->unlocked_ioctl(filp,
1133 			    cmd, (u_long)data));
1134 		} else {
1135 			error = ENOTTY;
1136 		}
1137 	}
1138 	if (size > 0) {
1139 		task->bsd_ioctl_data = NULL;
1140 		task->bsd_ioctl_len = 0;
1141 	}
1142 
1143 	if (error == EWOULDBLOCK) {
1144 		/* update kqfilter status, if any */
1145 		linux_file_kqfilter_poll(filp,
1146 		    LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
1147 	} else {
1148 		error = linux_get_error(task, error);
1149 	}
1150 	return (error);
1151 }
1152 
1153 #define	LINUX_POLL_TABLE_NORMAL ((poll_table *)1)
1154 
1155 /*
1156  * This function atomically updates the poll wakeup state and returns
1157  * the previous state at the time of update.
1158  */
1159 static uint8_t
1160 linux_poll_wakeup_state(atomic_t *v, const uint8_t *pstate)
1161 {
1162 	int c, old;
1163 
1164 	c = v->counter;
1165 
1166 	while ((old = atomic_cmpxchg(v, c, pstate[c])) != c)
1167 		c = old;
1168 
1169 	return (c);
1170 }
1171 
1172 static int
1173 linux_poll_wakeup_callback(wait_queue_t *wq, unsigned int wq_state, int flags, void *key)
1174 {
1175 	static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1176 		[LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_INIT, /* NOP */
1177 		[LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_NOT_READY, /* NOP */
1178 		[LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_READY,
1179 		[LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_READY, /* NOP */
1180 	};
1181 	struct linux_file *filp = container_of(wq, struct linux_file, f_wait_queue.wq);
1182 
1183 	switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1184 	case LINUX_FWQ_STATE_QUEUED:
1185 		linux_poll_wakeup(filp);
1186 		return (1);
1187 	default:
1188 		return (0);
1189 	}
1190 }
1191 
1192 void
1193 linux_poll_wait(struct linux_file *filp, wait_queue_head_t *wqh, poll_table *p)
1194 {
1195 	static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1196 		[LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_NOT_READY,
1197 		[LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_NOT_READY, /* NOP */
1198 		[LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_QUEUED, /* NOP */
1199 		[LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_QUEUED,
1200 	};
1201 
1202 	/* check if we are called inside the select system call */
1203 	if (p == LINUX_POLL_TABLE_NORMAL)
1204 		selrecord(curthread, &filp->f_selinfo);
1205 
1206 	switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1207 	case LINUX_FWQ_STATE_INIT:
1208 		/* NOTE: file handles can only belong to one wait-queue */
1209 		filp->f_wait_queue.wqh = wqh;
1210 		filp->f_wait_queue.wq.func = &linux_poll_wakeup_callback;
1211 		add_wait_queue(wqh, &filp->f_wait_queue.wq);
1212 		atomic_set(&filp->f_wait_queue.state, LINUX_FWQ_STATE_QUEUED);
1213 		break;
1214 	default:
1215 		break;
1216 	}
1217 }
1218 
1219 static void
1220 linux_poll_wait_dequeue(struct linux_file *filp)
1221 {
1222 	static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1223 		[LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_INIT,	/* NOP */
1224 		[LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_INIT,
1225 		[LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_INIT,
1226 		[LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_INIT,
1227 	};
1228 
1229 	seldrain(&filp->f_selinfo);
1230 
1231 	switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1232 	case LINUX_FWQ_STATE_NOT_READY:
1233 	case LINUX_FWQ_STATE_QUEUED:
1234 	case LINUX_FWQ_STATE_READY:
1235 		remove_wait_queue(filp->f_wait_queue.wqh, &filp->f_wait_queue.wq);
1236 		break;
1237 	default:
1238 		break;
1239 	}
1240 }
1241 
1242 void
1243 linux_poll_wakeup(struct linux_file *filp)
1244 {
1245 	/* this function should be NULL-safe */
1246 	if (filp == NULL)
1247 		return;
1248 
1249 	selwakeup(&filp->f_selinfo);
1250 
1251 	spin_lock(&filp->f_kqlock);
1252 	filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ |
1253 	    LINUX_KQ_FLAG_NEED_WRITE;
1254 
1255 	/* make sure the "knote" gets woken up */
1256 	KNOTE_LOCKED(&filp->f_selinfo.si_note, 1);
1257 	spin_unlock(&filp->f_kqlock);
1258 }
1259 
1260 static void
1261 linux_file_kqfilter_detach(struct knote *kn)
1262 {
1263 	struct linux_file *filp = kn->kn_hook;
1264 
1265 	spin_lock(&filp->f_kqlock);
1266 	knlist_remove(&filp->f_selinfo.si_note, kn, 1);
1267 	spin_unlock(&filp->f_kqlock);
1268 }
1269 
1270 static int
1271 linux_file_kqfilter_read_event(struct knote *kn, long hint)
1272 {
1273 	struct linux_file *filp = kn->kn_hook;
1274 
1275 	mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1276 
1277 	return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_READ) ? 1 : 0);
1278 }
1279 
1280 static int
1281 linux_file_kqfilter_write_event(struct knote *kn, long hint)
1282 {
1283 	struct linux_file *filp = kn->kn_hook;
1284 
1285 	mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1286 
1287 	return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_WRITE) ? 1 : 0);
1288 }
1289 
1290 static struct filterops linux_dev_kqfiltops_read = {
1291 	.f_isfd = 1,
1292 	.f_detach = linux_file_kqfilter_detach,
1293 	.f_event = linux_file_kqfilter_read_event,
1294 };
1295 
1296 static struct filterops linux_dev_kqfiltops_write = {
1297 	.f_isfd = 1,
1298 	.f_detach = linux_file_kqfilter_detach,
1299 	.f_event = linux_file_kqfilter_write_event,
1300 };
1301 
1302 static void
1303 linux_file_kqfilter_poll(struct linux_file *filp, int kqflags)
1304 {
1305 	struct thread *td;
1306 	const struct file_operations *fop;
1307 	struct linux_cdev *ldev;
1308 	int temp;
1309 
1310 	if ((filp->f_kqflags & kqflags) == 0)
1311 		return;
1312 
1313 	td = curthread;
1314 
1315 	linux_get_fop(filp, &fop, &ldev);
1316 	/* get the latest polling state */
1317 	temp = OPW(filp->_file, td, fop->poll(filp, NULL));
1318 	linux_drop_fop(ldev);
1319 
1320 	spin_lock(&filp->f_kqlock);
1321 	/* clear kqflags */
1322 	filp->f_kqflags &= ~(LINUX_KQ_FLAG_NEED_READ |
1323 	    LINUX_KQ_FLAG_NEED_WRITE);
1324 	/* update kqflags */
1325 	if ((temp & (POLLIN | POLLOUT)) != 0) {
1326 		if ((temp & POLLIN) != 0)
1327 			filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ;
1328 		if ((temp & POLLOUT) != 0)
1329 			filp->f_kqflags |= LINUX_KQ_FLAG_NEED_WRITE;
1330 
1331 		/* make sure the "knote" gets woken up */
1332 		KNOTE_LOCKED(&filp->f_selinfo.si_note, 0);
1333 	}
1334 	spin_unlock(&filp->f_kqlock);
1335 }
1336 
1337 static int
1338 linux_file_kqfilter(struct file *file, struct knote *kn)
1339 {
1340 	struct linux_file *filp;
1341 	struct thread *td;
1342 	int error;
1343 
1344 	td = curthread;
1345 	filp = (struct linux_file *)file->f_data;
1346 	filp->f_flags = file->f_flag;
1347 	if (filp->f_op->poll == NULL)
1348 		return (EINVAL);
1349 
1350 	spin_lock(&filp->f_kqlock);
1351 	switch (kn->kn_filter) {
1352 	case EVFILT_READ:
1353 		filp->f_kqflags |= LINUX_KQ_FLAG_HAS_READ;
1354 		kn->kn_fop = &linux_dev_kqfiltops_read;
1355 		kn->kn_hook = filp;
1356 		knlist_add(&filp->f_selinfo.si_note, kn, 1);
1357 		error = 0;
1358 		break;
1359 	case EVFILT_WRITE:
1360 		filp->f_kqflags |= LINUX_KQ_FLAG_HAS_WRITE;
1361 		kn->kn_fop = &linux_dev_kqfiltops_write;
1362 		kn->kn_hook = filp;
1363 		knlist_add(&filp->f_selinfo.si_note, kn, 1);
1364 		error = 0;
1365 		break;
1366 	default:
1367 		error = EINVAL;
1368 		break;
1369 	}
1370 	spin_unlock(&filp->f_kqlock);
1371 
1372 	if (error == 0) {
1373 		linux_set_current(td);
1374 
1375 		/* update kqfilter status, if any */
1376 		linux_file_kqfilter_poll(filp,
1377 		    LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
1378 	}
1379 	return (error);
1380 }
1381 
1382 static int
1383 linux_file_mmap_single(struct file *fp, const struct file_operations *fop,
1384     vm_ooffset_t *offset, vm_size_t size, struct vm_object **object,
1385     int nprot, bool is_shared, struct thread *td)
1386 {
1387 	struct task_struct *task;
1388 	struct vm_area_struct *vmap;
1389 	struct mm_struct *mm;
1390 	struct linux_file *filp;
1391 	vm_memattr_t attr;
1392 	int error;
1393 
1394 	filp = (struct linux_file *)fp->f_data;
1395 	filp->f_flags = fp->f_flag;
1396 
1397 	if (fop->mmap == NULL)
1398 		return (EOPNOTSUPP);
1399 
1400 	linux_set_current(td);
1401 
1402 	/*
1403 	 * The same VM object might be shared by multiple processes
1404 	 * and the mm_struct is usually freed when a process exits.
1405 	 *
1406 	 * The atomic reference below makes sure the mm_struct is
1407 	 * available as long as the vmap is in the linux_vma_head.
1408 	 */
1409 	task = current;
1410 	mm = task->mm;
1411 	if (atomic_inc_not_zero(&mm->mm_users) == 0)
1412 		return (EINVAL);
1413 
1414 	vmap = kzalloc(sizeof(*vmap), GFP_KERNEL);
1415 	vmap->vm_start = 0;
1416 	vmap->vm_end = size;
1417 	vmap->vm_pgoff = *offset / PAGE_SIZE;
1418 	vmap->vm_pfn = 0;
1419 	vmap->vm_flags = vmap->vm_page_prot = (nprot & VM_PROT_ALL);
1420 	if (is_shared)
1421 		vmap->vm_flags |= VM_SHARED;
1422 	vmap->vm_ops = NULL;
1423 	vmap->vm_file = get_file(filp);
1424 	vmap->vm_mm = mm;
1425 
1426 	if (unlikely(down_write_killable(&vmap->vm_mm->mmap_sem))) {
1427 		error = linux_get_error(task, EINTR);
1428 	} else {
1429 		error = -OPW(fp, td, fop->mmap(filp, vmap));
1430 		error = linux_get_error(task, error);
1431 		up_write(&vmap->vm_mm->mmap_sem);
1432 	}
1433 
1434 	if (error != 0) {
1435 		linux_cdev_handle_free(vmap);
1436 		return (error);
1437 	}
1438 
1439 	attr = pgprot2cachemode(vmap->vm_page_prot);
1440 
1441 	if (vmap->vm_ops != NULL) {
1442 		struct vm_area_struct *ptr;
1443 		void *vm_private_data;
1444 		bool vm_no_fault;
1445 
1446 		if (vmap->vm_ops->open == NULL ||
1447 		    vmap->vm_ops->close == NULL ||
1448 		    vmap->vm_private_data == NULL) {
1449 			/* free allocated VM area struct */
1450 			linux_cdev_handle_free(vmap);
1451 			return (EINVAL);
1452 		}
1453 
1454 		vm_private_data = vmap->vm_private_data;
1455 
1456 		rw_wlock(&linux_vma_lock);
1457 		TAILQ_FOREACH(ptr, &linux_vma_head, vm_entry) {
1458 			if (ptr->vm_private_data == vm_private_data)
1459 				break;
1460 		}
1461 		/* check if there is an existing VM area struct */
1462 		if (ptr != NULL) {
1463 			/* check if the VM area structure is invalid */
1464 			if (ptr->vm_ops == NULL ||
1465 			    ptr->vm_ops->open == NULL ||
1466 			    ptr->vm_ops->close == NULL) {
1467 				error = ESTALE;
1468 				vm_no_fault = 1;
1469 			} else {
1470 				error = EEXIST;
1471 				vm_no_fault = (ptr->vm_ops->fault == NULL);
1472 			}
1473 		} else {
1474 			/* insert VM area structure into list */
1475 			TAILQ_INSERT_TAIL(&linux_vma_head, vmap, vm_entry);
1476 			error = 0;
1477 			vm_no_fault = (vmap->vm_ops->fault == NULL);
1478 		}
1479 		rw_wunlock(&linux_vma_lock);
1480 
1481 		if (error != 0) {
1482 			/* free allocated VM area struct */
1483 			linux_cdev_handle_free(vmap);
1484 			/* check for stale VM area struct */
1485 			if (error != EEXIST)
1486 				return (error);
1487 		}
1488 
1489 		/* check if there is no fault handler */
1490 		if (vm_no_fault) {
1491 			*object = cdev_pager_allocate(vm_private_data, OBJT_DEVICE,
1492 			    &linux_cdev_pager_ops[1], size, nprot, *offset,
1493 			    td->td_ucred);
1494 		} else {
1495 			*object = cdev_pager_allocate(vm_private_data, OBJT_MGTDEVICE,
1496 			    &linux_cdev_pager_ops[0], size, nprot, *offset,
1497 			    td->td_ucred);
1498 		}
1499 
1500 		/* check if allocating the VM object failed */
1501 		if (*object == NULL) {
1502 			if (error == 0) {
1503 				/* remove VM area struct from list */
1504 				linux_cdev_handle_remove(vmap);
1505 				/* free allocated VM area struct */
1506 				linux_cdev_handle_free(vmap);
1507 			}
1508 			return (EINVAL);
1509 		}
1510 	} else {
1511 		struct sglist *sg;
1512 
1513 		sg = sglist_alloc(1, M_WAITOK);
1514 		sglist_append_phys(sg,
1515 		    (vm_paddr_t)vmap->vm_pfn << PAGE_SHIFT, vmap->vm_len);
1516 
1517 		*object = vm_pager_allocate(OBJT_SG, sg, vmap->vm_len,
1518 		    nprot, 0, td->td_ucred);
1519 
1520 		linux_cdev_handle_free(vmap);
1521 
1522 		if (*object == NULL) {
1523 			sglist_free(sg);
1524 			return (EINVAL);
1525 		}
1526 	}
1527 
1528 	if (attr != VM_MEMATTR_DEFAULT) {
1529 		VM_OBJECT_WLOCK(*object);
1530 		vm_object_set_memattr(*object, attr);
1531 		VM_OBJECT_WUNLOCK(*object);
1532 	}
1533 	*offset = 0;
1534 	return (0);
1535 }
1536 
1537 struct cdevsw linuxcdevsw = {
1538 	.d_version = D_VERSION,
1539 	.d_fdopen = linux_dev_fdopen,
1540 	.d_name = "lkpidev",
1541 };
1542 
1543 static int
1544 linux_file_read(struct file *file, struct uio *uio, struct ucred *active_cred,
1545     int flags, struct thread *td)
1546 {
1547 	struct linux_file *filp;
1548 	const struct file_operations *fop;
1549 	struct linux_cdev *ldev;
1550 	ssize_t bytes;
1551 	int error;
1552 
1553 	error = 0;
1554 	filp = (struct linux_file *)file->f_data;
1555 	filp->f_flags = file->f_flag;
1556 	/* XXX no support for I/O vectors currently */
1557 	if (uio->uio_iovcnt != 1)
1558 		return (EOPNOTSUPP);
1559 	if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1560 		return (EINVAL);
1561 	linux_set_current(td);
1562 	linux_get_fop(filp, &fop, &ldev);
1563 	if (fop->read != NULL) {
1564 		bytes = OPW(file, td, fop->read(filp,
1565 		    uio->uio_iov->iov_base,
1566 		    uio->uio_iov->iov_len, &uio->uio_offset));
1567 		if (bytes >= 0) {
1568 			uio->uio_iov->iov_base =
1569 			    ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1570 			uio->uio_iov->iov_len -= bytes;
1571 			uio->uio_resid -= bytes;
1572 		} else {
1573 			error = linux_get_error(current, -bytes);
1574 		}
1575 	} else
1576 		error = ENXIO;
1577 
1578 	/* update kqfilter status, if any */
1579 	linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_READ);
1580 	linux_drop_fop(ldev);
1581 
1582 	return (error);
1583 }
1584 
1585 static int
1586 linux_file_write(struct file *file, struct uio *uio, struct ucred *active_cred,
1587     int flags, struct thread *td)
1588 {
1589 	struct linux_file *filp;
1590 	const struct file_operations *fop;
1591 	struct linux_cdev *ldev;
1592 	ssize_t bytes;
1593 	int error;
1594 
1595 	filp = (struct linux_file *)file->f_data;
1596 	filp->f_flags = file->f_flag;
1597 	/* XXX no support for I/O vectors currently */
1598 	if (uio->uio_iovcnt != 1)
1599 		return (EOPNOTSUPP);
1600 	if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1601 		return (EINVAL);
1602 	linux_set_current(td);
1603 	linux_get_fop(filp, &fop, &ldev);
1604 	if (fop->write != NULL) {
1605 		bytes = OPW(file, td, fop->write(filp,
1606 		    uio->uio_iov->iov_base,
1607 		    uio->uio_iov->iov_len, &uio->uio_offset));
1608 		if (bytes >= 0) {
1609 			uio->uio_iov->iov_base =
1610 			    ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1611 			uio->uio_iov->iov_len -= bytes;
1612 			uio->uio_resid -= bytes;
1613 			error = 0;
1614 		} else {
1615 			error = linux_get_error(current, -bytes);
1616 		}
1617 	} else
1618 		error = ENXIO;
1619 
1620 	/* update kqfilter status, if any */
1621 	linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_WRITE);
1622 
1623 	linux_drop_fop(ldev);
1624 
1625 	return (error);
1626 }
1627 
1628 static int
1629 linux_file_poll(struct file *file, int events, struct ucred *active_cred,
1630     struct thread *td)
1631 {
1632 	struct linux_file *filp;
1633 	const struct file_operations *fop;
1634 	struct linux_cdev *ldev;
1635 	int revents;
1636 
1637 	filp = (struct linux_file *)file->f_data;
1638 	filp->f_flags = file->f_flag;
1639 	linux_set_current(td);
1640 	linux_get_fop(filp, &fop, &ldev);
1641 	if (fop->poll != NULL) {
1642 		revents = OPW(file, td, fop->poll(filp,
1643 		    LINUX_POLL_TABLE_NORMAL)) & events;
1644 	} else {
1645 		revents = 0;
1646 	}
1647 	linux_drop_fop(ldev);
1648 	return (revents);
1649 }
1650 
1651 static int
1652 linux_file_close(struct file *file, struct thread *td)
1653 {
1654 	struct linux_file *filp;
1655 	int (*release)(struct inode *, struct linux_file *);
1656 	const struct file_operations *fop;
1657 	struct linux_cdev *ldev;
1658 	int error;
1659 
1660 	filp = (struct linux_file *)file->f_data;
1661 
1662 	KASSERT(file_count(filp) == 0,
1663 	    ("File refcount(%d) is not zero", file_count(filp)));
1664 
1665 	if (td == NULL)
1666 		td = curthread;
1667 
1668 	error = 0;
1669 	filp->f_flags = file->f_flag;
1670 	linux_set_current(td);
1671 	linux_poll_wait_dequeue(filp);
1672 	linux_get_fop(filp, &fop, &ldev);
1673 	/*
1674 	 * Always use the real release function, if any, to avoid
1675 	 * leaking device resources:
1676 	 */
1677 	release = filp->f_op->release;
1678 	if (release != NULL)
1679 		error = -OPW(file, td, release(filp->f_vnode, filp));
1680 	funsetown(&filp->f_sigio);
1681 	if (filp->f_vnode != NULL)
1682 		vdrop(filp->f_vnode);
1683 	linux_drop_fop(ldev);
1684 	ldev = filp->f_cdev;
1685 	if (ldev != NULL)
1686 		linux_cdev_deref(ldev);
1687 	linux_synchronize_rcu(RCU_TYPE_REGULAR);
1688 	kfree(filp);
1689 
1690 	return (error);
1691 }
1692 
1693 static int
1694 linux_file_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *cred,
1695     struct thread *td)
1696 {
1697 	struct linux_file *filp;
1698 	const struct file_operations *fop;
1699 	struct linux_cdev *ldev;
1700 	struct fiodgname_arg *fgn;
1701 	const char *p;
1702 	int error, i;
1703 
1704 	error = 0;
1705 	filp = (struct linux_file *)fp->f_data;
1706 	filp->f_flags = fp->f_flag;
1707 	linux_get_fop(filp, &fop, &ldev);
1708 
1709 	linux_set_current(td);
1710 	switch (cmd) {
1711 	case FIONBIO:
1712 		break;
1713 	case FIOASYNC:
1714 		if (fop->fasync == NULL)
1715 			break;
1716 		error = -OPW(fp, td, fop->fasync(0, filp, fp->f_flag & FASYNC));
1717 		break;
1718 	case FIOSETOWN:
1719 		error = fsetown(*(int *)data, &filp->f_sigio);
1720 		if (error == 0) {
1721 			if (fop->fasync == NULL)
1722 				break;
1723 			error = -OPW(fp, td, fop->fasync(0, filp,
1724 			    fp->f_flag & FASYNC));
1725 		}
1726 		break;
1727 	case FIOGETOWN:
1728 		*(int *)data = fgetown(&filp->f_sigio);
1729 		break;
1730 	case FIODGNAME:
1731 #ifdef	COMPAT_FREEBSD32
1732 	case FIODGNAME_32:
1733 #endif
1734 		if (filp->f_cdev == NULL || filp->f_cdev->cdev == NULL) {
1735 			error = ENXIO;
1736 			break;
1737 		}
1738 		fgn = data;
1739 		p = devtoname(filp->f_cdev->cdev);
1740 		i = strlen(p) + 1;
1741 		if (i > fgn->len) {
1742 			error = EINVAL;
1743 			break;
1744 		}
1745 		error = copyout(p, fiodgname_buf_get_ptr(fgn, cmd), i);
1746 		break;
1747 	default:
1748 		error = linux_file_ioctl_sub(fp, filp, fop, cmd, data, td);
1749 		break;
1750 	}
1751 	linux_drop_fop(ldev);
1752 	return (error);
1753 }
1754 
1755 static int
1756 linux_file_mmap_sub(struct thread *td, vm_size_t objsize, vm_prot_t prot,
1757     vm_prot_t maxprot, int flags, struct file *fp,
1758     vm_ooffset_t *foff, const struct file_operations *fop, vm_object_t *objp)
1759 {
1760 	/*
1761 	 * Character devices do not provide private mappings
1762 	 * of any kind:
1763 	 */
1764 	if ((maxprot & VM_PROT_WRITE) == 0 &&
1765 	    (prot & VM_PROT_WRITE) != 0)
1766 		return (EACCES);
1767 	if ((flags & (MAP_PRIVATE | MAP_COPY)) != 0)
1768 		return (EINVAL);
1769 
1770 	return (linux_file_mmap_single(fp, fop, foff, objsize, objp,
1771 	    (int)prot, (flags & MAP_SHARED) ? true : false, td));
1772 }
1773 
1774 static int
1775 linux_file_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
1776     vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
1777     struct thread *td)
1778 {
1779 	struct linux_file *filp;
1780 	const struct file_operations *fop;
1781 	struct linux_cdev *ldev;
1782 	struct mount *mp;
1783 	struct vnode *vp;
1784 	vm_object_t object;
1785 	vm_prot_t maxprot;
1786 	int error;
1787 
1788 	filp = (struct linux_file *)fp->f_data;
1789 
1790 	vp = filp->f_vnode;
1791 	if (vp == NULL)
1792 		return (EOPNOTSUPP);
1793 
1794 	/*
1795 	 * Ensure that file and memory protections are
1796 	 * compatible.
1797 	 */
1798 	mp = vp->v_mount;
1799 	if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
1800 		maxprot = VM_PROT_NONE;
1801 		if ((prot & VM_PROT_EXECUTE) != 0)
1802 			return (EACCES);
1803 	} else
1804 		maxprot = VM_PROT_EXECUTE;
1805 	if ((fp->f_flag & FREAD) != 0)
1806 		maxprot |= VM_PROT_READ;
1807 	else if ((prot & VM_PROT_READ) != 0)
1808 		return (EACCES);
1809 
1810 	/*
1811 	 * If we are sharing potential changes via MAP_SHARED and we
1812 	 * are trying to get write permission although we opened it
1813 	 * without asking for it, bail out.
1814 	 *
1815 	 * Note that most character devices always share mappings.
1816 	 *
1817 	 * Rely on linux_file_mmap_sub() to fail invalid MAP_PRIVATE
1818 	 * requests rather than doing it here.
1819 	 */
1820 	if ((flags & MAP_SHARED) != 0) {
1821 		if ((fp->f_flag & FWRITE) != 0)
1822 			maxprot |= VM_PROT_WRITE;
1823 		else if ((prot & VM_PROT_WRITE) != 0)
1824 			return (EACCES);
1825 	}
1826 	maxprot &= cap_maxprot;
1827 
1828 	linux_get_fop(filp, &fop, &ldev);
1829 	error = linux_file_mmap_sub(td, size, prot, maxprot, flags, fp,
1830 	    &foff, fop, &object);
1831 	if (error != 0)
1832 		goto out;
1833 
1834 	error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
1835 	    foff, FALSE, td);
1836 	if (error != 0)
1837 		vm_object_deallocate(object);
1838 out:
1839 	linux_drop_fop(ldev);
1840 	return (error);
1841 }
1842 
1843 static int
1844 linux_file_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
1845 {
1846 	struct linux_file *filp;
1847 	struct vnode *vp;
1848 	int error;
1849 
1850 	filp = (struct linux_file *)fp->f_data;
1851 	if (filp->f_vnode == NULL)
1852 		return (EOPNOTSUPP);
1853 
1854 	vp = filp->f_vnode;
1855 
1856 	vn_lock(vp, LK_SHARED | LK_RETRY);
1857 	error = VOP_STAT(vp, sb, curthread->td_ucred, NOCRED);
1858 	VOP_UNLOCK(vp);
1859 
1860 	return (error);
1861 }
1862 
1863 static int
1864 linux_file_fill_kinfo(struct file *fp, struct kinfo_file *kif,
1865     struct filedesc *fdp)
1866 {
1867 	struct linux_file *filp;
1868 	struct vnode *vp;
1869 	int error;
1870 
1871 	filp = fp->f_data;
1872 	vp = filp->f_vnode;
1873 	if (vp == NULL) {
1874 		error = 0;
1875 		kif->kf_type = KF_TYPE_DEV;
1876 	} else {
1877 		vref(vp);
1878 		FILEDESC_SUNLOCK(fdp);
1879 		error = vn_fill_kinfo_vnode(vp, kif);
1880 		vrele(vp);
1881 		kif->kf_type = KF_TYPE_VNODE;
1882 		FILEDESC_SLOCK(fdp);
1883 	}
1884 	return (error);
1885 }
1886 
1887 unsigned int
1888 linux_iminor(struct inode *inode)
1889 {
1890 	struct linux_cdev *ldev;
1891 
1892 	if (inode == NULL || inode->v_rdev == NULL ||
1893 	    inode->v_rdev->si_devsw != &linuxcdevsw)
1894 		return (-1U);
1895 	ldev = inode->v_rdev->si_drv1;
1896 	if (ldev == NULL)
1897 		return (-1U);
1898 
1899 	return (minor(ldev->dev));
1900 }
1901 
1902 struct fileops linuxfileops = {
1903 	.fo_read = linux_file_read,
1904 	.fo_write = linux_file_write,
1905 	.fo_truncate = invfo_truncate,
1906 	.fo_kqfilter = linux_file_kqfilter,
1907 	.fo_stat = linux_file_stat,
1908 	.fo_fill_kinfo = linux_file_fill_kinfo,
1909 	.fo_poll = linux_file_poll,
1910 	.fo_close = linux_file_close,
1911 	.fo_ioctl = linux_file_ioctl,
1912 	.fo_mmap = linux_file_mmap,
1913 	.fo_chmod = invfo_chmod,
1914 	.fo_chown = invfo_chown,
1915 	.fo_sendfile = invfo_sendfile,
1916 	.fo_flags = DFLAG_PASSABLE,
1917 };
1918 
1919 /*
1920  * Hash of vmmap addresses.  This is infrequently accessed and does not
1921  * need to be particularly large.  This is done because we must store the
1922  * caller's idea of the map size to properly unmap.
1923  */
1924 struct vmmap {
1925 	LIST_ENTRY(vmmap)	vm_next;
1926 	void 			*vm_addr;
1927 	unsigned long		vm_size;
1928 };
1929 
1930 struct vmmaphd {
1931 	struct vmmap *lh_first;
1932 };
1933 #define	VMMAP_HASH_SIZE	64
1934 #define	VMMAP_HASH_MASK	(VMMAP_HASH_SIZE - 1)
1935 #define	VM_HASH(addr)	((uintptr_t)(addr) >> PAGE_SHIFT) & VMMAP_HASH_MASK
1936 static struct vmmaphd vmmaphead[VMMAP_HASH_SIZE];
1937 static struct mtx vmmaplock;
1938 
1939 static void
1940 vmmap_add(void *addr, unsigned long size)
1941 {
1942 	struct vmmap *vmmap;
1943 
1944 	vmmap = kmalloc(sizeof(*vmmap), GFP_KERNEL);
1945 	mtx_lock(&vmmaplock);
1946 	vmmap->vm_size = size;
1947 	vmmap->vm_addr = addr;
1948 	LIST_INSERT_HEAD(&vmmaphead[VM_HASH(addr)], vmmap, vm_next);
1949 	mtx_unlock(&vmmaplock);
1950 }
1951 
1952 static struct vmmap *
1953 vmmap_remove(void *addr)
1954 {
1955 	struct vmmap *vmmap;
1956 
1957 	mtx_lock(&vmmaplock);
1958 	LIST_FOREACH(vmmap, &vmmaphead[VM_HASH(addr)], vm_next)
1959 		if (vmmap->vm_addr == addr)
1960 			break;
1961 	if (vmmap)
1962 		LIST_REMOVE(vmmap, vm_next);
1963 	mtx_unlock(&vmmaplock);
1964 
1965 	return (vmmap);
1966 }
1967 
1968 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__) || defined(__aarch64__) || defined(__riscv)
1969 void *
1970 _ioremap_attr(vm_paddr_t phys_addr, unsigned long size, int attr)
1971 {
1972 	void *addr;
1973 
1974 	addr = pmap_mapdev_attr(phys_addr, size, attr);
1975 	if (addr == NULL)
1976 		return (NULL);
1977 	vmmap_add(addr, size);
1978 
1979 	return (addr);
1980 }
1981 #endif
1982 
1983 void
1984 iounmap(void *addr)
1985 {
1986 	struct vmmap *vmmap;
1987 
1988 	vmmap = vmmap_remove(addr);
1989 	if (vmmap == NULL)
1990 		return;
1991 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__) || defined(__aarch64__) || defined(__riscv)
1992 	pmap_unmapdev(addr, vmmap->vm_size);
1993 #endif
1994 	kfree(vmmap);
1995 }
1996 
1997 void *
1998 vmap(struct page **pages, unsigned int count, unsigned long flags, int prot)
1999 {
2000 	vm_offset_t off;
2001 	size_t size;
2002 
2003 	size = count * PAGE_SIZE;
2004 	off = kva_alloc(size);
2005 	if (off == 0)
2006 		return (NULL);
2007 	vmmap_add((void *)off, size);
2008 	pmap_qenter(off, pages, count);
2009 
2010 	return ((void *)off);
2011 }
2012 
2013 void
2014 vunmap(void *addr)
2015 {
2016 	struct vmmap *vmmap;
2017 
2018 	vmmap = vmmap_remove(addr);
2019 	if (vmmap == NULL)
2020 		return;
2021 	pmap_qremove((vm_offset_t)addr, vmmap->vm_size / PAGE_SIZE);
2022 	kva_free((vm_offset_t)addr, vmmap->vm_size);
2023 	kfree(vmmap);
2024 }
2025 
2026 static char *
2027 devm_kvasprintf(struct device *dev, gfp_t gfp, const char *fmt, va_list ap)
2028 {
2029 	unsigned int len;
2030 	char *p;
2031 	va_list aq;
2032 
2033 	va_copy(aq, ap);
2034 	len = vsnprintf(NULL, 0, fmt, aq);
2035 	va_end(aq);
2036 
2037 	if (dev != NULL)
2038 		p = devm_kmalloc(dev, len + 1, gfp);
2039 	else
2040 		p = kmalloc(len + 1, gfp);
2041 	if (p != NULL)
2042 		vsnprintf(p, len + 1, fmt, ap);
2043 
2044 	return (p);
2045 }
2046 
2047 char *
2048 kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
2049 {
2050 
2051 	return (devm_kvasprintf(NULL, gfp, fmt, ap));
2052 }
2053 
2054 char *
2055 lkpi_devm_kasprintf(struct device *dev, gfp_t gfp, const char *fmt, ...)
2056 {
2057 	va_list ap;
2058 	char *p;
2059 
2060 	va_start(ap, fmt);
2061 	p = devm_kvasprintf(dev, gfp, fmt, ap);
2062 	va_end(ap);
2063 
2064 	return (p);
2065 }
2066 
2067 char *
2068 kasprintf(gfp_t gfp, const char *fmt, ...)
2069 {
2070 	va_list ap;
2071 	char *p;
2072 
2073 	va_start(ap, fmt);
2074 	p = kvasprintf(gfp, fmt, ap);
2075 	va_end(ap);
2076 
2077 	return (p);
2078 }
2079 
2080 static void
2081 linux_timer_callback_wrapper(void *context)
2082 {
2083 	struct timer_list *timer;
2084 
2085 	timer = context;
2086 
2087 	if (linux_set_current_flags(curthread, M_NOWAIT)) {
2088 		/* try again later */
2089 		callout_reset(&timer->callout, 1,
2090 		    &linux_timer_callback_wrapper, timer);
2091 		return;
2092 	}
2093 
2094 	timer->function(timer->data);
2095 }
2096 
2097 int
2098 mod_timer(struct timer_list *timer, int expires)
2099 {
2100 	int ret;
2101 
2102 	timer->expires = expires;
2103 	ret = callout_reset(&timer->callout,
2104 	    linux_timer_jiffies_until(expires),
2105 	    &linux_timer_callback_wrapper, timer);
2106 
2107 	MPASS(ret == 0 || ret == 1);
2108 
2109 	return (ret == 1);
2110 }
2111 
2112 void
2113 add_timer(struct timer_list *timer)
2114 {
2115 
2116 	callout_reset(&timer->callout,
2117 	    linux_timer_jiffies_until(timer->expires),
2118 	    &linux_timer_callback_wrapper, timer);
2119 }
2120 
2121 void
2122 add_timer_on(struct timer_list *timer, int cpu)
2123 {
2124 
2125 	callout_reset_on(&timer->callout,
2126 	    linux_timer_jiffies_until(timer->expires),
2127 	    &linux_timer_callback_wrapper, timer, cpu);
2128 }
2129 
2130 int
2131 del_timer(struct timer_list *timer)
2132 {
2133 
2134 	if (callout_stop(&(timer)->callout) == -1)
2135 		return (0);
2136 	return (1);
2137 }
2138 
2139 int
2140 del_timer_sync(struct timer_list *timer)
2141 {
2142 
2143 	if (callout_drain(&(timer)->callout) == -1)
2144 		return (0);
2145 	return (1);
2146 }
2147 
2148 /* greatest common divisor, Euclid equation */
2149 static uint64_t
2150 lkpi_gcd_64(uint64_t a, uint64_t b)
2151 {
2152 	uint64_t an;
2153 	uint64_t bn;
2154 
2155 	while (b != 0) {
2156 		an = b;
2157 		bn = a % b;
2158 		a = an;
2159 		b = bn;
2160 	}
2161 	return (a);
2162 }
2163 
2164 uint64_t lkpi_nsec2hz_rem;
2165 uint64_t lkpi_nsec2hz_div = 1000000000ULL;
2166 uint64_t lkpi_nsec2hz_max;
2167 
2168 uint64_t lkpi_usec2hz_rem;
2169 uint64_t lkpi_usec2hz_div = 1000000ULL;
2170 uint64_t lkpi_usec2hz_max;
2171 
2172 uint64_t lkpi_msec2hz_rem;
2173 uint64_t lkpi_msec2hz_div = 1000ULL;
2174 uint64_t lkpi_msec2hz_max;
2175 
2176 static void
2177 linux_timer_init(void *arg)
2178 {
2179 	uint64_t gcd;
2180 
2181 	/*
2182 	 * Compute an internal HZ value which can divide 2**32 to
2183 	 * avoid timer rounding problems when the tick value wraps
2184 	 * around 2**32:
2185 	 */
2186 	linux_timer_hz_mask = 1;
2187 	while (linux_timer_hz_mask < (unsigned long)hz)
2188 		linux_timer_hz_mask *= 2;
2189 	linux_timer_hz_mask--;
2190 
2191 	/* compute some internal constants */
2192 
2193 	lkpi_nsec2hz_rem = hz;
2194 	lkpi_usec2hz_rem = hz;
2195 	lkpi_msec2hz_rem = hz;
2196 
2197 	gcd = lkpi_gcd_64(lkpi_nsec2hz_rem, lkpi_nsec2hz_div);
2198 	lkpi_nsec2hz_rem /= gcd;
2199 	lkpi_nsec2hz_div /= gcd;
2200 	lkpi_nsec2hz_max = -1ULL / lkpi_nsec2hz_rem;
2201 
2202 	gcd = lkpi_gcd_64(lkpi_usec2hz_rem, lkpi_usec2hz_div);
2203 	lkpi_usec2hz_rem /= gcd;
2204 	lkpi_usec2hz_div /= gcd;
2205 	lkpi_usec2hz_max = -1ULL / lkpi_usec2hz_rem;
2206 
2207 	gcd = lkpi_gcd_64(lkpi_msec2hz_rem, lkpi_msec2hz_div);
2208 	lkpi_msec2hz_rem /= gcd;
2209 	lkpi_msec2hz_div /= gcd;
2210 	lkpi_msec2hz_max = -1ULL / lkpi_msec2hz_rem;
2211 }
2212 SYSINIT(linux_timer, SI_SUB_DRIVERS, SI_ORDER_FIRST, linux_timer_init, NULL);
2213 
2214 void
2215 linux_complete_common(struct completion *c, int all)
2216 {
2217 	int wakeup_swapper;
2218 
2219 	sleepq_lock(c);
2220 	if (all) {
2221 		c->done = UINT_MAX;
2222 		wakeup_swapper = sleepq_broadcast(c, SLEEPQ_SLEEP, 0, 0);
2223 	} else {
2224 		if (c->done != UINT_MAX)
2225 			c->done++;
2226 		wakeup_swapper = sleepq_signal(c, SLEEPQ_SLEEP, 0, 0);
2227 	}
2228 	sleepq_release(c);
2229 	if (wakeup_swapper)
2230 		kick_proc0();
2231 }
2232 
2233 /*
2234  * Indefinite wait for done != 0 with or without signals.
2235  */
2236 int
2237 linux_wait_for_common(struct completion *c, int flags)
2238 {
2239 	struct task_struct *task;
2240 	int error;
2241 
2242 	if (SCHEDULER_STOPPED())
2243 		return (0);
2244 
2245 	task = current;
2246 
2247 	if (flags != 0)
2248 		flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
2249 	else
2250 		flags = SLEEPQ_SLEEP;
2251 	error = 0;
2252 	for (;;) {
2253 		sleepq_lock(c);
2254 		if (c->done)
2255 			break;
2256 		sleepq_add(c, NULL, "completion", flags, 0);
2257 		if (flags & SLEEPQ_INTERRUPTIBLE) {
2258 			DROP_GIANT();
2259 			error = -sleepq_wait_sig(c, 0);
2260 			PICKUP_GIANT();
2261 			if (error != 0) {
2262 				linux_schedule_save_interrupt_value(task, error);
2263 				error = -ERESTARTSYS;
2264 				goto intr;
2265 			}
2266 		} else {
2267 			DROP_GIANT();
2268 			sleepq_wait(c, 0);
2269 			PICKUP_GIANT();
2270 		}
2271 	}
2272 	if (c->done != UINT_MAX)
2273 		c->done--;
2274 	sleepq_release(c);
2275 
2276 intr:
2277 	return (error);
2278 }
2279 
2280 /*
2281  * Time limited wait for done != 0 with or without signals.
2282  */
2283 int
2284 linux_wait_for_timeout_common(struct completion *c, int timeout, int flags)
2285 {
2286 	struct task_struct *task;
2287 	int end = jiffies + timeout;
2288 	int error;
2289 
2290 	if (SCHEDULER_STOPPED())
2291 		return (0);
2292 
2293 	task = current;
2294 
2295 	if (flags != 0)
2296 		flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
2297 	else
2298 		flags = SLEEPQ_SLEEP;
2299 
2300 	for (;;) {
2301 		sleepq_lock(c);
2302 		if (c->done)
2303 			break;
2304 		sleepq_add(c, NULL, "completion", flags, 0);
2305 		sleepq_set_timeout(c, linux_timer_jiffies_until(end));
2306 
2307 		DROP_GIANT();
2308 		if (flags & SLEEPQ_INTERRUPTIBLE)
2309 			error = -sleepq_timedwait_sig(c, 0);
2310 		else
2311 			error = -sleepq_timedwait(c, 0);
2312 		PICKUP_GIANT();
2313 
2314 		if (error != 0) {
2315 			/* check for timeout */
2316 			if (error == -EWOULDBLOCK) {
2317 				error = 0;	/* timeout */
2318 			} else {
2319 				/* signal happened */
2320 				linux_schedule_save_interrupt_value(task, error);
2321 				error = -ERESTARTSYS;
2322 			}
2323 			goto done;
2324 		}
2325 	}
2326 	if (c->done != UINT_MAX)
2327 		c->done--;
2328 	sleepq_release(c);
2329 
2330 	/* return how many jiffies are left */
2331 	error = linux_timer_jiffies_until(end);
2332 done:
2333 	return (error);
2334 }
2335 
2336 int
2337 linux_try_wait_for_completion(struct completion *c)
2338 {
2339 	int isdone;
2340 
2341 	sleepq_lock(c);
2342 	isdone = (c->done != 0);
2343 	if (c->done != 0 && c->done != UINT_MAX)
2344 		c->done--;
2345 	sleepq_release(c);
2346 	return (isdone);
2347 }
2348 
2349 int
2350 linux_completion_done(struct completion *c)
2351 {
2352 	int isdone;
2353 
2354 	sleepq_lock(c);
2355 	isdone = (c->done != 0);
2356 	sleepq_release(c);
2357 	return (isdone);
2358 }
2359 
2360 static void
2361 linux_cdev_deref(struct linux_cdev *ldev)
2362 {
2363 	if (refcount_release(&ldev->refs) &&
2364 	    ldev->kobj.ktype == &linux_cdev_ktype)
2365 		kfree(ldev);
2366 }
2367 
2368 static void
2369 linux_cdev_release(struct kobject *kobj)
2370 {
2371 	struct linux_cdev *cdev;
2372 	struct kobject *parent;
2373 
2374 	cdev = container_of(kobj, struct linux_cdev, kobj);
2375 	parent = kobj->parent;
2376 	linux_destroy_dev(cdev);
2377 	linux_cdev_deref(cdev);
2378 	kobject_put(parent);
2379 }
2380 
2381 static void
2382 linux_cdev_static_release(struct kobject *kobj)
2383 {
2384 	struct cdev *cdev;
2385 	struct linux_cdev *ldev;
2386 
2387 	ldev = container_of(kobj, struct linux_cdev, kobj);
2388 	cdev = ldev->cdev;
2389 	if (cdev != NULL) {
2390 		destroy_dev(cdev);
2391 		ldev->cdev = NULL;
2392 	}
2393 	kobject_put(kobj->parent);
2394 }
2395 
2396 int
2397 linux_cdev_device_add(struct linux_cdev *ldev, struct device *dev)
2398 {
2399 	int ret;
2400 
2401 	if (dev->devt != 0) {
2402 		/* Set parent kernel object. */
2403 		ldev->kobj.parent = &dev->kobj;
2404 
2405 		/*
2406 		 * Unlike Linux we require the kobject of the
2407 		 * character device structure to have a valid name
2408 		 * before calling this function:
2409 		 */
2410 		if (ldev->kobj.name == NULL)
2411 			return (-EINVAL);
2412 
2413 		ret = cdev_add(ldev, dev->devt, 1);
2414 		if (ret)
2415 			return (ret);
2416 	}
2417 	ret = device_add(dev);
2418 	if (ret != 0 && dev->devt != 0)
2419 		cdev_del(ldev);
2420 	return (ret);
2421 }
2422 
2423 void
2424 linux_cdev_device_del(struct linux_cdev *ldev, struct device *dev)
2425 {
2426 	device_del(dev);
2427 
2428 	if (dev->devt != 0)
2429 		cdev_del(ldev);
2430 }
2431 
2432 static void
2433 linux_destroy_dev(struct linux_cdev *ldev)
2434 {
2435 
2436 	if (ldev->cdev == NULL)
2437 		return;
2438 
2439 	MPASS((ldev->siref & LDEV_SI_DTR) == 0);
2440 	MPASS(ldev->kobj.ktype == &linux_cdev_ktype);
2441 
2442 	atomic_set_int(&ldev->siref, LDEV_SI_DTR);
2443 	while ((atomic_load_int(&ldev->siref) & ~LDEV_SI_DTR) != 0)
2444 		pause("ldevdtr", hz / 4);
2445 
2446 	destroy_dev(ldev->cdev);
2447 	ldev->cdev = NULL;
2448 }
2449 
2450 const struct kobj_type linux_cdev_ktype = {
2451 	.release = linux_cdev_release,
2452 };
2453 
2454 const struct kobj_type linux_cdev_static_ktype = {
2455 	.release = linux_cdev_static_release,
2456 };
2457 
2458 static void
2459 linux_handle_ifnet_link_event(void *arg, struct ifnet *ifp, int linkstate)
2460 {
2461 	struct notifier_block *nb;
2462 	struct netdev_notifier_info ni;
2463 
2464 	nb = arg;
2465 	ni.ifp = ifp;
2466 	ni.dev = (struct net_device *)ifp;
2467 	if (linkstate == LINK_STATE_UP)
2468 		nb->notifier_call(nb, NETDEV_UP, &ni);
2469 	else
2470 		nb->notifier_call(nb, NETDEV_DOWN, &ni);
2471 }
2472 
2473 static void
2474 linux_handle_ifnet_arrival_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_REGISTER, &ni);
2483 }
2484 
2485 static void
2486 linux_handle_ifnet_departure_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_UNREGISTER, &ni);
2495 }
2496 
2497 static void
2498 linux_handle_iflladdr_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_CHANGEADDR, &ni);
2507 }
2508 
2509 static void
2510 linux_handle_ifaddr_event(void *arg, struct ifnet *ifp)
2511 {
2512 	struct notifier_block *nb;
2513 	struct netdev_notifier_info ni;
2514 
2515 	nb = arg;
2516 	ni.ifp = ifp;
2517 	ni.dev = (struct net_device *)ifp;
2518 	nb->notifier_call(nb, NETDEV_CHANGEIFADDR, &ni);
2519 }
2520 
2521 int
2522 register_netdevice_notifier(struct notifier_block *nb)
2523 {
2524 
2525 	nb->tags[NETDEV_UP] = EVENTHANDLER_REGISTER(
2526 	    ifnet_link_event, linux_handle_ifnet_link_event, nb, 0);
2527 	nb->tags[NETDEV_REGISTER] = EVENTHANDLER_REGISTER(
2528 	    ifnet_arrival_event, linux_handle_ifnet_arrival_event, nb, 0);
2529 	nb->tags[NETDEV_UNREGISTER] = EVENTHANDLER_REGISTER(
2530 	    ifnet_departure_event, linux_handle_ifnet_departure_event, nb, 0);
2531 	nb->tags[NETDEV_CHANGEADDR] = EVENTHANDLER_REGISTER(
2532 	    iflladdr_event, linux_handle_iflladdr_event, nb, 0);
2533 
2534 	return (0);
2535 }
2536 
2537 int
2538 register_inetaddr_notifier(struct notifier_block *nb)
2539 {
2540 
2541 	nb->tags[NETDEV_CHANGEIFADDR] = EVENTHANDLER_REGISTER(
2542 	    ifaddr_event, linux_handle_ifaddr_event, nb, 0);
2543 	return (0);
2544 }
2545 
2546 int
2547 unregister_netdevice_notifier(struct notifier_block *nb)
2548 {
2549 
2550 	EVENTHANDLER_DEREGISTER(ifnet_link_event,
2551 	    nb->tags[NETDEV_UP]);
2552 	EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
2553 	    nb->tags[NETDEV_REGISTER]);
2554 	EVENTHANDLER_DEREGISTER(ifnet_departure_event,
2555 	    nb->tags[NETDEV_UNREGISTER]);
2556 	EVENTHANDLER_DEREGISTER(iflladdr_event,
2557 	    nb->tags[NETDEV_CHANGEADDR]);
2558 
2559 	return (0);
2560 }
2561 
2562 int
2563 unregister_inetaddr_notifier(struct notifier_block *nb)
2564 {
2565 
2566 	EVENTHANDLER_DEREGISTER(ifaddr_event,
2567 	    nb->tags[NETDEV_CHANGEIFADDR]);
2568 
2569 	return (0);
2570 }
2571 
2572 struct list_sort_thunk {
2573 	int (*cmp)(void *, struct list_head *, struct list_head *);
2574 	void *priv;
2575 };
2576 
2577 static inline int
2578 linux_le_cmp(const void *d1, const void *d2, void *priv)
2579 {
2580 	struct list_head *le1, *le2;
2581 	struct list_sort_thunk *thunk;
2582 
2583 	thunk = priv;
2584 	le1 = *(__DECONST(struct list_head **, d1));
2585 	le2 = *(__DECONST(struct list_head **, d2));
2586 	return ((thunk->cmp)(thunk->priv, le1, le2));
2587 }
2588 
2589 void
2590 list_sort(void *priv, struct list_head *head, int (*cmp)(void *priv,
2591     struct list_head *a, struct list_head *b))
2592 {
2593 	struct list_sort_thunk thunk;
2594 	struct list_head **ar, *le;
2595 	size_t count, i;
2596 
2597 	count = 0;
2598 	list_for_each(le, head)
2599 		count++;
2600 	ar = malloc(sizeof(struct list_head *) * count, M_KMALLOC, M_WAITOK);
2601 	i = 0;
2602 	list_for_each(le, head)
2603 		ar[i++] = le;
2604 	thunk.cmp = cmp;
2605 	thunk.priv = priv;
2606 	qsort_r(ar, count, sizeof(struct list_head *), linux_le_cmp, &thunk);
2607 	INIT_LIST_HEAD(head);
2608 	for (i = 0; i < count; i++)
2609 		list_add_tail(ar[i], head);
2610 	free(ar, M_KMALLOC);
2611 }
2612 
2613 #if defined(__i386__) || defined(__amd64__)
2614 int
2615 linux_wbinvd_on_all_cpus(void)
2616 {
2617 
2618 	pmap_invalidate_cache();
2619 	return (0);
2620 }
2621 #endif
2622 
2623 int
2624 linux_on_each_cpu(void callback(void *), void *data)
2625 {
2626 
2627 	smp_rendezvous(smp_no_rendezvous_barrier, callback,
2628 	    smp_no_rendezvous_barrier, data);
2629 	return (0);
2630 }
2631 
2632 int
2633 linux_in_atomic(void)
2634 {
2635 
2636 	return ((curthread->td_pflags & TDP_NOFAULTING) != 0);
2637 }
2638 
2639 struct linux_cdev *
2640 linux_find_cdev(const char *name, unsigned major, unsigned minor)
2641 {
2642 	dev_t dev = MKDEV(major, minor);
2643 	struct cdev *cdev;
2644 
2645 	dev_lock();
2646 	LIST_FOREACH(cdev, &linuxcdevsw.d_devs, si_list) {
2647 		struct linux_cdev *ldev = cdev->si_drv1;
2648 		if (ldev->dev == dev &&
2649 		    strcmp(kobject_name(&ldev->kobj), name) == 0) {
2650 			break;
2651 		}
2652 	}
2653 	dev_unlock();
2654 
2655 	return (cdev != NULL ? cdev->si_drv1 : NULL);
2656 }
2657 
2658 int
2659 __register_chrdev(unsigned int major, unsigned int baseminor,
2660     unsigned int count, const char *name,
2661     const struct file_operations *fops)
2662 {
2663 	struct linux_cdev *cdev;
2664 	int ret = 0;
2665 	int i;
2666 
2667 	for (i = baseminor; i < baseminor + count; i++) {
2668 		cdev = cdev_alloc();
2669 		cdev->ops = fops;
2670 		kobject_set_name(&cdev->kobj, name);
2671 
2672 		ret = cdev_add(cdev, makedev(major, i), 1);
2673 		if (ret != 0)
2674 			break;
2675 	}
2676 	return (ret);
2677 }
2678 
2679 int
2680 __register_chrdev_p(unsigned int major, unsigned int baseminor,
2681     unsigned int count, const char *name,
2682     const struct file_operations *fops, uid_t uid,
2683     gid_t gid, int mode)
2684 {
2685 	struct linux_cdev *cdev;
2686 	int ret = 0;
2687 	int i;
2688 
2689 	for (i = baseminor; i < baseminor + count; i++) {
2690 		cdev = cdev_alloc();
2691 		cdev->ops = fops;
2692 		kobject_set_name(&cdev->kobj, name);
2693 
2694 		ret = cdev_add_ext(cdev, makedev(major, i), uid, gid, mode);
2695 		if (ret != 0)
2696 			break;
2697 	}
2698 	return (ret);
2699 }
2700 
2701 void
2702 __unregister_chrdev(unsigned int major, unsigned int baseminor,
2703     unsigned int count, const char *name)
2704 {
2705 	struct linux_cdev *cdevp;
2706 	int i;
2707 
2708 	for (i = baseminor; i < baseminor + count; i++) {
2709 		cdevp = linux_find_cdev(name, major, i);
2710 		if (cdevp != NULL)
2711 			cdev_del(cdevp);
2712 	}
2713 }
2714 
2715 void
2716 linux_dump_stack(void)
2717 {
2718 #ifdef STACK
2719 	struct stack st;
2720 
2721 	stack_save(&st);
2722 	stack_print(&st);
2723 #endif
2724 }
2725 
2726 int
2727 linuxkpi_net_ratelimit(void)
2728 {
2729 
2730 	return (ppsratecheck(&lkpi_net_lastlog, &lkpi_net_curpps,
2731 	   lkpi_net_maxpps));
2732 }
2733 
2734 struct io_mapping *
2735 io_mapping_create_wc(resource_size_t base, unsigned long size)
2736 {
2737 	struct io_mapping *mapping;
2738 
2739 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2740 	if (mapping == NULL)
2741 		return (NULL);
2742 	return (io_mapping_init_wc(mapping, base, size));
2743 }
2744 
2745 #if defined(__i386__) || defined(__amd64__)
2746 bool linux_cpu_has_clflush;
2747 struct cpuinfo_x86 boot_cpu_data;
2748 struct cpuinfo_x86 __cpu_data[MAXCPU];
2749 #endif
2750 
2751 cpumask_t *
2752 lkpi_get_static_single_cpu_mask(int cpuid)
2753 {
2754 
2755 	KASSERT((cpuid >= 0 && cpuid < MAXCPU), ("%s: invalid cpuid %d\n",
2756 	    __func__, cpuid));
2757 
2758 	return (&static_single_cpu_mask[cpuid]);
2759 }
2760 
2761 static void
2762 linux_compat_init(void *arg)
2763 {
2764 	struct sysctl_oid *rootoid;
2765 	int i;
2766 
2767 #if defined(__i386__) || defined(__amd64__)
2768 	linux_cpu_has_clflush = (cpu_feature & CPUID_CLFSH);
2769 	boot_cpu_data.x86_clflush_size = cpu_clflush_line_size;
2770 	boot_cpu_data.x86_max_cores = mp_ncpus;
2771 	boot_cpu_data.x86 = CPUID_TO_FAMILY(cpu_id);
2772 	boot_cpu_data.x86_model = CPUID_TO_MODEL(cpu_id);
2773 
2774 	for (i = 0; i < MAXCPU; i++) {
2775 		__cpu_data[i].x86_clflush_size = cpu_clflush_line_size;
2776 		__cpu_data[i].x86_max_cores = mp_ncpus;
2777 		__cpu_data[i].x86 = CPUID_TO_FAMILY(cpu_id);
2778 		__cpu_data[i].x86_model = CPUID_TO_MODEL(cpu_id);
2779 	}
2780 #endif
2781 	rw_init(&linux_vma_lock, "lkpi-vma-lock");
2782 
2783 	rootoid = SYSCTL_ADD_ROOT_NODE(NULL,
2784 	    OID_AUTO, "sys", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "sys");
2785 	kobject_init(&linux_class_root, &linux_class_ktype);
2786 	kobject_set_name(&linux_class_root, "class");
2787 	linux_class_root.oidp = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(rootoid),
2788 	    OID_AUTO, "class", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "class");
2789 	kobject_init(&linux_root_device.kobj, &linux_dev_ktype);
2790 	kobject_set_name(&linux_root_device.kobj, "device");
2791 	linux_root_device.kobj.oidp = SYSCTL_ADD_NODE(NULL,
2792 	    SYSCTL_CHILDREN(rootoid), OID_AUTO, "device",
2793 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "device");
2794 	linux_root_device.bsddev = root_bus;
2795 	linux_class_misc.name = "misc";
2796 	class_register(&linux_class_misc);
2797 	INIT_LIST_HEAD(&pci_drivers);
2798 	INIT_LIST_HEAD(&pci_devices);
2799 	spin_lock_init(&pci_lock);
2800 	mtx_init(&vmmaplock, "IO Map lock", NULL, MTX_DEF);
2801 	for (i = 0; i < VMMAP_HASH_SIZE; i++)
2802 		LIST_INIT(&vmmaphead[i]);
2803 	init_waitqueue_head(&linux_bit_waitq);
2804 	init_waitqueue_head(&linux_var_waitq);
2805 
2806 	CPU_COPY(&all_cpus, &cpu_online_mask);
2807 	/*
2808 	 * Generate a single-CPU cpumask_t for each CPU (possibly) in the system.
2809 	 * CPUs are indexed from 0..(MAXCPU-1).  The entry for cpuid 0 will only
2810 	 * have itself in the cpumask, cupid 1 only itself on entry 1, and so on.
2811 	 * This is used by cpumask_of() (and possibly others in the future) for,
2812 	 * e.g., drivers to pass hints to irq_set_affinity_hint().
2813 	 */
2814 	for (i = 0; i < MAXCPU; i++)
2815 		CPU_SET(i, &static_single_cpu_mask[i]);
2816 }
2817 SYSINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_init, NULL);
2818 
2819 static void
2820 linux_compat_uninit(void *arg)
2821 {
2822 	linux_kobject_kfree_name(&linux_class_root);
2823 	linux_kobject_kfree_name(&linux_root_device.kobj);
2824 	linux_kobject_kfree_name(&linux_class_misc.kobj);
2825 
2826 	mtx_destroy(&vmmaplock);
2827 	spin_lock_destroy(&pci_lock);
2828 	rw_destroy(&linux_vma_lock);
2829 }
2830 SYSUNINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_uninit, NULL);
2831 
2832 /*
2833  * NOTE: Linux frequently uses "unsigned long" for pointer to integer
2834  * conversion and vice versa, where in FreeBSD "uintptr_t" would be
2835  * used. Assert these types have the same size, else some parts of the
2836  * LinuxKPI may not work like expected:
2837  */
2838 CTASSERT(sizeof(unsigned long) == sizeof(uintptr_t));
2839