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