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