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