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