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