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