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