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-2017 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 <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/malloc.h>
36 #include <sys/kernel.h>
37 #include <sys/sysctl.h>
38 #include <sys/proc.h>
39 #include <sys/sglist.h>
40 #include <sys/sleepqueue.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/bus.h>
44 #include <sys/fcntl.h>
45 #include <sys/file.h>
46 #include <sys/filio.h>
47 #include <sys/rwlock.h>
48 
49 #include <vm/vm.h>
50 #include <vm/pmap.h>
51 #include <vm/vm_object.h>
52 #include <vm/vm_page.h>
53 #include <vm/vm_pager.h>
54 
55 #include <machine/stdarg.h>
56 
57 #if defined(__i386__) || defined(__amd64__)
58 #include <machine/md_var.h>
59 #endif
60 
61 #include <linux/kobject.h>
62 #include <linux/device.h>
63 #include <linux/slab.h>
64 #include <linux/module.h>
65 #include <linux/moduleparam.h>
66 #include <linux/cdev.h>
67 #include <linux/file.h>
68 #include <linux/sysfs.h>
69 #include <linux/mm.h>
70 #include <linux/io.h>
71 #include <linux/vmalloc.h>
72 #include <linux/netdevice.h>
73 #include <linux/timer.h>
74 #include <linux/interrupt.h>
75 #include <linux/uaccess.h>
76 #include <linux/list.h>
77 #include <linux/kthread.h>
78 #include <linux/kernel.h>
79 #include <linux/compat.h>
80 #include <linux/poll.h>
81 #include <linux/smp.h>
82 
83 #if defined(__i386__) || defined(__amd64__)
84 #include <asm/smp.h>
85 #endif
86 
87 SYSCTL_NODE(_compat, OID_AUTO, linuxkpi, CTLFLAG_RW, 0, "LinuxKPI parameters");
88 
89 MALLOC_DEFINE(M_KMALLOC, "linux", "Linux kmalloc compat");
90 
91 #include <linux/rbtree.h>
92 /* Undo Linux compat changes. */
93 #undef RB_ROOT
94 #undef file
95 #undef cdev
96 #define	RB_ROOT(head)	(head)->rbh_root
97 
98 static struct vm_area_struct *linux_cdev_handle_find(void *handle);
99 
100 struct kobject linux_class_root;
101 struct device linux_root_device;
102 struct class linux_class_misc;
103 struct list_head pci_drivers;
104 struct list_head pci_devices;
105 spinlock_t pci_lock;
106 
107 unsigned long linux_timer_hz_mask;
108 
109 int
110 panic_cmp(struct rb_node *one, struct rb_node *two)
111 {
112 	panic("no cmp");
113 }
114 
115 RB_GENERATE(linux_root, rb_node, __entry, panic_cmp);
116 
117 int
118 kobject_set_name_vargs(struct kobject *kobj, const char *fmt, va_list args)
119 {
120 	va_list tmp_va;
121 	int len;
122 	char *old;
123 	char *name;
124 	char dummy;
125 
126 	old = kobj->name;
127 
128 	if (old && fmt == NULL)
129 		return (0);
130 
131 	/* compute length of string */
132 	va_copy(tmp_va, args);
133 	len = vsnprintf(&dummy, 0, fmt, tmp_va);
134 	va_end(tmp_va);
135 
136 	/* account for zero termination */
137 	len++;
138 
139 	/* check for error */
140 	if (len < 1)
141 		return (-EINVAL);
142 
143 	/* allocate memory for string */
144 	name = kzalloc(len, GFP_KERNEL);
145 	if (name == NULL)
146 		return (-ENOMEM);
147 	vsnprintf(name, len, fmt, args);
148 	kobj->name = name;
149 
150 	/* free old string */
151 	kfree(old);
152 
153 	/* filter new string */
154 	for (; *name != '\0'; name++)
155 		if (*name == '/')
156 			*name = '!';
157 	return (0);
158 }
159 
160 int
161 kobject_set_name(struct kobject *kobj, const char *fmt, ...)
162 {
163 	va_list args;
164 	int error;
165 
166 	va_start(args, fmt);
167 	error = kobject_set_name_vargs(kobj, fmt, args);
168 	va_end(args);
169 
170 	return (error);
171 }
172 
173 static int
174 kobject_add_complete(struct kobject *kobj, struct kobject *parent)
175 {
176 	const struct kobj_type *t;
177 	int error;
178 
179 	kobj->parent = parent;
180 	error = sysfs_create_dir(kobj);
181 	if (error == 0 && kobj->ktype && kobj->ktype->default_attrs) {
182 		struct attribute **attr;
183 		t = kobj->ktype;
184 
185 		for (attr = t->default_attrs; *attr != NULL; attr++) {
186 			error = sysfs_create_file(kobj, *attr);
187 			if (error)
188 				break;
189 		}
190 		if (error)
191 			sysfs_remove_dir(kobj);
192 
193 	}
194 	return (error);
195 }
196 
197 int
198 kobject_add(struct kobject *kobj, struct kobject *parent, const char *fmt, ...)
199 {
200 	va_list args;
201 	int error;
202 
203 	va_start(args, fmt);
204 	error = kobject_set_name_vargs(kobj, fmt, args);
205 	va_end(args);
206 	if (error)
207 		return (error);
208 
209 	return kobject_add_complete(kobj, parent);
210 }
211 
212 void
213 linux_kobject_release(struct kref *kref)
214 {
215 	struct kobject *kobj;
216 	char *name;
217 
218 	kobj = container_of(kref, struct kobject, kref);
219 	sysfs_remove_dir(kobj);
220 	name = kobj->name;
221 	if (kobj->ktype && kobj->ktype->release)
222 		kobj->ktype->release(kobj);
223 	kfree(name);
224 }
225 
226 static void
227 linux_kobject_kfree(struct kobject *kobj)
228 {
229 	kfree(kobj);
230 }
231 
232 static void
233 linux_kobject_kfree_name(struct kobject *kobj)
234 {
235 	if (kobj) {
236 		kfree(kobj->name);
237 	}
238 }
239 
240 const struct kobj_type linux_kfree_type = {
241 	.release = linux_kobject_kfree
242 };
243 
244 static void
245 linux_device_release(struct device *dev)
246 {
247 	pr_debug("linux_device_release: %s\n", dev_name(dev));
248 	kfree(dev);
249 }
250 
251 static ssize_t
252 linux_class_show(struct kobject *kobj, struct attribute *attr, char *buf)
253 {
254 	struct class_attribute *dattr;
255 	ssize_t error;
256 
257 	dattr = container_of(attr, struct class_attribute, attr);
258 	error = -EIO;
259 	if (dattr->show)
260 		error = dattr->show(container_of(kobj, struct class, kobj),
261 		    dattr, buf);
262 	return (error);
263 }
264 
265 static ssize_t
266 linux_class_store(struct kobject *kobj, struct attribute *attr, const char *buf,
267     size_t count)
268 {
269 	struct class_attribute *dattr;
270 	ssize_t error;
271 
272 	dattr = container_of(attr, struct class_attribute, attr);
273 	error = -EIO;
274 	if (dattr->store)
275 		error = dattr->store(container_of(kobj, struct class, kobj),
276 		    dattr, buf, count);
277 	return (error);
278 }
279 
280 static void
281 linux_class_release(struct kobject *kobj)
282 {
283 	struct class *class;
284 
285 	class = container_of(kobj, struct class, kobj);
286 	if (class->class_release)
287 		class->class_release(class);
288 }
289 
290 static const struct sysfs_ops linux_class_sysfs = {
291 	.show  = linux_class_show,
292 	.store = linux_class_store,
293 };
294 
295 const struct kobj_type linux_class_ktype = {
296 	.release = linux_class_release,
297 	.sysfs_ops = &linux_class_sysfs
298 };
299 
300 static void
301 linux_dev_release(struct kobject *kobj)
302 {
303 	struct device *dev;
304 
305 	dev = container_of(kobj, struct device, kobj);
306 	/* This is the precedence defined by linux. */
307 	if (dev->release)
308 		dev->release(dev);
309 	else if (dev->class && dev->class->dev_release)
310 		dev->class->dev_release(dev);
311 }
312 
313 static ssize_t
314 linux_dev_show(struct kobject *kobj, struct attribute *attr, char *buf)
315 {
316 	struct device_attribute *dattr;
317 	ssize_t error;
318 
319 	dattr = container_of(attr, struct device_attribute, attr);
320 	error = -EIO;
321 	if (dattr->show)
322 		error = dattr->show(container_of(kobj, struct device, kobj),
323 		    dattr, buf);
324 	return (error);
325 }
326 
327 static ssize_t
328 linux_dev_store(struct kobject *kobj, struct attribute *attr, const char *buf,
329     size_t count)
330 {
331 	struct device_attribute *dattr;
332 	ssize_t error;
333 
334 	dattr = container_of(attr, struct device_attribute, attr);
335 	error = -EIO;
336 	if (dattr->store)
337 		error = dattr->store(container_of(kobj, struct device, kobj),
338 		    dattr, buf, count);
339 	return (error);
340 }
341 
342 static const struct sysfs_ops linux_dev_sysfs = {
343 	.show  = linux_dev_show,
344 	.store = linux_dev_store,
345 };
346 
347 const struct kobj_type linux_dev_ktype = {
348 	.release = linux_dev_release,
349 	.sysfs_ops = &linux_dev_sysfs
350 };
351 
352 struct device *
353 device_create(struct class *class, struct device *parent, dev_t devt,
354     void *drvdata, const char *fmt, ...)
355 {
356 	struct device *dev;
357 	va_list args;
358 
359 	dev = kzalloc(sizeof(*dev), M_WAITOK);
360 	dev->parent = parent;
361 	dev->class = class;
362 	dev->devt = devt;
363 	dev->driver_data = drvdata;
364 	dev->release = linux_device_release;
365 	va_start(args, fmt);
366 	kobject_set_name_vargs(&dev->kobj, fmt, args);
367 	va_end(args);
368 	device_register(dev);
369 
370 	return (dev);
371 }
372 
373 int
374 kobject_init_and_add(struct kobject *kobj, const struct kobj_type *ktype,
375     struct kobject *parent, const char *fmt, ...)
376 {
377 	va_list args;
378 	int error;
379 
380 	kobject_init(kobj, ktype);
381 	kobj->ktype = ktype;
382 	kobj->parent = parent;
383 	kobj->name = NULL;
384 
385 	va_start(args, fmt);
386 	error = kobject_set_name_vargs(kobj, fmt, args);
387 	va_end(args);
388 	if (error)
389 		return (error);
390 	return kobject_add_complete(kobj, parent);
391 }
392 
393 static void
394 linux_file_dtor(void *cdp)
395 {
396 	struct linux_file *filp;
397 
398 	linux_set_current(curthread);
399 	filp = cdp;
400 	filp->f_op->release(filp->f_vnode, filp);
401 	vdrop(filp->f_vnode);
402 	kfree(filp);
403 }
404 
405 static void
406 linux_kq_lock(void *arg)
407 {
408 	spinlock_t *s = arg;
409 
410 	spin_lock(s);
411 }
412 static void
413 linux_kq_unlock(void *arg)
414 {
415 	spinlock_t *s = arg;
416 
417 	spin_unlock(s);
418 }
419 
420 static void
421 linux_kq_lock_owned(void *arg)
422 {
423 #ifdef INVARIANTS
424 	spinlock_t *s = arg;
425 
426 	mtx_assert(&s->m, MA_OWNED);
427 #endif
428 }
429 
430 static void
431 linux_kq_lock_unowned(void *arg)
432 {
433 #ifdef INVARIANTS
434 	spinlock_t *s = arg;
435 
436 	mtx_assert(&s->m, MA_NOTOWNED);
437 #endif
438 }
439 
440 static void
441 linux_dev_kqfilter_poll(struct linux_file *, int);
442 
443 struct linux_file *
444 linux_file_alloc(void)
445 {
446 	struct linux_file *filp;
447 
448 	filp = kzalloc(sizeof(*filp), GFP_KERNEL);
449 
450 	/* set initial refcount */
451 	filp->f_count = 1;
452 
453 	/* setup fields needed by kqueue support */
454 	spin_lock_init(&filp->f_kqlock);
455 	knlist_init(&filp->f_selinfo.si_note, &filp->f_kqlock,
456 	    linux_kq_lock, linux_kq_unlock,
457 	    linux_kq_lock_owned, linux_kq_lock_unowned);
458 
459 	return (filp);
460 }
461 
462 void
463 linux_file_free(struct linux_file *filp)
464 {
465 	if (filp->_file == NULL) {
466 		kfree(filp);
467 	} else {
468 		/*
469 		 * The close method of the character device or file
470 		 * will free the linux_file structure:
471 		 */
472 		_fdrop(filp->_file, curthread);
473 	}
474 }
475 
476 static int
477 linux_cdev_pager_populate(vm_object_t vm_obj, vm_pindex_t pidx, int fault_type,
478     vm_prot_t max_prot, vm_pindex_t *first, vm_pindex_t *last)
479 {
480 	struct vm_area_struct *vmap;
481 	struct vm_fault vmf;
482 	int err;
483 
484 	linux_set_current(curthread);
485 
486 	/* get VM area structure */
487 	vmap = linux_cdev_handle_find(vm_obj->handle);
488 	MPASS(vmap != NULL);
489 	MPASS(vmap->vm_private_data == vm_obj->handle);
490 
491 	/* fill out VM fault structure */
492 	vmf.virtual_address = (void *)((uintptr_t)pidx << PAGE_SHIFT);
493 	vmf.flags = (fault_type & VM_PROT_WRITE) ? FAULT_FLAG_WRITE : 0;
494 	vmf.pgoff = 0;
495 	vmf.page = NULL;
496 
497 	VM_OBJECT_WUNLOCK(vm_obj);
498 
499 	down_write(&vmap->vm_mm->mmap_sem);
500 	if (unlikely(vmap->vm_ops == NULL)) {
501 		err = VM_FAULT_SIGBUS;
502 	} else {
503 		vmap->vm_pfn_count = 0;
504 		vmap->vm_pfn_pcount = &vmap->vm_pfn_count;
505 		vmap->vm_obj = vm_obj;
506 
507 		err = vmap->vm_ops->fault(vmap, &vmf);
508 
509 		while (vmap->vm_pfn_count == 0 && err == VM_FAULT_NOPAGE) {
510 			kern_yield(PRI_USER);
511 			err = vmap->vm_ops->fault(vmap, &vmf);
512 		}
513 	}
514 
515 	/* translate return code */
516 	switch (err) {
517 	case VM_FAULT_OOM:
518 		err = VM_PAGER_AGAIN;
519 		break;
520 	case VM_FAULT_SIGBUS:
521 		err = VM_PAGER_BAD;
522 		break;
523 	case VM_FAULT_NOPAGE:
524 		/*
525 		 * By contract the fault handler will return having
526 		 * busied all the pages itself. If pidx is already
527 		 * found in the object, it will simply xbusy the first
528 		 * page and return with vm_pfn_count set to 1.
529 		 */
530 		*first = vmap->vm_pfn_first;
531 		*last = *first + vmap->vm_pfn_count - 1;
532 		err = VM_PAGER_OK;
533 		break;
534 	default:
535 		err = VM_PAGER_ERROR;
536 		break;
537 	}
538 	up_write(&vmap->vm_mm->mmap_sem);
539 	VM_OBJECT_WLOCK(vm_obj);
540 	return (err);
541 }
542 
543 static struct rwlock linux_vma_lock;
544 static TAILQ_HEAD(, vm_area_struct) linux_vma_head =
545     TAILQ_HEAD_INITIALIZER(linux_vma_head);
546 
547 static void
548 linux_cdev_handle_free(struct vm_area_struct *vmap)
549 {
550 	/* Drop reference on vm_file */
551 	if (vmap->vm_file != NULL)
552 		fput(vmap->vm_file);
553 
554 	/* Drop reference on mm_struct */
555 	mmput(vmap->vm_mm);
556 
557 	kfree(vmap);
558 }
559 
560 static struct vm_area_struct *
561 linux_cdev_handle_insert(void *handle, struct vm_area_struct *vmap)
562 {
563 	struct vm_area_struct *ptr;
564 
565 	rw_wlock(&linux_vma_lock);
566 	TAILQ_FOREACH(ptr, &linux_vma_head, vm_entry) {
567 		if (ptr->vm_private_data == handle) {
568 			rw_wunlock(&linux_vma_lock);
569 			linux_cdev_handle_free(vmap);
570 			return (NULL);
571 		}
572 	}
573 	TAILQ_INSERT_TAIL(&linux_vma_head, vmap, vm_entry);
574 	rw_wunlock(&linux_vma_lock);
575 	return (vmap);
576 }
577 
578 static void
579 linux_cdev_handle_remove(struct vm_area_struct *vmap)
580 {
581 	rw_wlock(&linux_vma_lock);
582 	TAILQ_REMOVE(&linux_vma_head, vmap, vm_entry);
583 	rw_wunlock(&linux_vma_lock);
584 }
585 
586 static struct vm_area_struct *
587 linux_cdev_handle_find(void *handle)
588 {
589 	struct vm_area_struct *vmap;
590 
591 	rw_rlock(&linux_vma_lock);
592 	TAILQ_FOREACH(vmap, &linux_vma_head, vm_entry) {
593 		if (vmap->vm_private_data == handle)
594 			break;
595 	}
596 	rw_runlock(&linux_vma_lock);
597 	return (vmap);
598 }
599 
600 static int
601 linux_cdev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
602 		      vm_ooffset_t foff, struct ucred *cred, u_short *color)
603 {
604 
605 	MPASS(linux_cdev_handle_find(handle) != NULL);
606 	*color = 0;
607 	return (0);
608 }
609 
610 static void
611 linux_cdev_pager_dtor(void *handle)
612 {
613 	const struct vm_operations_struct *vm_ops;
614 	struct vm_area_struct *vmap;
615 
616 	vmap = linux_cdev_handle_find(handle);
617 	MPASS(vmap != NULL);
618 
619 	/*
620 	 * Remove handle before calling close operation to prevent
621 	 * other threads from reusing the handle pointer.
622 	 */
623 	linux_cdev_handle_remove(vmap);
624 
625 	down_write(&vmap->vm_mm->mmap_sem);
626 	vm_ops = vmap->vm_ops;
627 	if (likely(vm_ops != NULL))
628 		vm_ops->close(vmap);
629 	up_write(&vmap->vm_mm->mmap_sem);
630 
631 	linux_cdev_handle_free(vmap);
632 }
633 
634 static struct cdev_pager_ops linux_cdev_pager_ops = {
635 	.cdev_pg_populate	= linux_cdev_pager_populate,
636 	.cdev_pg_ctor	= linux_cdev_pager_ctor,
637 	.cdev_pg_dtor	= linux_cdev_pager_dtor
638 };
639 
640 static int
641 linux_dev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
642 {
643 	struct linux_cdev *ldev;
644 	struct linux_file *filp;
645 	struct file *file;
646 	int error;
647 
648 	file = td->td_fpop;
649 	ldev = dev->si_drv1;
650 	if (ldev == NULL)
651 		return (ENODEV);
652 
653 	filp = linux_file_alloc();
654 	filp->f_dentry = &filp->f_dentry_store;
655 	filp->f_op = ldev->ops;
656 	filp->f_flags = file->f_flag;
657 	vhold(file->f_vnode);
658 	filp->f_vnode = file->f_vnode;
659 	filp->_file = file;
660 
661 	linux_set_current(td);
662 
663 	if (filp->f_op->open) {
664 		error = -filp->f_op->open(file->f_vnode, filp);
665 		if (error) {
666 			vdrop(filp->f_vnode);
667 			kfree(filp);
668 			goto done;
669 		}
670 	}
671 	error = devfs_set_cdevpriv(filp, linux_file_dtor);
672 	if (error) {
673 		filp->f_op->release(file->f_vnode, filp);
674 		vdrop(filp->f_vnode);
675 		kfree(filp);
676 	}
677 done:
678 	return (error);
679 }
680 
681 static int
682 linux_dev_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
683 {
684 	struct linux_file *filp;
685 	struct file *file;
686 	int error;
687 
688 	file = td->td_fpop;
689 	if (dev->si_drv1 == NULL)
690 		return (0);
691 	if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
692 		return (error);
693 	filp->f_flags = file->f_flag;
694 	devfs_clear_cdevpriv();
695 
696 	return (0);
697 }
698 
699 #define	LINUX_IOCTL_MIN_PTR 0x10000UL
700 #define	LINUX_IOCTL_MAX_PTR (LINUX_IOCTL_MIN_PTR + IOCPARM_MAX)
701 
702 static inline int
703 linux_remap_address(void **uaddr, size_t len)
704 {
705 	uintptr_t uaddr_val = (uintptr_t)(*uaddr);
706 
707 	if (unlikely(uaddr_val >= LINUX_IOCTL_MIN_PTR &&
708 	    uaddr_val < LINUX_IOCTL_MAX_PTR)) {
709 		struct task_struct *pts = current;
710 		if (pts == NULL) {
711 			*uaddr = NULL;
712 			return (1);
713 		}
714 
715 		/* compute data offset */
716 		uaddr_val -= LINUX_IOCTL_MIN_PTR;
717 
718 		/* check that length is within bounds */
719 		if ((len > IOCPARM_MAX) ||
720 		    (uaddr_val + len) > pts->bsd_ioctl_len) {
721 			*uaddr = NULL;
722 			return (1);
723 		}
724 
725 		/* re-add kernel buffer address */
726 		uaddr_val += (uintptr_t)pts->bsd_ioctl_data;
727 
728 		/* update address location */
729 		*uaddr = (void *)uaddr_val;
730 		return (1);
731 	}
732 	return (0);
733 }
734 
735 int
736 linux_copyin(const void *uaddr, void *kaddr, size_t len)
737 {
738 	if (linux_remap_address(__DECONST(void **, &uaddr), len)) {
739 		if (uaddr == NULL)
740 			return (-EFAULT);
741 		memcpy(kaddr, uaddr, len);
742 		return (0);
743 	}
744 	return (-copyin(uaddr, kaddr, len));
745 }
746 
747 int
748 linux_copyout(const void *kaddr, void *uaddr, size_t len)
749 {
750 	if (linux_remap_address(&uaddr, len)) {
751 		if (uaddr == NULL)
752 			return (-EFAULT);
753 		memcpy(uaddr, kaddr, len);
754 		return (0);
755 	}
756 	return (-copyout(kaddr, uaddr, len));
757 }
758 
759 size_t
760 linux_clear_user(void *_uaddr, size_t _len)
761 {
762 	uint8_t *uaddr = _uaddr;
763 	size_t len = _len;
764 
765 	/* make sure uaddr is aligned before going into the fast loop */
766 	while (((uintptr_t)uaddr & 7) != 0 && len > 7) {
767 		if (subyte(uaddr, 0))
768 			return (_len);
769 		uaddr++;
770 		len--;
771 	}
772 
773 	/* zero 8 bytes at a time */
774 	while (len > 7) {
775 #ifdef __LP64__
776 		if (suword64(uaddr, 0))
777 			return (_len);
778 #else
779 		if (suword32(uaddr, 0))
780 			return (_len);
781 		if (suword32(uaddr + 4, 0))
782 			return (_len);
783 #endif
784 		uaddr += 8;
785 		len -= 8;
786 	}
787 
788 	/* zero fill end, if any */
789 	while (len > 0) {
790 		if (subyte(uaddr, 0))
791 			return (_len);
792 		uaddr++;
793 		len--;
794 	}
795 	return (0);
796 }
797 
798 int
799 linux_access_ok(int rw, const void *uaddr, size_t len)
800 {
801 	uintptr_t saddr;
802 	uintptr_t eaddr;
803 
804 	/* get start and end address */
805 	saddr = (uintptr_t)uaddr;
806 	eaddr = (uintptr_t)uaddr + len;
807 
808 	/* verify addresses are valid for userspace */
809 	return ((saddr == eaddr) ||
810 	    (eaddr > saddr && eaddr <= VM_MAXUSER_ADDRESS));
811 }
812 
813 static int
814 linux_dev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
815     struct thread *td)
816 {
817 	struct linux_file *filp;
818 	struct file *file;
819 	unsigned size;
820 	int error;
821 
822 	file = td->td_fpop;
823 	if (dev->si_drv1 == NULL)
824 		return (ENXIO);
825 	if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
826 		return (error);
827 	filp->f_flags = file->f_flag;
828 
829 	/* the LinuxKPI supports blocking and non-blocking I/O */
830 	if (cmd == FIONBIO || cmd == FIOASYNC)
831 		return (0);
832 
833 	linux_set_current(td);
834 	size = IOCPARM_LEN(cmd);
835 	/* refer to logic in sys_ioctl() */
836 	if (size > 0) {
837 		/*
838 		 * Setup hint for linux_copyin() and linux_copyout().
839 		 *
840 		 * Background: Linux code expects a user-space address
841 		 * while FreeBSD supplies a kernel-space address.
842 		 */
843 		current->bsd_ioctl_data = data;
844 		current->bsd_ioctl_len = size;
845 		data = (void *)LINUX_IOCTL_MIN_PTR;
846 	} else {
847 		/* fetch user-space pointer */
848 		data = *(void **)data;
849 	}
850 	if (filp->f_op->unlocked_ioctl)
851 		error = -filp->f_op->unlocked_ioctl(filp, cmd, (u_long)data);
852 	else
853 		error = ENOTTY;
854 	if (size > 0) {
855 		current->bsd_ioctl_data = NULL;
856 		current->bsd_ioctl_len = 0;
857 	}
858 
859 	if (error == EWOULDBLOCK) {
860 		/* update kqfilter status, if any */
861 		linux_dev_kqfilter_poll(filp,
862 		    LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
863 	} else if (error == ERESTARTSYS)
864 		error = ERESTART;
865 	return (error);
866 }
867 
868 static int
869 linux_dev_read(struct cdev *dev, struct uio *uio, int ioflag)
870 {
871 	struct linux_file *filp;
872 	struct thread *td;
873 	struct file *file;
874 	ssize_t bytes;
875 	int error;
876 
877 	td = curthread;
878 	file = td->td_fpop;
879 	if (dev->si_drv1 == NULL)
880 		return (ENXIO);
881 	if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
882 		return (error);
883 	filp->f_flags = file->f_flag;
884 	/* XXX no support for I/O vectors currently */
885 	if (uio->uio_iovcnt != 1)
886 		return (EOPNOTSUPP);
887 	linux_set_current(td);
888 	if (filp->f_op->read) {
889 		bytes = filp->f_op->read(filp, uio->uio_iov->iov_base,
890 		    uio->uio_iov->iov_len, &uio->uio_offset);
891 		if (bytes >= 0) {
892 			uio->uio_iov->iov_base =
893 			    ((uint8_t *)uio->uio_iov->iov_base) + bytes;
894 			uio->uio_iov->iov_len -= bytes;
895 			uio->uio_resid -= bytes;
896 		} else {
897 			error = -bytes;
898 			if (error == ERESTARTSYS)
899 				error = ERESTART;
900 		}
901 	} else
902 		error = ENXIO;
903 
904 	/* update kqfilter status, if any */
905 	linux_dev_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_READ);
906 
907 	return (error);
908 }
909 
910 static int
911 linux_dev_write(struct cdev *dev, struct uio *uio, int ioflag)
912 {
913 	struct linux_file *filp;
914 	struct thread *td;
915 	struct file *file;
916 	ssize_t bytes;
917 	int error;
918 
919 	td = curthread;
920 	file = td->td_fpop;
921 	if (dev->si_drv1 == NULL)
922 		return (ENXIO);
923 	if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
924 		return (error);
925 	filp->f_flags = file->f_flag;
926 	/* XXX no support for I/O vectors currently */
927 	if (uio->uio_iovcnt != 1)
928 		return (EOPNOTSUPP);
929 	linux_set_current(td);
930 	if (filp->f_op->write) {
931 		bytes = filp->f_op->write(filp, uio->uio_iov->iov_base,
932 		    uio->uio_iov->iov_len, &uio->uio_offset);
933 		if (bytes >= 0) {
934 			uio->uio_iov->iov_base =
935 			    ((uint8_t *)uio->uio_iov->iov_base) + bytes;
936 			uio->uio_iov->iov_len -= bytes;
937 			uio->uio_resid -= bytes;
938 		} else {
939 			error = -bytes;
940 			if (error == ERESTARTSYS)
941 				error = ERESTART;
942 		}
943 	} else
944 		error = ENXIO;
945 
946 	/* update kqfilter status, if any */
947 	linux_dev_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_WRITE);
948 
949 	return (error);
950 }
951 
952 static int
953 linux_dev_poll(struct cdev *dev, int events, struct thread *td)
954 {
955 	struct linux_file *filp;
956 	struct file *file;
957 	int revents;
958 
959 	if (dev->si_drv1 == NULL)
960 		goto error;
961 	if (devfs_get_cdevpriv((void **)&filp) != 0)
962 		goto error;
963 
964 	file = td->td_fpop;
965 	filp->f_flags = file->f_flag;
966 	linux_set_current(td);
967 	if (filp->f_op->poll != NULL) {
968 		selrecord(td, &filp->f_selinfo);
969 		revents = filp->f_op->poll(filp, NULL) & events;
970 	} else
971 		revents = 0;
972 
973 	return (revents);
974 error:
975 	return (events & (POLLHUP|POLLIN|POLLRDNORM|POLLOUT|POLLWRNORM));
976 }
977 
978 void
979 linux_poll_wakeup(struct linux_file *filp)
980 {
981 	/* this function should be NULL-safe */
982 	if (filp == NULL)
983 		return;
984 
985 	selwakeup(&filp->f_selinfo);
986 
987 	spin_lock(&filp->f_kqlock);
988 	filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ |
989 	    LINUX_KQ_FLAG_NEED_WRITE;
990 
991 	/* make sure the "knote" gets woken up */
992 	KNOTE_LOCKED(&filp->f_selinfo.si_note, 1);
993 	spin_unlock(&filp->f_kqlock);
994 }
995 
996 static void
997 linux_dev_kqfilter_detach(struct knote *kn)
998 {
999 	struct linux_file *filp = kn->kn_hook;
1000 
1001 	spin_lock(&filp->f_kqlock);
1002 	knlist_remove(&filp->f_selinfo.si_note, kn, 1);
1003 	spin_unlock(&filp->f_kqlock);
1004 }
1005 
1006 static int
1007 linux_dev_kqfilter_read_event(struct knote *kn, long hint)
1008 {
1009 	struct linux_file *filp = kn->kn_hook;
1010 
1011 	mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1012 
1013 	return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_READ) ? 1 : 0);
1014 }
1015 
1016 static int
1017 linux_dev_kqfilter_write_event(struct knote *kn, long hint)
1018 {
1019 	struct linux_file *filp = kn->kn_hook;
1020 
1021 	mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1022 
1023 	return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_WRITE) ? 1 : 0);
1024 }
1025 
1026 static struct filterops linux_dev_kqfiltops_read = {
1027 	.f_isfd = 1,
1028 	.f_detach = linux_dev_kqfilter_detach,
1029 	.f_event = linux_dev_kqfilter_read_event,
1030 };
1031 
1032 static struct filterops linux_dev_kqfiltops_write = {
1033 	.f_isfd = 1,
1034 	.f_detach = linux_dev_kqfilter_detach,
1035 	.f_event = linux_dev_kqfilter_write_event,
1036 };
1037 
1038 static void
1039 linux_dev_kqfilter_poll(struct linux_file *filp, int kqflags)
1040 {
1041 	int temp;
1042 
1043 	if (filp->f_kqflags & kqflags) {
1044 		/* get the latest polling state */
1045 		temp = filp->f_op->poll(filp, NULL);
1046 
1047 		spin_lock(&filp->f_kqlock);
1048 		/* clear kqflags */
1049 		filp->f_kqflags &= ~(LINUX_KQ_FLAG_NEED_READ |
1050 		    LINUX_KQ_FLAG_NEED_WRITE);
1051 		/* update kqflags */
1052 		if (temp & (POLLIN | POLLOUT)) {
1053 			if (temp & POLLIN)
1054 				filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ;
1055 			if (temp & POLLOUT)
1056 				filp->f_kqflags |= LINUX_KQ_FLAG_NEED_WRITE;
1057 
1058 			/* make sure the "knote" gets woken up */
1059 			KNOTE_LOCKED(&filp->f_selinfo.si_note, 0);
1060 		}
1061 		spin_unlock(&filp->f_kqlock);
1062 	}
1063 }
1064 
1065 static int
1066 linux_dev_kqfilter(struct cdev *dev, struct knote *kn)
1067 {
1068 	struct linux_file *filp;
1069 	struct file *file;
1070 	struct thread *td;
1071 	int error;
1072 
1073 	td = curthread;
1074 	file = td->td_fpop;
1075 	if (dev->si_drv1 == NULL)
1076 		return (ENXIO);
1077 	if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
1078 		return (error);
1079 	filp->f_flags = file->f_flag;
1080 	if (filp->f_op->poll == NULL)
1081 		return (EINVAL);
1082 
1083 	spin_lock(&filp->f_kqlock);
1084 	switch (kn->kn_filter) {
1085 	case EVFILT_READ:
1086 		filp->f_kqflags |= LINUX_KQ_FLAG_HAS_READ;
1087 		kn->kn_fop = &linux_dev_kqfiltops_read;
1088 		kn->kn_hook = filp;
1089 		knlist_add(&filp->f_selinfo.si_note, kn, 1);
1090 		break;
1091 	case EVFILT_WRITE:
1092 		filp->f_kqflags |= LINUX_KQ_FLAG_HAS_WRITE;
1093 		kn->kn_fop = &linux_dev_kqfiltops_write;
1094 		kn->kn_hook = filp;
1095 		knlist_add(&filp->f_selinfo.si_note, kn, 1);
1096 		break;
1097 	default:
1098 		error = EINVAL;
1099 		break;
1100 	}
1101 	spin_unlock(&filp->f_kqlock);
1102 
1103 	if (error == 0) {
1104 		linux_set_current(td);
1105 
1106 		/* update kqfilter status, if any */
1107 		linux_dev_kqfilter_poll(filp,
1108 		    LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
1109 	}
1110 	return (error);
1111 }
1112 
1113 static int
1114 linux_dev_mmap_single(struct cdev *dev, vm_ooffset_t *offset,
1115     vm_size_t size, struct vm_object **object, int nprot)
1116 {
1117 	struct vm_area_struct *vmap;
1118 	struct mm_struct *mm;
1119 	struct linux_file *filp;
1120 	struct thread *td;
1121 	struct file *file;
1122 	vm_memattr_t attr;
1123 	int error;
1124 
1125 	td = curthread;
1126 	file = td->td_fpop;
1127 	if (dev->si_drv1 == NULL)
1128 		return (ENODEV);
1129 	if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
1130 		return (error);
1131 	filp->f_flags = file->f_flag;
1132 
1133 	if (filp->f_op->mmap == NULL)
1134 		return (ENODEV);
1135 
1136 	linux_set_current(td);
1137 
1138 	/*
1139 	 * The same VM object might be shared by multiple processes
1140 	 * and the mm_struct is usually freed when a process exits.
1141 	 *
1142 	 * The atomic reference below makes sure the mm_struct is
1143 	 * available as long as the vmap is in the linux_vma_head.
1144 	 */
1145 	mm = current->mm;
1146 	if (atomic_inc_not_zero(&mm->mm_users) == 0)
1147 		return (EINVAL);
1148 
1149 	vmap = kzalloc(sizeof(*vmap), GFP_KERNEL);
1150 	vmap->vm_start = 0;
1151 	vmap->vm_end = size;
1152 	vmap->vm_pgoff = *offset / PAGE_SIZE;
1153 	vmap->vm_pfn = 0;
1154 	vmap->vm_flags = vmap->vm_page_prot = nprot;
1155 	vmap->vm_ops = NULL;
1156 	vmap->vm_file = get_file(filp);
1157 	vmap->vm_mm = mm;
1158 
1159 	if (unlikely(down_write_killable(&vmap->vm_mm->mmap_sem))) {
1160 		error = EINTR;
1161 	} else {
1162 		error = -filp->f_op->mmap(filp, vmap);
1163 		up_write(&vmap->vm_mm->mmap_sem);
1164 	}
1165 
1166 	if (error != 0) {
1167 		linux_cdev_handle_free(vmap);
1168 		return (error);
1169 	}
1170 
1171 	attr = pgprot2cachemode(vmap->vm_page_prot);
1172 
1173 	if (vmap->vm_ops != NULL) {
1174 		void *vm_private_data;
1175 
1176 		if (vmap->vm_ops->fault == NULL ||
1177 		    vmap->vm_ops->open == NULL ||
1178 		    vmap->vm_ops->close == NULL ||
1179 		    vmap->vm_private_data == NULL) {
1180 			linux_cdev_handle_free(vmap);
1181 			return (EINVAL);
1182 		}
1183 
1184 		vm_private_data = vmap->vm_private_data;
1185 
1186 		vmap = linux_cdev_handle_insert(vm_private_data, vmap);
1187 
1188 		*object = cdev_pager_allocate(vm_private_data, OBJT_MGTDEVICE,
1189 		    &linux_cdev_pager_ops, size, nprot, *offset, curthread->td_ucred);
1190 
1191 		if (*object == NULL) {
1192 			linux_cdev_handle_remove(vmap);
1193 			linux_cdev_handle_free(vmap);
1194 			return (EINVAL);
1195 		}
1196 	} else {
1197 		struct sglist *sg;
1198 
1199 		sg = sglist_alloc(1, M_WAITOK);
1200 		sglist_append_phys(sg, (vm_paddr_t)vmap->vm_pfn << PAGE_SHIFT, vmap->vm_len);
1201 
1202 		*object = vm_pager_allocate(OBJT_SG, sg, vmap->vm_len,
1203 		    nprot, 0, curthread->td_ucred);
1204 
1205 		linux_cdev_handle_free(vmap);
1206 
1207 		if (*object == NULL) {
1208 			sglist_free(sg);
1209 			return (EINVAL);
1210 		}
1211 	}
1212 
1213 	if (attr != VM_MEMATTR_DEFAULT) {
1214 		VM_OBJECT_WLOCK(*object);
1215 		vm_object_set_memattr(*object, attr);
1216 		VM_OBJECT_WUNLOCK(*object);
1217 	}
1218 	*offset = 0;
1219 	return (0);
1220 }
1221 
1222 struct cdevsw linuxcdevsw = {
1223 	.d_version = D_VERSION,
1224 	.d_flags = D_TRACKCLOSE,
1225 	.d_open = linux_dev_open,
1226 	.d_close = linux_dev_close,
1227 	.d_read = linux_dev_read,
1228 	.d_write = linux_dev_write,
1229 	.d_ioctl = linux_dev_ioctl,
1230 	.d_mmap_single = linux_dev_mmap_single,
1231 	.d_poll = linux_dev_poll,
1232 	.d_kqfilter = linux_dev_kqfilter,
1233 	.d_name = "lkpidev",
1234 };
1235 
1236 static int
1237 linux_file_read(struct file *file, struct uio *uio, struct ucred *active_cred,
1238     int flags, struct thread *td)
1239 {
1240 	struct linux_file *filp;
1241 	ssize_t bytes;
1242 	int error;
1243 
1244 	error = 0;
1245 	filp = (struct linux_file *)file->f_data;
1246 	filp->f_flags = file->f_flag;
1247 	/* XXX no support for I/O vectors currently */
1248 	if (uio->uio_iovcnt != 1)
1249 		return (EOPNOTSUPP);
1250 	linux_set_current(td);
1251 	if (filp->f_op->read) {
1252 		bytes = filp->f_op->read(filp, uio->uio_iov->iov_base,
1253 		    uio->uio_iov->iov_len, &uio->uio_offset);
1254 		if (bytes >= 0) {
1255 			uio->uio_iov->iov_base =
1256 			    ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1257 			uio->uio_iov->iov_len -= bytes;
1258 			uio->uio_resid -= bytes;
1259 		} else
1260 			error = -bytes;
1261 	} else
1262 		error = ENXIO;
1263 
1264 	return (error);
1265 }
1266 
1267 static int
1268 linux_file_poll(struct file *file, int events, struct ucred *active_cred,
1269     struct thread *td)
1270 {
1271 	struct linux_file *filp;
1272 	int revents;
1273 
1274 	filp = (struct linux_file *)file->f_data;
1275 	filp->f_flags = file->f_flag;
1276 	linux_set_current(td);
1277 	if (filp->f_op->poll != NULL) {
1278 		selrecord(td, &filp->f_selinfo);
1279 		revents = filp->f_op->poll(filp, NULL) & events;
1280 	} else
1281 		revents = 0;
1282 
1283 	return (revents);
1284 }
1285 
1286 static int
1287 linux_file_close(struct file *file, struct thread *td)
1288 {
1289 	struct linux_file *filp;
1290 	int error;
1291 
1292 	filp = (struct linux_file *)file->f_data;
1293 	filp->f_flags = file->f_flag;
1294 	linux_set_current(td);
1295 	error = -filp->f_op->release(NULL, filp);
1296 	funsetown(&filp->f_sigio);
1297 	kfree(filp);
1298 
1299 	return (error);
1300 }
1301 
1302 static int
1303 linux_file_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *cred,
1304     struct thread *td)
1305 {
1306 	struct linux_file *filp;
1307 	int error;
1308 
1309 	filp = (struct linux_file *)fp->f_data;
1310 	filp->f_flags = fp->f_flag;
1311 	error = 0;
1312 
1313 	linux_set_current(td);
1314 	switch (cmd) {
1315 	case FIONBIO:
1316 		break;
1317 	case FIOASYNC:
1318 		if (filp->f_op->fasync == NULL)
1319 			break;
1320 		error = filp->f_op->fasync(0, filp, fp->f_flag & FASYNC);
1321 		break;
1322 	case FIOSETOWN:
1323 		error = fsetown(*(int *)data, &filp->f_sigio);
1324 		if (error == 0)
1325 			error = filp->f_op->fasync(0, filp,
1326 			    fp->f_flag & FASYNC);
1327 		break;
1328 	case FIOGETOWN:
1329 		*(int *)data = fgetown(&filp->f_sigio);
1330 		break;
1331 	default:
1332 		error = ENOTTY;
1333 		break;
1334 	}
1335 	return (error);
1336 }
1337 
1338 static int
1339 linux_file_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
1340     struct thread *td)
1341 {
1342 
1343 	return (EOPNOTSUPP);
1344 }
1345 
1346 static int
1347 linux_file_fill_kinfo(struct file *fp, struct kinfo_file *kif,
1348     struct filedesc *fdp)
1349 {
1350 
1351 	return (0);
1352 }
1353 
1354 struct fileops linuxfileops = {
1355 	.fo_read = linux_file_read,
1356 	.fo_write = invfo_rdwr,
1357 	.fo_truncate = invfo_truncate,
1358 	.fo_kqfilter = invfo_kqfilter,
1359 	.fo_stat = linux_file_stat,
1360 	.fo_fill_kinfo = linux_file_fill_kinfo,
1361 	.fo_poll = linux_file_poll,
1362 	.fo_close = linux_file_close,
1363 	.fo_ioctl = linux_file_ioctl,
1364 	.fo_chmod = invfo_chmod,
1365 	.fo_chown = invfo_chown,
1366 	.fo_sendfile = invfo_sendfile,
1367 };
1368 
1369 /*
1370  * Hash of vmmap addresses.  This is infrequently accessed and does not
1371  * need to be particularly large.  This is done because we must store the
1372  * caller's idea of the map size to properly unmap.
1373  */
1374 struct vmmap {
1375 	LIST_ENTRY(vmmap)	vm_next;
1376 	void 			*vm_addr;
1377 	unsigned long		vm_size;
1378 };
1379 
1380 struct vmmaphd {
1381 	struct vmmap *lh_first;
1382 };
1383 #define	VMMAP_HASH_SIZE	64
1384 #define	VMMAP_HASH_MASK	(VMMAP_HASH_SIZE - 1)
1385 #define	VM_HASH(addr)	((uintptr_t)(addr) >> PAGE_SHIFT) & VMMAP_HASH_MASK
1386 static struct vmmaphd vmmaphead[VMMAP_HASH_SIZE];
1387 static struct mtx vmmaplock;
1388 
1389 static void
1390 vmmap_add(void *addr, unsigned long size)
1391 {
1392 	struct vmmap *vmmap;
1393 
1394 	vmmap = kmalloc(sizeof(*vmmap), GFP_KERNEL);
1395 	mtx_lock(&vmmaplock);
1396 	vmmap->vm_size = size;
1397 	vmmap->vm_addr = addr;
1398 	LIST_INSERT_HEAD(&vmmaphead[VM_HASH(addr)], vmmap, vm_next);
1399 	mtx_unlock(&vmmaplock);
1400 }
1401 
1402 static struct vmmap *
1403 vmmap_remove(void *addr)
1404 {
1405 	struct vmmap *vmmap;
1406 
1407 	mtx_lock(&vmmaplock);
1408 	LIST_FOREACH(vmmap, &vmmaphead[VM_HASH(addr)], vm_next)
1409 		if (vmmap->vm_addr == addr)
1410 			break;
1411 	if (vmmap)
1412 		LIST_REMOVE(vmmap, vm_next);
1413 	mtx_unlock(&vmmaplock);
1414 
1415 	return (vmmap);
1416 }
1417 
1418 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
1419 void *
1420 _ioremap_attr(vm_paddr_t phys_addr, unsigned long size, int attr)
1421 {
1422 	void *addr;
1423 
1424 	addr = pmap_mapdev_attr(phys_addr, size, attr);
1425 	if (addr == NULL)
1426 		return (NULL);
1427 	vmmap_add(addr, size);
1428 
1429 	return (addr);
1430 }
1431 #endif
1432 
1433 void
1434 iounmap(void *addr)
1435 {
1436 	struct vmmap *vmmap;
1437 
1438 	vmmap = vmmap_remove(addr);
1439 	if (vmmap == NULL)
1440 		return;
1441 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__)
1442 	pmap_unmapdev((vm_offset_t)addr, vmmap->vm_size);
1443 #endif
1444 	kfree(vmmap);
1445 }
1446 
1447 
1448 void *
1449 vmap(struct page **pages, unsigned int count, unsigned long flags, int prot)
1450 {
1451 	vm_offset_t off;
1452 	size_t size;
1453 
1454 	size = count * PAGE_SIZE;
1455 	off = kva_alloc(size);
1456 	if (off == 0)
1457 		return (NULL);
1458 	vmmap_add((void *)off, size);
1459 	pmap_qenter(off, pages, count);
1460 
1461 	return ((void *)off);
1462 }
1463 
1464 void
1465 vunmap(void *addr)
1466 {
1467 	struct vmmap *vmmap;
1468 
1469 	vmmap = vmmap_remove(addr);
1470 	if (vmmap == NULL)
1471 		return;
1472 	pmap_qremove((vm_offset_t)addr, vmmap->vm_size / PAGE_SIZE);
1473 	kva_free((vm_offset_t)addr, vmmap->vm_size);
1474 	kfree(vmmap);
1475 }
1476 
1477 char *
1478 kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
1479 {
1480 	unsigned int len;
1481 	char *p;
1482 	va_list aq;
1483 
1484 	va_copy(aq, ap);
1485 	len = vsnprintf(NULL, 0, fmt, aq);
1486 	va_end(aq);
1487 
1488 	p = kmalloc(len + 1, gfp);
1489 	if (p != NULL)
1490 		vsnprintf(p, len + 1, fmt, ap);
1491 
1492 	return (p);
1493 }
1494 
1495 char *
1496 kasprintf(gfp_t gfp, const char *fmt, ...)
1497 {
1498 	va_list ap;
1499 	char *p;
1500 
1501 	va_start(ap, fmt);
1502 	p = kvasprintf(gfp, fmt, ap);
1503 	va_end(ap);
1504 
1505 	return (p);
1506 }
1507 
1508 static void
1509 linux_timer_callback_wrapper(void *context)
1510 {
1511 	struct timer_list *timer;
1512 
1513 	linux_set_current(curthread);
1514 
1515 	timer = context;
1516 	timer->function(timer->data);
1517 }
1518 
1519 void
1520 mod_timer(struct timer_list *timer, unsigned long expires)
1521 {
1522 
1523 	timer->expires = expires;
1524 	callout_reset(&timer->timer_callout,
1525 	    linux_timer_jiffies_until(expires),
1526 	    &linux_timer_callback_wrapper, timer);
1527 }
1528 
1529 void
1530 add_timer(struct timer_list *timer)
1531 {
1532 
1533 	callout_reset(&timer->timer_callout,
1534 	    linux_timer_jiffies_until(timer->expires),
1535 	    &linux_timer_callback_wrapper, timer);
1536 }
1537 
1538 void
1539 add_timer_on(struct timer_list *timer, int cpu)
1540 {
1541 
1542 	callout_reset_on(&timer->timer_callout,
1543 	    linux_timer_jiffies_until(timer->expires),
1544 	    &linux_timer_callback_wrapper, timer, cpu);
1545 }
1546 
1547 static void
1548 linux_timer_init(void *arg)
1549 {
1550 
1551 	/*
1552 	 * Compute an internal HZ value which can divide 2**32 to
1553 	 * avoid timer rounding problems when the tick value wraps
1554 	 * around 2**32:
1555 	 */
1556 	linux_timer_hz_mask = 1;
1557 	while (linux_timer_hz_mask < (unsigned long)hz)
1558 		linux_timer_hz_mask *= 2;
1559 	linux_timer_hz_mask--;
1560 }
1561 SYSINIT(linux_timer, SI_SUB_DRIVERS, SI_ORDER_FIRST, linux_timer_init, NULL);
1562 
1563 void
1564 linux_complete_common(struct completion *c, int all)
1565 {
1566 	int wakeup_swapper;
1567 
1568 	sleepq_lock(c);
1569 	c->done++;
1570 	if (all)
1571 		wakeup_swapper = sleepq_broadcast(c, SLEEPQ_SLEEP, 0, 0);
1572 	else
1573 		wakeup_swapper = sleepq_signal(c, SLEEPQ_SLEEP, 0, 0);
1574 	sleepq_release(c);
1575 	if (wakeup_swapper)
1576 		kick_proc0();
1577 }
1578 
1579 /*
1580  * Indefinite wait for done != 0 with or without signals.
1581  */
1582 long
1583 linux_wait_for_common(struct completion *c, int flags)
1584 {
1585 	long error;
1586 
1587 	if (SCHEDULER_STOPPED())
1588 		return (0);
1589 
1590 	DROP_GIANT();
1591 
1592 	if (flags != 0)
1593 		flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
1594 	else
1595 		flags = SLEEPQ_SLEEP;
1596 	error = 0;
1597 	for (;;) {
1598 		sleepq_lock(c);
1599 		if (c->done)
1600 			break;
1601 		sleepq_add(c, NULL, "completion", flags, 0);
1602 		if (flags & SLEEPQ_INTERRUPTIBLE) {
1603 			if (sleepq_wait_sig(c, 0) != 0) {
1604 				error = -ERESTARTSYS;
1605 				goto intr;
1606 			}
1607 		} else
1608 			sleepq_wait(c, 0);
1609 	}
1610 	c->done--;
1611 	sleepq_release(c);
1612 
1613 intr:
1614 	PICKUP_GIANT();
1615 
1616 	return (error);
1617 }
1618 
1619 /*
1620  * Time limited wait for done != 0 with or without signals.
1621  */
1622 long
1623 linux_wait_for_timeout_common(struct completion *c, long timeout, int flags)
1624 {
1625 	long end = jiffies + timeout, error;
1626 	int ret;
1627 
1628 	if (SCHEDULER_STOPPED())
1629 		return (0);
1630 
1631 	DROP_GIANT();
1632 
1633 	if (flags != 0)
1634 		flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
1635 	else
1636 		flags = SLEEPQ_SLEEP;
1637 
1638 	error = 0;
1639 	ret = 0;
1640 	for (;;) {
1641 		sleepq_lock(c);
1642 		if (c->done)
1643 			break;
1644 		sleepq_add(c, NULL, "completion", flags, 0);
1645 		sleepq_set_timeout(c, linux_timer_jiffies_until(end));
1646 		if (flags & SLEEPQ_INTERRUPTIBLE)
1647 			ret = sleepq_timedwait_sig(c, 0);
1648 		else
1649 			ret = sleepq_timedwait(c, 0);
1650 		if (ret != 0) {
1651 			/* check for timeout or signal */
1652 			if (ret == EWOULDBLOCK)
1653 				error = 0;
1654 			else
1655 				error = -ERESTARTSYS;
1656 			goto intr;
1657 		}
1658 	}
1659 	c->done--;
1660 	sleepq_release(c);
1661 
1662 intr:
1663 	PICKUP_GIANT();
1664 
1665 	/* return how many jiffies are left */
1666 	return (ret != 0 ? error : linux_timer_jiffies_until(end));
1667 }
1668 
1669 int
1670 linux_try_wait_for_completion(struct completion *c)
1671 {
1672 	int isdone;
1673 
1674 	isdone = 1;
1675 	sleepq_lock(c);
1676 	if (c->done)
1677 		c->done--;
1678 	else
1679 		isdone = 0;
1680 	sleepq_release(c);
1681 	return (isdone);
1682 }
1683 
1684 int
1685 linux_completion_done(struct completion *c)
1686 {
1687 	int isdone;
1688 
1689 	isdone = 1;
1690 	sleepq_lock(c);
1691 	if (c->done == 0)
1692 		isdone = 0;
1693 	sleepq_release(c);
1694 	return (isdone);
1695 }
1696 
1697 static void
1698 linux_cdev_release(struct kobject *kobj)
1699 {
1700 	struct linux_cdev *cdev;
1701 	struct kobject *parent;
1702 
1703 	cdev = container_of(kobj, struct linux_cdev, kobj);
1704 	parent = kobj->parent;
1705 	if (cdev->cdev)
1706 		destroy_dev(cdev->cdev);
1707 	kfree(cdev);
1708 	kobject_put(parent);
1709 }
1710 
1711 static void
1712 linux_cdev_static_release(struct kobject *kobj)
1713 {
1714 	struct linux_cdev *cdev;
1715 	struct kobject *parent;
1716 
1717 	cdev = container_of(kobj, struct linux_cdev, kobj);
1718 	parent = kobj->parent;
1719 	if (cdev->cdev)
1720 		destroy_dev(cdev->cdev);
1721 	kobject_put(parent);
1722 }
1723 
1724 const struct kobj_type linux_cdev_ktype = {
1725 	.release = linux_cdev_release,
1726 };
1727 
1728 const struct kobj_type linux_cdev_static_ktype = {
1729 	.release = linux_cdev_static_release,
1730 };
1731 
1732 static void
1733 linux_handle_ifnet_link_event(void *arg, struct ifnet *ifp, int linkstate)
1734 {
1735 	struct notifier_block *nb;
1736 
1737 	nb = arg;
1738 	if (linkstate == LINK_STATE_UP)
1739 		nb->notifier_call(nb, NETDEV_UP, ifp);
1740 	else
1741 		nb->notifier_call(nb, NETDEV_DOWN, ifp);
1742 }
1743 
1744 static void
1745 linux_handle_ifnet_arrival_event(void *arg, struct ifnet *ifp)
1746 {
1747 	struct notifier_block *nb;
1748 
1749 	nb = arg;
1750 	nb->notifier_call(nb, NETDEV_REGISTER, ifp);
1751 }
1752 
1753 static void
1754 linux_handle_ifnet_departure_event(void *arg, struct ifnet *ifp)
1755 {
1756 	struct notifier_block *nb;
1757 
1758 	nb = arg;
1759 	nb->notifier_call(nb, NETDEV_UNREGISTER, ifp);
1760 }
1761 
1762 static void
1763 linux_handle_iflladdr_event(void *arg, struct ifnet *ifp)
1764 {
1765 	struct notifier_block *nb;
1766 
1767 	nb = arg;
1768 	nb->notifier_call(nb, NETDEV_CHANGEADDR, ifp);
1769 }
1770 
1771 static void
1772 linux_handle_ifaddr_event(void *arg, struct ifnet *ifp)
1773 {
1774 	struct notifier_block *nb;
1775 
1776 	nb = arg;
1777 	nb->notifier_call(nb, NETDEV_CHANGEIFADDR, ifp);
1778 }
1779 
1780 int
1781 register_netdevice_notifier(struct notifier_block *nb)
1782 {
1783 
1784 	nb->tags[NETDEV_UP] = EVENTHANDLER_REGISTER(
1785 	    ifnet_link_event, linux_handle_ifnet_link_event, nb, 0);
1786 	nb->tags[NETDEV_REGISTER] = EVENTHANDLER_REGISTER(
1787 	    ifnet_arrival_event, linux_handle_ifnet_arrival_event, nb, 0);
1788 	nb->tags[NETDEV_UNREGISTER] = EVENTHANDLER_REGISTER(
1789 	    ifnet_departure_event, linux_handle_ifnet_departure_event, nb, 0);
1790 	nb->tags[NETDEV_CHANGEADDR] = EVENTHANDLER_REGISTER(
1791 	    iflladdr_event, linux_handle_iflladdr_event, nb, 0);
1792 
1793 	return (0);
1794 }
1795 
1796 int
1797 register_inetaddr_notifier(struct notifier_block *nb)
1798 {
1799 
1800         nb->tags[NETDEV_CHANGEIFADDR] = EVENTHANDLER_REGISTER(
1801             ifaddr_event, linux_handle_ifaddr_event, nb, 0);
1802         return (0);
1803 }
1804 
1805 int
1806 unregister_netdevice_notifier(struct notifier_block *nb)
1807 {
1808 
1809         EVENTHANDLER_DEREGISTER(ifnet_link_event,
1810 	    nb->tags[NETDEV_UP]);
1811         EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
1812 	    nb->tags[NETDEV_REGISTER]);
1813         EVENTHANDLER_DEREGISTER(ifnet_departure_event,
1814 	    nb->tags[NETDEV_UNREGISTER]);
1815         EVENTHANDLER_DEREGISTER(iflladdr_event,
1816 	    nb->tags[NETDEV_CHANGEADDR]);
1817 
1818 	return (0);
1819 }
1820 
1821 int
1822 unregister_inetaddr_notifier(struct notifier_block *nb)
1823 {
1824 
1825         EVENTHANDLER_DEREGISTER(ifaddr_event,
1826             nb->tags[NETDEV_CHANGEIFADDR]);
1827 
1828         return (0);
1829 }
1830 
1831 struct list_sort_thunk {
1832 	int (*cmp)(void *, struct list_head *, struct list_head *);
1833 	void *priv;
1834 };
1835 
1836 static inline int
1837 linux_le_cmp(void *priv, const void *d1, const void *d2)
1838 {
1839 	struct list_head *le1, *le2;
1840 	struct list_sort_thunk *thunk;
1841 
1842 	thunk = priv;
1843 	le1 = *(__DECONST(struct list_head **, d1));
1844 	le2 = *(__DECONST(struct list_head **, d2));
1845 	return ((thunk->cmp)(thunk->priv, le1, le2));
1846 }
1847 
1848 void
1849 list_sort(void *priv, struct list_head *head, int (*cmp)(void *priv,
1850     struct list_head *a, struct list_head *b))
1851 {
1852 	struct list_sort_thunk thunk;
1853 	struct list_head **ar, *le;
1854 	size_t count, i;
1855 
1856 	count = 0;
1857 	list_for_each(le, head)
1858 		count++;
1859 	ar = malloc(sizeof(struct list_head *) * count, M_KMALLOC, M_WAITOK);
1860 	i = 0;
1861 	list_for_each(le, head)
1862 		ar[i++] = le;
1863 	thunk.cmp = cmp;
1864 	thunk.priv = priv;
1865 	qsort_r(ar, count, sizeof(struct list_head *), &thunk, linux_le_cmp);
1866 	INIT_LIST_HEAD(head);
1867 	for (i = 0; i < count; i++)
1868 		list_add_tail(ar[i], head);
1869 	free(ar, M_KMALLOC);
1870 }
1871 
1872 void
1873 linux_irq_handler(void *ent)
1874 {
1875 	struct irq_ent *irqe;
1876 
1877 	linux_set_current(curthread);
1878 
1879 	irqe = ent;
1880 	irqe->handler(irqe->irq, irqe->arg);
1881 }
1882 
1883 #if defined(__i386__) || defined(__amd64__)
1884 int
1885 linux_wbinvd_on_all_cpus(void)
1886 {
1887 
1888 	pmap_invalidate_cache();
1889 	return (0);
1890 }
1891 #endif
1892 
1893 int
1894 linux_on_each_cpu(void callback(void *), void *data)
1895 {
1896 
1897 	smp_rendezvous(smp_no_rendezvous_barrier, callback,
1898 	    smp_no_rendezvous_barrier, data);
1899 	return (0);
1900 }
1901 
1902 int
1903 linux_in_atomic(void)
1904 {
1905 
1906 	return ((curthread->td_pflags & TDP_NOFAULTING) != 0);
1907 }
1908 
1909 struct linux_cdev *
1910 linux_find_cdev(const char *name, unsigned major, unsigned minor)
1911 {
1912 	int unit = MKDEV(major, minor);
1913 	struct cdev *cdev;
1914 
1915 	dev_lock();
1916 	LIST_FOREACH(cdev, &linuxcdevsw.d_devs, si_list) {
1917 		struct linux_cdev *ldev = cdev->si_drv1;
1918 		if (dev2unit(cdev) == unit &&
1919 		    strcmp(kobject_name(&ldev->kobj), name) == 0) {
1920 			break;
1921 		}
1922 	}
1923 	dev_unlock();
1924 
1925 	return (cdev != NULL ? cdev->si_drv1 : NULL);
1926 }
1927 
1928 int
1929 __register_chrdev(unsigned int major, unsigned int baseminor,
1930     unsigned int count, const char *name,
1931     const struct file_operations *fops)
1932 {
1933 	struct linux_cdev *cdev;
1934 	int ret = 0;
1935 	int i;
1936 
1937 	for (i = baseminor; i < baseminor + count; i++) {
1938 		cdev = cdev_alloc();
1939 		cdev_init(cdev, fops);
1940 		kobject_set_name(&cdev->kobj, name);
1941 
1942 		ret = cdev_add(cdev, makedev(major, i), 1);
1943 		if (ret != 0)
1944 			break;
1945 	}
1946 	return (ret);
1947 }
1948 
1949 int
1950 __register_chrdev_p(unsigned int major, unsigned int baseminor,
1951     unsigned int count, const char *name,
1952     const struct file_operations *fops, uid_t uid,
1953     gid_t gid, int mode)
1954 {
1955 	struct linux_cdev *cdev;
1956 	int ret = 0;
1957 	int i;
1958 
1959 	for (i = baseminor; i < baseminor + count; i++) {
1960 		cdev = cdev_alloc();
1961 		cdev_init(cdev, fops);
1962 		kobject_set_name(&cdev->kobj, name);
1963 
1964 		ret = cdev_add_ext(cdev, makedev(major, i), uid, gid, mode);
1965 		if (ret != 0)
1966 			break;
1967 	}
1968 	return (ret);
1969 }
1970 
1971 void
1972 __unregister_chrdev(unsigned int major, unsigned int baseminor,
1973     unsigned int count, const char *name)
1974 {
1975 	struct linux_cdev *cdevp;
1976 	int i;
1977 
1978 	for (i = baseminor; i < baseminor + count; i++) {
1979 		cdevp = linux_find_cdev(name, major, i);
1980 		if (cdevp != NULL)
1981 			cdev_del(cdevp);
1982 	}
1983 }
1984 
1985 #if defined(__i386__) || defined(__amd64__)
1986 bool linux_cpu_has_clflush;
1987 #endif
1988 
1989 static void
1990 linux_compat_init(void *arg)
1991 {
1992 	struct sysctl_oid *rootoid;
1993 	int i;
1994 
1995 #if defined(__i386__) || defined(__amd64__)
1996 	linux_cpu_has_clflush = (cpu_feature & CPUID_CLFSH);
1997 #endif
1998 	rw_init(&linux_vma_lock, "lkpi-vma-lock");
1999 
2000 	rootoid = SYSCTL_ADD_ROOT_NODE(NULL,
2001 	    OID_AUTO, "sys", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "sys");
2002 	kobject_init(&linux_class_root, &linux_class_ktype);
2003 	kobject_set_name(&linux_class_root, "class");
2004 	linux_class_root.oidp = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(rootoid),
2005 	    OID_AUTO, "class", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "class");
2006 	kobject_init(&linux_root_device.kobj, &linux_dev_ktype);
2007 	kobject_set_name(&linux_root_device.kobj, "device");
2008 	linux_root_device.kobj.oidp = SYSCTL_ADD_NODE(NULL,
2009 	    SYSCTL_CHILDREN(rootoid), OID_AUTO, "device", CTLFLAG_RD, NULL,
2010 	    "device");
2011 	linux_root_device.bsddev = root_bus;
2012 	linux_class_misc.name = "misc";
2013 	class_register(&linux_class_misc);
2014 	INIT_LIST_HEAD(&pci_drivers);
2015 	INIT_LIST_HEAD(&pci_devices);
2016 	spin_lock_init(&pci_lock);
2017 	mtx_init(&vmmaplock, "IO Map lock", NULL, MTX_DEF);
2018 	for (i = 0; i < VMMAP_HASH_SIZE; i++)
2019 		LIST_INIT(&vmmaphead[i]);
2020 }
2021 SYSINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_init, NULL);
2022 
2023 static void
2024 linux_compat_uninit(void *arg)
2025 {
2026 	linux_kobject_kfree_name(&linux_class_root);
2027 	linux_kobject_kfree_name(&linux_root_device.kobj);
2028 	linux_kobject_kfree_name(&linux_class_misc.kobj);
2029 
2030 	rw_destroy(&linux_vma_lock);
2031 }
2032 SYSUNINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_uninit, NULL);
2033 
2034 /*
2035  * NOTE: Linux frequently uses "unsigned long" for pointer to integer
2036  * conversion and vice versa, where in FreeBSD "uintptr_t" would be
2037  * used. Assert these types have the same size, else some parts of the
2038  * LinuxKPI may not work like expected:
2039  */
2040 CTASSERT(sizeof(unsigned long) == sizeof(uintptr_t));
2041