2 * Copyright (c) 2010 Isilon Systems, Inc.
3 * Copyright (c) 2010 iX Systems, Inc.
4 * Copyright (c) 2010 Panasas, Inc.
5 * Copyright (c) 2013-2021 Mellanox Technologies, Ltd.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice unmodified, this list of conditions, and the following
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.
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.
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
33 #include "opt_stack.h"
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>
41 #include <sys/sglist.h>
42 #include <sys/sleepqueue.h>
43 #include <sys/refcount.h>
45 #include <sys/mutex.h>
47 #include <sys/eventhandler.h>
48 #include <sys/fcntl.h>
50 #include <sys/filio.h>
51 #include <sys/rwlock.h>
53 #include <sys/stack.h>
54 #include <sys/sysent.h>
60 #include <vm/vm_object.h>
61 #include <vm/vm_page.h>
62 #include <vm/vm_pager.h>
64 #include <machine/stdarg.h>
66 #if defined(__i386__) || defined(__amd64__)
67 #include <machine/md_var.h>
70 #include <linux/kobject.h>
71 #include <linux/cpu.h>
72 #include <linux/device.h>
73 #include <linux/slab.h>
74 #include <linux/module.h>
75 #include <linux/moduleparam.h>
76 #include <linux/cdev.h>
77 #include <linux/file.h>
78 #include <linux/sysfs.h>
81 #include <linux/vmalloc.h>
82 #include <linux/netdevice.h>
83 #include <linux/timer.h>
84 #include <linux/interrupt.h>
85 #include <linux/uaccess.h>
86 #include <linux/utsname.h>
87 #include <linux/list.h>
88 #include <linux/kthread.h>
89 #include <linux/kernel.h>
90 #include <linux/compat.h>
91 #include <linux/io-mapping.h>
92 #include <linux/poll.h>
93 #include <linux/smp.h>
94 #include <linux/wait_bit.h>
95 #include <linux/rcupdate.h>
96 #include <linux/interval_tree.h>
97 #include <linux/interval_tree_generic.h>
99 #if defined(__i386__) || defined(__amd64__)
101 #include <asm/processor.h>
104 SYSCTL_NODE(_compat, OID_AUTO, linuxkpi, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
105 "LinuxKPI parameters");
108 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, debug, CTLFLAG_RWTUN,
109 &linuxkpi_debug, 0, "Set to enable pr_debug() prints. Clear to disable.");
111 int linuxkpi_warn_dump_stack = 0;
112 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, warn_dump_stack, CTLFLAG_RWTUN,
113 &linuxkpi_warn_dump_stack, 0,
114 "Set to enable stack traces from WARN_ON(). Clear to disable.");
116 static struct timeval lkpi_net_lastlog;
117 static int lkpi_net_curpps;
118 static int lkpi_net_maxpps = 99;
119 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, net_ratelimit, CTLFLAG_RWTUN,
120 &lkpi_net_maxpps, 0, "Limit number of LinuxKPI net messages per second.");
122 MALLOC_DEFINE(M_KMALLOC, "lkpikmalloc", "Linux kmalloc compat");
124 #include <linux/rbtree.h>
125 /* Undo Linux compat changes. */
129 #define RB_ROOT(head) (head)->rbh_root
131 static void linux_destroy_dev(struct linux_cdev *);
132 static void linux_cdev_deref(struct linux_cdev *ldev);
133 static struct vm_area_struct *linux_cdev_handle_find(void *handle);
135 cpumask_t cpu_online_mask;
136 static cpumask_t static_single_cpu_mask[MAXCPU];
137 struct kobject linux_class_root;
138 struct device linux_root_device;
139 struct class linux_class_misc;
140 struct list_head pci_drivers;
141 struct list_head pci_devices;
143 struct uts_namespace init_uts_ns;
145 unsigned long linux_timer_hz_mask;
147 wait_queue_head_t linux_bit_waitq;
148 wait_queue_head_t linux_var_waitq;
151 panic_cmp(struct rb_node *one, struct rb_node *two)
156 RB_GENERATE(linux_root, rb_node, __entry, panic_cmp);
158 #define START(node) ((node)->start)
159 #define LAST(node) ((node)->last)
161 INTERVAL_TREE_DEFINE(struct interval_tree_node, rb, unsigned long,, START,
162 LAST,, lkpi_interval_tree)
167 struct kobject *kobj;
169 kobj = kzalloc(sizeof(*kobj), GFP_KERNEL);
172 kobject_init(kobj, &linux_kfree_type);
179 kobject_set_name_vargs(struct kobject *kobj, const char *fmt, va_list args)
189 if (old && fmt == NULL)
192 /* compute length of string */
193 va_copy(tmp_va, args);
194 len = vsnprintf(&dummy, 0, fmt, tmp_va);
197 /* account for zero termination */
200 /* check for error */
204 /* allocate memory for string */
205 name = kzalloc(len, GFP_KERNEL);
208 vsnprintf(name, len, fmt, args);
211 /* free old string */
214 /* filter new string */
215 for (; *name != '\0'; name++)
222 kobject_set_name(struct kobject *kobj, const char *fmt, ...)
228 error = kobject_set_name_vargs(kobj, fmt, args);
235 kobject_add_complete(struct kobject *kobj, struct kobject *parent)
237 const struct kobj_type *t;
240 kobj->parent = parent;
241 error = sysfs_create_dir(kobj);
242 if (error == 0 && kobj->ktype && kobj->ktype->default_attrs) {
243 struct attribute **attr;
246 for (attr = t->default_attrs; *attr != NULL; attr++) {
247 error = sysfs_create_file(kobj, *attr);
252 sysfs_remove_dir(kobj);
258 kobject_add(struct kobject *kobj, struct kobject *parent, const char *fmt, ...)
264 error = kobject_set_name_vargs(kobj, fmt, args);
269 return kobject_add_complete(kobj, parent);
273 linux_kobject_release(struct kref *kref)
275 struct kobject *kobj;
278 kobj = container_of(kref, struct kobject, kref);
279 sysfs_remove_dir(kobj);
281 if (kobj->ktype && kobj->ktype->release)
282 kobj->ktype->release(kobj);
287 linux_kobject_kfree(struct kobject *kobj)
293 linux_kobject_kfree_name(struct kobject *kobj)
300 const struct kobj_type linux_kfree_type = {
301 .release = linux_kobject_kfree
305 lkpi_kobj_attr_show(struct kobject *kobj, struct attribute *attr, char *buf)
307 struct kobj_attribute *ka =
308 container_of(attr, struct kobj_attribute, attr);
310 if (ka->show == NULL)
313 return (ka->show(kobj, ka, buf));
317 lkpi_kobj_attr_store(struct kobject *kobj, struct attribute *attr,
318 const char *buf, size_t count)
320 struct kobj_attribute *ka =
321 container_of(attr, struct kobj_attribute, attr);
323 if (ka->store == NULL)
326 return (ka->store(kobj, ka, buf, count));
329 const struct sysfs_ops kobj_sysfs_ops = {
330 .show = lkpi_kobj_attr_show,
331 .store = lkpi_kobj_attr_store,
335 linux_device_release(struct device *dev)
337 pr_debug("linux_device_release: %s\n", dev_name(dev));
342 linux_class_show(struct kobject *kobj, struct attribute *attr, char *buf)
344 struct class_attribute *dattr;
347 dattr = container_of(attr, struct class_attribute, attr);
350 error = dattr->show(container_of(kobj, struct class, kobj),
356 linux_class_store(struct kobject *kobj, struct attribute *attr, const char *buf,
359 struct class_attribute *dattr;
362 dattr = container_of(attr, struct class_attribute, attr);
365 error = dattr->store(container_of(kobj, struct class, kobj),
371 linux_class_release(struct kobject *kobj)
375 class = container_of(kobj, struct class, kobj);
376 if (class->class_release)
377 class->class_release(class);
380 static const struct sysfs_ops linux_class_sysfs = {
381 .show = linux_class_show,
382 .store = linux_class_store,
385 const struct kobj_type linux_class_ktype = {
386 .release = linux_class_release,
387 .sysfs_ops = &linux_class_sysfs
391 linux_dev_release(struct kobject *kobj)
395 dev = container_of(kobj, struct device, kobj);
396 /* This is the precedence defined by linux. */
399 else if (dev->class && dev->class->dev_release)
400 dev->class->dev_release(dev);
404 linux_dev_show(struct kobject *kobj, struct attribute *attr, char *buf)
406 struct device_attribute *dattr;
409 dattr = container_of(attr, struct device_attribute, attr);
412 error = dattr->show(container_of(kobj, struct device, kobj),
418 linux_dev_store(struct kobject *kobj, struct attribute *attr, const char *buf,
421 struct device_attribute *dattr;
424 dattr = container_of(attr, struct device_attribute, attr);
427 error = dattr->store(container_of(kobj, struct device, kobj),
432 static const struct sysfs_ops linux_dev_sysfs = {
433 .show = linux_dev_show,
434 .store = linux_dev_store,
437 const struct kobj_type linux_dev_ktype = {
438 .release = linux_dev_release,
439 .sysfs_ops = &linux_dev_sysfs
443 device_create(struct class *class, struct device *parent, dev_t devt,
444 void *drvdata, const char *fmt, ...)
449 dev = kzalloc(sizeof(*dev), M_WAITOK);
450 dev->parent = parent;
453 dev->driver_data = drvdata;
454 dev->release = linux_device_release;
456 kobject_set_name_vargs(&dev->kobj, fmt, args);
458 device_register(dev);
464 device_create_groups_vargs(struct class *class, struct device *parent,
465 dev_t devt, void *drvdata, const struct attribute_group **groups,
466 const char *fmt, va_list args)
468 struct device *dev = NULL;
469 int retval = -ENODEV;
471 if (class == NULL || IS_ERR(class))
474 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
482 dev->parent = parent;
483 dev->groups = groups;
484 dev->release = device_create_release;
485 /* device_initialize() needs the class and parent to be set */
486 device_initialize(dev);
487 dev_set_drvdata(dev, drvdata);
489 retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
493 retval = device_add(dev);
501 return ERR_PTR(retval);
505 class_create(struct module *owner, const char *name)
510 class = kzalloc(sizeof(*class), M_WAITOK);
511 class->owner = owner;
513 class->class_release = linux_class_kfree;
514 error = class_register(class);
524 kobject_init_and_add(struct kobject *kobj, const struct kobj_type *ktype,
525 struct kobject *parent, const char *fmt, ...)
530 kobject_init(kobj, ktype);
532 kobj->parent = parent;
536 error = kobject_set_name_vargs(kobj, fmt, args);
540 return kobject_add_complete(kobj, parent);
544 linux_kq_lock(void *arg)
551 linux_kq_unlock(void *arg)
559 linux_kq_assert_lock(void *arg, int what)
564 if (what == LA_LOCKED)
565 mtx_assert(&s->m, MA_OWNED);
567 mtx_assert(&s->m, MA_NOTOWNED);
572 linux_file_kqfilter_poll(struct linux_file *, int);
575 linux_file_alloc(void)
577 struct linux_file *filp;
579 filp = kzalloc(sizeof(*filp), GFP_KERNEL);
581 /* set initial refcount */
584 /* setup fields needed by kqueue support */
585 spin_lock_init(&filp->f_kqlock);
586 knlist_init(&filp->f_selinfo.si_note, &filp->f_kqlock,
587 linux_kq_lock, linux_kq_unlock, linux_kq_assert_lock);
593 linux_file_free(struct linux_file *filp)
595 if (filp->_file == NULL) {
596 if (filp->f_op != NULL && filp->f_op->release != NULL)
597 filp->f_op->release(filp->f_vnode, filp);
598 if (filp->f_shmem != NULL)
599 vm_object_deallocate(filp->f_shmem);
600 kfree_rcu(filp, rcu);
603 * The close method of the character device or file
604 * will free the linux_file structure:
606 _fdrop(filp->_file, curthread);
613 struct linux_cdev *cdev;
615 cdev = kzalloc(sizeof(struct linux_cdev), M_WAITOK);
616 kobject_init(&cdev->kobj, &linux_cdev_ktype);
622 linux_cdev_pager_fault(vm_object_t vm_obj, vm_ooffset_t offset, int prot,
625 struct vm_area_struct *vmap;
627 vmap = linux_cdev_handle_find(vm_obj->handle);
630 MPASS(vmap->vm_private_data == vm_obj->handle);
632 if (likely(vmap->vm_ops != NULL && offset < vmap->vm_len)) {
633 vm_paddr_t paddr = IDX_TO_OFF(vmap->vm_pfn) + offset;
636 if (((*mres)->flags & PG_FICTITIOUS) != 0) {
638 * If the passed in result page is a fake
639 * page, update it with the new physical
643 vm_page_updatefake(page, paddr, vm_obj->memattr);
646 * Replace the passed in "mres" page with our
647 * own fake page and free up the all of the
650 VM_OBJECT_WUNLOCK(vm_obj);
651 page = vm_page_getfake(paddr, vm_obj->memattr);
652 VM_OBJECT_WLOCK(vm_obj);
654 vm_page_replace(page, vm_obj, (*mres)->pindex, *mres);
658 return (VM_PAGER_OK);
660 return (VM_PAGER_FAIL);
664 linux_cdev_pager_populate(vm_object_t vm_obj, vm_pindex_t pidx, int fault_type,
665 vm_prot_t max_prot, vm_pindex_t *first, vm_pindex_t *last)
667 struct vm_area_struct *vmap;
670 /* get VM area structure */
671 vmap = linux_cdev_handle_find(vm_obj->handle);
673 MPASS(vmap->vm_private_data == vm_obj->handle);
675 VM_OBJECT_WUNLOCK(vm_obj);
677 linux_set_current(curthread);
679 down_write(&vmap->vm_mm->mmap_sem);
680 if (unlikely(vmap->vm_ops == NULL)) {
681 err = VM_FAULT_SIGBUS;
685 /* fill out VM fault structure */
686 vmf.virtual_address = (void *)(uintptr_t)IDX_TO_OFF(pidx);
687 vmf.flags = (fault_type & VM_PROT_WRITE) ? FAULT_FLAG_WRITE : 0;
692 vmap->vm_pfn_count = 0;
693 vmap->vm_pfn_pcount = &vmap->vm_pfn_count;
694 vmap->vm_obj = vm_obj;
696 err = vmap->vm_ops->fault(&vmf);
698 while (vmap->vm_pfn_count == 0 && err == VM_FAULT_NOPAGE) {
699 kern_yield(PRI_USER);
700 err = vmap->vm_ops->fault(&vmf);
704 /* translate return code */
707 err = VM_PAGER_AGAIN;
709 case VM_FAULT_SIGBUS:
712 case VM_FAULT_NOPAGE:
714 * By contract the fault handler will return having
715 * busied all the pages itself. If pidx is already
716 * found in the object, it will simply xbusy the first
717 * page and return with vm_pfn_count set to 1.
719 *first = vmap->vm_pfn_first;
720 *last = *first + vmap->vm_pfn_count - 1;
724 err = VM_PAGER_ERROR;
727 up_write(&vmap->vm_mm->mmap_sem);
728 VM_OBJECT_WLOCK(vm_obj);
732 static struct rwlock linux_vma_lock;
733 static TAILQ_HEAD(, vm_area_struct) linux_vma_head =
734 TAILQ_HEAD_INITIALIZER(linux_vma_head);
737 linux_cdev_handle_free(struct vm_area_struct *vmap)
739 /* Drop reference on vm_file */
740 if (vmap->vm_file != NULL)
743 /* Drop reference on mm_struct */
750 linux_cdev_handle_remove(struct vm_area_struct *vmap)
752 rw_wlock(&linux_vma_lock);
753 TAILQ_REMOVE(&linux_vma_head, vmap, vm_entry);
754 rw_wunlock(&linux_vma_lock);
757 static struct vm_area_struct *
758 linux_cdev_handle_find(void *handle)
760 struct vm_area_struct *vmap;
762 rw_rlock(&linux_vma_lock);
763 TAILQ_FOREACH(vmap, &linux_vma_head, vm_entry) {
764 if (vmap->vm_private_data == handle)
767 rw_runlock(&linux_vma_lock);
772 linux_cdev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
773 vm_ooffset_t foff, struct ucred *cred, u_short *color)
776 MPASS(linux_cdev_handle_find(handle) != NULL);
782 linux_cdev_pager_dtor(void *handle)
784 const struct vm_operations_struct *vm_ops;
785 struct vm_area_struct *vmap;
787 vmap = linux_cdev_handle_find(handle);
791 * Remove handle before calling close operation to prevent
792 * other threads from reusing the handle pointer.
794 linux_cdev_handle_remove(vmap);
796 down_write(&vmap->vm_mm->mmap_sem);
797 vm_ops = vmap->vm_ops;
798 if (likely(vm_ops != NULL))
800 up_write(&vmap->vm_mm->mmap_sem);
802 linux_cdev_handle_free(vmap);
805 static struct cdev_pager_ops linux_cdev_pager_ops[2] = {
808 .cdev_pg_populate = linux_cdev_pager_populate,
809 .cdev_pg_ctor = linux_cdev_pager_ctor,
810 .cdev_pg_dtor = linux_cdev_pager_dtor
814 .cdev_pg_fault = linux_cdev_pager_fault,
815 .cdev_pg_ctor = linux_cdev_pager_ctor,
816 .cdev_pg_dtor = linux_cdev_pager_dtor
821 zap_vma_ptes(struct vm_area_struct *vma, unsigned long address,
828 if (obj == NULL || (obj->flags & OBJ_UNMANAGED) != 0)
830 VM_OBJECT_RLOCK(obj);
831 for (m = vm_page_find_least(obj, OFF_TO_IDX(address));
832 m != NULL && m->pindex < OFF_TO_IDX(address + size);
833 m = TAILQ_NEXT(m, listq))
835 VM_OBJECT_RUNLOCK(obj);
840 vma_set_file(struct vm_area_struct *vma, struct linux_file *file)
842 struct linux_file *tmp;
844 /* Changing an anonymous vma with this is illegal */
851 static struct file_operations dummy_ldev_ops = {
855 static struct linux_cdev dummy_ldev = {
856 .ops = &dummy_ldev_ops,
859 #define LDEV_SI_DTR 0x0001
860 #define LDEV_SI_REF 0x0002
863 linux_get_fop(struct linux_file *filp, const struct file_operations **fop,
864 struct linux_cdev **dev)
866 struct linux_cdev *ldev;
872 if (ldev->kobj.ktype == &linux_cdev_static_ktype) {
873 refcount_acquire(&ldev->refs);
875 for (siref = ldev->siref;;) {
876 if ((siref & LDEV_SI_DTR) != 0) {
880 MPASS((ldev->siref & LDEV_SI_DTR) == 0);
881 } else if (atomic_fcmpset_int(&ldev->siref,
882 &siref, siref + LDEV_SI_REF)) {
892 linux_drop_fop(struct linux_cdev *ldev)
897 if (ldev->kobj.ktype == &linux_cdev_static_ktype) {
898 linux_cdev_deref(ldev);
900 MPASS(ldev->kobj.ktype == &linux_cdev_ktype);
901 MPASS((ldev->siref & ~LDEV_SI_DTR) != 0);
902 atomic_subtract_int(&ldev->siref, LDEV_SI_REF);
906 #define OPW(fp,td,code) ({ \
907 struct file *__fpop; \
908 __typeof(code) __retval; \
910 __fpop = (td)->td_fpop; \
911 (td)->td_fpop = (fp); \
913 (td)->td_fpop = __fpop; \
918 linux_dev_fdopen(struct cdev *dev, int fflags, struct thread *td,
921 struct linux_cdev *ldev;
922 struct linux_file *filp;
923 const struct file_operations *fop;
928 filp = linux_file_alloc();
929 filp->f_dentry = &filp->f_dentry_store;
930 filp->f_op = ldev->ops;
931 filp->f_mode = file->f_flag;
932 filp->f_flags = file->f_flag;
933 filp->f_vnode = file->f_vnode;
935 refcount_acquire(&ldev->refs);
938 linux_set_current(td);
939 linux_get_fop(filp, &fop, &ldev);
941 if (fop->open != NULL) {
942 error = -fop->open(file->f_vnode, filp);
944 linux_drop_fop(ldev);
945 linux_cdev_deref(filp->f_cdev);
951 /* hold on to the vnode - used for fstat() */
952 vhold(filp->f_vnode);
954 /* release the file from devfs */
955 finit(file, filp->f_mode, DTYPE_DEV, filp, &linuxfileops);
956 linux_drop_fop(ldev);
960 #define LINUX_IOCTL_MIN_PTR 0x10000UL
961 #define LINUX_IOCTL_MAX_PTR (LINUX_IOCTL_MIN_PTR + IOCPARM_MAX)
964 linux_remap_address(void **uaddr, size_t len)
966 uintptr_t uaddr_val = (uintptr_t)(*uaddr);
968 if (unlikely(uaddr_val >= LINUX_IOCTL_MIN_PTR &&
969 uaddr_val < LINUX_IOCTL_MAX_PTR)) {
970 struct task_struct *pts = current;
976 /* compute data offset */
977 uaddr_val -= LINUX_IOCTL_MIN_PTR;
979 /* check that length is within bounds */
980 if ((len > IOCPARM_MAX) ||
981 (uaddr_val + len) > pts->bsd_ioctl_len) {
986 /* re-add kernel buffer address */
987 uaddr_val += (uintptr_t)pts->bsd_ioctl_data;
989 /* update address location */
990 *uaddr = (void *)uaddr_val;
997 linux_copyin(const void *uaddr, void *kaddr, size_t len)
999 if (linux_remap_address(__DECONST(void **, &uaddr), len)) {
1002 memcpy(kaddr, uaddr, len);
1005 return (-copyin(uaddr, kaddr, len));
1009 linux_copyout(const void *kaddr, void *uaddr, size_t len)
1011 if (linux_remap_address(&uaddr, len)) {
1014 memcpy(uaddr, kaddr, len);
1017 return (-copyout(kaddr, uaddr, len));
1021 linux_clear_user(void *_uaddr, size_t _len)
1023 uint8_t *uaddr = _uaddr;
1026 /* make sure uaddr is aligned before going into the fast loop */
1027 while (((uintptr_t)uaddr & 7) != 0 && len > 7) {
1028 if (subyte(uaddr, 0))
1034 /* zero 8 bytes at a time */
1037 if (suword64(uaddr, 0))
1040 if (suword32(uaddr, 0))
1042 if (suword32(uaddr + 4, 0))
1049 /* zero fill end, if any */
1051 if (subyte(uaddr, 0))
1060 linux_access_ok(const void *uaddr, size_t len)
1065 /* get start and end address */
1066 saddr = (uintptr_t)uaddr;
1067 eaddr = (uintptr_t)uaddr + len;
1069 /* verify addresses are valid for userspace */
1070 return ((saddr == eaddr) ||
1071 (eaddr > saddr && eaddr <= VM_MAXUSER_ADDRESS));
1075 * This function should return either EINTR or ERESTART depending on
1076 * the signal type sent to this thread:
1079 linux_get_error(struct task_struct *task, int error)
1081 /* check for signal type interrupt code */
1082 if (error == EINTR || error == ERESTARTSYS || error == ERESTART) {
1083 error = -linux_schedule_get_interrupt_value(task);
1091 linux_file_ioctl_sub(struct file *fp, struct linux_file *filp,
1092 const struct file_operations *fop, u_long cmd, caddr_t data,
1095 struct task_struct *task = current;
1099 size = IOCPARM_LEN(cmd);
1100 /* refer to logic in sys_ioctl() */
1103 * Setup hint for linux_copyin() and linux_copyout().
1105 * Background: Linux code expects a user-space address
1106 * while FreeBSD supplies a kernel-space address.
1108 task->bsd_ioctl_data = data;
1109 task->bsd_ioctl_len = size;
1110 data = (void *)LINUX_IOCTL_MIN_PTR;
1112 /* fetch user-space pointer */
1113 data = *(void **)data;
1115 #ifdef COMPAT_FREEBSD32
1116 if (SV_PROC_FLAG(td->td_proc, SV_ILP32)) {
1117 /* try the compat IOCTL handler first */
1118 if (fop->compat_ioctl != NULL) {
1119 error = -OPW(fp, td, fop->compat_ioctl(filp,
1120 cmd, (u_long)data));
1125 /* fallback to the regular IOCTL handler, if any */
1126 if (error == ENOTTY && fop->unlocked_ioctl != NULL) {
1127 error = -OPW(fp, td, fop->unlocked_ioctl(filp,
1128 cmd, (u_long)data));
1133 if (fop->unlocked_ioctl != NULL) {
1134 error = -OPW(fp, td, fop->unlocked_ioctl(filp,
1135 cmd, (u_long)data));
1141 task->bsd_ioctl_data = NULL;
1142 task->bsd_ioctl_len = 0;
1145 if (error == EWOULDBLOCK) {
1146 /* update kqfilter status, if any */
1147 linux_file_kqfilter_poll(filp,
1148 LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
1150 error = linux_get_error(task, error);
1155 #define LINUX_POLL_TABLE_NORMAL ((poll_table *)1)
1158 * This function atomically updates the poll wakeup state and returns
1159 * the previous state at the time of update.
1162 linux_poll_wakeup_state(atomic_t *v, const uint8_t *pstate)
1168 while ((old = atomic_cmpxchg(v, c, pstate[c])) != c)
1175 linux_poll_wakeup_callback(wait_queue_t *wq, unsigned int wq_state, int flags, void *key)
1177 static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1178 [LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_INIT, /* NOP */
1179 [LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_NOT_READY, /* NOP */
1180 [LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_READY,
1181 [LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_READY, /* NOP */
1183 struct linux_file *filp = container_of(wq, struct linux_file, f_wait_queue.wq);
1185 switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1186 case LINUX_FWQ_STATE_QUEUED:
1187 linux_poll_wakeup(filp);
1195 linux_poll_wait(struct linux_file *filp, wait_queue_head_t *wqh, poll_table *p)
1197 static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1198 [LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_NOT_READY,
1199 [LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_NOT_READY, /* NOP */
1200 [LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_QUEUED, /* NOP */
1201 [LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_QUEUED,
1204 /* check if we are called inside the select system call */
1205 if (p == LINUX_POLL_TABLE_NORMAL)
1206 selrecord(curthread, &filp->f_selinfo);
1208 switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1209 case LINUX_FWQ_STATE_INIT:
1210 /* NOTE: file handles can only belong to one wait-queue */
1211 filp->f_wait_queue.wqh = wqh;
1212 filp->f_wait_queue.wq.func = &linux_poll_wakeup_callback;
1213 add_wait_queue(wqh, &filp->f_wait_queue.wq);
1214 atomic_set(&filp->f_wait_queue.state, LINUX_FWQ_STATE_QUEUED);
1222 linux_poll_wait_dequeue(struct linux_file *filp)
1224 static const uint8_t state[LINUX_FWQ_STATE_MAX] = {
1225 [LINUX_FWQ_STATE_INIT] = LINUX_FWQ_STATE_INIT, /* NOP */
1226 [LINUX_FWQ_STATE_NOT_READY] = LINUX_FWQ_STATE_INIT,
1227 [LINUX_FWQ_STATE_QUEUED] = LINUX_FWQ_STATE_INIT,
1228 [LINUX_FWQ_STATE_READY] = LINUX_FWQ_STATE_INIT,
1231 seldrain(&filp->f_selinfo);
1233 switch (linux_poll_wakeup_state(&filp->f_wait_queue.state, state)) {
1234 case LINUX_FWQ_STATE_NOT_READY:
1235 case LINUX_FWQ_STATE_QUEUED:
1236 case LINUX_FWQ_STATE_READY:
1237 remove_wait_queue(filp->f_wait_queue.wqh, &filp->f_wait_queue.wq);
1245 linux_poll_wakeup(struct linux_file *filp)
1247 /* this function should be NULL-safe */
1251 selwakeup(&filp->f_selinfo);
1253 spin_lock(&filp->f_kqlock);
1254 filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ |
1255 LINUX_KQ_FLAG_NEED_WRITE;
1257 /* make sure the "knote" gets woken up */
1258 KNOTE_LOCKED(&filp->f_selinfo.si_note, 1);
1259 spin_unlock(&filp->f_kqlock);
1263 linux_file_kqfilter_detach(struct knote *kn)
1265 struct linux_file *filp = kn->kn_hook;
1267 spin_lock(&filp->f_kqlock);
1268 knlist_remove(&filp->f_selinfo.si_note, kn, 1);
1269 spin_unlock(&filp->f_kqlock);
1273 linux_file_kqfilter_read_event(struct knote *kn, long hint)
1275 struct linux_file *filp = kn->kn_hook;
1277 mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1279 return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_READ) ? 1 : 0);
1283 linux_file_kqfilter_write_event(struct knote *kn, long hint)
1285 struct linux_file *filp = kn->kn_hook;
1287 mtx_assert(&filp->f_kqlock.m, MA_OWNED);
1289 return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_WRITE) ? 1 : 0);
1292 static struct filterops linux_dev_kqfiltops_read = {
1294 .f_detach = linux_file_kqfilter_detach,
1295 .f_event = linux_file_kqfilter_read_event,
1298 static struct filterops linux_dev_kqfiltops_write = {
1300 .f_detach = linux_file_kqfilter_detach,
1301 .f_event = linux_file_kqfilter_write_event,
1305 linux_file_kqfilter_poll(struct linux_file *filp, int kqflags)
1308 const struct file_operations *fop;
1309 struct linux_cdev *ldev;
1312 if ((filp->f_kqflags & kqflags) == 0)
1317 linux_get_fop(filp, &fop, &ldev);
1318 /* get the latest polling state */
1319 temp = OPW(filp->_file, td, fop->poll(filp, NULL));
1320 linux_drop_fop(ldev);
1322 spin_lock(&filp->f_kqlock);
1324 filp->f_kqflags &= ~(LINUX_KQ_FLAG_NEED_READ |
1325 LINUX_KQ_FLAG_NEED_WRITE);
1326 /* update kqflags */
1327 if ((temp & (POLLIN | POLLOUT)) != 0) {
1328 if ((temp & POLLIN) != 0)
1329 filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ;
1330 if ((temp & POLLOUT) != 0)
1331 filp->f_kqflags |= LINUX_KQ_FLAG_NEED_WRITE;
1333 /* make sure the "knote" gets woken up */
1334 KNOTE_LOCKED(&filp->f_selinfo.si_note, 0);
1336 spin_unlock(&filp->f_kqlock);
1340 linux_file_kqfilter(struct file *file, struct knote *kn)
1342 struct linux_file *filp;
1347 filp = (struct linux_file *)file->f_data;
1348 filp->f_flags = file->f_flag;
1349 if (filp->f_op->poll == NULL)
1352 spin_lock(&filp->f_kqlock);
1353 switch (kn->kn_filter) {
1355 filp->f_kqflags |= LINUX_KQ_FLAG_HAS_READ;
1356 kn->kn_fop = &linux_dev_kqfiltops_read;
1358 knlist_add(&filp->f_selinfo.si_note, kn, 1);
1362 filp->f_kqflags |= LINUX_KQ_FLAG_HAS_WRITE;
1363 kn->kn_fop = &linux_dev_kqfiltops_write;
1365 knlist_add(&filp->f_selinfo.si_note, kn, 1);
1372 spin_unlock(&filp->f_kqlock);
1375 linux_set_current(td);
1377 /* update kqfilter status, if any */
1378 linux_file_kqfilter_poll(filp,
1379 LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
1385 linux_file_mmap_single(struct file *fp, const struct file_operations *fop,
1386 vm_ooffset_t *offset, vm_size_t size, struct vm_object **object,
1387 int nprot, bool is_shared, struct thread *td)
1389 struct task_struct *task;
1390 struct vm_area_struct *vmap;
1391 struct mm_struct *mm;
1392 struct linux_file *filp;
1396 filp = (struct linux_file *)fp->f_data;
1397 filp->f_flags = fp->f_flag;
1399 if (fop->mmap == NULL)
1400 return (EOPNOTSUPP);
1402 linux_set_current(td);
1405 * The same VM object might be shared by multiple processes
1406 * and the mm_struct is usually freed when a process exits.
1408 * The atomic reference below makes sure the mm_struct is
1409 * available as long as the vmap is in the linux_vma_head.
1413 if (atomic_inc_not_zero(&mm->mm_users) == 0)
1416 vmap = kzalloc(sizeof(*vmap), GFP_KERNEL);
1418 vmap->vm_end = size;
1419 vmap->vm_pgoff = *offset / PAGE_SIZE;
1421 vmap->vm_flags = vmap->vm_page_prot = (nprot & VM_PROT_ALL);
1423 vmap->vm_flags |= VM_SHARED;
1424 vmap->vm_ops = NULL;
1425 vmap->vm_file = get_file(filp);
1428 if (unlikely(down_write_killable(&vmap->vm_mm->mmap_sem))) {
1429 error = linux_get_error(task, EINTR);
1431 error = -OPW(fp, td, fop->mmap(filp, vmap));
1432 error = linux_get_error(task, error);
1433 up_write(&vmap->vm_mm->mmap_sem);
1437 linux_cdev_handle_free(vmap);
1441 attr = pgprot2cachemode(vmap->vm_page_prot);
1443 if (vmap->vm_ops != NULL) {
1444 struct vm_area_struct *ptr;
1445 void *vm_private_data;
1448 if (vmap->vm_ops->open == NULL ||
1449 vmap->vm_ops->close == NULL ||
1450 vmap->vm_private_data == NULL) {
1451 /* free allocated VM area struct */
1452 linux_cdev_handle_free(vmap);
1456 vm_private_data = vmap->vm_private_data;
1458 rw_wlock(&linux_vma_lock);
1459 TAILQ_FOREACH(ptr, &linux_vma_head, vm_entry) {
1460 if (ptr->vm_private_data == vm_private_data)
1463 /* check if there is an existing VM area struct */
1465 /* check if the VM area structure is invalid */
1466 if (ptr->vm_ops == NULL ||
1467 ptr->vm_ops->open == NULL ||
1468 ptr->vm_ops->close == NULL) {
1473 vm_no_fault = (ptr->vm_ops->fault == NULL);
1476 /* insert VM area structure into list */
1477 TAILQ_INSERT_TAIL(&linux_vma_head, vmap, vm_entry);
1479 vm_no_fault = (vmap->vm_ops->fault == NULL);
1481 rw_wunlock(&linux_vma_lock);
1484 /* free allocated VM area struct */
1485 linux_cdev_handle_free(vmap);
1486 /* check for stale VM area struct */
1487 if (error != EEXIST)
1491 /* check if there is no fault handler */
1493 *object = cdev_pager_allocate(vm_private_data, OBJT_DEVICE,
1494 &linux_cdev_pager_ops[1], size, nprot, *offset,
1497 *object = cdev_pager_allocate(vm_private_data, OBJT_MGTDEVICE,
1498 &linux_cdev_pager_ops[0], size, nprot, *offset,
1502 /* check if allocating the VM object failed */
1503 if (*object == NULL) {
1505 /* remove VM area struct from list */
1506 linux_cdev_handle_remove(vmap);
1507 /* free allocated VM area struct */
1508 linux_cdev_handle_free(vmap);
1515 sg = sglist_alloc(1, M_WAITOK);
1516 sglist_append_phys(sg,
1517 (vm_paddr_t)vmap->vm_pfn << PAGE_SHIFT, vmap->vm_len);
1519 *object = vm_pager_allocate(OBJT_SG, sg, vmap->vm_len,
1520 nprot, 0, td->td_ucred);
1522 linux_cdev_handle_free(vmap);
1524 if (*object == NULL) {
1530 if (attr != VM_MEMATTR_DEFAULT) {
1531 VM_OBJECT_WLOCK(*object);
1532 vm_object_set_memattr(*object, attr);
1533 VM_OBJECT_WUNLOCK(*object);
1539 struct cdevsw linuxcdevsw = {
1540 .d_version = D_VERSION,
1541 .d_fdopen = linux_dev_fdopen,
1542 .d_name = "lkpidev",
1546 linux_file_read(struct file *file, struct uio *uio, struct ucred *active_cred,
1547 int flags, struct thread *td)
1549 struct linux_file *filp;
1550 const struct file_operations *fop;
1551 struct linux_cdev *ldev;
1556 filp = (struct linux_file *)file->f_data;
1557 filp->f_flags = file->f_flag;
1558 /* XXX no support for I/O vectors currently */
1559 if (uio->uio_iovcnt != 1)
1560 return (EOPNOTSUPP);
1561 if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1563 linux_set_current(td);
1564 linux_get_fop(filp, &fop, &ldev);
1565 if (fop->read != NULL) {
1566 bytes = OPW(file, td, fop->read(filp,
1567 uio->uio_iov->iov_base,
1568 uio->uio_iov->iov_len, &uio->uio_offset));
1570 uio->uio_iov->iov_base =
1571 ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1572 uio->uio_iov->iov_len -= bytes;
1573 uio->uio_resid -= bytes;
1575 error = linux_get_error(current, -bytes);
1580 /* update kqfilter status, if any */
1581 linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_READ);
1582 linux_drop_fop(ldev);
1588 linux_file_write(struct file *file, struct uio *uio, struct ucred *active_cred,
1589 int flags, struct thread *td)
1591 struct linux_file *filp;
1592 const struct file_operations *fop;
1593 struct linux_cdev *ldev;
1597 filp = (struct linux_file *)file->f_data;
1598 filp->f_flags = file->f_flag;
1599 /* XXX no support for I/O vectors currently */
1600 if (uio->uio_iovcnt != 1)
1601 return (EOPNOTSUPP);
1602 if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1604 linux_set_current(td);
1605 linux_get_fop(filp, &fop, &ldev);
1606 if (fop->write != NULL) {
1607 bytes = OPW(file, td, fop->write(filp,
1608 uio->uio_iov->iov_base,
1609 uio->uio_iov->iov_len, &uio->uio_offset));
1611 uio->uio_iov->iov_base =
1612 ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1613 uio->uio_iov->iov_len -= bytes;
1614 uio->uio_resid -= bytes;
1617 error = linux_get_error(current, -bytes);
1622 /* update kqfilter status, if any */
1623 linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_WRITE);
1625 linux_drop_fop(ldev);
1631 linux_file_poll(struct file *file, int events, struct ucred *active_cred,
1634 struct linux_file *filp;
1635 const struct file_operations *fop;
1636 struct linux_cdev *ldev;
1639 filp = (struct linux_file *)file->f_data;
1640 filp->f_flags = file->f_flag;
1641 linux_set_current(td);
1642 linux_get_fop(filp, &fop, &ldev);
1643 if (fop->poll != NULL) {
1644 revents = OPW(file, td, fop->poll(filp,
1645 LINUX_POLL_TABLE_NORMAL)) & events;
1649 linux_drop_fop(ldev);
1654 linux_file_close(struct file *file, struct thread *td)
1656 struct linux_file *filp;
1657 int (*release)(struct inode *, struct linux_file *);
1658 const struct file_operations *fop;
1659 struct linux_cdev *ldev;
1662 filp = (struct linux_file *)file->f_data;
1664 KASSERT(file_count(filp) == 0,
1665 ("File refcount(%d) is not zero", file_count(filp)));
1671 filp->f_flags = file->f_flag;
1672 linux_set_current(td);
1673 linux_poll_wait_dequeue(filp);
1674 linux_get_fop(filp, &fop, &ldev);
1676 * Always use the real release function, if any, to avoid
1677 * leaking device resources:
1679 release = filp->f_op->release;
1680 if (release != NULL)
1681 error = -OPW(file, td, release(filp->f_vnode, filp));
1682 funsetown(&filp->f_sigio);
1683 if (filp->f_vnode != NULL)
1684 vdrop(filp->f_vnode);
1685 linux_drop_fop(ldev);
1686 ldev = filp->f_cdev;
1688 linux_cdev_deref(ldev);
1689 linux_synchronize_rcu(RCU_TYPE_REGULAR);
1696 linux_file_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *cred,
1699 struct linux_file *filp;
1700 const struct file_operations *fop;
1701 struct linux_cdev *ldev;
1702 struct fiodgname_arg *fgn;
1707 filp = (struct linux_file *)fp->f_data;
1708 filp->f_flags = fp->f_flag;
1709 linux_get_fop(filp, &fop, &ldev);
1711 linux_set_current(td);
1716 if (fop->fasync == NULL)
1718 error = -OPW(fp, td, fop->fasync(0, filp, fp->f_flag & FASYNC));
1721 error = fsetown(*(int *)data, &filp->f_sigio);
1723 if (fop->fasync == NULL)
1725 error = -OPW(fp, td, fop->fasync(0, filp,
1726 fp->f_flag & FASYNC));
1730 *(int *)data = fgetown(&filp->f_sigio);
1733 #ifdef COMPAT_FREEBSD32
1736 if (filp->f_cdev == NULL || filp->f_cdev->cdev == NULL) {
1741 p = devtoname(filp->f_cdev->cdev);
1747 error = copyout(p, fiodgname_buf_get_ptr(fgn, cmd), i);
1750 error = linux_file_ioctl_sub(fp, filp, fop, cmd, data, td);
1753 linux_drop_fop(ldev);
1758 linux_file_mmap_sub(struct thread *td, vm_size_t objsize, vm_prot_t prot,
1759 vm_prot_t maxprot, int flags, struct file *fp,
1760 vm_ooffset_t *foff, const struct file_operations *fop, vm_object_t *objp)
1763 * Character devices do not provide private mappings
1766 if ((maxprot & VM_PROT_WRITE) == 0 &&
1767 (prot & VM_PROT_WRITE) != 0)
1769 if ((flags & (MAP_PRIVATE | MAP_COPY)) != 0)
1772 return (linux_file_mmap_single(fp, fop, foff, objsize, objp,
1773 (int)prot, (flags & MAP_SHARED) ? true : false, td));
1777 linux_file_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
1778 vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
1781 struct linux_file *filp;
1782 const struct file_operations *fop;
1783 struct linux_cdev *ldev;
1790 filp = (struct linux_file *)fp->f_data;
1794 return (EOPNOTSUPP);
1797 * Ensure that file and memory protections are
1801 if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
1802 maxprot = VM_PROT_NONE;
1803 if ((prot & VM_PROT_EXECUTE) != 0)
1806 maxprot = VM_PROT_EXECUTE;
1807 if ((fp->f_flag & FREAD) != 0)
1808 maxprot |= VM_PROT_READ;
1809 else if ((prot & VM_PROT_READ) != 0)
1813 * If we are sharing potential changes via MAP_SHARED and we
1814 * are trying to get write permission although we opened it
1815 * without asking for it, bail out.
1817 * Note that most character devices always share mappings.
1819 * Rely on linux_file_mmap_sub() to fail invalid MAP_PRIVATE
1820 * requests rather than doing it here.
1822 if ((flags & MAP_SHARED) != 0) {
1823 if ((fp->f_flag & FWRITE) != 0)
1824 maxprot |= VM_PROT_WRITE;
1825 else if ((prot & VM_PROT_WRITE) != 0)
1828 maxprot &= cap_maxprot;
1830 linux_get_fop(filp, &fop, &ldev);
1831 error = linux_file_mmap_sub(td, size, prot, maxprot, flags, fp,
1832 &foff, fop, &object);
1836 error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
1839 vm_object_deallocate(object);
1841 linux_drop_fop(ldev);
1846 linux_file_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
1848 struct linux_file *filp;
1852 filp = (struct linux_file *)fp->f_data;
1853 if (filp->f_vnode == NULL)
1854 return (EOPNOTSUPP);
1858 vn_lock(vp, LK_SHARED | LK_RETRY);
1859 error = VOP_STAT(vp, sb, curthread->td_ucred, NOCRED);
1866 linux_file_fill_kinfo(struct file *fp, struct kinfo_file *kif,
1867 struct filedesc *fdp)
1869 struct linux_file *filp;
1877 kif->kf_type = KF_TYPE_DEV;
1880 FILEDESC_SUNLOCK(fdp);
1881 error = vn_fill_kinfo_vnode(vp, kif);
1883 kif->kf_type = KF_TYPE_VNODE;
1884 FILEDESC_SLOCK(fdp);
1890 linux_iminor(struct inode *inode)
1892 struct linux_cdev *ldev;
1894 if (inode == NULL || inode->v_rdev == NULL ||
1895 inode->v_rdev->si_devsw != &linuxcdevsw)
1897 ldev = inode->v_rdev->si_drv1;
1901 return (minor(ldev->dev));
1904 struct fileops linuxfileops = {
1905 .fo_read = linux_file_read,
1906 .fo_write = linux_file_write,
1907 .fo_truncate = invfo_truncate,
1908 .fo_kqfilter = linux_file_kqfilter,
1909 .fo_stat = linux_file_stat,
1910 .fo_fill_kinfo = linux_file_fill_kinfo,
1911 .fo_poll = linux_file_poll,
1912 .fo_close = linux_file_close,
1913 .fo_ioctl = linux_file_ioctl,
1914 .fo_mmap = linux_file_mmap,
1915 .fo_chmod = invfo_chmod,
1916 .fo_chown = invfo_chown,
1917 .fo_sendfile = invfo_sendfile,
1918 .fo_flags = DFLAG_PASSABLE,
1922 * Hash of vmmap addresses. This is infrequently accessed and does not
1923 * need to be particularly large. This is done because we must store the
1924 * caller's idea of the map size to properly unmap.
1927 LIST_ENTRY(vmmap) vm_next;
1929 unsigned long vm_size;
1933 struct vmmap *lh_first;
1935 #define VMMAP_HASH_SIZE 64
1936 #define VMMAP_HASH_MASK (VMMAP_HASH_SIZE - 1)
1937 #define VM_HASH(addr) ((uintptr_t)(addr) >> PAGE_SHIFT) & VMMAP_HASH_MASK
1938 static struct vmmaphd vmmaphead[VMMAP_HASH_SIZE];
1939 static struct mtx vmmaplock;
1942 vmmap_add(void *addr, unsigned long size)
1944 struct vmmap *vmmap;
1946 vmmap = kmalloc(sizeof(*vmmap), GFP_KERNEL);
1947 mtx_lock(&vmmaplock);
1948 vmmap->vm_size = size;
1949 vmmap->vm_addr = addr;
1950 LIST_INSERT_HEAD(&vmmaphead[VM_HASH(addr)], vmmap, vm_next);
1951 mtx_unlock(&vmmaplock);
1954 static struct vmmap *
1955 vmmap_remove(void *addr)
1957 struct vmmap *vmmap;
1959 mtx_lock(&vmmaplock);
1960 LIST_FOREACH(vmmap, &vmmaphead[VM_HASH(addr)], vm_next)
1961 if (vmmap->vm_addr == addr)
1964 LIST_REMOVE(vmmap, vm_next);
1965 mtx_unlock(&vmmaplock);
1970 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__) || defined(__aarch64__) || defined(__riscv)
1972 _ioremap_attr(vm_paddr_t phys_addr, unsigned long size, int attr)
1976 addr = pmap_mapdev_attr(phys_addr, size, attr);
1979 vmmap_add(addr, size);
1988 struct vmmap *vmmap;
1990 vmmap = vmmap_remove(addr);
1993 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__) || defined(__aarch64__) || defined(__riscv)
1994 pmap_unmapdev(addr, vmmap->vm_size);
2000 vmap(struct page **pages, unsigned int count, unsigned long flags, int prot)
2005 size = count * PAGE_SIZE;
2006 off = kva_alloc(size);
2009 vmmap_add((void *)off, size);
2010 pmap_qenter(off, pages, count);
2012 return ((void *)off);
2018 struct vmmap *vmmap;
2020 vmmap = vmmap_remove(addr);
2023 pmap_qremove((vm_offset_t)addr, vmmap->vm_size / PAGE_SIZE);
2024 kva_free((vm_offset_t)addr, vmmap->vm_size);
2029 devm_kvasprintf(struct device *dev, gfp_t gfp, const char *fmt, va_list ap)
2036 len = vsnprintf(NULL, 0, fmt, aq);
2040 p = devm_kmalloc(dev, len + 1, gfp);
2042 p = kmalloc(len + 1, gfp);
2044 vsnprintf(p, len + 1, fmt, ap);
2050 kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
2053 return (devm_kvasprintf(NULL, gfp, fmt, ap));
2057 lkpi_devm_kasprintf(struct device *dev, gfp_t gfp, const char *fmt, ...)
2063 p = devm_kvasprintf(dev, gfp, fmt, ap);
2070 kasprintf(gfp_t gfp, const char *fmt, ...)
2076 p = kvasprintf(gfp, fmt, ap);
2083 linux_timer_callback_wrapper(void *context)
2085 struct timer_list *timer;
2089 if (linux_set_current_flags(curthread, M_NOWAIT)) {
2090 /* try again later */
2091 callout_reset(&timer->callout, 1,
2092 &linux_timer_callback_wrapper, timer);
2096 timer->function(timer->data);
2100 mod_timer(struct timer_list *timer, int expires)
2104 timer->expires = expires;
2105 ret = callout_reset(&timer->callout,
2106 linux_timer_jiffies_until(expires),
2107 &linux_timer_callback_wrapper, timer);
2109 MPASS(ret == 0 || ret == 1);
2115 add_timer(struct timer_list *timer)
2118 callout_reset(&timer->callout,
2119 linux_timer_jiffies_until(timer->expires),
2120 &linux_timer_callback_wrapper, timer);
2124 add_timer_on(struct timer_list *timer, int cpu)
2127 callout_reset_on(&timer->callout,
2128 linux_timer_jiffies_until(timer->expires),
2129 &linux_timer_callback_wrapper, timer, cpu);
2133 del_timer(struct timer_list *timer)
2136 if (callout_stop(&(timer)->callout) == -1)
2142 del_timer_sync(struct timer_list *timer)
2145 if (callout_drain(&(timer)->callout) == -1)
2150 /* greatest common divisor, Euclid equation */
2152 lkpi_gcd_64(uint64_t a, uint64_t b)
2166 uint64_t lkpi_nsec2hz_rem;
2167 uint64_t lkpi_nsec2hz_div = 1000000000ULL;
2168 uint64_t lkpi_nsec2hz_max;
2170 uint64_t lkpi_usec2hz_rem;
2171 uint64_t lkpi_usec2hz_div = 1000000ULL;
2172 uint64_t lkpi_usec2hz_max;
2174 uint64_t lkpi_msec2hz_rem;
2175 uint64_t lkpi_msec2hz_div = 1000ULL;
2176 uint64_t lkpi_msec2hz_max;
2179 linux_timer_init(void *arg)
2184 * Compute an internal HZ value which can divide 2**32 to
2185 * avoid timer rounding problems when the tick value wraps
2188 linux_timer_hz_mask = 1;
2189 while (linux_timer_hz_mask < (unsigned long)hz)
2190 linux_timer_hz_mask *= 2;
2191 linux_timer_hz_mask--;
2193 /* compute some internal constants */
2195 lkpi_nsec2hz_rem = hz;
2196 lkpi_usec2hz_rem = hz;
2197 lkpi_msec2hz_rem = hz;
2199 gcd = lkpi_gcd_64(lkpi_nsec2hz_rem, lkpi_nsec2hz_div);
2200 lkpi_nsec2hz_rem /= gcd;
2201 lkpi_nsec2hz_div /= gcd;
2202 lkpi_nsec2hz_max = -1ULL / lkpi_nsec2hz_rem;
2204 gcd = lkpi_gcd_64(lkpi_usec2hz_rem, lkpi_usec2hz_div);
2205 lkpi_usec2hz_rem /= gcd;
2206 lkpi_usec2hz_div /= gcd;
2207 lkpi_usec2hz_max = -1ULL / lkpi_usec2hz_rem;
2209 gcd = lkpi_gcd_64(lkpi_msec2hz_rem, lkpi_msec2hz_div);
2210 lkpi_msec2hz_rem /= gcd;
2211 lkpi_msec2hz_div /= gcd;
2212 lkpi_msec2hz_max = -1ULL / lkpi_msec2hz_rem;
2214 SYSINIT(linux_timer, SI_SUB_DRIVERS, SI_ORDER_FIRST, linux_timer_init, NULL);
2217 linux_complete_common(struct completion *c, int all)
2224 wakeup_swapper = sleepq_broadcast(c, SLEEPQ_SLEEP, 0, 0);
2226 if (c->done != UINT_MAX)
2228 wakeup_swapper = sleepq_signal(c, SLEEPQ_SLEEP, 0, 0);
2236 * Indefinite wait for done != 0 with or without signals.
2239 linux_wait_for_common(struct completion *c, int flags)
2241 struct task_struct *task;
2244 if (SCHEDULER_STOPPED())
2250 flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
2252 flags = SLEEPQ_SLEEP;
2258 sleepq_add(c, NULL, "completion", flags, 0);
2259 if (flags & SLEEPQ_INTERRUPTIBLE) {
2261 error = -sleepq_wait_sig(c, 0);
2264 linux_schedule_save_interrupt_value(task, error);
2265 error = -ERESTARTSYS;
2274 if (c->done != UINT_MAX)
2283 * Time limited wait for done != 0 with or without signals.
2286 linux_wait_for_timeout_common(struct completion *c, int timeout, int flags)
2288 struct task_struct *task;
2289 int end = jiffies + timeout;
2292 if (SCHEDULER_STOPPED())
2298 flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
2300 flags = SLEEPQ_SLEEP;
2306 sleepq_add(c, NULL, "completion", flags, 0);
2307 sleepq_set_timeout(c, linux_timer_jiffies_until(end));
2310 if (flags & SLEEPQ_INTERRUPTIBLE)
2311 error = -sleepq_timedwait_sig(c, 0);
2313 error = -sleepq_timedwait(c, 0);
2317 /* check for timeout */
2318 if (error == -EWOULDBLOCK) {
2319 error = 0; /* timeout */
2321 /* signal happened */
2322 linux_schedule_save_interrupt_value(task, error);
2323 error = -ERESTARTSYS;
2328 if (c->done != UINT_MAX)
2332 /* return how many jiffies are left */
2333 error = linux_timer_jiffies_until(end);
2339 linux_try_wait_for_completion(struct completion *c)
2344 isdone = (c->done != 0);
2345 if (c->done != 0 && c->done != UINT_MAX)
2352 linux_completion_done(struct completion *c)
2357 isdone = (c->done != 0);
2363 linux_cdev_deref(struct linux_cdev *ldev)
2365 if (refcount_release(&ldev->refs) &&
2366 ldev->kobj.ktype == &linux_cdev_ktype)
2371 linux_cdev_release(struct kobject *kobj)
2373 struct linux_cdev *cdev;
2374 struct kobject *parent;
2376 cdev = container_of(kobj, struct linux_cdev, kobj);
2377 parent = kobj->parent;
2378 linux_destroy_dev(cdev);
2379 linux_cdev_deref(cdev);
2380 kobject_put(parent);
2384 linux_cdev_static_release(struct kobject *kobj)
2387 struct linux_cdev *ldev;
2389 ldev = container_of(kobj, struct linux_cdev, kobj);
2395 kobject_put(kobj->parent);
2399 linux_cdev_device_add(struct linux_cdev *ldev, struct device *dev)
2403 if (dev->devt != 0) {
2404 /* Set parent kernel object. */
2405 ldev->kobj.parent = &dev->kobj;
2408 * Unlike Linux we require the kobject of the
2409 * character device structure to have a valid name
2410 * before calling this function:
2412 if (ldev->kobj.name == NULL)
2415 ret = cdev_add(ldev, dev->devt, 1);
2419 ret = device_add(dev);
2420 if (ret != 0 && dev->devt != 0)
2426 linux_cdev_device_del(struct linux_cdev *ldev, struct device *dev)
2435 linux_destroy_dev(struct linux_cdev *ldev)
2438 if (ldev->cdev == NULL)
2441 MPASS((ldev->siref & LDEV_SI_DTR) == 0);
2442 MPASS(ldev->kobj.ktype == &linux_cdev_ktype);
2444 atomic_set_int(&ldev->siref, LDEV_SI_DTR);
2445 while ((atomic_load_int(&ldev->siref) & ~LDEV_SI_DTR) != 0)
2446 pause("ldevdtr", hz / 4);
2448 destroy_dev(ldev->cdev);
2452 const struct kobj_type linux_cdev_ktype = {
2453 .release = linux_cdev_release,
2456 const struct kobj_type linux_cdev_static_ktype = {
2457 .release = linux_cdev_static_release,
2461 linux_handle_ifnet_link_event(void *arg, struct ifnet *ifp, int linkstate)
2463 struct notifier_block *nb;
2464 struct netdev_notifier_info ni;
2468 ni.dev = (struct net_device *)ifp;
2469 if (linkstate == LINK_STATE_UP)
2470 nb->notifier_call(nb, NETDEV_UP, &ni);
2472 nb->notifier_call(nb, NETDEV_DOWN, &ni);
2476 linux_handle_ifnet_arrival_event(void *arg, struct ifnet *ifp)
2478 struct notifier_block *nb;
2479 struct netdev_notifier_info ni;
2483 ni.dev = (struct net_device *)ifp;
2484 nb->notifier_call(nb, NETDEV_REGISTER, &ni);
2488 linux_handle_ifnet_departure_event(void *arg, struct ifnet *ifp)
2490 struct notifier_block *nb;
2491 struct netdev_notifier_info ni;
2495 ni.dev = (struct net_device *)ifp;
2496 nb->notifier_call(nb, NETDEV_UNREGISTER, &ni);
2500 linux_handle_iflladdr_event(void *arg, struct ifnet *ifp)
2502 struct notifier_block *nb;
2503 struct netdev_notifier_info ni;
2507 ni.dev = (struct net_device *)ifp;
2508 nb->notifier_call(nb, NETDEV_CHANGEADDR, &ni);
2512 linux_handle_ifaddr_event(void *arg, struct ifnet *ifp)
2514 struct notifier_block *nb;
2515 struct netdev_notifier_info ni;
2519 ni.dev = (struct net_device *)ifp;
2520 nb->notifier_call(nb, NETDEV_CHANGEIFADDR, &ni);
2524 register_netdevice_notifier(struct notifier_block *nb)
2527 nb->tags[NETDEV_UP] = EVENTHANDLER_REGISTER(
2528 ifnet_link_event, linux_handle_ifnet_link_event, nb, 0);
2529 nb->tags[NETDEV_REGISTER] = EVENTHANDLER_REGISTER(
2530 ifnet_arrival_event, linux_handle_ifnet_arrival_event, nb, 0);
2531 nb->tags[NETDEV_UNREGISTER] = EVENTHANDLER_REGISTER(
2532 ifnet_departure_event, linux_handle_ifnet_departure_event, nb, 0);
2533 nb->tags[NETDEV_CHANGEADDR] = EVENTHANDLER_REGISTER(
2534 iflladdr_event, linux_handle_iflladdr_event, nb, 0);
2540 register_inetaddr_notifier(struct notifier_block *nb)
2543 nb->tags[NETDEV_CHANGEIFADDR] = EVENTHANDLER_REGISTER(
2544 ifaddr_event, linux_handle_ifaddr_event, nb, 0);
2549 unregister_netdevice_notifier(struct notifier_block *nb)
2552 EVENTHANDLER_DEREGISTER(ifnet_link_event,
2553 nb->tags[NETDEV_UP]);
2554 EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
2555 nb->tags[NETDEV_REGISTER]);
2556 EVENTHANDLER_DEREGISTER(ifnet_departure_event,
2557 nb->tags[NETDEV_UNREGISTER]);
2558 EVENTHANDLER_DEREGISTER(iflladdr_event,
2559 nb->tags[NETDEV_CHANGEADDR]);
2565 unregister_inetaddr_notifier(struct notifier_block *nb)
2568 EVENTHANDLER_DEREGISTER(ifaddr_event,
2569 nb->tags[NETDEV_CHANGEIFADDR]);
2574 struct list_sort_thunk {
2575 int (*cmp)(void *, struct list_head *, struct list_head *);
2580 linux_le_cmp(const void *d1, const void *d2, void *priv)
2582 struct list_head *le1, *le2;
2583 struct list_sort_thunk *thunk;
2586 le1 = *(__DECONST(struct list_head **, d1));
2587 le2 = *(__DECONST(struct list_head **, d2));
2588 return ((thunk->cmp)(thunk->priv, le1, le2));
2592 list_sort(void *priv, struct list_head *head, int (*cmp)(void *priv,
2593 struct list_head *a, struct list_head *b))
2595 struct list_sort_thunk thunk;
2596 struct list_head **ar, *le;
2600 list_for_each(le, head)
2602 ar = malloc(sizeof(struct list_head *) * count, M_KMALLOC, M_WAITOK);
2604 list_for_each(le, head)
2608 qsort_r(ar, count, sizeof(struct list_head *), linux_le_cmp, &thunk);
2609 INIT_LIST_HEAD(head);
2610 for (i = 0; i < count; i++)
2611 list_add_tail(ar[i], head);
2612 free(ar, M_KMALLOC);
2615 #if defined(__i386__) || defined(__amd64__)
2617 linux_wbinvd_on_all_cpus(void)
2620 pmap_invalidate_cache();
2626 linux_on_each_cpu(void callback(void *), void *data)
2629 smp_rendezvous(smp_no_rendezvous_barrier, callback,
2630 smp_no_rendezvous_barrier, data);
2635 linux_in_atomic(void)
2638 return ((curthread->td_pflags & TDP_NOFAULTING) != 0);
2642 linux_find_cdev(const char *name, unsigned major, unsigned minor)
2644 dev_t dev = MKDEV(major, minor);
2648 LIST_FOREACH(cdev, &linuxcdevsw.d_devs, si_list) {
2649 struct linux_cdev *ldev = cdev->si_drv1;
2650 if (ldev->dev == dev &&
2651 strcmp(kobject_name(&ldev->kobj), name) == 0) {
2657 return (cdev != NULL ? cdev->si_drv1 : NULL);
2661 __register_chrdev(unsigned int major, unsigned int baseminor,
2662 unsigned int count, const char *name,
2663 const struct file_operations *fops)
2665 struct linux_cdev *cdev;
2669 for (i = baseminor; i < baseminor + count; i++) {
2670 cdev = cdev_alloc();
2672 kobject_set_name(&cdev->kobj, name);
2674 ret = cdev_add(cdev, makedev(major, i), 1);
2682 __register_chrdev_p(unsigned int major, unsigned int baseminor,
2683 unsigned int count, const char *name,
2684 const struct file_operations *fops, uid_t uid,
2685 gid_t gid, int mode)
2687 struct linux_cdev *cdev;
2691 for (i = baseminor; i < baseminor + count; i++) {
2692 cdev = cdev_alloc();
2694 kobject_set_name(&cdev->kobj, name);
2696 ret = cdev_add_ext(cdev, makedev(major, i), uid, gid, mode);
2704 __unregister_chrdev(unsigned int major, unsigned int baseminor,
2705 unsigned int count, const char *name)
2707 struct linux_cdev *cdevp;
2710 for (i = baseminor; i < baseminor + count; i++) {
2711 cdevp = linux_find_cdev(name, major, i);
2718 linux_dump_stack(void)
2729 linuxkpi_net_ratelimit(void)
2732 return (ppsratecheck(&lkpi_net_lastlog, &lkpi_net_curpps,
2737 io_mapping_create_wc(resource_size_t base, unsigned long size)
2739 struct io_mapping *mapping;
2741 mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2742 if (mapping == NULL)
2744 return (io_mapping_init_wc(mapping, base, size));
2747 #if defined(__i386__) || defined(__amd64__)
2748 bool linux_cpu_has_clflush;
2749 struct cpuinfo_x86 boot_cpu_data;
2750 struct cpuinfo_x86 __cpu_data[MAXCPU];
2754 lkpi_get_static_single_cpu_mask(int cpuid)
2757 KASSERT((cpuid >= 0 && cpuid < MAXCPU), ("%s: invalid cpuid %d\n",
2760 return (&static_single_cpu_mask[cpuid]);
2764 linux_compat_init(void *arg)
2766 struct sysctl_oid *rootoid;
2769 #if defined(__i386__) || defined(__amd64__)
2770 linux_cpu_has_clflush = (cpu_feature & CPUID_CLFSH);
2771 boot_cpu_data.x86_clflush_size = cpu_clflush_line_size;
2772 boot_cpu_data.x86_max_cores = mp_ncpus;
2773 boot_cpu_data.x86 = CPUID_TO_FAMILY(cpu_id);
2774 boot_cpu_data.x86_model = CPUID_TO_MODEL(cpu_id);
2776 for (i = 0; i < MAXCPU; i++) {
2777 __cpu_data[i].x86_clflush_size = cpu_clflush_line_size;
2778 __cpu_data[i].x86_max_cores = mp_ncpus;
2779 __cpu_data[i].x86 = CPUID_TO_FAMILY(cpu_id);
2780 __cpu_data[i].x86_model = CPUID_TO_MODEL(cpu_id);
2783 rw_init(&linux_vma_lock, "lkpi-vma-lock");
2785 rootoid = SYSCTL_ADD_ROOT_NODE(NULL,
2786 OID_AUTO, "sys", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "sys");
2787 kobject_init(&linux_class_root, &linux_class_ktype);
2788 kobject_set_name(&linux_class_root, "class");
2789 linux_class_root.oidp = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(rootoid),
2790 OID_AUTO, "class", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "class");
2791 kobject_init(&linux_root_device.kobj, &linux_dev_ktype);
2792 kobject_set_name(&linux_root_device.kobj, "device");
2793 linux_root_device.kobj.oidp = SYSCTL_ADD_NODE(NULL,
2794 SYSCTL_CHILDREN(rootoid), OID_AUTO, "device",
2795 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "device");
2796 linux_root_device.bsddev = root_bus;
2797 linux_class_misc.name = "misc";
2798 class_register(&linux_class_misc);
2799 INIT_LIST_HEAD(&pci_drivers);
2800 INIT_LIST_HEAD(&pci_devices);
2801 spin_lock_init(&pci_lock);
2802 mtx_init(&vmmaplock, "IO Map lock", NULL, MTX_DEF);
2803 for (i = 0; i < VMMAP_HASH_SIZE; i++)
2804 LIST_INIT(&vmmaphead[i]);
2805 init_waitqueue_head(&linux_bit_waitq);
2806 init_waitqueue_head(&linux_var_waitq);
2808 CPU_COPY(&all_cpus, &cpu_online_mask);
2810 * Generate a single-CPU cpumask_t for each CPU (possibly) in the system.
2811 * CPUs are indexed from 0..(MAXCPU-1). The entry for cpuid 0 will only
2812 * have itself in the cpumask, cupid 1 only itself on entry 1, and so on.
2813 * This is used by cpumask_of() (and possibly others in the future) for,
2814 * e.g., drivers to pass hints to irq_set_affinity_hint().
2816 for (i = 0; i < MAXCPU; i++)
2817 CPU_SET(i, &static_single_cpu_mask[i]);
2819 strlcpy(init_uts_ns.name.release, osrelease, sizeof(init_uts_ns.name.release));
2821 SYSINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_init, NULL);
2824 linux_compat_uninit(void *arg)
2826 linux_kobject_kfree_name(&linux_class_root);
2827 linux_kobject_kfree_name(&linux_root_device.kobj);
2828 linux_kobject_kfree_name(&linux_class_misc.kobj);
2830 mtx_destroy(&vmmaplock);
2831 spin_lock_destroy(&pci_lock);
2832 rw_destroy(&linux_vma_lock);
2834 SYSUNINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_uninit, NULL);
2837 * NOTE: Linux frequently uses "unsigned long" for pointer to integer
2838 * conversion and vice versa, where in FreeBSD "uintptr_t" would be
2839 * used. Assert these types have the same size, else some parts of the
2840 * LinuxKPI may not work like expected:
2842 CTASSERT(sizeof(unsigned long) == sizeof(uintptr_t));