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