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