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