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