]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/compat/linuxkpi/common/src/linux_compat.c
Set "current" for all PCI enumeration callbacks.
[FreeBSD/FreeBSD.git] / sys / compat / linuxkpi / common / src / linux_compat.c
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-2016 Mellanox Technologies, Ltd.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice unmodified, this list of conditions, and the following
13  *    disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #include <sys/param.h>
34 #include <sys/systm.h>
35 #include <sys/malloc.h>
36 #include <sys/kernel.h>
37 #include <sys/sysctl.h>
38 #include <sys/proc.h>
39 #include <sys/sglist.h>
40 #include <sys/sleepqueue.h>
41 #include <sys/lock.h>
42 #include <sys/mutex.h>
43 #include <sys/bus.h>
44 #include <sys/fcntl.h>
45 #include <sys/file.h>
46 #include <sys/filio.h>
47 #include <sys/rwlock.h>
48
49 #include <vm/vm.h>
50 #include <vm/pmap.h>
51
52 #include <machine/stdarg.h>
53
54 #if defined(__i386__) || defined(__amd64__)
55 #include <machine/md_var.h>
56 #endif
57
58 #include <linux/kobject.h>
59 #include <linux/device.h>
60 #include <linux/slab.h>
61 #include <linux/module.h>
62 #include <linux/cdev.h>
63 #include <linux/file.h>
64 #include <linux/sysfs.h>
65 #include <linux/mm.h>
66 #include <linux/io.h>
67 #include <linux/vmalloc.h>
68 #include <linux/netdevice.h>
69 #include <linux/timer.h>
70 #include <linux/workqueue.h>
71 #include <linux/rcupdate.h>
72 #include <linux/interrupt.h>
73 #include <linux/uaccess.h>
74 #include <linux/kernel.h>
75 #include <linux/list.h>
76 #include <linux/compat.h>
77
78 #include <vm/vm_pager.h>
79
80 MALLOC_DEFINE(M_KMALLOC, "linux", "Linux kmalloc compat");
81
82 #include <linux/rbtree.h>
83 /* Undo Linux compat changes. */
84 #undef RB_ROOT
85 #undef file
86 #undef cdev
87 #define RB_ROOT(head)   (head)->rbh_root
88
89 struct kobject linux_class_root;
90 struct device linux_root_device;
91 struct class linux_class_misc;
92 struct list_head pci_drivers;
93 struct list_head pci_devices;
94 struct net init_net;
95 spinlock_t pci_lock;
96 struct sx linux_global_rcu_lock;
97
98 unsigned long linux_timer_hz_mask;
99
100 int
101 panic_cmp(struct rb_node *one, struct rb_node *two)
102 {
103         panic("no cmp");
104 }
105
106 RB_GENERATE(linux_root, rb_node, __entry, panic_cmp);
107
108 int
109 kobject_set_name_vargs(struct kobject *kobj, const char *fmt, va_list args)
110 {
111         va_list tmp_va;
112         int len;
113         char *old;
114         char *name;
115         char dummy;
116
117         old = kobj->name;
118
119         if (old && fmt == NULL)
120                 return (0);
121
122         /* compute length of string */
123         va_copy(tmp_va, args);
124         len = vsnprintf(&dummy, 0, fmt, tmp_va);
125         va_end(tmp_va);
126
127         /* account for zero termination */
128         len++;
129
130         /* check for error */
131         if (len < 1)
132                 return (-EINVAL);
133
134         /* allocate memory for string */
135         name = kzalloc(len, GFP_KERNEL);
136         if (name == NULL)
137                 return (-ENOMEM);
138         vsnprintf(name, len, fmt, args);
139         kobj->name = name;
140
141         /* free old string */
142         kfree(old);
143
144         /* filter new string */
145         for (; *name != '\0'; name++)
146                 if (*name == '/')
147                         *name = '!';
148         return (0);
149 }
150
151 int
152 kobject_set_name(struct kobject *kobj, const char *fmt, ...)
153 {
154         va_list args;
155         int error;
156
157         va_start(args, fmt);
158         error = kobject_set_name_vargs(kobj, fmt, args);
159         va_end(args);
160
161         return (error);
162 }
163
164 static int
165 kobject_add_complete(struct kobject *kobj, struct kobject *parent)
166 {
167         const struct kobj_type *t;
168         int error;
169
170         kobj->parent = parent;
171         error = sysfs_create_dir(kobj);
172         if (error == 0 && kobj->ktype && kobj->ktype->default_attrs) {
173                 struct attribute **attr;
174                 t = kobj->ktype;
175
176                 for (attr = t->default_attrs; *attr != NULL; attr++) {
177                         error = sysfs_create_file(kobj, *attr);
178                         if (error)
179                                 break;
180                 }
181                 if (error)
182                         sysfs_remove_dir(kobj);
183                 
184         }
185         return (error);
186 }
187
188 int
189 kobject_add(struct kobject *kobj, struct kobject *parent, const char *fmt, ...)
190 {
191         va_list args;
192         int error;
193
194         va_start(args, fmt);
195         error = kobject_set_name_vargs(kobj, fmt, args);
196         va_end(args);
197         if (error)
198                 return (error);
199
200         return kobject_add_complete(kobj, parent);
201 }
202
203 void
204 linux_kobject_release(struct kref *kref)
205 {
206         struct kobject *kobj;
207         char *name;
208
209         kobj = container_of(kref, struct kobject, kref);
210         sysfs_remove_dir(kobj);
211         name = kobj->name;
212         if (kobj->ktype && kobj->ktype->release)
213                 kobj->ktype->release(kobj);
214         kfree(name);
215 }
216
217 static void
218 linux_kobject_kfree(struct kobject *kobj)
219 {
220         kfree(kobj);
221 }
222
223 static void
224 linux_kobject_kfree_name(struct kobject *kobj)
225 {
226         if (kobj) {
227                 kfree(kobj->name);
228         }
229 }
230
231 const struct kobj_type linux_kfree_type = {
232         .release = linux_kobject_kfree
233 };
234
235 static void
236 linux_device_release(struct device *dev)
237 {
238         pr_debug("linux_device_release: %s\n", dev_name(dev));
239         kfree(dev);
240 }
241
242 static ssize_t
243 linux_class_show(struct kobject *kobj, struct attribute *attr, char *buf)
244 {
245         struct class_attribute *dattr;
246         ssize_t error;
247
248         dattr = container_of(attr, struct class_attribute, attr);
249         error = -EIO;
250         if (dattr->show)
251                 error = dattr->show(container_of(kobj, struct class, kobj),
252                     dattr, buf);
253         return (error);
254 }
255
256 static ssize_t
257 linux_class_store(struct kobject *kobj, struct attribute *attr, const char *buf,
258     size_t count)
259 {
260         struct class_attribute *dattr;
261         ssize_t error;
262
263         dattr = container_of(attr, struct class_attribute, attr);
264         error = -EIO;
265         if (dattr->store)
266                 error = dattr->store(container_of(kobj, struct class, kobj),
267                     dattr, buf, count);
268         return (error);
269 }
270
271 static void
272 linux_class_release(struct kobject *kobj)
273 {
274         struct class *class;
275
276         class = container_of(kobj, struct class, kobj);
277         if (class->class_release)
278                 class->class_release(class);
279 }
280
281 static const struct sysfs_ops linux_class_sysfs = {
282         .show  = linux_class_show,
283         .store = linux_class_store,
284 };
285
286 const struct kobj_type linux_class_ktype = {
287         .release = linux_class_release,
288         .sysfs_ops = &linux_class_sysfs
289 };
290
291 static void
292 linux_dev_release(struct kobject *kobj)
293 {
294         struct device *dev;
295
296         dev = container_of(kobj, struct device, kobj);
297         /* This is the precedence defined by linux. */
298         if (dev->release)
299                 dev->release(dev);
300         else if (dev->class && dev->class->dev_release)
301                 dev->class->dev_release(dev);
302 }
303
304 static ssize_t
305 linux_dev_show(struct kobject *kobj, struct attribute *attr, char *buf)
306 {
307         struct device_attribute *dattr;
308         ssize_t error;
309
310         dattr = container_of(attr, struct device_attribute, attr);
311         error = -EIO;
312         if (dattr->show)
313                 error = dattr->show(container_of(kobj, struct device, kobj),
314                     dattr, buf);
315         return (error);
316 }
317
318 static ssize_t
319 linux_dev_store(struct kobject *kobj, struct attribute *attr, const char *buf,
320     size_t count)
321 {
322         struct device_attribute *dattr;
323         ssize_t error;
324
325         dattr = container_of(attr, struct device_attribute, attr);
326         error = -EIO;
327         if (dattr->store)
328                 error = dattr->store(container_of(kobj, struct device, kobj),
329                     dattr, buf, count);
330         return (error);
331 }
332
333 static const struct sysfs_ops linux_dev_sysfs = {
334         .show  = linux_dev_show,
335         .store = linux_dev_store,
336 };
337
338 const struct kobj_type linux_dev_ktype = {
339         .release = linux_dev_release,
340         .sysfs_ops = &linux_dev_sysfs
341 };
342
343 struct device *
344 device_create(struct class *class, struct device *parent, dev_t devt,
345     void *drvdata, const char *fmt, ...)
346 {
347         struct device *dev;
348         va_list args;
349
350         dev = kzalloc(sizeof(*dev), M_WAITOK);
351         dev->parent = parent;
352         dev->class = class;
353         dev->devt = devt;
354         dev->driver_data = drvdata;
355         dev->release = linux_device_release;
356         va_start(args, fmt);
357         kobject_set_name_vargs(&dev->kobj, fmt, args);
358         va_end(args);
359         device_register(dev);
360
361         return (dev);
362 }
363
364 int
365 kobject_init_and_add(struct kobject *kobj, const struct kobj_type *ktype,
366     struct kobject *parent, const char *fmt, ...)
367 {
368         va_list args;
369         int error;
370
371         kobject_init(kobj, ktype);
372         kobj->ktype = ktype;
373         kobj->parent = parent;
374         kobj->name = NULL;
375
376         va_start(args, fmt);
377         error = kobject_set_name_vargs(kobj, fmt, args);
378         va_end(args);
379         if (error)
380                 return (error);
381         return kobject_add_complete(kobj, parent);
382 }
383
384 void
385 linux_set_current(struct thread *td, struct task_struct *t)
386 {
387         memset(t, 0, sizeof(*t));
388         task_struct_fill(td, t);
389         task_struct_set(td, t);
390 }
391
392 void
393 linux_clear_current(struct thread *td)
394 {
395         task_struct_set(td, NULL);
396 }
397
398 static void
399 linux_file_dtor(void *cdp)
400 {
401         struct linux_file *filp;
402         struct task_struct t;
403         struct thread *td;
404
405         td = curthread;
406         filp = cdp;
407         linux_set_current(td, &t);
408         filp->f_op->release(filp->f_vnode, filp);
409         linux_clear_current(td);
410         vdrop(filp->f_vnode);
411         kfree(filp);
412 }
413
414 static int
415 linux_dev_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
416 {
417         struct linux_cdev *ldev;
418         struct linux_file *filp;
419         struct task_struct t;
420         struct file *file;
421         int error;
422
423         file = td->td_fpop;
424         ldev = dev->si_drv1;
425         if (ldev == NULL)
426                 return (ENODEV);
427         filp = kzalloc(sizeof(*filp), GFP_KERNEL);
428         filp->f_dentry = &filp->f_dentry_store;
429         filp->f_op = ldev->ops;
430         filp->f_flags = file->f_flag;
431         vhold(file->f_vnode);
432         filp->f_vnode = file->f_vnode;
433         linux_set_current(td, &t);
434         if (filp->f_op->open) {
435                 error = -filp->f_op->open(file->f_vnode, filp);
436                 if (error) {
437                         kfree(filp);
438                         goto done;
439                 }
440         }
441         error = devfs_set_cdevpriv(filp, linux_file_dtor);
442         if (error) {
443                 filp->f_op->release(file->f_vnode, filp);
444                 kfree(filp);
445         }
446 done:
447         linux_clear_current(td);
448         return (error);
449 }
450
451 static int
452 linux_dev_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
453 {
454         struct linux_cdev *ldev;
455         struct linux_file *filp;
456         struct file *file;
457         int error;
458
459         file = td->td_fpop;
460         ldev = dev->si_drv1;
461         if (ldev == NULL)
462                 return (0);
463         if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
464                 return (error);
465         filp->f_flags = file->f_flag;
466         devfs_clear_cdevpriv();
467         
468
469         return (0);
470 }
471
472 #define LINUX_IOCTL_MIN_PTR 0x10000UL
473 #define LINUX_IOCTL_MAX_PTR (LINUX_IOCTL_MIN_PTR + IOCPARM_MAX)
474
475 static inline int
476 linux_remap_address(void **uaddr, size_t len)
477 {
478         uintptr_t uaddr_val = (uintptr_t)(*uaddr);
479
480         if (unlikely(uaddr_val >= LINUX_IOCTL_MIN_PTR &&
481             uaddr_val < LINUX_IOCTL_MAX_PTR)) {
482                 struct task_struct *pts = current;
483                 if (pts == NULL) {
484                         *uaddr = NULL;
485                         return (1);
486                 }
487
488                 /* compute data offset */
489                 uaddr_val -= LINUX_IOCTL_MIN_PTR;
490
491                 /* check that length is within bounds */
492                 if ((len > IOCPARM_MAX) ||
493                     (uaddr_val + len) > pts->bsd_ioctl_len) {
494                         *uaddr = NULL;
495                         return (1);
496                 }
497
498                 /* re-add kernel buffer address */
499                 uaddr_val += (uintptr_t)pts->bsd_ioctl_data;
500
501                 /* update address location */
502                 *uaddr = (void *)uaddr_val;
503                 return (1);
504         }
505         return (0);
506 }
507
508 int
509 linux_copyin(const void *uaddr, void *kaddr, size_t len)
510 {
511         if (linux_remap_address(__DECONST(void **, &uaddr), len)) {
512                 if (uaddr == NULL)
513                         return (-EFAULT);
514                 memcpy(kaddr, uaddr, len);
515                 return (0);
516         }
517         return (-copyin(uaddr, kaddr, len));
518 }
519
520 int
521 linux_copyout(const void *kaddr, void *uaddr, size_t len)
522 {
523         if (linux_remap_address(&uaddr, len)) {
524                 if (uaddr == NULL)
525                         return (-EFAULT);
526                 memcpy(uaddr, kaddr, len);
527                 return (0);
528         }
529         return (-copyout(kaddr, uaddr, len));
530 }
531
532 static int
533 linux_dev_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag,
534     struct thread *td)
535 {
536         struct linux_cdev *ldev;
537         struct linux_file *filp;
538         struct task_struct t;
539         struct file *file;
540         unsigned size;
541         int error;
542
543         file = td->td_fpop;
544         ldev = dev->si_drv1;
545         if (ldev == NULL)
546                 return (0);
547         if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
548                 return (error);
549         filp->f_flags = file->f_flag;
550         linux_set_current(td, &t);
551         size = IOCPARM_LEN(cmd);
552         /* refer to logic in sys_ioctl() */
553         if (size > 0) {
554                 /*
555                  * Setup hint for linux_copyin() and linux_copyout().
556                  *
557                  * Background: Linux code expects a user-space address
558                  * while FreeBSD supplies a kernel-space address.
559                  */
560                 t.bsd_ioctl_data = data;
561                 t.bsd_ioctl_len = size;
562                 data = (void *)LINUX_IOCTL_MIN_PTR;
563         } else {
564                 /* fetch user-space pointer */
565                 data = *(void **)data;
566         }
567         if (filp->f_op->unlocked_ioctl)
568                 error = -filp->f_op->unlocked_ioctl(filp, cmd, (u_long)data);
569         else
570                 error = ENOTTY;
571         linux_clear_current(td);
572
573         return (error);
574 }
575
576 static int
577 linux_dev_read(struct cdev *dev, struct uio *uio, int ioflag)
578 {
579         struct linux_cdev *ldev;
580         struct linux_file *filp;
581         struct task_struct t;
582         struct thread *td;
583         struct file *file;
584         ssize_t bytes;
585         int error;
586
587         td = curthread;
588         file = td->td_fpop;
589         ldev = dev->si_drv1;
590         if (ldev == NULL)
591                 return (0);
592         if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
593                 return (error);
594         filp->f_flags = file->f_flag;
595         /* XXX no support for I/O vectors currently */
596         if (uio->uio_iovcnt != 1)
597                 return (EOPNOTSUPP);
598         linux_set_current(td, &t);
599         if (filp->f_op->read) {
600                 bytes = filp->f_op->read(filp, uio->uio_iov->iov_base,
601                     uio->uio_iov->iov_len, &uio->uio_offset);
602                 if (bytes >= 0) {
603                         uio->uio_iov->iov_base =
604                             ((uint8_t *)uio->uio_iov->iov_base) + bytes;
605                         uio->uio_iov->iov_len -= bytes;
606                         uio->uio_resid -= bytes;
607                 } else
608                         error = -bytes;
609         } else
610                 error = ENXIO;
611         linux_clear_current(td);
612
613         return (error);
614 }
615
616 static int
617 linux_dev_write(struct cdev *dev, struct uio *uio, int ioflag)
618 {
619         struct linux_cdev *ldev;
620         struct linux_file *filp;
621         struct task_struct t;
622         struct thread *td;
623         struct file *file;
624         ssize_t bytes;
625         int error;
626
627         td = curthread;
628         file = td->td_fpop;
629         ldev = dev->si_drv1;
630         if (ldev == NULL)
631                 return (0);
632         if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
633                 return (error);
634         filp->f_flags = file->f_flag;
635         /* XXX no support for I/O vectors currently */
636         if (uio->uio_iovcnt != 1)
637                 return (EOPNOTSUPP);
638         linux_set_current(td, &t);
639         if (filp->f_op->write) {
640                 bytes = filp->f_op->write(filp, uio->uio_iov->iov_base,
641                     uio->uio_iov->iov_len, &uio->uio_offset);
642                 if (bytes >= 0) {
643                         uio->uio_iov->iov_base =
644                             ((uint8_t *)uio->uio_iov->iov_base) + bytes;
645                         uio->uio_iov->iov_len -= bytes;
646                         uio->uio_resid -= bytes;
647                 } else
648                         error = -bytes;
649         } else
650                 error = ENXIO;
651         linux_clear_current(td);
652
653         return (error);
654 }
655
656 static int
657 linux_dev_poll(struct cdev *dev, int events, struct thread *td)
658 {
659         struct linux_cdev *ldev;
660         struct linux_file *filp;
661         struct task_struct t;
662         struct file *file;
663         int revents;
664         int error;
665
666         file = td->td_fpop;
667         ldev = dev->si_drv1;
668         if (ldev == NULL)
669                 return (0);
670         if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
671                 return (error);
672         filp->f_flags = file->f_flag;
673         linux_set_current(td, &t);
674         if (filp->f_op->poll)
675                 revents = filp->f_op->poll(filp, NULL) & events;
676         else
677                 revents = 0;
678         linux_clear_current(td);
679
680         return (revents);
681 }
682
683 static int
684 linux_dev_mmap_single(struct cdev *dev, vm_ooffset_t *offset,
685     vm_size_t size, struct vm_object **object, int nprot)
686 {
687         struct linux_cdev *ldev;
688         struct linux_file *filp;
689         struct thread *td;
690         struct task_struct t;
691         struct file *file;
692         struct vm_area_struct vma;
693         int error;
694
695         td = curthread;
696         file = td->td_fpop;
697         ldev = dev->si_drv1;
698         if (ldev == NULL)
699                 return (ENODEV);
700         if ((error = devfs_get_cdevpriv((void **)&filp)) != 0)
701                 return (error);
702         filp->f_flags = file->f_flag;
703         linux_set_current(td, &t);
704         vma.vm_start = 0;
705         vma.vm_end = size;
706         vma.vm_pgoff = *offset / PAGE_SIZE;
707         vma.vm_pfn = 0;
708         vma.vm_page_prot = VM_MEMATTR_DEFAULT;
709         if (filp->f_op->mmap) {
710                 error = -filp->f_op->mmap(filp, &vma);
711                 if (error == 0) {
712                         struct sglist *sg;
713
714                         sg = sglist_alloc(1, M_WAITOK);
715                         sglist_append_phys(sg,
716                             (vm_paddr_t)vma.vm_pfn << PAGE_SHIFT, vma.vm_len);
717                         *object = vm_pager_allocate(OBJT_SG, sg, vma.vm_len,
718                             nprot, 0, td->td_ucred);
719                         if (*object == NULL) {
720                                 sglist_free(sg);
721                                 error = EINVAL;
722                                 goto done;
723                         }
724                         *offset = 0;
725                         if (vma.vm_page_prot != VM_MEMATTR_DEFAULT) {
726                                 VM_OBJECT_WLOCK(*object);
727                                 vm_object_set_memattr(*object,
728                                     vma.vm_page_prot);
729                                 VM_OBJECT_WUNLOCK(*object);
730                         }
731                 }
732         } else
733                 error = ENODEV;
734 done:
735         linux_clear_current(td);
736         return (error);
737 }
738
739 struct cdevsw linuxcdevsw = {
740         .d_version = D_VERSION,
741         .d_flags = D_TRACKCLOSE,
742         .d_open = linux_dev_open,
743         .d_close = linux_dev_close,
744         .d_read = linux_dev_read,
745         .d_write = linux_dev_write,
746         .d_ioctl = linux_dev_ioctl,
747         .d_mmap_single = linux_dev_mmap_single,
748         .d_poll = linux_dev_poll,
749 };
750
751 static int
752 linux_file_read(struct file *file, struct uio *uio, struct ucred *active_cred,
753     int flags, struct thread *td)
754 {
755         struct linux_file *filp;
756         struct task_struct t;
757         ssize_t bytes;
758         int error;
759
760         error = 0;
761         filp = (struct linux_file *)file->f_data;
762         filp->f_flags = file->f_flag;
763         /* XXX no support for I/O vectors currently */
764         if (uio->uio_iovcnt != 1)
765                 return (EOPNOTSUPP);
766         linux_set_current(td, &t);
767         if (filp->f_op->read) {
768                 bytes = filp->f_op->read(filp, uio->uio_iov->iov_base,
769                     uio->uio_iov->iov_len, &uio->uio_offset);
770                 if (bytes >= 0) {
771                         uio->uio_iov->iov_base =
772                             ((uint8_t *)uio->uio_iov->iov_base) + bytes;
773                         uio->uio_iov->iov_len -= bytes;
774                         uio->uio_resid -= bytes;
775                 } else
776                         error = -bytes;
777         } else
778                 error = ENXIO;
779         linux_clear_current(td);
780
781         return (error);
782 }
783
784 static int
785 linux_file_poll(struct file *file, int events, struct ucred *active_cred,
786     struct thread *td)
787 {
788         struct linux_file *filp;
789         struct task_struct t;
790         int revents;
791
792         filp = (struct linux_file *)file->f_data;
793         filp->f_flags = file->f_flag;
794         linux_set_current(td, &t);
795         if (filp->f_op->poll)
796                 revents = filp->f_op->poll(filp, NULL) & events;
797         else
798                 revents = 0;
799         linux_clear_current(td);
800
801         return (revents);
802 }
803
804 static int
805 linux_file_close(struct file *file, struct thread *td)
806 {
807         struct linux_file *filp;
808         struct task_struct t;
809         int error;
810
811         filp = (struct linux_file *)file->f_data;
812         filp->f_flags = file->f_flag;
813         linux_set_current(td, &t);
814         error = -filp->f_op->release(NULL, filp);
815         linux_clear_current(td);
816         funsetown(&filp->f_sigio);
817         kfree(filp);
818
819         return (error);
820 }
821
822 static int
823 linux_file_ioctl(struct file *fp, u_long cmd, void *data, struct ucred *cred,
824     struct thread *td)
825 {
826         struct linux_file *filp;
827         struct task_struct t;
828         int error;
829
830         filp = (struct linux_file *)fp->f_data;
831         filp->f_flags = fp->f_flag;
832         error = 0;
833
834         linux_set_current(td, &t);
835         switch (cmd) {
836         case FIONBIO:
837                 break;
838         case FIOASYNC:
839                 if (filp->f_op->fasync == NULL)
840                         break;
841                 error = filp->f_op->fasync(0, filp, fp->f_flag & FASYNC);
842                 break;
843         case FIOSETOWN:
844                 error = fsetown(*(int *)data, &filp->f_sigio);
845                 if (error == 0)
846                         error = filp->f_op->fasync(0, filp,
847                             fp->f_flag & FASYNC);
848                 break;
849         case FIOGETOWN:
850                 *(int *)data = fgetown(&filp->f_sigio);
851                 break;
852         default:
853                 error = ENOTTY;
854                 break;
855         }
856         linux_clear_current(td);
857         return (error);
858 }
859
860 static int
861 linux_file_stat(struct file *fp, struct stat *sb, struct ucred *active_cred,
862     struct thread *td)
863 {
864
865         return (EOPNOTSUPP);
866 }
867
868 static int
869 linux_file_fill_kinfo(struct file *fp, struct kinfo_file *kif,
870     struct filedesc *fdp)
871 {
872
873         return (0);
874 }
875
876 struct fileops linuxfileops = {
877         .fo_read = linux_file_read,
878         .fo_write = invfo_rdwr,
879         .fo_truncate = invfo_truncate,
880         .fo_kqfilter = invfo_kqfilter,
881         .fo_stat = linux_file_stat,
882         .fo_fill_kinfo = linux_file_fill_kinfo,
883         .fo_poll = linux_file_poll,
884         .fo_close = linux_file_close,
885         .fo_ioctl = linux_file_ioctl,
886         .fo_chmod = invfo_chmod,
887         .fo_chown = invfo_chown,
888         .fo_sendfile = invfo_sendfile,
889 };
890
891 /*
892  * Hash of vmmap addresses.  This is infrequently accessed and does not
893  * need to be particularly large.  This is done because we must store the
894  * caller's idea of the map size to properly unmap.
895  */
896 struct vmmap {
897         LIST_ENTRY(vmmap)       vm_next;
898         void                    *vm_addr;
899         unsigned long           vm_size;
900 };
901
902 struct vmmaphd {
903         struct vmmap *lh_first;
904 };
905 #define VMMAP_HASH_SIZE 64
906 #define VMMAP_HASH_MASK (VMMAP_HASH_SIZE - 1)
907 #define VM_HASH(addr)   ((uintptr_t)(addr) >> PAGE_SHIFT) & VMMAP_HASH_MASK
908 static struct vmmaphd vmmaphead[VMMAP_HASH_SIZE];
909 static struct mtx vmmaplock;
910
911 static void
912 vmmap_add(void *addr, unsigned long size)
913 {
914         struct vmmap *vmmap;
915
916         vmmap = kmalloc(sizeof(*vmmap), GFP_KERNEL);
917         mtx_lock(&vmmaplock);
918         vmmap->vm_size = size;
919         vmmap->vm_addr = addr;
920         LIST_INSERT_HEAD(&vmmaphead[VM_HASH(addr)], vmmap, vm_next);
921         mtx_unlock(&vmmaplock);
922 }
923
924 static struct vmmap *
925 vmmap_remove(void *addr)
926 {
927         struct vmmap *vmmap;
928
929         mtx_lock(&vmmaplock);
930         LIST_FOREACH(vmmap, &vmmaphead[VM_HASH(addr)], vm_next)
931                 if (vmmap->vm_addr == addr)
932                         break;
933         if (vmmap)
934                 LIST_REMOVE(vmmap, vm_next);
935         mtx_unlock(&vmmaplock);
936
937         return (vmmap);
938 }
939
940 #if defined(__i386__) || defined(__amd64__)
941 void *
942 _ioremap_attr(vm_paddr_t phys_addr, unsigned long size, int attr)
943 {
944         void *addr;
945
946         addr = pmap_mapdev_attr(phys_addr, size, attr);
947         if (addr == NULL)
948                 return (NULL);
949         vmmap_add(addr, size);
950
951         return (addr);
952 }
953 #endif
954
955 void
956 iounmap(void *addr)
957 {
958         struct vmmap *vmmap;
959
960         vmmap = vmmap_remove(addr);
961         if (vmmap == NULL)
962                 return;
963 #if defined(__i386__) || defined(__amd64__)
964         pmap_unmapdev((vm_offset_t)addr, vmmap->vm_size);
965 #endif
966         kfree(vmmap);
967 }
968
969
970 void *
971 vmap(struct page **pages, unsigned int count, unsigned long flags, int prot)
972 {
973         vm_offset_t off;
974         size_t size;
975
976         size = count * PAGE_SIZE;
977         off = kva_alloc(size);
978         if (off == 0)
979                 return (NULL);
980         vmmap_add((void *)off, size);
981         pmap_qenter(off, pages, count);
982
983         return ((void *)off);
984 }
985
986 void
987 vunmap(void *addr)
988 {
989         struct vmmap *vmmap;
990
991         vmmap = vmmap_remove(addr);
992         if (vmmap == NULL)
993                 return;
994         pmap_qremove((vm_offset_t)addr, vmmap->vm_size / PAGE_SIZE);
995         kva_free((vm_offset_t)addr, vmmap->vm_size);
996         kfree(vmmap);
997 }
998
999 char *
1000 kvasprintf(gfp_t gfp, const char *fmt, va_list ap)
1001 {
1002         unsigned int len;
1003         char *p;
1004         va_list aq;
1005
1006         va_copy(aq, ap);
1007         len = vsnprintf(NULL, 0, fmt, aq);
1008         va_end(aq);
1009
1010         p = kmalloc(len + 1, gfp);
1011         if (p != NULL)
1012                 vsnprintf(p, len + 1, fmt, ap);
1013
1014         return (p);
1015 }
1016
1017 char *
1018 kasprintf(gfp_t gfp, const char *fmt, ...)
1019 {
1020         va_list ap;
1021         char *p;
1022
1023         va_start(ap, fmt);
1024         p = kvasprintf(gfp, fmt, ap);
1025         va_end(ap);
1026
1027         return (p);
1028 }
1029
1030 static void
1031 linux_timer_callback_wrapper(void *context)
1032 {
1033         struct timer_list *timer;
1034
1035         timer = context;
1036         timer->function(timer->data);
1037 }
1038
1039 void
1040 mod_timer(struct timer_list *timer, unsigned long expires)
1041 {
1042
1043         timer->expires = expires;
1044         callout_reset(&timer->timer_callout,                  
1045             linux_timer_jiffies_until(expires),
1046             &linux_timer_callback_wrapper, timer);
1047 }
1048
1049 void
1050 add_timer(struct timer_list *timer)
1051 {
1052
1053         callout_reset(&timer->timer_callout,
1054             linux_timer_jiffies_until(timer->expires),
1055             &linux_timer_callback_wrapper, timer);
1056 }
1057
1058 static void
1059 linux_timer_init(void *arg)
1060 {
1061
1062         /*
1063          * Compute an internal HZ value which can divide 2**32 to
1064          * avoid timer rounding problems when the tick value wraps
1065          * around 2**32:
1066          */
1067         linux_timer_hz_mask = 1;
1068         while (linux_timer_hz_mask < (unsigned long)hz)
1069                 linux_timer_hz_mask *= 2;
1070         linux_timer_hz_mask--;
1071 }
1072 SYSINIT(linux_timer, SI_SUB_DRIVERS, SI_ORDER_FIRST, linux_timer_init, NULL);
1073
1074 void
1075 linux_complete_common(struct completion *c, int all)
1076 {
1077         int wakeup_swapper;
1078
1079         sleepq_lock(c);
1080         c->done++;
1081         if (all)
1082                 wakeup_swapper = sleepq_broadcast(c, SLEEPQ_SLEEP, 0, 0);
1083         else
1084                 wakeup_swapper = sleepq_signal(c, SLEEPQ_SLEEP, 0, 0);
1085         sleepq_release(c);
1086         if (wakeup_swapper)
1087                 kick_proc0();
1088 }
1089
1090 /*
1091  * Indefinite wait for done != 0 with or without signals.
1092  */
1093 long
1094 linux_wait_for_common(struct completion *c, int flags)
1095 {
1096
1097         if (flags != 0)
1098                 flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
1099         else
1100                 flags = SLEEPQ_SLEEP;
1101         for (;;) {
1102                 sleepq_lock(c);
1103                 if (c->done)
1104                         break;
1105                 sleepq_add(c, NULL, "completion", flags, 0);
1106                 if (flags & SLEEPQ_INTERRUPTIBLE) {
1107                         if (sleepq_wait_sig(c, 0) != 0)
1108                                 return (-ERESTARTSYS);
1109                 } else
1110                         sleepq_wait(c, 0);
1111         }
1112         c->done--;
1113         sleepq_release(c);
1114
1115         return (0);
1116 }
1117
1118 /*
1119  * Time limited wait for done != 0 with or without signals.
1120  */
1121 long
1122 linux_wait_for_timeout_common(struct completion *c, long timeout, int flags)
1123 {
1124         long end = jiffies + timeout;
1125
1126         if (flags != 0)
1127                 flags = SLEEPQ_INTERRUPTIBLE | SLEEPQ_SLEEP;
1128         else
1129                 flags = SLEEPQ_SLEEP;
1130         for (;;) {
1131                 int ret;
1132
1133                 sleepq_lock(c);
1134                 if (c->done)
1135                         break;
1136                 sleepq_add(c, NULL, "completion", flags, 0);
1137                 sleepq_set_timeout(c, linux_timer_jiffies_until(end));
1138                 if (flags & SLEEPQ_INTERRUPTIBLE)
1139                         ret = sleepq_timedwait_sig(c, 0);
1140                 else
1141                         ret = sleepq_timedwait(c, 0);
1142                 if (ret != 0) {
1143                         /* check for timeout or signal */
1144                         if (ret == EWOULDBLOCK)
1145                                 return (0);
1146                         else
1147                                 return (-ERESTARTSYS);
1148                 }
1149         }
1150         c->done--;
1151         sleepq_release(c);
1152
1153         /* return how many jiffies are left */
1154         return (linux_timer_jiffies_until(end));
1155 }
1156
1157 int
1158 linux_try_wait_for_completion(struct completion *c)
1159 {
1160         int isdone;
1161
1162         isdone = 1;
1163         sleepq_lock(c);
1164         if (c->done)
1165                 c->done--;
1166         else
1167                 isdone = 0;
1168         sleepq_release(c);
1169         return (isdone);
1170 }
1171
1172 int
1173 linux_completion_done(struct completion *c)
1174 {
1175         int isdone;
1176
1177         isdone = 1;
1178         sleepq_lock(c);
1179         if (c->done == 0)
1180                 isdone = 0;
1181         sleepq_release(c);
1182         return (isdone);
1183 }
1184
1185 void
1186 linux_delayed_work_fn(void *arg)
1187 {
1188         struct delayed_work *work;
1189
1190         work = arg;
1191         taskqueue_enqueue(work->work.taskqueue, &work->work.work_task);
1192 }
1193
1194 void
1195 linux_work_fn(void *context, int pending)
1196 {
1197         struct work_struct *work;
1198
1199         work = context;
1200         work->fn(work);
1201 }
1202
1203 void
1204 linux_flush_fn(void *context, int pending)
1205 {
1206 }
1207
1208 struct workqueue_struct *
1209 linux_create_workqueue_common(const char *name, int cpus)
1210 {
1211         struct workqueue_struct *wq;
1212
1213         wq = kmalloc(sizeof(*wq), M_WAITOK);
1214         wq->taskqueue = taskqueue_create(name, M_WAITOK,
1215             taskqueue_thread_enqueue,  &wq->taskqueue);
1216         atomic_set(&wq->draining, 0);
1217         taskqueue_start_threads(&wq->taskqueue, cpus, PWAIT, "%s", name);
1218
1219         return (wq);
1220 }
1221
1222 void
1223 destroy_workqueue(struct workqueue_struct *wq)
1224 {
1225         taskqueue_free(wq->taskqueue);
1226         kfree(wq);
1227 }
1228
1229 static void
1230 linux_cdev_release(struct kobject *kobj)
1231 {
1232         struct linux_cdev *cdev;
1233         struct kobject *parent;
1234
1235         cdev = container_of(kobj, struct linux_cdev, kobj);
1236         parent = kobj->parent;
1237         if (cdev->cdev)
1238                 destroy_dev(cdev->cdev);
1239         kfree(cdev);
1240         kobject_put(parent);
1241 }
1242
1243 static void
1244 linux_cdev_static_release(struct kobject *kobj)
1245 {
1246         struct linux_cdev *cdev;
1247         struct kobject *parent;
1248
1249         cdev = container_of(kobj, struct linux_cdev, kobj);
1250         parent = kobj->parent;
1251         if (cdev->cdev)
1252                 destroy_dev(cdev->cdev);
1253         kobject_put(parent);
1254 }
1255
1256 const struct kobj_type linux_cdev_ktype = {
1257         .release = linux_cdev_release,
1258 };
1259
1260 const struct kobj_type linux_cdev_static_ktype = {
1261         .release = linux_cdev_static_release,
1262 };
1263
1264 static void
1265 linux_handle_ifnet_link_event(void *arg, struct ifnet *ifp, int linkstate)
1266 {
1267         struct notifier_block *nb;
1268
1269         nb = arg;
1270         if (linkstate == LINK_STATE_UP)
1271                 nb->notifier_call(nb, NETDEV_UP, ifp);
1272         else
1273                 nb->notifier_call(nb, NETDEV_DOWN, ifp);
1274 }
1275
1276 static void
1277 linux_handle_ifnet_arrival_event(void *arg, struct ifnet *ifp)
1278 {
1279         struct notifier_block *nb;
1280
1281         nb = arg;
1282         nb->notifier_call(nb, NETDEV_REGISTER, ifp);
1283 }
1284
1285 static void
1286 linux_handle_ifnet_departure_event(void *arg, struct ifnet *ifp)
1287 {
1288         struct notifier_block *nb;
1289
1290         nb = arg;
1291         nb->notifier_call(nb, NETDEV_UNREGISTER, ifp);
1292 }
1293
1294 static void
1295 linux_handle_iflladdr_event(void *arg, struct ifnet *ifp)
1296 {
1297         struct notifier_block *nb;
1298
1299         nb = arg;
1300         nb->notifier_call(nb, NETDEV_CHANGEADDR, ifp);
1301 }
1302
1303 static void
1304 linux_handle_ifaddr_event(void *arg, struct ifnet *ifp)
1305 {
1306         struct notifier_block *nb;
1307
1308         nb = arg;
1309         nb->notifier_call(nb, NETDEV_CHANGEIFADDR, ifp);
1310 }
1311
1312 int
1313 register_netdevice_notifier(struct notifier_block *nb)
1314 {
1315
1316         nb->tags[NETDEV_UP] = EVENTHANDLER_REGISTER(
1317             ifnet_link_event, linux_handle_ifnet_link_event, nb, 0);
1318         nb->tags[NETDEV_REGISTER] = EVENTHANDLER_REGISTER(
1319             ifnet_arrival_event, linux_handle_ifnet_arrival_event, nb, 0);
1320         nb->tags[NETDEV_UNREGISTER] = EVENTHANDLER_REGISTER(
1321             ifnet_departure_event, linux_handle_ifnet_departure_event, nb, 0);
1322         nb->tags[NETDEV_CHANGEADDR] = EVENTHANDLER_REGISTER(
1323             iflladdr_event, linux_handle_iflladdr_event, nb, 0);
1324
1325         return (0);
1326 }
1327
1328 int
1329 register_inetaddr_notifier(struct notifier_block *nb)
1330 {
1331
1332         nb->tags[NETDEV_CHANGEIFADDR] = EVENTHANDLER_REGISTER(
1333             ifaddr_event, linux_handle_ifaddr_event, nb, 0);
1334         return (0);
1335 }
1336
1337 int
1338 unregister_netdevice_notifier(struct notifier_block *nb)
1339 {
1340
1341         EVENTHANDLER_DEREGISTER(ifnet_link_event,
1342             nb->tags[NETDEV_UP]);
1343         EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
1344             nb->tags[NETDEV_REGISTER]);
1345         EVENTHANDLER_DEREGISTER(ifnet_departure_event,
1346             nb->tags[NETDEV_UNREGISTER]);
1347         EVENTHANDLER_DEREGISTER(iflladdr_event,
1348             nb->tags[NETDEV_CHANGEADDR]);
1349
1350         return (0);
1351 }
1352
1353 int
1354 unregister_inetaddr_notifier(struct notifier_block *nb)
1355 {
1356
1357         EVENTHANDLER_DEREGISTER(ifaddr_event,
1358             nb->tags[NETDEV_CHANGEIFADDR]);
1359
1360         return (0);
1361 }
1362
1363 struct list_sort_thunk {
1364         int (*cmp)(void *, struct list_head *, struct list_head *);
1365         void *priv;
1366 };
1367
1368 static inline int
1369 linux_le_cmp(void *priv, const void *d1, const void *d2)
1370 {
1371         struct list_head *le1, *le2;
1372         struct list_sort_thunk *thunk;
1373
1374         thunk = priv;
1375         le1 = *(__DECONST(struct list_head **, d1));
1376         le2 = *(__DECONST(struct list_head **, d2));
1377         return ((thunk->cmp)(thunk->priv, le1, le2));
1378 }
1379
1380 void
1381 list_sort(void *priv, struct list_head *head, int (*cmp)(void *priv,
1382     struct list_head *a, struct list_head *b))
1383 {
1384         struct list_sort_thunk thunk;
1385         struct list_head **ar, *le;
1386         size_t count, i;
1387
1388         count = 0;
1389         list_for_each(le, head)
1390                 count++;
1391         ar = malloc(sizeof(struct list_head *) * count, M_KMALLOC, M_WAITOK);
1392         i = 0;
1393         list_for_each(le, head)
1394                 ar[i++] = le;
1395         thunk.cmp = cmp;
1396         thunk.priv = priv;
1397         qsort_r(ar, count, sizeof(struct list_head *), &thunk, linux_le_cmp);
1398         INIT_LIST_HEAD(head);
1399         for (i = 0; i < count; i++)
1400                 list_add_tail(ar[i], head);
1401         free(ar, M_KMALLOC);
1402 }
1403
1404 void
1405 linux_irq_handler(void *ent)
1406 {
1407         struct irq_ent *irqe;
1408
1409         irqe = ent;
1410         irqe->handler(irqe->irq, irqe->arg);
1411 }
1412
1413 #if defined(__i386__) || defined(__amd64__)
1414 bool linux_cpu_has_clflush;
1415 #endif
1416
1417 static void
1418 linux_compat_init(void *arg)
1419 {
1420         struct sysctl_oid *rootoid;
1421         int i;
1422
1423 #if defined(__i386__) || defined(__amd64__)
1424         linux_cpu_has_clflush = (cpu_feature & CPUID_CLFSH);
1425 #endif
1426         sx_init(&linux_global_rcu_lock, "LinuxGlobalRCU");
1427
1428         rootoid = SYSCTL_ADD_ROOT_NODE(NULL,
1429             OID_AUTO, "sys", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "sys");
1430         kobject_init(&linux_class_root, &linux_class_ktype);
1431         kobject_set_name(&linux_class_root, "class");
1432         linux_class_root.oidp = SYSCTL_ADD_NODE(NULL, SYSCTL_CHILDREN(rootoid),
1433             OID_AUTO, "class", CTLFLAG_RD|CTLFLAG_MPSAFE, NULL, "class");
1434         kobject_init(&linux_root_device.kobj, &linux_dev_ktype);
1435         kobject_set_name(&linux_root_device.kobj, "device");
1436         linux_root_device.kobj.oidp = SYSCTL_ADD_NODE(NULL,
1437             SYSCTL_CHILDREN(rootoid), OID_AUTO, "device", CTLFLAG_RD, NULL,
1438             "device");
1439         linux_root_device.bsddev = root_bus;
1440         linux_class_misc.name = "misc";
1441         class_register(&linux_class_misc);
1442         INIT_LIST_HEAD(&pci_drivers);
1443         INIT_LIST_HEAD(&pci_devices);
1444         spin_lock_init(&pci_lock);
1445         mtx_init(&vmmaplock, "IO Map lock", NULL, MTX_DEF);
1446         for (i = 0; i < VMMAP_HASH_SIZE; i++)
1447                 LIST_INIT(&vmmaphead[i]);
1448 }
1449 SYSINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_init, NULL);
1450
1451 static void
1452 linux_compat_uninit(void *arg)
1453 {
1454         linux_kobject_kfree_name(&linux_class_root);
1455         linux_kobject_kfree_name(&linux_root_device.kobj);
1456         linux_kobject_kfree_name(&linux_class_misc.kobj);
1457
1458         synchronize_rcu();
1459         sx_destroy(&linux_global_rcu_lock);
1460 }
1461 SYSUNINIT(linux_compat, SI_SUB_DRIVERS, SI_ORDER_SECOND, linux_compat_uninit, NULL);
1462
1463 /*
1464  * NOTE: Linux frequently uses "unsigned long" for pointer to integer
1465  * conversion and vice versa, where in FreeBSD "uintptr_t" would be
1466  * used. Assert these types have the same size, else some parts of the
1467  * LinuxKPI may not work like expected:
1468  */
1469 CTASSERT(sizeof(unsigned long) == sizeof(uintptr_t));