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