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