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/stdarg.h>
54 #include <sys/sysent.h>
55 #include <sys/time.h>
56 #include <sys/user.h>
57
58 #include <vm/vm.h>
59 #include <vm/pmap.h>
60 #include <vm/vm_object.h>
61 #include <vm/vm_page.h>
62 #include <vm/vm_pager.h>
63 #include <vm/vm_radix.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/fs.h>
79 #include <linux/sysfs.h>
80 #include <linux/mm.h>
81 #include <linux/io.h>
82 #include <linux/vmalloc.h>
83 #include <linux/netdevice.h>
84 #include <linux/timer.h>
85 #include <linux/interrupt.h>
86 #include <linux/uaccess.h>
87 #include <linux/utsname.h>
88 #include <linux/list.h>
89 #include <linux/kthread.h>
90 #include <linux/kernel.h>
91 #include <linux/compat.h>
92 #include <linux/io-mapping.h>
93 #include <linux/poll.h>
94 #include <linux/smp.h>
95 #include <linux/wait_bit.h>
96 #include <linux/rcupdate.h>
97 #include <linux/interval_tree.h>
98 #include <linux/interval_tree_generic.h>
99 #include <linux/printk.h>
100 #include <linux/seq_file.h>
101
102 #if defined(__i386__) || defined(__amd64__)
103 #include <asm/smp.h>
104 #include <asm/processor.h>
105 #endif
106
107 #include <xen/xen.h>
108 #ifdef XENHVM
109 #undef xen_pv_domain
110 #undef xen_initial_domain
111 /* xen/xen-os.h redefines __must_check */
112 #undef __must_check
113 #include <xen/xen-os.h>
114 #endif
115
116 SYSCTL_NODE(_compat, OID_AUTO, linuxkpi, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
117 "LinuxKPI parameters");
118
119 int linuxkpi_debug;
120 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, debug, CTLFLAG_RWTUN,
121 &linuxkpi_debug, 0, "Set to enable pr_debug() prints. Clear to disable.");
122
123 int linuxkpi_rcu_debug;
124 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, rcu_debug, CTLFLAG_RWTUN,
125 &linuxkpi_rcu_debug, 0, "Set to enable RCU warning. Clear to disable.");
126
127 int linuxkpi_warn_dump_stack = 0;
128 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, warn_dump_stack, CTLFLAG_RWTUN,
129 &linuxkpi_warn_dump_stack, 0,
130 "Set to enable stack traces from WARN_ON(). Clear to disable.");
131
132 static struct timeval lkpi_net_lastlog;
133 static int lkpi_net_curpps;
134 static int lkpi_net_maxpps = 99;
135 SYSCTL_INT(_compat_linuxkpi, OID_AUTO, net_ratelimit, CTLFLAG_RWTUN,
136 &lkpi_net_maxpps, 0, "Limit number of LinuxKPI net messages per second.");
137
138 MALLOC_DEFINE(M_KMALLOC, "lkpikmalloc", "Linux kmalloc compat");
139
140 #include <linux/rbtree.h>
141 /* Undo Linux compat changes. */
142 #undef RB_ROOT
143 #undef file
144 #undef cdev
145 #define RB_ROOT(head) (head)->rbh_root
146
147 static void linux_destroy_dev(struct linux_cdev *);
148 static void linux_cdev_deref(struct linux_cdev *ldev);
149 static struct vm_area_struct *linux_cdev_handle_find(void *handle);
150
151 cpumask_t cpu_online_mask;
152 static cpumask_t **static_single_cpu_mask;
153 static cpumask_t *static_single_cpu_mask_lcs;
154 struct kobject linux_class_root;
155 struct device linux_root_device;
156 struct class linux_class_misc;
157 struct list_head pci_drivers;
158 struct list_head pci_devices;
159 spinlock_t pci_lock;
160 struct uts_namespace init_uts_ns;
161
162 unsigned long linux_timer_hz_mask;
163
164 wait_queue_head_t linux_bit_waitq;
165 wait_queue_head_t linux_var_waitq;
166
167 int
panic_cmp(struct rb_node * one,struct rb_node * two)168 panic_cmp(struct rb_node *one, struct rb_node *two)
169 {
170 panic("no cmp");
171 }
172
173 RB_GENERATE(linux_root, rb_node, __entry, panic_cmp);
174
175 #define START(node) ((node)->start)
176 #define LAST(node) ((node)->last)
177
178 INTERVAL_TREE_DEFINE(struct interval_tree_node, rb, unsigned long,, START,
179 LAST,, lkpi_interval_tree)
180
181 static void
linux_device_release(struct device * dev)182 linux_device_release(struct device *dev)
183 {
184 pr_debug("linux_device_release: %s\n", dev_name(dev));
185 kfree(dev);
186 }
187
188 static ssize_t
linux_class_show(struct kobject * kobj,struct attribute * attr,char * buf)189 linux_class_show(struct kobject *kobj, struct attribute *attr, char *buf)
190 {
191 struct class_attribute *dattr;
192 ssize_t error;
193
194 dattr = container_of(attr, struct class_attribute, attr);
195 error = -EIO;
196 if (dattr->show)
197 error = dattr->show(container_of(kobj, struct class, kobj),
198 dattr, buf);
199 return (error);
200 }
201
202 static ssize_t
linux_class_store(struct kobject * kobj,struct attribute * attr,const char * buf,size_t count)203 linux_class_store(struct kobject *kobj, struct attribute *attr, const char *buf,
204 size_t count)
205 {
206 struct class_attribute *dattr;
207 ssize_t error;
208
209 dattr = container_of(attr, struct class_attribute, attr);
210 error = -EIO;
211 if (dattr->store)
212 error = dattr->store(container_of(kobj, struct class, kobj),
213 dattr, buf, count);
214 return (error);
215 }
216
217 static void
linux_class_release(struct kobject * kobj)218 linux_class_release(struct kobject *kobj)
219 {
220 struct class *class;
221
222 class = container_of(kobj, struct class, kobj);
223 if (class->class_release)
224 class->class_release(class);
225 }
226
227 static const struct sysfs_ops linux_class_sysfs = {
228 .show = linux_class_show,
229 .store = linux_class_store,
230 };
231
232 const struct kobj_type linux_class_ktype = {
233 .release = linux_class_release,
234 .sysfs_ops = &linux_class_sysfs
235 };
236
237 static void
linux_dev_release(struct kobject * kobj)238 linux_dev_release(struct kobject *kobj)
239 {
240 struct device *dev;
241
242 dev = container_of(kobj, struct device, kobj);
243 /* This is the precedence defined by linux. */
244 if (dev->release)
245 dev->release(dev);
246 else if (dev->class && dev->class->dev_release)
247 dev->class->dev_release(dev);
248 }
249
250 static ssize_t
linux_dev_show(struct kobject * kobj,struct attribute * attr,char * buf)251 linux_dev_show(struct kobject *kobj, struct attribute *attr, char *buf)
252 {
253 struct device_attribute *dattr;
254 ssize_t error;
255
256 dattr = container_of(attr, struct device_attribute, attr);
257 error = -EIO;
258 if (dattr->show)
259 error = dattr->show(container_of(kobj, struct device, kobj),
260 dattr, buf);
261 return (error);
262 }
263
264 static ssize_t
linux_dev_store(struct kobject * kobj,struct attribute * attr,const char * buf,size_t count)265 linux_dev_store(struct kobject *kobj, struct attribute *attr, const char *buf,
266 size_t count)
267 {
268 struct device_attribute *dattr;
269 ssize_t error;
270
271 dattr = container_of(attr, struct device_attribute, attr);
272 error = -EIO;
273 if (dattr->store)
274 error = dattr->store(container_of(kobj, struct device, kobj),
275 dattr, buf, count);
276 return (error);
277 }
278
279 static const struct sysfs_ops linux_dev_sysfs = {
280 .show = linux_dev_show,
281 .store = linux_dev_store,
282 };
283
284 const struct kobj_type linux_dev_ktype = {
285 .release = linux_dev_release,
286 .sysfs_ops = &linux_dev_sysfs
287 };
288
289 struct device *
device_create(struct class * class,struct device * parent,dev_t devt,void * drvdata,const char * fmt,...)290 device_create(struct class *class, struct device *parent, dev_t devt,
291 void *drvdata, const char *fmt, ...)
292 {
293 struct device *dev;
294 va_list args;
295
296 dev = kzalloc(sizeof(*dev), M_WAITOK);
297 dev->parent = parent;
298 dev->class = class;
299 dev->devt = devt;
300 dev->driver_data = drvdata;
301 dev->release = linux_device_release;
302 va_start(args, fmt);
303 kobject_set_name_vargs(&dev->kobj, fmt, args);
304 va_end(args);
305 device_register(dev);
306
307 return (dev);
308 }
309
310 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)311 device_create_groups_vargs(struct class *class, struct device *parent,
312 dev_t devt, void *drvdata, const struct attribute_group **groups,
313 const char *fmt, va_list args)
314 {
315 struct device *dev = NULL;
316 int retval = -ENODEV;
317
318 if (class == NULL || IS_ERR(class))
319 goto error;
320
321 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
322 if (!dev) {
323 retval = -ENOMEM;
324 goto error;
325 }
326
327 dev->devt = devt;
328 dev->class = class;
329 dev->parent = parent;
330 dev->groups = groups;
331 dev->release = device_create_release;
332 /* device_initialize() needs the class and parent to be set */
333 device_initialize(dev);
334 dev_set_drvdata(dev, drvdata);
335
336 retval = kobject_set_name_vargs(&dev->kobj, fmt, args);
337 if (retval)
338 goto error;
339
340 retval = device_add(dev);
341 if (retval)
342 goto error;
343
344 return dev;
345
346 error:
347 put_device(dev);
348 return ERR_PTR(retval);
349 }
350
351 struct class *
lkpi_class_create(const char * name)352 lkpi_class_create(const char *name)
353 {
354 struct class *class;
355 int error;
356
357 class = kzalloc(sizeof(*class), M_WAITOK);
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 struct pctrie_iter pages;
651 vm_object_t obj;
652 vm_page_t m;
653
654 obj = vma->vm_obj;
655 if (obj == NULL || (obj->flags & OBJ_UNMANAGED) != 0)
656 return (-ENOTSUP);
657 VM_OBJECT_RLOCK(obj);
658 vm_page_iter_limit_init(&pages, obj, OFF_TO_IDX(address + size));
659 VM_RADIX_FOREACH_FROM(m, &pages, OFF_TO_IDX(address))
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 struct linux_file *
__get_file_rcu(struct linux_file ** f)1089 __get_file_rcu(struct linux_file **f)
1090 {
1091 struct linux_file *file1, *file2;
1092
1093 file1 = READ_ONCE(*f);
1094 if (file1 == NULL)
1095 return (NULL);
1096
1097 if (!refcount_acquire_if_not_zero(
1098 file1->_file == NULL ? &file1->f_count : &file1->_file->f_count))
1099 return (ERR_PTR(-EAGAIN));
1100
1101 file2 = READ_ONCE(*f);
1102 if (file2 == file1)
1103 return (file2);
1104
1105 fput(file1);
1106 return (ERR_PTR(-EAGAIN));
1107 }
1108
1109 struct linux_file *
linux_get_file_rcu(struct linux_file ** f)1110 linux_get_file_rcu(struct linux_file **f)
1111 {
1112 struct linux_file *file1;
1113
1114 for (;;) {
1115 file1 = __get_file_rcu(f);
1116 if (file1 == NULL)
1117 return (NULL);
1118
1119 if (IS_ERR(file1))
1120 continue;
1121
1122 return (file1);
1123 }
1124 }
1125
1126 struct linux_file *
get_file_active(struct linux_file ** f)1127 get_file_active(struct linux_file **f)
1128 {
1129 struct linux_file *file1;
1130
1131 rcu_read_lock();
1132 file1 = __get_file_rcu(f);
1133 rcu_read_unlock();
1134 if (IS_ERR(file1))
1135 file1 = NULL;
1136
1137 return (file1);
1138 }
1139
1140 static void
linux_file_kqfilter_detach(struct knote * kn)1141 linux_file_kqfilter_detach(struct knote *kn)
1142 {
1143 struct linux_file *filp = kn->kn_hook;
1144
1145 spin_lock(&filp->f_kqlock);
1146 knlist_remove(&filp->f_selinfo.si_note, kn, 1);
1147 spin_unlock(&filp->f_kqlock);
1148 }
1149
1150 static int
linux_file_kqfilter_read_event(struct knote * kn,long hint)1151 linux_file_kqfilter_read_event(struct knote *kn, long hint)
1152 {
1153 struct linux_file *filp = kn->kn_hook;
1154
1155 mtx_assert(&filp->f_kqlock, MA_OWNED);
1156
1157 return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_READ) ? 1 : 0);
1158 }
1159
1160 static int
linux_file_kqfilter_write_event(struct knote * kn,long hint)1161 linux_file_kqfilter_write_event(struct knote *kn, long hint)
1162 {
1163 struct linux_file *filp = kn->kn_hook;
1164
1165 mtx_assert(&filp->f_kqlock, MA_OWNED);
1166
1167 return ((filp->f_kqflags & LINUX_KQ_FLAG_NEED_WRITE) ? 1 : 0);
1168 }
1169
1170 static const struct filterops linux_dev_kqfiltops_read = {
1171 .f_isfd = 1,
1172 .f_detach = linux_file_kqfilter_detach,
1173 .f_event = linux_file_kqfilter_read_event,
1174 };
1175
1176 static const struct filterops linux_dev_kqfiltops_write = {
1177 .f_isfd = 1,
1178 .f_detach = linux_file_kqfilter_detach,
1179 .f_event = linux_file_kqfilter_write_event,
1180 };
1181
1182 static void
linux_file_kqfilter_poll(struct linux_file * filp,int kqflags)1183 linux_file_kqfilter_poll(struct linux_file *filp, int kqflags)
1184 {
1185 struct thread *td;
1186 const struct file_operations *fop;
1187 struct linux_cdev *ldev;
1188 int temp;
1189
1190 if ((filp->f_kqflags & kqflags) == 0)
1191 return;
1192
1193 td = curthread;
1194
1195 linux_get_fop(filp, &fop, &ldev);
1196 /* get the latest polling state */
1197 temp = OPW(filp->_file, td, fop->poll(filp, NULL));
1198 linux_drop_fop(ldev);
1199
1200 spin_lock(&filp->f_kqlock);
1201 /* clear kqflags */
1202 filp->f_kqflags &= ~(LINUX_KQ_FLAG_NEED_READ |
1203 LINUX_KQ_FLAG_NEED_WRITE);
1204 /* update kqflags */
1205 if ((temp & (POLLIN | POLLOUT)) != 0) {
1206 if ((temp & POLLIN) != 0)
1207 filp->f_kqflags |= LINUX_KQ_FLAG_NEED_READ;
1208 if ((temp & POLLOUT) != 0)
1209 filp->f_kqflags |= LINUX_KQ_FLAG_NEED_WRITE;
1210
1211 /* make sure the "knote" gets woken up */
1212 KNOTE_LOCKED(&filp->f_selinfo.si_note, 0);
1213 }
1214 spin_unlock(&filp->f_kqlock);
1215 }
1216
1217 static int
linux_file_kqfilter(struct file * file,struct knote * kn)1218 linux_file_kqfilter(struct file *file, struct knote *kn)
1219 {
1220 struct linux_file *filp;
1221 struct thread *td;
1222 int error;
1223
1224 td = curthread;
1225 filp = (struct linux_file *)file->f_data;
1226 filp->f_flags = file->f_flag;
1227 if (filp->f_op->poll == NULL)
1228 return (EINVAL);
1229
1230 spin_lock(&filp->f_kqlock);
1231 switch (kn->kn_filter) {
1232 case EVFILT_READ:
1233 filp->f_kqflags |= LINUX_KQ_FLAG_HAS_READ;
1234 kn->kn_fop = &linux_dev_kqfiltops_read;
1235 kn->kn_hook = filp;
1236 knlist_add(&filp->f_selinfo.si_note, kn, 1);
1237 error = 0;
1238 break;
1239 case EVFILT_WRITE:
1240 filp->f_kqflags |= LINUX_KQ_FLAG_HAS_WRITE;
1241 kn->kn_fop = &linux_dev_kqfiltops_write;
1242 kn->kn_hook = filp;
1243 knlist_add(&filp->f_selinfo.si_note, kn, 1);
1244 error = 0;
1245 break;
1246 default:
1247 error = EINVAL;
1248 break;
1249 }
1250 spin_unlock(&filp->f_kqlock);
1251
1252 if (error == 0) {
1253 linux_set_current(td);
1254
1255 /* update kqfilter status, if any */
1256 linux_file_kqfilter_poll(filp,
1257 LINUX_KQ_FLAG_HAS_READ | LINUX_KQ_FLAG_HAS_WRITE);
1258 }
1259 return (error);
1260 }
1261
1262 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)1263 linux_file_mmap_single(struct file *fp, const struct file_operations *fop,
1264 vm_ooffset_t *offset, vm_size_t size, struct vm_object **object,
1265 int nprot, bool is_shared, struct thread *td)
1266 {
1267 struct task_struct *task;
1268 struct vm_area_struct *vmap;
1269 struct mm_struct *mm;
1270 struct linux_file *filp;
1271 vm_memattr_t attr;
1272 int error;
1273
1274 filp = (struct linux_file *)fp->f_data;
1275 filp->f_flags = fp->f_flag;
1276
1277 if (fop->mmap == NULL)
1278 return (EOPNOTSUPP);
1279
1280 linux_set_current(td);
1281
1282 /*
1283 * The same VM object might be shared by multiple processes
1284 * and the mm_struct is usually freed when a process exits.
1285 *
1286 * The atomic reference below makes sure the mm_struct is
1287 * available as long as the vmap is in the linux_vma_head.
1288 */
1289 task = current;
1290 mm = task->mm;
1291 if (atomic_inc_not_zero(&mm->mm_users) == 0)
1292 return (EINVAL);
1293
1294 vmap = kzalloc(sizeof(*vmap), GFP_KERNEL);
1295 vmap->vm_start = 0;
1296 vmap->vm_end = size;
1297 vmap->vm_pgoff = *offset / PAGE_SIZE;
1298 vmap->vm_pfn = 0;
1299 vmap->vm_flags = vmap->vm_page_prot = (nprot & VM_PROT_ALL);
1300 if (is_shared)
1301 vmap->vm_flags |= VM_SHARED;
1302 vmap->vm_ops = NULL;
1303 vmap->vm_file = get_file(filp);
1304 vmap->vm_mm = mm;
1305
1306 if (unlikely(down_write_killable(&vmap->vm_mm->mmap_sem))) {
1307 error = linux_get_error(task, EINTR);
1308 } else {
1309 error = -OPW(fp, td, fop->mmap(filp, vmap));
1310 error = linux_get_error(task, error);
1311 up_write(&vmap->vm_mm->mmap_sem);
1312 }
1313
1314 if (error != 0) {
1315 linux_cdev_handle_free(vmap);
1316 return (error);
1317 }
1318
1319 attr = pgprot2cachemode(vmap->vm_page_prot);
1320
1321 if (vmap->vm_ops != NULL) {
1322 struct vm_area_struct *ptr;
1323 void *vm_private_data;
1324 bool vm_no_fault;
1325
1326 if (vmap->vm_ops->open == NULL ||
1327 vmap->vm_ops->close == NULL ||
1328 vmap->vm_private_data == NULL) {
1329 /* free allocated VM area struct */
1330 linux_cdev_handle_free(vmap);
1331 return (EINVAL);
1332 }
1333
1334 vm_private_data = vmap->vm_private_data;
1335
1336 rw_wlock(&linux_vma_lock);
1337 TAILQ_FOREACH(ptr, &linux_vma_head, vm_entry) {
1338 if (ptr->vm_private_data == vm_private_data)
1339 break;
1340 }
1341 /* check if there is an existing VM area struct */
1342 if (ptr != NULL) {
1343 /* check if the VM area structure is invalid */
1344 if (ptr->vm_ops == NULL ||
1345 ptr->vm_ops->open == NULL ||
1346 ptr->vm_ops->close == NULL) {
1347 error = ESTALE;
1348 vm_no_fault = 1;
1349 } else {
1350 error = EEXIST;
1351 vm_no_fault = (ptr->vm_ops->fault == NULL);
1352 }
1353 } else {
1354 /* insert VM area structure into list */
1355 TAILQ_INSERT_TAIL(&linux_vma_head, vmap, vm_entry);
1356 error = 0;
1357 vm_no_fault = (vmap->vm_ops->fault == NULL);
1358 }
1359 rw_wunlock(&linux_vma_lock);
1360
1361 if (error != 0) {
1362 /* free allocated VM area struct */
1363 linux_cdev_handle_free(vmap);
1364 /* check for stale VM area struct */
1365 if (error != EEXIST)
1366 return (error);
1367 }
1368
1369 /* check if there is no fault handler */
1370 if (vm_no_fault) {
1371 *object = cdev_pager_allocate(vm_private_data, OBJT_DEVICE,
1372 &linux_cdev_pager_ops[1], size, nprot, *offset,
1373 td->td_ucred);
1374 } else {
1375 *object = cdev_pager_allocate(vm_private_data, OBJT_MGTDEVICE,
1376 &linux_cdev_pager_ops[0], size, nprot, *offset,
1377 td->td_ucred);
1378 }
1379
1380 /* check if allocating the VM object failed */
1381 if (*object == NULL) {
1382 if (error == 0) {
1383 /* remove VM area struct from list */
1384 linux_cdev_handle_remove(vmap);
1385 /* free allocated VM area struct */
1386 linux_cdev_handle_free(vmap);
1387 }
1388 return (EINVAL);
1389 }
1390 } else {
1391 struct sglist *sg;
1392
1393 sg = sglist_alloc(1, M_WAITOK);
1394 sglist_append_phys(sg,
1395 (vm_paddr_t)vmap->vm_pfn << PAGE_SHIFT, vmap->vm_len);
1396
1397 *object = vm_pager_allocate(OBJT_SG, sg, vmap->vm_len,
1398 nprot, 0, td->td_ucred);
1399
1400 linux_cdev_handle_free(vmap);
1401
1402 if (*object == NULL) {
1403 sglist_free(sg);
1404 return (EINVAL);
1405 }
1406 }
1407
1408 if (attr != VM_MEMATTR_DEFAULT) {
1409 VM_OBJECT_WLOCK(*object);
1410 vm_object_set_memattr(*object, attr);
1411 VM_OBJECT_WUNLOCK(*object);
1412 }
1413 *offset = 0;
1414 return (0);
1415 }
1416
1417 struct cdevsw linuxcdevsw = {
1418 .d_version = D_VERSION,
1419 .d_fdopen = linux_dev_fdopen,
1420 .d_name = "lkpidev",
1421 };
1422
1423 static int
linux_file_read(struct file * file,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)1424 linux_file_read(struct file *file, struct uio *uio, struct ucred *active_cred,
1425 int flags, struct thread *td)
1426 {
1427 struct linux_file *filp;
1428 const struct file_operations *fop;
1429 struct linux_cdev *ldev;
1430 ssize_t bytes;
1431 int error;
1432
1433 error = 0;
1434 filp = (struct linux_file *)file->f_data;
1435 filp->f_flags = file->f_flag;
1436 /* XXX no support for I/O vectors currently */
1437 if (uio->uio_iovcnt != 1)
1438 return (EOPNOTSUPP);
1439 if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1440 return (EINVAL);
1441 linux_set_current(td);
1442 linux_get_fop(filp, &fop, &ldev);
1443 if (fop->read != NULL) {
1444 bytes = OPW(file, td, fop->read(filp,
1445 uio->uio_iov->iov_base,
1446 uio->uio_iov->iov_len, &uio->uio_offset));
1447 if (bytes >= 0) {
1448 uio->uio_iov->iov_base =
1449 ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1450 uio->uio_iov->iov_len -= bytes;
1451 uio->uio_resid -= bytes;
1452 } else {
1453 error = linux_get_error(current, -bytes);
1454 }
1455 } else
1456 error = ENXIO;
1457
1458 /* update kqfilter status, if any */
1459 linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_READ);
1460 linux_drop_fop(ldev);
1461
1462 return (error);
1463 }
1464
1465 static int
linux_file_write(struct file * file,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)1466 linux_file_write(struct file *file, struct uio *uio, struct ucred *active_cred,
1467 int flags, struct thread *td)
1468 {
1469 struct linux_file *filp;
1470 const struct file_operations *fop;
1471 struct linux_cdev *ldev;
1472 ssize_t bytes;
1473 int error;
1474
1475 filp = (struct linux_file *)file->f_data;
1476 filp->f_flags = file->f_flag;
1477 /* XXX no support for I/O vectors currently */
1478 if (uio->uio_iovcnt != 1)
1479 return (EOPNOTSUPP);
1480 if (uio->uio_resid > DEVFS_IOSIZE_MAX)
1481 return (EINVAL);
1482 linux_set_current(td);
1483 linux_get_fop(filp, &fop, &ldev);
1484 if (fop->write != NULL) {
1485 bytes = OPW(file, td, fop->write(filp,
1486 uio->uio_iov->iov_base,
1487 uio->uio_iov->iov_len, &uio->uio_offset));
1488 if (bytes >= 0) {
1489 uio->uio_iov->iov_base =
1490 ((uint8_t *)uio->uio_iov->iov_base) + bytes;
1491 uio->uio_iov->iov_len -= bytes;
1492 uio->uio_resid -= bytes;
1493 error = 0;
1494 } else {
1495 error = linux_get_error(current, -bytes);
1496 }
1497 } else
1498 error = ENXIO;
1499
1500 /* update kqfilter status, if any */
1501 linux_file_kqfilter_poll(filp, LINUX_KQ_FLAG_HAS_WRITE);
1502
1503 linux_drop_fop(ldev);
1504
1505 return (error);
1506 }
1507
1508 static int
linux_file_poll(struct file * file,int events,struct ucred * active_cred,struct thread * td)1509 linux_file_poll(struct file *file, int events, struct ucred *active_cred,
1510 struct thread *td)
1511 {
1512 struct linux_file *filp;
1513 const struct file_operations *fop;
1514 struct linux_cdev *ldev;
1515 int revents;
1516
1517 filp = (struct linux_file *)file->f_data;
1518 filp->f_flags = file->f_flag;
1519 linux_set_current(td);
1520 linux_get_fop(filp, &fop, &ldev);
1521 if (fop->poll != NULL) {
1522 revents = OPW(file, td, fop->poll(filp,
1523 LINUX_POLL_TABLE_NORMAL)) & events;
1524 } else {
1525 revents = 0;
1526 }
1527 linux_drop_fop(ldev);
1528 return (revents);
1529 }
1530
1531 static int
linux_file_close(struct file * file,struct thread * td)1532 linux_file_close(struct file *file, struct thread *td)
1533 {
1534 struct linux_file *filp;
1535 int (*release)(struct inode *, struct linux_file *);
1536 const struct file_operations *fop;
1537 struct linux_cdev *ldev;
1538 int error;
1539
1540 filp = (struct linux_file *)file->f_data;
1541
1542 KASSERT(file_count(filp) == 0,
1543 ("File refcount(%d) is not zero", file_count(filp)));
1544
1545 if (td == NULL)
1546 td = curthread;
1547
1548 error = 0;
1549 filp->f_flags = file->f_flag;
1550 linux_set_current(td);
1551 linux_poll_wait_dequeue(filp);
1552 linux_get_fop(filp, &fop, &ldev);
1553 /*
1554 * Always use the real release function, if any, to avoid
1555 * leaking device resources:
1556 */
1557 release = filp->f_op->release;
1558 if (release != NULL)
1559 error = -OPW(file, td, release(filp->f_vnode, filp));
1560 funsetown(&filp->f_sigio);
1561 if (filp->f_vnode != NULL)
1562 vrele(filp->f_vnode);
1563 linux_drop_fop(ldev);
1564 ldev = filp->f_cdev;
1565 if (ldev != NULL)
1566 linux_cdev_deref(ldev);
1567 linux_synchronize_rcu(RCU_TYPE_REGULAR);
1568 kfree(filp);
1569
1570 return (error);
1571 }
1572
1573 static int
linux_file_ioctl(struct file * fp,u_long cmd,void * data,struct ucred * cred,struct thread * td)1574 linux_file_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *cred,
1575 struct thread *td)
1576 {
1577 struct linux_file *filp;
1578 const struct file_operations *fop;
1579 struct linux_cdev *ldev;
1580 struct fiodgname_arg *fgn;
1581 const char *p;
1582 int error, i;
1583
1584 error = 0;
1585 filp = (struct linux_file *)fp->f_data;
1586 filp->f_flags = fp->f_flag;
1587 linux_get_fop(filp, &fop, &ldev);
1588
1589 linux_set_current(td);
1590 switch (cmd) {
1591 case FIONBIO:
1592 break;
1593 case FIOASYNC:
1594 if (fop->fasync == NULL)
1595 break;
1596 error = -OPW(fp, td, fop->fasync(0, filp, fp->f_flag & FASYNC));
1597 break;
1598 case FIOSETOWN:
1599 error = fsetown(*(int *)data, &filp->f_sigio);
1600 if (error == 0) {
1601 if (fop->fasync == NULL)
1602 break;
1603 error = -OPW(fp, td, fop->fasync(0, filp,
1604 fp->f_flag & FASYNC));
1605 }
1606 break;
1607 case FIOGETOWN:
1608 *(int *)data = fgetown(&filp->f_sigio);
1609 break;
1610 case FIODGNAME:
1611 #ifdef COMPAT_FREEBSD32
1612 case FIODGNAME_32:
1613 #endif
1614 if (filp->f_cdev == NULL || filp->f_cdev->cdev == NULL) {
1615 error = ENXIO;
1616 break;
1617 }
1618 fgn = data;
1619 p = devtoname(filp->f_cdev->cdev);
1620 i = strlen(p) + 1;
1621 if (i > fgn->len) {
1622 error = EINVAL;
1623 break;
1624 }
1625 error = copyout(p, fiodgname_buf_get_ptr(fgn, cmd), i);
1626 break;
1627 default:
1628 error = linux_file_ioctl_sub(fp, filp, fop, cmd, data, td);
1629 break;
1630 }
1631 linux_drop_fop(ldev);
1632 return (error);
1633 }
1634
1635 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)1636 linux_file_mmap_sub(struct thread *td, vm_size_t objsize, vm_prot_t prot,
1637 vm_prot_t maxprot, int flags, struct file *fp,
1638 vm_ooffset_t *foff, const struct file_operations *fop, vm_object_t *objp)
1639 {
1640 /*
1641 * Character devices do not provide private mappings
1642 * of any kind:
1643 */
1644 if ((maxprot & VM_PROT_WRITE) == 0 &&
1645 (prot & VM_PROT_WRITE) != 0)
1646 return (EACCES);
1647 if ((flags & (MAP_PRIVATE | MAP_COPY)) != 0)
1648 return (EINVAL);
1649
1650 return (linux_file_mmap_single(fp, fop, foff, objsize, objp,
1651 (int)prot, (flags & MAP_SHARED) ? true : false, td));
1652 }
1653
1654 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)1655 linux_file_mmap(struct file *fp, vm_map_t map, vm_offset_t *addr, vm_size_t size,
1656 vm_prot_t prot, vm_prot_t cap_maxprot, int flags, vm_ooffset_t foff,
1657 struct thread *td)
1658 {
1659 struct linux_file *filp;
1660 const struct file_operations *fop;
1661 struct linux_cdev *ldev;
1662 struct mount *mp;
1663 struct vnode *vp;
1664 vm_object_t object;
1665 vm_prot_t maxprot;
1666 int error;
1667
1668 filp = (struct linux_file *)fp->f_data;
1669
1670 vp = filp->f_vnode;
1671 if (vp == NULL)
1672 return (EOPNOTSUPP);
1673
1674 /*
1675 * Ensure that file and memory protections are
1676 * compatible.
1677 */
1678 mp = vp->v_mount;
1679 if (mp != NULL && (mp->mnt_flag & MNT_NOEXEC) != 0) {
1680 maxprot = VM_PROT_NONE;
1681 if ((prot & VM_PROT_EXECUTE) != 0)
1682 return (EACCES);
1683 } else
1684 maxprot = VM_PROT_EXECUTE;
1685 if ((fp->f_flag & FREAD) != 0)
1686 maxprot |= VM_PROT_READ;
1687 else if ((prot & VM_PROT_READ) != 0)
1688 return (EACCES);
1689
1690 /*
1691 * If we are sharing potential changes via MAP_SHARED and we
1692 * are trying to get write permission although we opened it
1693 * without asking for it, bail out.
1694 *
1695 * Note that most character devices always share mappings.
1696 *
1697 * Rely on linux_file_mmap_sub() to fail invalid MAP_PRIVATE
1698 * requests rather than doing it here.
1699 */
1700 if ((flags & MAP_SHARED) != 0) {
1701 if ((fp->f_flag & FWRITE) != 0)
1702 maxprot |= VM_PROT_WRITE;
1703 else if ((prot & VM_PROT_WRITE) != 0)
1704 return (EACCES);
1705 }
1706 maxprot &= cap_maxprot;
1707
1708 linux_get_fop(filp, &fop, &ldev);
1709 error = linux_file_mmap_sub(td, size, prot, maxprot, flags, fp,
1710 &foff, fop, &object);
1711 if (error != 0)
1712 goto out;
1713
1714 error = vm_mmap_object(map, addr, size, prot, maxprot, flags, object,
1715 foff, FALSE, td);
1716 if (error != 0)
1717 vm_object_deallocate(object);
1718 out:
1719 linux_drop_fop(ldev);
1720 return (error);
1721 }
1722
1723 static int
linux_file_stat(struct file * fp,struct stat * sb,struct ucred * active_cred)1724 linux_file_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
1725 {
1726 struct linux_file *filp;
1727 struct vnode *vp;
1728 int error;
1729
1730 filp = (struct linux_file *)fp->f_data;
1731 if (filp->f_vnode == NULL)
1732 return (EOPNOTSUPP);
1733
1734 vp = filp->f_vnode;
1735
1736 vn_lock(vp, LK_SHARED | LK_RETRY);
1737 error = VOP_STAT(vp, sb, curthread->td_ucred, NOCRED);
1738 VOP_UNLOCK(vp);
1739
1740 return (error);
1741 }
1742
1743 static int
linux_file_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)1744 linux_file_fill_kinfo(struct file *fp, struct kinfo_file *kif,
1745 struct filedesc *fdp)
1746 {
1747 struct linux_file *filp;
1748 struct vnode *vp;
1749 int error;
1750
1751 filp = fp->f_data;
1752 vp = filp->f_vnode;
1753 if (vp == NULL) {
1754 error = 0;
1755 kif->kf_type = KF_TYPE_DEV;
1756 } else {
1757 vref(vp);
1758 FILEDESC_SUNLOCK(fdp);
1759 error = vn_fill_kinfo_vnode(vp, kif);
1760 vrele(vp);
1761 kif->kf_type = KF_TYPE_VNODE;
1762 FILEDESC_SLOCK(fdp);
1763 }
1764 return (error);
1765 }
1766
1767 unsigned int
linux_iminor(struct inode * inode)1768 linux_iminor(struct inode *inode)
1769 {
1770 struct linux_cdev *ldev;
1771
1772 if (inode == NULL || inode->v_rdev == NULL ||
1773 inode->v_rdev->si_devsw != &linuxcdevsw)
1774 return (-1U);
1775 ldev = inode->v_rdev->si_drv1;
1776 if (ldev == NULL)
1777 return (-1U);
1778
1779 return (minor(ldev->dev));
1780 }
1781
1782 static int
linux_file_kcmp(struct file * fp1,struct file * fp2,struct thread * td)1783 linux_file_kcmp(struct file *fp1, struct file *fp2, struct thread *td)
1784 {
1785 struct linux_file *filp1, *filp2;
1786
1787 if (fp2->f_type != DTYPE_DEV)
1788 return (3);
1789
1790 filp1 = fp1->f_data;
1791 filp2 = fp2->f_data;
1792 return (kcmp_cmp((uintptr_t)filp1->f_cdev, (uintptr_t)filp2->f_cdev));
1793 }
1794
1795 const struct fileops linuxfileops = {
1796 .fo_read = linux_file_read,
1797 .fo_write = linux_file_write,
1798 .fo_truncate = invfo_truncate,
1799 .fo_kqfilter = linux_file_kqfilter,
1800 .fo_stat = linux_file_stat,
1801 .fo_fill_kinfo = linux_file_fill_kinfo,
1802 .fo_poll = linux_file_poll,
1803 .fo_close = linux_file_close,
1804 .fo_ioctl = linux_file_ioctl,
1805 .fo_mmap = linux_file_mmap,
1806 .fo_chmod = invfo_chmod,
1807 .fo_chown = invfo_chown,
1808 .fo_sendfile = invfo_sendfile,
1809 .fo_cmp = linux_file_kcmp,
1810 .fo_flags = DFLAG_PASSABLE,
1811 };
1812
1813 /*
1814 * Hash of vmmap addresses. This is infrequently accessed and does not
1815 * need to be particularly large. This is done because we must store the
1816 * caller's idea of the map size to properly unmap.
1817 */
1818 struct vmmap {
1819 LIST_ENTRY(vmmap) vm_next;
1820 void *vm_addr;
1821 unsigned long vm_size;
1822 };
1823
1824 struct vmmaphd {
1825 struct vmmap *lh_first;
1826 };
1827 #define VMMAP_HASH_SIZE 64
1828 #define VMMAP_HASH_MASK (VMMAP_HASH_SIZE - 1)
1829 #define VM_HASH(addr) ((uintptr_t)(addr) >> PAGE_SHIFT) & VMMAP_HASH_MASK
1830 static struct vmmaphd vmmaphead[VMMAP_HASH_SIZE];
1831 static struct mtx vmmaplock;
1832
1833 static void
vmmap_add(void * addr,unsigned long size)1834 vmmap_add(void *addr, unsigned long size)
1835 {
1836 struct vmmap *vmmap;
1837
1838 vmmap = kmalloc(sizeof(*vmmap), GFP_KERNEL);
1839 mtx_lock(&vmmaplock);
1840 vmmap->vm_size = size;
1841 vmmap->vm_addr = addr;
1842 LIST_INSERT_HEAD(&vmmaphead[VM_HASH(addr)], vmmap, vm_next);
1843 mtx_unlock(&vmmaplock);
1844 }
1845
1846 static struct vmmap *
vmmap_remove(void * addr)1847 vmmap_remove(void *addr)
1848 {
1849 struct vmmap *vmmap;
1850
1851 mtx_lock(&vmmaplock);
1852 LIST_FOREACH(vmmap, &vmmaphead[VM_HASH(addr)], vm_next)
1853 if (vmmap->vm_addr == addr)
1854 break;
1855 if (vmmap)
1856 LIST_REMOVE(vmmap, vm_next);
1857 mtx_unlock(&vmmaplock);
1858
1859 return (vmmap);
1860 }
1861
1862 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__) || defined(__aarch64__) || defined(__riscv)
1863 void *
_ioremap_attr(vm_paddr_t phys_addr,unsigned long size,int attr)1864 _ioremap_attr(vm_paddr_t phys_addr, unsigned long size, int attr)
1865 {
1866 void *addr;
1867
1868 addr = pmap_mapdev_attr(phys_addr, size, attr);
1869 if (addr == NULL)
1870 return (NULL);
1871 vmmap_add(addr, size);
1872
1873 return (addr);
1874 }
1875 #endif
1876
1877 void
iounmap(void * addr)1878 iounmap(void *addr)
1879 {
1880 struct vmmap *vmmap;
1881
1882 vmmap = vmmap_remove(addr);
1883 if (vmmap == NULL)
1884 return;
1885 #if defined(__i386__) || defined(__amd64__) || defined(__powerpc__) || defined(__aarch64__) || defined(__riscv)
1886 pmap_unmapdev(addr, vmmap->vm_size);
1887 #endif
1888 kfree(vmmap);
1889 }
1890
1891 void *
vmap(struct page ** pages,unsigned int count,unsigned long flags,int prot)1892 vmap(struct page **pages, unsigned int count, unsigned long flags, int prot)
1893 {
1894 vm_offset_t off;
1895 size_t size;
1896
1897 size = count * PAGE_SIZE;
1898 off = kva_alloc(size);
1899 if (off == 0)
1900 return (NULL);
1901 vmmap_add((void *)off, size);
1902 pmap_qenter(off, pages, count);
1903
1904 return ((void *)off);
1905 }
1906
1907 void
vunmap(void * addr)1908 vunmap(void *addr)
1909 {
1910 struct vmmap *vmmap;
1911
1912 vmmap = vmmap_remove(addr);
1913 if (vmmap == NULL)
1914 return;
1915 pmap_qremove((vm_offset_t)addr, vmmap->vm_size / PAGE_SIZE);
1916 kva_free((vm_offset_t)addr, vmmap->vm_size);
1917 kfree(vmmap);
1918 }
1919
1920 static char *
devm_kvasprintf(struct device * dev,gfp_t gfp,const char * fmt,va_list ap)1921 devm_kvasprintf(struct device *dev, gfp_t gfp, const char *fmt, va_list ap)
1922 {
1923 unsigned int len;
1924 char *p;
1925 va_list aq;
1926
1927 va_copy(aq, ap);
1928 len = vsnprintf(NULL, 0, fmt, aq);
1929 va_end(aq);
1930
1931 if (dev != NULL)
1932 p = devm_kmalloc(dev, len + 1, gfp);
1933 else
1934 p = kmalloc(len + 1, gfp);
1935 if (p != NULL)
1936 vsnprintf(p, len + 1, fmt, ap);
1937
1938 return (p);
1939 }
1940
1941 char *
kvasprintf(gfp_t gfp,const char * fmt,va_list ap)1942 kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
1943 {
1944
1945 return (devm_kvasprintf(NULL, gfp, fmt, ap));
1946 }
1947
1948 char *
lkpi_devm_kasprintf(struct device * dev,gfp_t gfp,const char * fmt,...)1949 lkpi_devm_kasprintf(struct device *dev, gfp_t gfp, const char *fmt, ...)
1950 {
1951 va_list ap;
1952 char *p;
1953
1954 va_start(ap, fmt);
1955 p = devm_kvasprintf(dev, gfp, fmt, ap);
1956 va_end(ap);
1957
1958 return (p);
1959 }
1960
1961 char *
kasprintf(gfp_t gfp,const char * fmt,...)1962 kasprintf(gfp_t gfp, const char *fmt, ...)
1963 {
1964 va_list ap;
1965 char *p;
1966
1967 va_start(ap, fmt);
1968 p = kvasprintf(gfp, fmt, ap);
1969 va_end(ap);
1970
1971 return (p);
1972 }
1973
1974 int
__lkpi_hexdump_printf(void * arg1 __unused,const char * fmt,...)1975 __lkpi_hexdump_printf(void *arg1 __unused, const char *fmt, ...)
1976 {
1977 va_list ap;
1978 int result;
1979
1980 va_start(ap, fmt);
1981 result = vprintf(fmt, ap);
1982 va_end(ap);
1983 return (result);
1984 }
1985
1986 int
__lkpi_hexdump_sbuf_printf(void * arg1,const char * fmt,...)1987 __lkpi_hexdump_sbuf_printf(void *arg1, const char *fmt, ...)
1988 {
1989 va_list ap;
1990 int result;
1991
1992 va_start(ap, fmt);
1993 result = sbuf_vprintf(arg1, fmt, ap);
1994 va_end(ap);
1995 return (result);
1996 }
1997
1998 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)1999 lkpi_hex_dump(int(*_fpf)(void *, const char *, ...), void *arg1,
2000 const char *level, const char *prefix_str,
2001 const int prefix_type, const int rowsize, const int groupsize,
2002 const void *buf, size_t len, const bool ascii)
2003 {
2004 typedef const struct { long long value; } __packed *print_64p_t;
2005 typedef const struct { uint32_t value; } __packed *print_32p_t;
2006 typedef const struct { uint16_t value; } __packed *print_16p_t;
2007 const void *buf_old = buf;
2008 int row;
2009
2010 while (len > 0) {
2011 if (level != NULL)
2012 _fpf(arg1, "%s", level);
2013 if (prefix_str != NULL)
2014 _fpf(arg1, "%s ", prefix_str);
2015
2016 switch (prefix_type) {
2017 case DUMP_PREFIX_ADDRESS:
2018 _fpf(arg1, "[%p] ", buf);
2019 break;
2020 case DUMP_PREFIX_OFFSET:
2021 _fpf(arg1, "[%#tx] ", ((const char *)buf -
2022 (const char *)buf_old));
2023 break;
2024 default:
2025 break;
2026 }
2027 for (row = 0; row != rowsize; row++) {
2028 if (groupsize == 8 && len > 7) {
2029 _fpf(arg1, "%016llx ", ((print_64p_t)buf)->value);
2030 buf = (const uint8_t *)buf + 8;
2031 len -= 8;
2032 } else if (groupsize == 4 && len > 3) {
2033 _fpf(arg1, "%08x ", ((print_32p_t)buf)->value);
2034 buf = (const uint8_t *)buf + 4;
2035 len -= 4;
2036 } else if (groupsize == 2 && len > 1) {
2037 _fpf(arg1, "%04x ", ((print_16p_t)buf)->value);
2038 buf = (const uint8_t *)buf + 2;
2039 len -= 2;
2040 } else if (len > 0) {
2041 _fpf(arg1, "%02x ", *(const uint8_t *)buf);
2042 buf = (const uint8_t *)buf + 1;
2043 len--;
2044 } else {
2045 break;
2046 }
2047 }
2048 _fpf(arg1, "\n");
2049 }
2050 }
2051
2052 static void
linux_timer_callback_wrapper(void * context)2053 linux_timer_callback_wrapper(void *context)
2054 {
2055 struct timer_list *timer;
2056
2057 timer = context;
2058
2059 /* the timer is about to be shutdown permanently */
2060 if (timer->function == NULL)
2061 return;
2062
2063 if (linux_set_current_flags(curthread, M_NOWAIT)) {
2064 /* try again later */
2065 callout_reset(&timer->callout, 1,
2066 &linux_timer_callback_wrapper, timer);
2067 return;
2068 }
2069
2070 timer->function(timer->data);
2071 }
2072
2073 static int
linux_timer_jiffies_until(unsigned long expires)2074 linux_timer_jiffies_until(unsigned long expires)
2075 {
2076 unsigned long delta = expires - jiffies;
2077
2078 /*
2079 * Guard against already expired values and make sure that the value can
2080 * be used as a tick count, rather than a jiffies count.
2081 */
2082 if ((long)delta < 1)
2083 delta = 1;
2084 else if (delta > INT_MAX)
2085 delta = INT_MAX;
2086 return ((int)delta);
2087 }
2088
2089 int
mod_timer(struct timer_list * timer,unsigned long expires)2090 mod_timer(struct timer_list *timer, unsigned long expires)
2091 {
2092 int ret;
2093
2094 timer->expires = expires;
2095 ret = callout_reset(&timer->callout,
2096 linux_timer_jiffies_until(expires),
2097 &linux_timer_callback_wrapper, timer);
2098
2099 MPASS(ret == 0 || ret == 1);
2100
2101 return (ret == 1);
2102 }
2103
2104 void
add_timer(struct timer_list * timer)2105 add_timer(struct timer_list *timer)
2106 {
2107
2108 callout_reset(&timer->callout,
2109 linux_timer_jiffies_until(timer->expires),
2110 &linux_timer_callback_wrapper, timer);
2111 }
2112
2113 void
add_timer_on(struct timer_list * timer,int cpu)2114 add_timer_on(struct timer_list *timer, int cpu)
2115 {
2116
2117 callout_reset_on(&timer->callout,
2118 linux_timer_jiffies_until(timer->expires),
2119 &linux_timer_callback_wrapper, timer, cpu);
2120 }
2121
2122 int
del_timer(struct timer_list * timer)2123 del_timer(struct timer_list *timer)
2124 {
2125
2126 if (callout_stop(&(timer)->callout) == -1)
2127 return (0);
2128 return (1);
2129 }
2130
2131 int
del_timer_sync(struct timer_list * timer)2132 del_timer_sync(struct timer_list *timer)
2133 {
2134
2135 if (callout_drain(&(timer)->callout) == -1)
2136 return (0);
2137 return (1);
2138 }
2139
2140 int
timer_delete_sync(struct timer_list * timer)2141 timer_delete_sync(struct timer_list *timer)
2142 {
2143
2144 return (del_timer_sync(timer));
2145 }
2146
2147 int
timer_shutdown_sync(struct timer_list * timer)2148 timer_shutdown_sync(struct timer_list *timer)
2149 {
2150
2151 timer->function = NULL;
2152 return (del_timer_sync(timer));
2153 }
2154
2155 /* greatest common divisor, Euclid equation */
2156 static uint64_t
lkpi_gcd_64(uint64_t a,uint64_t b)2157 lkpi_gcd_64(uint64_t a, uint64_t b)
2158 {
2159 uint64_t an;
2160 uint64_t bn;
2161
2162 while (b != 0) {
2163 an = b;
2164 bn = a % b;
2165 a = an;
2166 b = bn;
2167 }
2168 return (a);
2169 }
2170
2171 uint64_t lkpi_nsec2hz_rem;
2172 uint64_t lkpi_nsec2hz_div = 1000000000ULL;
2173 uint64_t lkpi_nsec2hz_max;
2174
2175 uint64_t lkpi_usec2hz_rem;
2176 uint64_t lkpi_usec2hz_div = 1000000ULL;
2177 uint64_t lkpi_usec2hz_max;
2178
2179 uint64_t lkpi_msec2hz_rem;
2180 uint64_t lkpi_msec2hz_div = 1000ULL;
2181 uint64_t lkpi_msec2hz_max;
2182
2183 static void
linux_timer_init(void * arg)2184 linux_timer_init(void *arg)
2185 {
2186 uint64_t gcd;
2187
2188 /*
2189 * Compute an internal HZ value which can divide 2**32 to
2190 * avoid timer rounding problems when the tick value wraps
2191 * around 2**32:
2192 */
2193 linux_timer_hz_mask = 1;
2194 while (linux_timer_hz_mask < (unsigned long)hz)
2195 linux_timer_hz_mask *= 2;
2196 linux_timer_hz_mask--;
2197
2198 /* compute some internal constants */
2199
2200 lkpi_nsec2hz_rem = hz;
2201 lkpi_usec2hz_rem = hz;
2202 lkpi_msec2hz_rem = hz;
2203
2204 gcd = lkpi_gcd_64(lkpi_nsec2hz_rem, lkpi_nsec2hz_div);
2205 lkpi_nsec2hz_rem /= gcd;
2206 lkpi_nsec2hz_div /= gcd;
2207 lkpi_nsec2hz_max = -1ULL / lkpi_nsec2hz_rem;
2208
2209 gcd = lkpi_gcd_64(lkpi_usec2hz_rem, lkpi_usec2hz_div);
2210 lkpi_usec2hz_rem /= gcd;
2211 lkpi_usec2hz_div /= gcd;
2212 lkpi_usec2hz_max = -1ULL / lkpi_usec2hz_rem;
2213
2214 gcd = lkpi_gcd_64(lkpi_msec2hz_rem, lkpi_msec2hz_div);
2215 lkpi_msec2hz_rem /= gcd;
2216 lkpi_msec2hz_div /= gcd;
2217 lkpi_msec2hz_max = -1ULL / lkpi_msec2hz_rem;
2218 }
2219 SYSINIT(linux_timer, SI_SUB_DRIVERS, SI_ORDER_FIRST, linux_timer_init, NULL);
2220
2221 void
linux_complete_common(struct completion * c,int all)2222 linux_complete_common(struct completion *c, int all)
2223 {
2224 sleepq_lock(c);
2225 if (all) {
2226 c->done = UINT_MAX;
2227 sleepq_broadcast(c, SLEEPQ_SLEEP, 0, 0);
2228 } else {
2229 if (c->done != UINT_MAX)
2230 c->done++;
2231 sleepq_signal(c, SLEEPQ_SLEEP, 0, 0);
2232 }
2233 sleepq_release(c);
2234 }
2235
2236 /*
2237 * Indefinite wait for done != 0 with or without signals.
2238 */
2239 int
linux_wait_for_common(struct completion * c,int flags)2240 linux_wait_for_common(struct completion *c, int flags)
2241 {
2242 struct task_struct *task;
2243 int error;
2244
2245 if (SCHEDULER_STOPPED())
2246 return (0);
2247
2248 task = current;
2249
2250 if (flags != 0)
2251 flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
2252 else
2253 flags = SLEEPQ_SLEEP;
2254 error = 0;
2255 for (;;) {
2256 sleepq_lock(c);
2257 if (c->done)
2258 break;
2259 sleepq_add(c, NULL, "completion", flags, 0);
2260 if (flags & SLEEPQ_INTERRUPTIBLE) {
2261 DROP_GIANT();
2262 error = -sleepq_wait_sig(c, 0);
2263 PICKUP_GIANT();
2264 if (error != 0) {
2265 linux_schedule_save_interrupt_value(task, error);
2266 error = -ERESTARTSYS;
2267 goto intr;
2268 }
2269 } else {
2270 DROP_GIANT();
2271 sleepq_wait(c, 0);
2272 PICKUP_GIANT();
2273 }
2274 }
2275 if (c->done != UINT_MAX)
2276 c->done--;
2277 sleepq_release(c);
2278
2279 intr:
2280 return (error);
2281 }
2282
2283 /*
2284 * Time limited wait for done != 0 with or without signals.
2285 */
2286 unsigned long
linux_wait_for_timeout_common(struct completion * c,unsigned long timeout,int flags)2287 linux_wait_for_timeout_common(struct completion *c, unsigned long timeout,
2288 int flags)
2289 {
2290 struct task_struct *task;
2291 unsigned long end = jiffies + timeout, error;
2292
2293 if (SCHEDULER_STOPPED())
2294 return (0);
2295
2296 task = current;
2297
2298 if (flags != 0)
2299 flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
2300 else
2301 flags = SLEEPQ_SLEEP;
2302
2303 for (;;) {
2304 sleepq_lock(c);
2305 if (c->done)
2306 break;
2307 sleepq_add(c, NULL, "completion", flags, 0);
2308 sleepq_set_timeout(c, linux_timer_jiffies_until(end));
2309
2310 DROP_GIANT();
2311 if (flags & SLEEPQ_INTERRUPTIBLE)
2312 error = -sleepq_timedwait_sig(c, 0);
2313 else
2314 error = -sleepq_timedwait(c, 0);
2315 PICKUP_GIANT();
2316
2317 if (error != 0) {
2318 /* check for timeout */
2319 if (error == -EWOULDBLOCK) {
2320 error = 0; /* timeout */
2321 } else {
2322 /* signal happened */
2323 linux_schedule_save_interrupt_value(task, error);
2324 error = -ERESTARTSYS;
2325 }
2326 goto done;
2327 }
2328 }
2329 if (c->done != UINT_MAX)
2330 c->done--;
2331 sleepq_release(c);
2332
2333 /* return how many jiffies are left */
2334 error = linux_timer_jiffies_until(end);
2335 done:
2336 return (error);
2337 }
2338
2339 int
linux_try_wait_for_completion(struct completion * c)2340 linux_try_wait_for_completion(struct completion *c)
2341 {
2342 int isdone;
2343
2344 sleepq_lock(c);
2345 isdone = (c->done != 0);
2346 if (c->done != 0 && c->done != UINT_MAX)
2347 c->done--;
2348 sleepq_release(c);
2349 return (isdone);
2350 }
2351
2352 int
linux_completion_done(struct completion * c)2353 linux_completion_done(struct completion *c)
2354 {
2355 int isdone;
2356
2357 sleepq_lock(c);
2358 isdone = (c->done != 0);
2359 sleepq_release(c);
2360 return (isdone);
2361 }
2362
2363 static void
linux_cdev_deref(struct linux_cdev * ldev)2364 linux_cdev_deref(struct linux_cdev *ldev)
2365 {
2366 if (refcount_release(&ldev->refs) &&
2367 ldev->kobj.ktype == &linux_cdev_ktype)
2368 kfree(ldev);
2369 }
2370
2371 static void
linux_cdev_release(struct kobject * kobj)2372 linux_cdev_release(struct kobject *kobj)
2373 {
2374 struct linux_cdev *cdev;
2375 struct kobject *parent;
2376
2377 cdev = container_of(kobj, struct linux_cdev, kobj);
2378 parent = kobj->parent;
2379 linux_destroy_dev(cdev);
2380 linux_cdev_deref(cdev);
2381 kobject_put(parent);
2382 }
2383
2384 static void
linux_cdev_static_release(struct kobject * kobj)2385 linux_cdev_static_release(struct kobject *kobj)
2386 {
2387 struct cdev *cdev;
2388 struct linux_cdev *ldev;
2389
2390 ldev = container_of(kobj, struct linux_cdev, kobj);
2391 cdev = ldev->cdev;
2392 if (cdev != NULL) {
2393 destroy_dev(cdev);
2394 ldev->cdev = NULL;
2395 }
2396 kobject_put(kobj->parent);
2397 }
2398
2399 int
linux_cdev_device_add(struct linux_cdev * ldev,struct device * dev)2400 linux_cdev_device_add(struct linux_cdev *ldev, struct device *dev)
2401 {
2402 int ret;
2403
2404 if (dev->devt != 0) {
2405 /* Set parent kernel object. */
2406 ldev->kobj.parent = &dev->kobj;
2407
2408 /*
2409 * Unlike Linux we require the kobject of the
2410 * character device structure to have a valid name
2411 * before calling this function:
2412 */
2413 if (ldev->kobj.name == NULL)
2414 return (-EINVAL);
2415
2416 ret = cdev_add(ldev, dev->devt, 1);
2417 if (ret)
2418 return (ret);
2419 }
2420 ret = device_add(dev);
2421 if (ret != 0 && dev->devt != 0)
2422 cdev_del(ldev);
2423 return (ret);
2424 }
2425
2426 void
linux_cdev_device_del(struct linux_cdev * ldev,struct device * dev)2427 linux_cdev_device_del(struct linux_cdev *ldev, struct device *dev)
2428 {
2429 device_del(dev);
2430
2431 if (dev->devt != 0)
2432 cdev_del(ldev);
2433 }
2434
2435 static void
linux_destroy_dev(struct linux_cdev * ldev)2436 linux_destroy_dev(struct linux_cdev *ldev)
2437 {
2438
2439 if (ldev->cdev == NULL)
2440 return;
2441
2442 MPASS((ldev->siref & LDEV_SI_DTR) == 0);
2443 MPASS(ldev->kobj.ktype == &linux_cdev_ktype);
2444
2445 atomic_set_int(&ldev->siref, LDEV_SI_DTR);
2446 while ((atomic_load_int(&ldev->siref) & ~LDEV_SI_DTR) != 0)
2447 pause("ldevdtr", hz / 4);
2448
2449 destroy_dev(ldev->cdev);
2450 ldev->cdev = NULL;
2451 }
2452
2453 const struct kobj_type linux_cdev_ktype = {
2454 .release = linux_cdev_release,
2455 };
2456
2457 const struct kobj_type linux_cdev_static_ktype = {
2458 .release = linux_cdev_static_release,
2459 };
2460
2461 static void
linux_handle_ifnet_link_event(void * arg,struct ifnet * ifp,int linkstate)2462 linux_handle_ifnet_link_event(void *arg, struct ifnet *ifp, int linkstate)
2463 {
2464 struct notifier_block *nb;
2465 struct netdev_notifier_info ni;
2466
2467 nb = arg;
2468 ni.ifp = ifp;
2469 ni.dev = (struct net_device *)ifp;
2470 if (linkstate == LINK_STATE_UP)
2471 nb->notifier_call(nb, NETDEV_UP, &ni);
2472 else
2473 nb->notifier_call(nb, NETDEV_DOWN, &ni);
2474 }
2475
2476 static void
linux_handle_ifnet_arrival_event(void * arg,struct ifnet * ifp)2477 linux_handle_ifnet_arrival_event(void *arg, struct ifnet *ifp)
2478 {
2479 struct notifier_block *nb;
2480 struct netdev_notifier_info ni;
2481
2482 nb = arg;
2483 ni.ifp = ifp;
2484 ni.dev = (struct net_device *)ifp;
2485 nb->notifier_call(nb, NETDEV_REGISTER, &ni);
2486 }
2487
2488 static void
linux_handle_ifnet_departure_event(void * arg,struct ifnet * ifp)2489 linux_handle_ifnet_departure_event(void *arg, struct ifnet *ifp)
2490 {
2491 struct notifier_block *nb;
2492 struct netdev_notifier_info ni;
2493
2494 nb = arg;
2495 ni.ifp = ifp;
2496 ni.dev = (struct net_device *)ifp;
2497 nb->notifier_call(nb, NETDEV_UNREGISTER, &ni);
2498 }
2499
2500 static void
linux_handle_iflladdr_event(void * arg,struct ifnet * ifp)2501 linux_handle_iflladdr_event(void *arg, struct ifnet *ifp)
2502 {
2503 struct notifier_block *nb;
2504 struct netdev_notifier_info ni;
2505
2506 nb = arg;
2507 ni.ifp = ifp;
2508 ni.dev = (struct net_device *)ifp;
2509 nb->notifier_call(nb, NETDEV_CHANGEADDR, &ni);
2510 }
2511
2512 static void
linux_handle_ifaddr_event(void * arg,struct ifnet * ifp)2513 linux_handle_ifaddr_event(void *arg, struct ifnet *ifp)
2514 {
2515 struct notifier_block *nb;
2516 struct netdev_notifier_info ni;
2517
2518 nb = arg;
2519 ni.ifp = ifp;
2520 ni.dev = (struct net_device *)ifp;
2521 nb->notifier_call(nb, NETDEV_CHANGEIFADDR, &ni);
2522 }
2523
2524 int
register_netdevice_notifier(struct notifier_block * nb)2525 register_netdevice_notifier(struct notifier_block *nb)
2526 {
2527
2528 nb->tags[NETDEV_UP] = EVENTHANDLER_REGISTER(
2529 ifnet_link_event, linux_handle_ifnet_link_event, nb, 0);
2530 nb->tags[NETDEV_REGISTER] = EVENTHANDLER_REGISTER(
2531 ifnet_arrival_event, linux_handle_ifnet_arrival_event, nb, 0);
2532 nb->tags[NETDEV_UNREGISTER] = EVENTHANDLER_REGISTER(
2533 ifnet_departure_event, linux_handle_ifnet_departure_event, nb, 0);
2534 nb->tags[NETDEV_CHANGEADDR] = EVENTHANDLER_REGISTER(
2535 iflladdr_event, linux_handle_iflladdr_event, nb, 0);
2536
2537 return (0);
2538 }
2539
2540 int
register_inetaddr_notifier(struct notifier_block * nb)2541 register_inetaddr_notifier(struct notifier_block *nb)
2542 {
2543
2544 nb->tags[NETDEV_CHANGEIFADDR] = EVENTHANDLER_REGISTER(
2545 ifaddr_event, linux_handle_ifaddr_event, nb, 0);
2546 return (0);
2547 }
2548
2549 int
unregister_netdevice_notifier(struct notifier_block * nb)2550 unregister_netdevice_notifier(struct notifier_block *nb)
2551 {
2552
2553 EVENTHANDLER_DEREGISTER(ifnet_link_event,
2554 nb->tags[NETDEV_UP]);
2555 EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
2556 nb->tags[NETDEV_REGISTER]);
2557 EVENTHANDLER_DEREGISTER(ifnet_departure_event,
2558 nb->tags[NETDEV_UNREGISTER]);
2559 EVENTHANDLER_DEREGISTER(iflladdr_event,
2560 nb->tags[NETDEV_CHANGEADDR]);
2561
2562 return (0);
2563 }
2564
2565 int
unregister_inetaddr_notifier(struct notifier_block * nb)2566 unregister_inetaddr_notifier(struct notifier_block *nb)
2567 {
2568
2569 EVENTHANDLER_DEREGISTER(ifaddr_event,
2570 nb->tags[NETDEV_CHANGEIFADDR]);
2571
2572 return (0);
2573 }
2574
2575 struct list_sort_thunk {
2576 int (*cmp)(void *, struct list_head *, struct list_head *);
2577 void *priv;
2578 };
2579
2580 static inline int
linux_le_cmp(const void * d1,const void * d2,void * priv)2581 linux_le_cmp(const void *d1, const void *d2, void *priv)
2582 {
2583 struct list_head *le1, *le2;
2584 struct list_sort_thunk *thunk;
2585
2586 thunk = priv;
2587 le1 = *(__DECONST(struct list_head **, d1));
2588 le2 = *(__DECONST(struct list_head **, d2));
2589 return ((thunk->cmp)(thunk->priv, le1, le2));
2590 }
2591
2592 void
list_sort(void * priv,struct list_head * head,int (* cmp)(void * priv,struct list_head * a,struct list_head * b))2593 list_sort(void *priv, struct list_head *head, int (*cmp)(void *priv,
2594 struct list_head *a, struct list_head *b))
2595 {
2596 struct list_sort_thunk thunk;
2597 struct list_head **ar, *le;
2598 size_t count, i;
2599
2600 count = 0;
2601 list_for_each(le, head)
2602 count++;
2603 ar = malloc(sizeof(struct list_head *) * count, M_KMALLOC, M_WAITOK);
2604 i = 0;
2605 list_for_each(le, head)
2606 ar[i++] = le;
2607 thunk.cmp = cmp;
2608 thunk.priv = priv;
2609 qsort_r(ar, count, sizeof(struct list_head *), linux_le_cmp, &thunk);
2610 INIT_LIST_HEAD(head);
2611 for (i = 0; i < count; i++)
2612 list_add_tail(ar[i], head);
2613 free(ar, M_KMALLOC);
2614 }
2615
2616 #if defined(__i386__) || defined(__amd64__)
2617 int
linux_wbinvd_on_all_cpus(void)2618 linux_wbinvd_on_all_cpus(void)
2619 {
2620
2621 pmap_invalidate_cache();
2622 return (0);
2623 }
2624 #endif
2625
2626 int
linux_on_each_cpu(void callback (void *),void * data)2627 linux_on_each_cpu(void callback(void *), void *data)
2628 {
2629
2630 smp_rendezvous(smp_no_rendezvous_barrier, callback,
2631 smp_no_rendezvous_barrier, data);
2632 return (0);
2633 }
2634
2635 int
linux_in_atomic(void)2636 linux_in_atomic(void)
2637 {
2638
2639 return ((curthread->td_pflags & TDP_NOFAULTING) != 0);
2640 }
2641
2642 struct linux_cdev *
linux_find_cdev(const char * name,unsigned major,unsigned minor)2643 linux_find_cdev(const char *name, unsigned major, unsigned minor)
2644 {
2645 dev_t dev = MKDEV(major, minor);
2646 struct cdev *cdev;
2647
2648 dev_lock();
2649 LIST_FOREACH(cdev, &linuxcdevsw.d_devs, si_list) {
2650 struct linux_cdev *ldev = cdev->si_drv1;
2651 if (ldev->dev == dev &&
2652 strcmp(kobject_name(&ldev->kobj), name) == 0) {
2653 break;
2654 }
2655 }
2656 dev_unlock();
2657
2658 return (cdev != NULL ? cdev->si_drv1 : NULL);
2659 }
2660
2661 int
__register_chrdev(unsigned int major,unsigned int baseminor,unsigned int count,const char * name,const struct file_operations * fops)2662 __register_chrdev(unsigned int major, unsigned int baseminor,
2663 unsigned int count, const char *name,
2664 const struct file_operations *fops)
2665 {
2666 struct linux_cdev *cdev;
2667 int ret = 0;
2668 int i;
2669
2670 for (i = baseminor; i < baseminor + count; i++) {
2671 cdev = cdev_alloc();
2672 cdev->ops = fops;
2673 kobject_set_name(&cdev->kobj, name);
2674
2675 ret = cdev_add(cdev, makedev(major, i), 1);
2676 if (ret != 0)
2677 break;
2678 }
2679 return (ret);
2680 }
2681
2682 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)2683 __register_chrdev_p(unsigned int major, unsigned int baseminor,
2684 unsigned int count, const char *name,
2685 const struct file_operations *fops, uid_t uid,
2686 gid_t gid, int mode)
2687 {
2688 struct linux_cdev *cdev;
2689 int ret = 0;
2690 int i;
2691
2692 for (i = baseminor; i < baseminor + count; i++) {
2693 cdev = cdev_alloc();
2694 cdev->ops = fops;
2695 kobject_set_name(&cdev->kobj, name);
2696
2697 ret = cdev_add_ext(cdev, makedev(major, i), uid, gid, mode);
2698 if (ret != 0)
2699 break;
2700 }
2701 return (ret);
2702 }
2703
2704 void
__unregister_chrdev(unsigned int major,unsigned int baseminor,unsigned int count,const char * name)2705 __unregister_chrdev(unsigned int major, unsigned int baseminor,
2706 unsigned int count, const char *name)
2707 {
2708 struct linux_cdev *cdevp;
2709 int i;
2710
2711 for (i = baseminor; i < baseminor + count; i++) {
2712 cdevp = linux_find_cdev(name, major, i);
2713 if (cdevp != NULL)
2714 cdev_del(cdevp);
2715 }
2716 }
2717
2718 void
linux_dump_stack(void)2719 linux_dump_stack(void)
2720 {
2721 #ifdef STACK
2722 struct stack st;
2723
2724 stack_save(&st);
2725 stack_print(&st);
2726 #endif
2727 }
2728
2729 int
linuxkpi_net_ratelimit(void)2730 linuxkpi_net_ratelimit(void)
2731 {
2732
2733 return (ppsratecheck(&lkpi_net_lastlog, &lkpi_net_curpps,
2734 lkpi_net_maxpps));
2735 }
2736
2737 struct io_mapping *
io_mapping_create_wc(resource_size_t base,unsigned long size)2738 io_mapping_create_wc(resource_size_t base, unsigned long size)
2739 {
2740 struct io_mapping *mapping;
2741
2742 mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2743 if (mapping == NULL)
2744 return (NULL);
2745 return (io_mapping_init_wc(mapping, base, size));
2746 }
2747
2748 /* We likely want a linuxkpi_device.c at some point. */
2749 bool
device_can_wakeup(struct device * dev)2750 device_can_wakeup(struct device *dev)
2751 {
2752
2753 if (dev == NULL)
2754 return (false);
2755 /*
2756 * XXX-BZ iwlwifi queries it as part of enabling WoWLAN.
2757 * Normally this would be based on a bool in dev->power.XXX.
2758 * Check such as PCI PCIM_PCAP_*PME. We have no way to enable this yet.
2759 * We may get away by directly calling into bsddev for as long as
2760 * we can assume PCI only avoiding changing struct device breaking KBI.
2761 */
2762 pr_debug("%s:%d: not enabled; see comment.\n", __func__, __LINE__);
2763 return (false);
2764 }
2765
2766 static void
devm_device_group_remove(struct device * dev,void * p)2767 devm_device_group_remove(struct device *dev, void *p)
2768 {
2769 const struct attribute_group **dr = p;
2770 const struct attribute_group *group = *dr;
2771
2772 sysfs_remove_group(&dev->kobj, group);
2773 }
2774
2775 int
lkpi_devm_device_add_group(struct device * dev,const struct attribute_group * group)2776 lkpi_devm_device_add_group(struct device *dev,
2777 const struct attribute_group *group)
2778 {
2779 const struct attribute_group **dr;
2780 int ret;
2781
2782 dr = devres_alloc(devm_device_group_remove, sizeof(*dr), GFP_KERNEL);
2783 if (dr == NULL)
2784 return (-ENOMEM);
2785
2786 ret = sysfs_create_group(&dev->kobj, group);
2787 if (ret == 0) {
2788 *dr = group;
2789 devres_add(dev, dr);
2790 } else
2791 devres_free(dr);
2792
2793 return (ret);
2794 }
2795
2796 #if defined(__i386__) || defined(__amd64__)
2797 bool linux_cpu_has_clflush;
2798 struct cpuinfo_x86 boot_cpu_data;
2799 struct cpuinfo_x86 *__cpu_data;
2800 #endif
2801
2802 cpumask_t *
lkpi_get_static_single_cpu_mask(int cpuid)2803 lkpi_get_static_single_cpu_mask(int cpuid)
2804 {
2805
2806 KASSERT((cpuid >= 0 && cpuid <= mp_maxid), ("%s: invalid cpuid %d\n",
2807 __func__, cpuid));
2808 KASSERT(!CPU_ABSENT(cpuid), ("%s: cpu with cpuid %d is absent\n",
2809 __func__, cpuid));
2810
2811 return (static_single_cpu_mask[cpuid]);
2812 }
2813
2814 bool
lkpi_xen_initial_domain(void)2815 lkpi_xen_initial_domain(void)
2816 {
2817 #ifdef XENHVM
2818 return (xen_initial_domain());
2819 #else
2820 return (false);
2821 #endif
2822 }
2823
2824 bool
lkpi_xen_pv_domain(void)2825 lkpi_xen_pv_domain(void)
2826 {
2827 #ifdef XENHVM
2828 return (xen_pv_domain());
2829 #else
2830 return (false);
2831 #endif
2832 }
2833
2834 static void
linux_compat_init(void * arg)2835 linux_compat_init(void *arg)
2836 {
2837 struct sysctl_oid *rootoid;
2838 int i;
2839
2840 #if defined(__i386__) || defined(__amd64__)
2841 static const uint32_t x86_vendors[X86_VENDOR_NUM] = {
2842 [X86_VENDOR_INTEL] = CPU_VENDOR_INTEL,
2843 [X86_VENDOR_CYRIX] = CPU_VENDOR_CYRIX,
2844 [X86_VENDOR_AMD] = CPU_VENDOR_AMD,
2845 [X86_VENDOR_UMC] = CPU_VENDOR_UMC,
2846 [X86_VENDOR_CENTAUR] = CPU_VENDOR_CENTAUR,
2847 [X86_VENDOR_TRANSMETA] = CPU_VENDOR_TRANSMETA,
2848 [X86_VENDOR_NSC] = CPU_VENDOR_NSC,
2849 [X86_VENDOR_HYGON] = CPU_VENDOR_HYGON,
2850 };
2851 uint8_t x86_vendor = X86_VENDOR_UNKNOWN;
2852
2853 for (i = 0; i < X86_VENDOR_NUM; i++) {
2854 if (cpu_vendor_id != 0 && cpu_vendor_id == x86_vendors[i]) {
2855 x86_vendor = i;
2856 break;
2857 }
2858 }
2859 linux_cpu_has_clflush = (cpu_feature & CPUID_CLFSH);
2860 boot_cpu_data.x86_clflush_size = cpu_clflush_line_size;
2861 boot_cpu_data.x86_max_cores = mp_ncpus;
2862 boot_cpu_data.x86 = CPUID_TO_FAMILY(cpu_id);
2863 boot_cpu_data.x86_model = CPUID_TO_MODEL(cpu_id);
2864 boot_cpu_data.x86_vendor = x86_vendor;
2865
2866 __cpu_data = kmalloc_array(mp_maxid + 1,
2867 sizeof(*__cpu_data), M_WAITOK | M_ZERO);
2868 CPU_FOREACH(i) {
2869 __cpu_data[i].x86_clflush_size = cpu_clflush_line_size;
2870 __cpu_data[i].x86_max_cores = mp_ncpus;
2871 __cpu_data[i].x86 = CPUID_TO_FAMILY(cpu_id);
2872 __cpu_data[i].x86_model = CPUID_TO_MODEL(cpu_id);
2873 __cpu_data[i].x86_vendor = x86_vendor;
2874 }
2875 #endif
2876 rw_init(&linux_vma_lock, "lkpi-vma-lock");
2877
2878 rootoid = SYSCTL_ADD_ROOT_NODE(NULL,
2879 OID_AUTO, "sys", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "sys");
2880 kobject_init(&linux_class_root, &linux_class_ktype);
2881 kobject_set_name(&linux_class_root, "class");
2882 linux_class_root.oidp = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(rootoid),
2883 OID_AUTO, "class", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "class");
2884 kobject_init(&linux_root_device.kobj, &linux_dev_ktype);
2885 kobject_set_name(&linux_root_device.kobj, "device");
2886 linux_root_device.kobj.oidp = SYSCTL_ADD_NODE(NULL,
2887 SYSCTL_CHILDREN(rootoid), OID_AUTO, "device",
2888 CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "device");
2889 linux_root_device.bsddev = root_bus;
2890 linux_class_misc.name = "misc";
2891 class_register(&linux_class_misc);
2892 INIT_LIST_HEAD(&pci_drivers);
2893 INIT_LIST_HEAD(&pci_devices);
2894 spin_lock_init(&pci_lock);
2895 mtx_init(&vmmaplock, "IO Map lock", NULL, MTX_DEF);
2896 for (i = 0; i < VMMAP_HASH_SIZE; i++)
2897 LIST_INIT(&vmmaphead[i]);
2898 init_waitqueue_head(&linux_bit_waitq);
2899 init_waitqueue_head(&linux_var_waitq);
2900
2901 CPU_COPY(&all_cpus, &cpu_online_mask);
2902 /*
2903 * Generate a single-CPU cpumask_t for each CPU (possibly) in the system.
2904 * CPUs are indexed from 0..(mp_maxid). The entry for cpuid 0 will only
2905 * have itself in the cpumask, cupid 1 only itself on entry 1, and so on.
2906 * This is used by cpumask_of() (and possibly others in the future) for,
2907 * e.g., drivers to pass hints to irq_set_affinity_hint().
2908 */
2909 static_single_cpu_mask = kmalloc_array(mp_maxid + 1,
2910 sizeof(static_single_cpu_mask), M_WAITOK | M_ZERO);
2911
2912 /*
2913 * When the number of CPUs reach a threshold, we start to save memory
2914 * given the sets are static by overlapping those having their single
2915 * bit set at same position in a bitset word. Asymptotically, this
2916 * regular scheme is in O(n²) whereas the overlapping one is in O(n)
2917 * only with n being the maximum number of CPUs, so the gain will become
2918 * huge quite quickly. The threshold for 64-bit architectures is 128
2919 * CPUs.
2920 */
2921 if (mp_ncpus < (2 * _BITSET_BITS)) {
2922 cpumask_t *sscm_ptr;
2923
2924 /*
2925 * This represents 'mp_ncpus * __bitset_words(CPU_SETSIZE) *
2926 * (_BITSET_BITS / 8)' bytes (for comparison with the
2927 * overlapping scheme).
2928 */
2929 static_single_cpu_mask_lcs = kmalloc_array(mp_ncpus,
2930 sizeof(*static_single_cpu_mask_lcs),
2931 M_WAITOK | M_ZERO);
2932
2933 sscm_ptr = static_single_cpu_mask_lcs;
2934 CPU_FOREACH(i) {
2935 static_single_cpu_mask[i] = sscm_ptr++;
2936 CPU_SET(i, static_single_cpu_mask[i]);
2937 }
2938 } else {
2939 /* Pointer to a bitset word. */
2940 __typeof(((cpuset_t *)NULL)->__bits[0]) *bwp;
2941
2942 /*
2943 * Allocate memory for (static) spans of 'cpumask_t' ('cpuset_t'
2944 * really) with a single bit set that can be reused for all
2945 * single CPU masks by making them start at different offsets.
2946 * We need '__bitset_words(CPU_SETSIZE) - 1' bitset words before
2947 * the word having its single bit set, and the same amount
2948 * after.
2949 */
2950 static_single_cpu_mask_lcs = mallocarray(_BITSET_BITS,
2951 (2 * __bitset_words(CPU_SETSIZE) - 1) * (_BITSET_BITS / 8),
2952 M_KMALLOC, M_WAITOK | M_ZERO);
2953
2954 /*
2955 * We rely below on cpuset_t and the bitset generic
2956 * implementation assigning words in the '__bits' array in the
2957 * same order of bits (i.e., little-endian ordering, not to be
2958 * confused with machine endianness, which concerns bits in
2959 * words and other integers). This is an imperfect test, but it
2960 * will detect a change to big-endian ordering.
2961 */
2962 _Static_assert(
2963 __bitset_word(_BITSET_BITS + 1, _BITSET_BITS) == 1,
2964 "Assumes a bitset implementation that is little-endian "
2965 "on its words");
2966
2967 /* Initialize the single bit of each static span. */
2968 bwp = (__typeof(bwp))static_single_cpu_mask_lcs +
2969 (__bitset_words(CPU_SETSIZE) - 1);
2970 for (i = 0; i < _BITSET_BITS; i++) {
2971 CPU_SET(i, (cpuset_t *)bwp);
2972 bwp += (2 * __bitset_words(CPU_SETSIZE) - 1);
2973 }
2974
2975 /*
2976 * Finally set all CPU masks to the proper word in their
2977 * relevant span.
2978 */
2979 CPU_FOREACH(i) {
2980 bwp = (__typeof(bwp))static_single_cpu_mask_lcs;
2981 /* Find the non-zero word of the relevant span. */
2982 bwp += (2 * __bitset_words(CPU_SETSIZE) - 1) *
2983 (i % _BITSET_BITS) +
2984 __bitset_words(CPU_SETSIZE) - 1;
2985 /* Shift to find the CPU mask start. */
2986 bwp -= (i / _BITSET_BITS);
2987 static_single_cpu_mask[i] = (cpuset_t *)bwp;
2988 }
2989 }
2990
2991 strlcpy(init_uts_ns.name.release, osrelease, sizeof(init_uts_ns.name.release));
2992 }
2993 SYSINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_init, NULL);
2994
2995 static void
linux_compat_uninit(void * arg)2996 linux_compat_uninit(void *arg)
2997 {
2998 linux_kobject_kfree_name(&linux_class_root);
2999 linux_kobject_kfree_name(&linux_root_device.kobj);
3000 linux_kobject_kfree_name(&linux_class_misc.kobj);
3001
3002 free(static_single_cpu_mask_lcs, M_KMALLOC);
3003 free(static_single_cpu_mask, M_KMALLOC);
3004 #if defined(__i386__) || defined(__amd64__)
3005 free(__cpu_data, M_KMALLOC);
3006 #endif
3007
3008 mtx_destroy(&vmmaplock);
3009 spin_lock_destroy(&pci_lock);
3010 rw_destroy(&linux_vma_lock);
3011 }
3012 SYSUNINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_uninit, NULL);
3013
3014 /*
3015 * NOTE: Linux frequently uses "unsigned long" for pointer to integer
3016 * conversion and vice versa, where in FreeBSD "uintptr_t" would be
3017 * used. Assert these types have the same size, else some parts of the
3018 * LinuxKPI may not work like expected:
3019 */
3020 CTASSERT(sizeof(unsigned long) == sizeof(uintptr_t));
3021