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