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