]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - lib/libvmmapi/vmmapi.c
libvmmapi: Split the ioctl list into MI and MD lists
[FreeBSD/FreeBSD.git] / lib / libvmmapi / vmmapi.c
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 NetApp, Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY NETAPP, INC ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL NETAPP, INC OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/param.h>
30 #include <sys/capsicum.h>
31 #include <sys/sysctl.h>
32 #include <sys/ioctl.h>
33 #include <sys/mman.h>
34 #include <sys/linker.h>
35 #include <sys/module.h>
36 #include <sys/_iovec.h>
37 #include <sys/cpuset.h>
38
39 #include <capsicum_helpers.h>
40 #include <errno.h>
41 #include <stdbool.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <assert.h>
45 #include <string.h>
46 #include <fcntl.h>
47 #include <unistd.h>
48
49 #include <libutil.h>
50
51 #include <vm/vm.h>
52 #include <machine/vmm.h>
53 #include <machine/vmm_dev.h>
54 #include <machine/vmm_snapshot.h>
55
56 #include "vmmapi.h"
57 #include "internal.h"
58
59 #define MB      (1024 * 1024UL)
60 #define GB      (1024 * 1024 * 1024UL)
61
62 /*
63  * Size of the guard region before and after the virtual address space
64  * mapping the guest physical memory. This must be a multiple of the
65  * superpage size for performance reasons.
66  */
67 #define VM_MMAP_GUARD_SIZE      (4 * MB)
68
69 #define PROT_RW         (PROT_READ | PROT_WRITE)
70 #define PROT_ALL        (PROT_READ | PROT_WRITE | PROT_EXEC)
71
72 #define CREATE(x)  sysctlbyname("hw.vmm.create", NULL, NULL, (x), strlen((x)))
73 #define DESTROY(x) sysctlbyname("hw.vmm.destroy", NULL, NULL, (x), strlen((x)))
74
75 static int
76 vm_device_open(const char *name)
77 {
78         int fd, len;
79         char *vmfile;
80
81         len = strlen("/dev/vmm/") + strlen(name) + 1;
82         vmfile = malloc(len);
83         assert(vmfile != NULL);
84         snprintf(vmfile, len, "/dev/vmm/%s", name);
85
86         /* Open the device file */
87         fd = open(vmfile, O_RDWR, 0);
88
89         free(vmfile);
90         return (fd);
91 }
92
93 int
94 vm_create(const char *name)
95 {
96         /* Try to load vmm(4) module before creating a guest. */
97         if (modfind("vmm") < 0)
98                 kldload("vmm");
99         return (CREATE(name));
100 }
101
102 struct vmctx *
103 vm_open(const char *name)
104 {
105         struct vmctx *vm;
106         int saved_errno;
107
108         vm = malloc(sizeof(struct vmctx) + strlen(name) + 1);
109         assert(vm != NULL);
110
111         vm->fd = -1;
112         vm->memflags = 0;
113         vm->lowmem_limit = 3 * GB;
114         vm->name = (char *)(vm + 1);
115         strcpy(vm->name, name);
116
117         if ((vm->fd = vm_device_open(vm->name)) < 0)
118                 goto err;
119
120         return (vm);
121 err:
122         saved_errno = errno;
123         free(vm);
124         errno = saved_errno;
125         return (NULL);
126 }
127
128 void
129 vm_close(struct vmctx *vm)
130 {
131         assert(vm != NULL);
132
133         close(vm->fd);
134         free(vm);
135 }
136
137 void
138 vm_destroy(struct vmctx *vm)
139 {
140         assert(vm != NULL);
141
142         if (vm->fd >= 0)
143                 close(vm->fd);
144         DESTROY(vm->name);
145
146         free(vm);
147 }
148
149 struct vcpu *
150 vm_vcpu_open(struct vmctx *ctx, int vcpuid)
151 {
152         struct vcpu *vcpu;
153
154         vcpu = malloc(sizeof(*vcpu));
155         vcpu->ctx = ctx;
156         vcpu->vcpuid = vcpuid;
157         return (vcpu);
158 }
159
160 void
161 vm_vcpu_close(struct vcpu *vcpu)
162 {
163         free(vcpu);
164 }
165
166 int
167 vcpu_id(struct vcpu *vcpu)
168 {
169         return (vcpu->vcpuid);
170 }
171
172 int
173 vm_parse_memsize(const char *opt, size_t *ret_memsize)
174 {
175         char *endptr;
176         size_t optval;
177         int error;
178
179         optval = strtoul(opt, &endptr, 0);
180         if (*opt != '\0' && *endptr == '\0') {
181                 /*
182                  * For the sake of backward compatibility if the memory size
183                  * specified on the command line is less than a megabyte then
184                  * it is interpreted as being in units of MB.
185                  */
186                 if (optval < MB)
187                         optval *= MB;
188                 *ret_memsize = optval;
189                 error = 0;
190         } else
191                 error = expand_number(opt, ret_memsize);
192
193         return (error);
194 }
195
196 uint32_t
197 vm_get_lowmem_limit(struct vmctx *ctx)
198 {
199
200         return (ctx->lowmem_limit);
201 }
202
203 void
204 vm_set_lowmem_limit(struct vmctx *ctx, uint32_t limit)
205 {
206
207         ctx->lowmem_limit = limit;
208 }
209
210 void
211 vm_set_memflags(struct vmctx *ctx, int flags)
212 {
213
214         ctx->memflags = flags;
215 }
216
217 int
218 vm_get_memflags(struct vmctx *ctx)
219 {
220
221         return (ctx->memflags);
222 }
223
224 /*
225  * Map segment 'segid' starting at 'off' into guest address range [gpa,gpa+len).
226  */
227 int
228 vm_mmap_memseg(struct vmctx *ctx, vm_paddr_t gpa, int segid, vm_ooffset_t off,
229     size_t len, int prot)
230 {
231         struct vm_memmap memmap;
232         int error, flags;
233
234         memmap.gpa = gpa;
235         memmap.segid = segid;
236         memmap.segoff = off;
237         memmap.len = len;
238         memmap.prot = prot;
239         memmap.flags = 0;
240
241         if (ctx->memflags & VM_MEM_F_WIRED)
242                 memmap.flags |= VM_MEMMAP_F_WIRED;
243
244         /*
245          * If this mapping already exists then don't create it again. This
246          * is the common case for SYSMEM mappings created by bhyveload(8).
247          */
248         error = vm_mmap_getnext(ctx, &gpa, &segid, &off, &len, &prot, &flags);
249         if (error == 0 && gpa == memmap.gpa) {
250                 if (segid != memmap.segid || off != memmap.segoff ||
251                     prot != memmap.prot || flags != memmap.flags) {
252                         errno = EEXIST;
253                         return (-1);
254                 } else {
255                         return (0);
256                 }
257         }
258
259         error = ioctl(ctx->fd, VM_MMAP_MEMSEG, &memmap);
260         return (error);
261 }
262
263 int
264 vm_get_guestmem_from_ctx(struct vmctx *ctx, char **guest_baseaddr,
265     size_t *lowmem_size, size_t *highmem_size)
266 {
267
268         *guest_baseaddr = ctx->baseaddr;
269         *lowmem_size = ctx->lowmem;
270         *highmem_size = ctx->highmem;
271         return (0);
272 }
273
274 int
275 vm_munmap_memseg(struct vmctx *ctx, vm_paddr_t gpa, size_t len)
276 {
277         struct vm_munmap munmap;
278         int error;
279
280         munmap.gpa = gpa;
281         munmap.len = len;
282
283         error = ioctl(ctx->fd, VM_MUNMAP_MEMSEG, &munmap);
284         return (error);
285 }
286
287 int
288 vm_mmap_getnext(struct vmctx *ctx, vm_paddr_t *gpa, int *segid,
289     vm_ooffset_t *segoff, size_t *len, int *prot, int *flags)
290 {
291         struct vm_memmap memmap;
292         int error;
293
294         bzero(&memmap, sizeof(struct vm_memmap));
295         memmap.gpa = *gpa;
296         error = ioctl(ctx->fd, VM_MMAP_GETNEXT, &memmap);
297         if (error == 0) {
298                 *gpa = memmap.gpa;
299                 *segid = memmap.segid;
300                 *segoff = memmap.segoff;
301                 *len = memmap.len;
302                 *prot = memmap.prot;
303                 *flags = memmap.flags;
304         }
305         return (error);
306 }
307
308 /*
309  * Return 0 if the segments are identical and non-zero otherwise.
310  *
311  * This is slightly complicated by the fact that only device memory segments
312  * are named.
313  */
314 static int
315 cmpseg(size_t len, const char *str, size_t len2, const char *str2)
316 {
317
318         if (len == len2) {
319                 if ((!str && !str2) || (str && str2 && !strcmp(str, str2)))
320                         return (0);
321         }
322         return (-1);
323 }
324
325 static int
326 vm_alloc_memseg(struct vmctx *ctx, int segid, size_t len, const char *name)
327 {
328         struct vm_memseg memseg;
329         size_t n;
330         int error;
331
332         /*
333          * If the memory segment has already been created then just return.
334          * This is the usual case for the SYSMEM segment created by userspace
335          * loaders like bhyveload(8).
336          */
337         error = vm_get_memseg(ctx, segid, &memseg.len, memseg.name,
338             sizeof(memseg.name));
339         if (error)
340                 return (error);
341
342         if (memseg.len != 0) {
343                 if (cmpseg(len, name, memseg.len, VM_MEMSEG_NAME(&memseg))) {
344                         errno = EINVAL;
345                         return (-1);
346                 } else {
347                         return (0);
348                 }
349         }
350
351         bzero(&memseg, sizeof(struct vm_memseg));
352         memseg.segid = segid;
353         memseg.len = len;
354         if (name != NULL) {
355                 n = strlcpy(memseg.name, name, sizeof(memseg.name));
356                 if (n >= sizeof(memseg.name)) {
357                         errno = ENAMETOOLONG;
358                         return (-1);
359                 }
360         }
361
362         error = ioctl(ctx->fd, VM_ALLOC_MEMSEG, &memseg);
363         return (error);
364 }
365
366 int
367 vm_get_memseg(struct vmctx *ctx, int segid, size_t *lenp, char *namebuf,
368     size_t bufsize)
369 {
370         struct vm_memseg memseg;
371         size_t n;
372         int error;
373
374         memseg.segid = segid;
375         error = ioctl(ctx->fd, VM_GET_MEMSEG, &memseg);
376         if (error == 0) {
377                 *lenp = memseg.len;
378                 n = strlcpy(namebuf, memseg.name, bufsize);
379                 if (n >= bufsize) {
380                         errno = ENAMETOOLONG;
381                         error = -1;
382                 }
383         }
384         return (error);
385 }
386
387 static int
388 setup_memory_segment(struct vmctx *ctx, vm_paddr_t gpa, size_t len, char *base)
389 {
390         char *ptr;
391         int error, flags;
392
393         /* Map 'len' bytes starting at 'gpa' in the guest address space */
394         error = vm_mmap_memseg(ctx, gpa, VM_SYSMEM, gpa, len, PROT_ALL);
395         if (error)
396                 return (error);
397
398         flags = MAP_SHARED | MAP_FIXED;
399         if ((ctx->memflags & VM_MEM_F_INCORE) == 0)
400                 flags |= MAP_NOCORE;
401
402         /* mmap into the process address space on the host */
403         ptr = mmap(base + gpa, len, PROT_RW, flags, ctx->fd, gpa);
404         if (ptr == MAP_FAILED)
405                 return (-1);
406
407         return (0);
408 }
409
410 int
411 vm_setup_memory(struct vmctx *ctx, size_t memsize, enum vm_mmap_style vms)
412 {
413         size_t objsize, len;
414         vm_paddr_t gpa;
415         char *baseaddr, *ptr;
416         int error;
417
418         assert(vms == VM_MMAP_ALL);
419
420         /*
421          * If 'memsize' cannot fit entirely in the 'lowmem' segment then
422          * create another 'highmem' segment above 4GB for the remainder.
423          */
424         if (memsize > ctx->lowmem_limit) {
425                 ctx->lowmem = ctx->lowmem_limit;
426                 ctx->highmem = memsize - ctx->lowmem_limit;
427                 objsize = 4*GB + ctx->highmem;
428         } else {
429                 ctx->lowmem = memsize;
430                 ctx->highmem = 0;
431                 objsize = ctx->lowmem;
432         }
433
434         error = vm_alloc_memseg(ctx, VM_SYSMEM, objsize, NULL);
435         if (error)
436                 return (error);
437
438         /*
439          * Stake out a contiguous region covering the guest physical memory
440          * and the adjoining guard regions.
441          */
442         len = VM_MMAP_GUARD_SIZE + objsize + VM_MMAP_GUARD_SIZE;
443         ptr = mmap(NULL, len, PROT_NONE, MAP_GUARD | MAP_ALIGNED_SUPER, -1, 0);
444         if (ptr == MAP_FAILED)
445                 return (-1);
446
447         baseaddr = ptr + VM_MMAP_GUARD_SIZE;
448         if (ctx->highmem > 0) {
449                 gpa = 4*GB;
450                 len = ctx->highmem;
451                 error = setup_memory_segment(ctx, gpa, len, baseaddr);
452                 if (error)
453                         return (error);
454         }
455
456         if (ctx->lowmem > 0) {
457                 gpa = 0;
458                 len = ctx->lowmem;
459                 error = setup_memory_segment(ctx, gpa, len, baseaddr);
460                 if (error)
461                         return (error);
462         }
463
464         ctx->baseaddr = baseaddr;
465
466         return (0);
467 }
468
469 /*
470  * Returns a non-NULL pointer if [gaddr, gaddr+len) is entirely contained in
471  * the lowmem or highmem regions.
472  *
473  * In particular return NULL if [gaddr, gaddr+len) falls in guest MMIO region.
474  * The instruction emulation code depends on this behavior.
475  */
476 void *
477 vm_map_gpa(struct vmctx *ctx, vm_paddr_t gaddr, size_t len)
478 {
479
480         if (ctx->lowmem > 0) {
481                 if (gaddr < ctx->lowmem && len <= ctx->lowmem &&
482                     gaddr + len <= ctx->lowmem)
483                         return (ctx->baseaddr + gaddr);
484         }
485
486         if (ctx->highmem > 0) {
487                 if (gaddr >= 4*GB) {
488                         if (gaddr < 4*GB + ctx->highmem &&
489                             len <= ctx->highmem &&
490                             gaddr + len <= 4*GB + ctx->highmem)
491                                 return (ctx->baseaddr + gaddr);
492                 }
493         }
494
495         return (NULL);
496 }
497
498 vm_paddr_t
499 vm_rev_map_gpa(struct vmctx *ctx, void *addr)
500 {
501         vm_paddr_t offaddr;
502
503         offaddr = (char *)addr - ctx->baseaddr;
504
505         if (ctx->lowmem > 0)
506                 if (offaddr <= ctx->lowmem)
507                         return (offaddr);
508
509         if (ctx->highmem > 0)
510                 if (offaddr >= 4*GB && offaddr < 4*GB + ctx->highmem)
511                         return (offaddr);
512
513         return ((vm_paddr_t)-1);
514 }
515
516 const char *
517 vm_get_name(struct vmctx *ctx)
518 {
519
520         return (ctx->name);
521 }
522
523 size_t
524 vm_get_lowmem_size(struct vmctx *ctx)
525 {
526
527         return (ctx->lowmem);
528 }
529
530 size_t
531 vm_get_highmem_size(struct vmctx *ctx)
532 {
533
534         return (ctx->highmem);
535 }
536
537 void *
538 vm_create_devmem(struct vmctx *ctx, int segid, const char *name, size_t len)
539 {
540         char pathname[MAXPATHLEN];
541         size_t len2;
542         char *base, *ptr;
543         int fd, error, flags;
544
545         fd = -1;
546         ptr = MAP_FAILED;
547         if (name == NULL || strlen(name) == 0) {
548                 errno = EINVAL;
549                 goto done;
550         }
551
552         error = vm_alloc_memseg(ctx, segid, len, name);
553         if (error)
554                 goto done;
555
556         strlcpy(pathname, "/dev/vmm.io/", sizeof(pathname));
557         strlcat(pathname, ctx->name, sizeof(pathname));
558         strlcat(pathname, ".", sizeof(pathname));
559         strlcat(pathname, name, sizeof(pathname));
560
561         fd = open(pathname, O_RDWR);
562         if (fd < 0)
563                 goto done;
564
565         /*
566          * Stake out a contiguous region covering the device memory and the
567          * adjoining guard regions.
568          */
569         len2 = VM_MMAP_GUARD_SIZE + len + VM_MMAP_GUARD_SIZE;
570         base = mmap(NULL, len2, PROT_NONE, MAP_GUARD | MAP_ALIGNED_SUPER, -1,
571             0);
572         if (base == MAP_FAILED)
573                 goto done;
574
575         flags = MAP_SHARED | MAP_FIXED;
576         if ((ctx->memflags & VM_MEM_F_INCORE) == 0)
577                 flags |= MAP_NOCORE;
578
579         /* mmap the devmem region in the host address space */
580         ptr = mmap(base + VM_MMAP_GUARD_SIZE, len, PROT_RW, flags, fd, 0);
581 done:
582         if (fd >= 0)
583                 close(fd);
584         return (ptr);
585 }
586
587 int
588 vcpu_ioctl(struct vcpu *vcpu, u_long cmd, void *arg)
589 {
590         /*
591          * XXX: fragile, handle with care
592          * Assumes that the first field of the ioctl data
593          * is the vcpuid.
594          */
595         *(int *)arg = vcpu->vcpuid;
596         return (ioctl(vcpu->ctx->fd, cmd, arg));
597 }
598
599 int
600 vm_set_register(struct vcpu *vcpu, int reg, uint64_t val)
601 {
602         int error;
603         struct vm_register vmreg;
604
605         bzero(&vmreg, sizeof(vmreg));
606         vmreg.regnum = reg;
607         vmreg.regval = val;
608
609         error = vcpu_ioctl(vcpu, VM_SET_REGISTER, &vmreg);
610         return (error);
611 }
612
613 int
614 vm_get_register(struct vcpu *vcpu, int reg, uint64_t *ret_val)
615 {
616         int error;
617         struct vm_register vmreg;
618
619         bzero(&vmreg, sizeof(vmreg));
620         vmreg.regnum = reg;
621
622         error = vcpu_ioctl(vcpu, VM_GET_REGISTER, &vmreg);
623         *ret_val = vmreg.regval;
624         return (error);
625 }
626
627 int
628 vm_set_register_set(struct vcpu *vcpu, unsigned int count,
629     const int *regnums, uint64_t *regvals)
630 {
631         int error;
632         struct vm_register_set vmregset;
633
634         bzero(&vmregset, sizeof(vmregset));
635         vmregset.count = count;
636         vmregset.regnums = regnums;
637         vmregset.regvals = regvals;
638
639         error = vcpu_ioctl(vcpu, VM_SET_REGISTER_SET, &vmregset);
640         return (error);
641 }
642
643 int
644 vm_get_register_set(struct vcpu *vcpu, unsigned int count,
645     const int *regnums, uint64_t *regvals)
646 {
647         int error;
648         struct vm_register_set vmregset;
649
650         bzero(&vmregset, sizeof(vmregset));
651         vmregset.count = count;
652         vmregset.regnums = regnums;
653         vmregset.regvals = regvals;
654
655         error = vcpu_ioctl(vcpu, VM_GET_REGISTER_SET, &vmregset);
656         return (error);
657 }
658
659 int
660 vm_run(struct vcpu *vcpu, struct vm_run *vmrun)
661 {
662         return (vcpu_ioctl(vcpu, VM_RUN, vmrun));
663 }
664
665 int
666 vm_suspend(struct vmctx *ctx, enum vm_suspend_how how)
667 {
668         struct vm_suspend vmsuspend;
669
670         bzero(&vmsuspend, sizeof(vmsuspend));
671         vmsuspend.how = how;
672         return (ioctl(ctx->fd, VM_SUSPEND, &vmsuspend));
673 }
674
675 int
676 vm_reinit(struct vmctx *ctx)
677 {
678
679         return (ioctl(ctx->fd, VM_REINIT, 0));
680 }
681
682 int
683 vm_inject_exception(struct vcpu *vcpu, int vector, int errcode_valid,
684     uint32_t errcode, int restart_instruction)
685 {
686         struct vm_exception exc;
687
688         exc.vector = vector;
689         exc.error_code = errcode;
690         exc.error_code_valid = errcode_valid;
691         exc.restart_instruction = restart_instruction;
692
693         return (vcpu_ioctl(vcpu, VM_INJECT_EXCEPTION, &exc));
694 }
695
696 int
697 vm_readwrite_kernemu_device(struct vcpu *vcpu, vm_paddr_t gpa,
698     bool write, int size, uint64_t *value)
699 {
700         struct vm_readwrite_kernemu_device irp = {
701                 .access_width = fls(size) - 1,
702                 .gpa = gpa,
703                 .value = write ? *value : ~0ul,
704         };
705         long cmd = (write ? VM_SET_KERNEMU_DEV : VM_GET_KERNEMU_DEV);
706         int rc;
707
708         rc = vcpu_ioctl(vcpu, cmd, &irp);
709         if (rc == 0 && !write)
710                 *value = irp.value;
711         return (rc);
712 }
713
714 int
715 vm_capability_name2type(const char *capname)
716 {
717         int i;
718
719         for (i = 0; i < VM_CAP_MAX; i++) {
720                 if (vm_capstrmap[i] != NULL &&
721                     strcmp(vm_capstrmap[i], capname) == 0)
722                         return (i);
723         }
724
725         return (-1);
726 }
727
728 const char *
729 vm_capability_type2name(int type)
730 {
731         if (type >= 0 && type < VM_CAP_MAX)
732                 return (vm_capstrmap[type]);
733
734         return (NULL);
735 }
736
737 int
738 vm_get_capability(struct vcpu *vcpu, enum vm_cap_type cap, int *retval)
739 {
740         int error;
741         struct vm_capability vmcap;
742
743         bzero(&vmcap, sizeof(vmcap));
744         vmcap.captype = cap;
745
746         error = vcpu_ioctl(vcpu, VM_GET_CAPABILITY, &vmcap);
747         *retval = vmcap.capval;
748         return (error);
749 }
750
751 int
752 vm_set_capability(struct vcpu *vcpu, enum vm_cap_type cap, int val)
753 {
754         struct vm_capability vmcap;
755
756         bzero(&vmcap, sizeof(vmcap));
757         vmcap.captype = cap;
758         vmcap.capval = val;
759
760         return (vcpu_ioctl(vcpu, VM_SET_CAPABILITY, &vmcap));
761 }
762
763 int
764 vm_assign_pptdev(struct vmctx *ctx, int bus, int slot, int func)
765 {
766         struct vm_pptdev pptdev;
767
768         bzero(&pptdev, sizeof(pptdev));
769         pptdev.bus = bus;
770         pptdev.slot = slot;
771         pptdev.func = func;
772
773         return (ioctl(ctx->fd, VM_BIND_PPTDEV, &pptdev));
774 }
775
776 int
777 vm_unassign_pptdev(struct vmctx *ctx, int bus, int slot, int func)
778 {
779         struct vm_pptdev pptdev;
780
781         bzero(&pptdev, sizeof(pptdev));
782         pptdev.bus = bus;
783         pptdev.slot = slot;
784         pptdev.func = func;
785
786         return (ioctl(ctx->fd, VM_UNBIND_PPTDEV, &pptdev));
787 }
788
789 int
790 vm_map_pptdev_mmio(struct vmctx *ctx, int bus, int slot, int func,
791                    vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
792 {
793         struct vm_pptdev_mmio pptmmio;
794
795         bzero(&pptmmio, sizeof(pptmmio));
796         pptmmio.bus = bus;
797         pptmmio.slot = slot;
798         pptmmio.func = func;
799         pptmmio.gpa = gpa;
800         pptmmio.len = len;
801         pptmmio.hpa = hpa;
802
803         return (ioctl(ctx->fd, VM_MAP_PPTDEV_MMIO, &pptmmio));
804 }
805
806 int
807 vm_unmap_pptdev_mmio(struct vmctx *ctx, int bus, int slot, int func,
808                      vm_paddr_t gpa, size_t len)
809 {
810         struct vm_pptdev_mmio pptmmio;
811
812         bzero(&pptmmio, sizeof(pptmmio));
813         pptmmio.bus = bus;
814         pptmmio.slot = slot;
815         pptmmio.func = func;
816         pptmmio.gpa = gpa;
817         pptmmio.len = len;
818
819         return (ioctl(ctx->fd, VM_UNMAP_PPTDEV_MMIO, &pptmmio));
820 }
821
822 int
823 vm_setup_pptdev_msi(struct vmctx *ctx, int bus, int slot, int func,
824     uint64_t addr, uint64_t msg, int numvec)
825 {
826         struct vm_pptdev_msi pptmsi;
827
828         bzero(&pptmsi, sizeof(pptmsi));
829         pptmsi.bus = bus;
830         pptmsi.slot = slot;
831         pptmsi.func = func;
832         pptmsi.msg = msg;
833         pptmsi.addr = addr;
834         pptmsi.numvec = numvec;
835
836         return (ioctl(ctx->fd, VM_PPTDEV_MSI, &pptmsi));
837 }
838
839 int     
840 vm_setup_pptdev_msix(struct vmctx *ctx, int bus, int slot, int func,
841     int idx, uint64_t addr, uint64_t msg, uint32_t vector_control)
842 {
843         struct vm_pptdev_msix pptmsix;
844
845         bzero(&pptmsix, sizeof(pptmsix));
846         pptmsix.bus = bus;
847         pptmsix.slot = slot;
848         pptmsix.func = func;
849         pptmsix.idx = idx;
850         pptmsix.msg = msg;
851         pptmsix.addr = addr;
852         pptmsix.vector_control = vector_control;
853
854         return ioctl(ctx->fd, VM_PPTDEV_MSIX, &pptmsix);
855 }
856
857 int
858 vm_disable_pptdev_msix(struct vmctx *ctx, int bus, int slot, int func)
859 {
860         struct vm_pptdev ppt;
861
862         bzero(&ppt, sizeof(ppt));
863         ppt.bus = bus;
864         ppt.slot = slot;
865         ppt.func = func;
866
867         return ioctl(ctx->fd, VM_PPTDEV_DISABLE_MSIX, &ppt);
868 }
869
870 uint64_t *
871 vm_get_stats(struct vcpu *vcpu, struct timeval *ret_tv,
872              int *ret_entries)
873 {
874         static _Thread_local uint64_t *stats_buf;
875         static _Thread_local u_int stats_count;
876         uint64_t *new_stats;
877         struct vm_stats vmstats;
878         u_int count, index;
879         bool have_stats;
880
881         have_stats = false;
882         count = 0;
883         for (index = 0;; index += nitems(vmstats.statbuf)) {
884                 vmstats.index = index;
885                 if (vcpu_ioctl(vcpu, VM_STATS, &vmstats) != 0)
886                         break;
887                 if (stats_count < index + vmstats.num_entries) {
888                         new_stats = realloc(stats_buf,
889                             (index + vmstats.num_entries) * sizeof(uint64_t));
890                         if (new_stats == NULL) {
891                                 errno = ENOMEM;
892                                 return (NULL);
893                         }
894                         stats_count = index + vmstats.num_entries;
895                         stats_buf = new_stats;
896                 }
897                 memcpy(stats_buf + index, vmstats.statbuf,
898                     vmstats.num_entries * sizeof(uint64_t));
899                 count += vmstats.num_entries;
900                 have_stats = true;
901
902                 if (vmstats.num_entries != nitems(vmstats.statbuf))
903                         break;
904         }
905         if (have_stats) {
906                 if (ret_entries)
907                         *ret_entries = count;
908                 if (ret_tv)
909                         *ret_tv = vmstats.tv;
910                 return (stats_buf);
911         } else
912                 return (NULL);
913 }
914
915 const char *
916 vm_get_stat_desc(struct vmctx *ctx, int index)
917 {
918         static struct vm_stat_desc statdesc;
919
920         statdesc.index = index;
921         if (ioctl(ctx->fd, VM_STAT_DESC, &statdesc) == 0)
922                 return (statdesc.desc);
923         else
924                 return (NULL);
925 }
926
927 int
928 vm_get_x2apic_state(struct vcpu *vcpu, enum x2apic_state *state)
929 {
930         int error;
931         struct vm_x2apic x2apic;
932
933         bzero(&x2apic, sizeof(x2apic));
934
935         error = vcpu_ioctl(vcpu, VM_GET_X2APIC_STATE, &x2apic);
936         *state = x2apic.state;
937         return (error);
938 }
939
940 int
941 vm_set_x2apic_state(struct vcpu *vcpu, enum x2apic_state state)
942 {
943         int error;
944         struct vm_x2apic x2apic;
945
946         bzero(&x2apic, sizeof(x2apic));
947         x2apic.state = state;
948
949         error = vcpu_ioctl(vcpu, VM_SET_X2APIC_STATE, &x2apic);
950
951         return (error);
952 }
953
954 int
955 vm_get_gpa_pmap(struct vmctx *ctx, uint64_t gpa, uint64_t *pte, int *num)
956 {
957         int error, i;
958         struct vm_gpa_pte gpapte;
959
960         bzero(&gpapte, sizeof(gpapte));
961         gpapte.gpa = gpa;
962
963         error = ioctl(ctx->fd, VM_GET_GPA_PMAP, &gpapte);
964
965         if (error == 0) {
966                 *num = gpapte.ptenum;
967                 for (i = 0; i < gpapte.ptenum; i++)
968                         pte[i] = gpapte.pte[i];
969         }
970
971         return (error);
972 }
973
974 int
975 vm_get_hpet_capabilities(struct vmctx *ctx, uint32_t *capabilities)
976 {
977         int error;
978         struct vm_hpet_cap cap;
979
980         bzero(&cap, sizeof(struct vm_hpet_cap));
981         error = ioctl(ctx->fd, VM_GET_HPET_CAPABILITIES, &cap);
982         if (capabilities != NULL)
983                 *capabilities = cap.capabilities;
984         return (error);
985 }
986
987 int
988 vm_gla2gpa(struct vcpu *vcpu, struct vm_guest_paging *paging,
989     uint64_t gla, int prot, uint64_t *gpa, int *fault)
990 {
991         struct vm_gla2gpa gg;
992         int error;
993
994         bzero(&gg, sizeof(struct vm_gla2gpa));
995         gg.prot = prot;
996         gg.gla = gla;
997         gg.paging = *paging;
998
999         error = vcpu_ioctl(vcpu, VM_GLA2GPA, &gg);
1000         if (error == 0) {
1001                 *fault = gg.fault;
1002                 *gpa = gg.gpa;
1003         }
1004         return (error);
1005 }
1006
1007 int
1008 vm_gla2gpa_nofault(struct vcpu *vcpu, struct vm_guest_paging *paging,
1009     uint64_t gla, int prot, uint64_t *gpa, int *fault)
1010 {
1011         struct vm_gla2gpa gg;
1012         int error;
1013
1014         bzero(&gg, sizeof(struct vm_gla2gpa));
1015         gg.prot = prot;
1016         gg.gla = gla;
1017         gg.paging = *paging;
1018
1019         error = vcpu_ioctl(vcpu, VM_GLA2GPA_NOFAULT, &gg);
1020         if (error == 0) {
1021                 *fault = gg.fault;
1022                 *gpa = gg.gpa;
1023         }
1024         return (error);
1025 }
1026
1027 #ifndef min
1028 #define min(a,b)        (((a) < (b)) ? (a) : (b))
1029 #endif
1030
1031 int
1032 vm_copy_setup(struct vcpu *vcpu, struct vm_guest_paging *paging,
1033     uint64_t gla, size_t len, int prot, struct iovec *iov, int iovcnt,
1034     int *fault)
1035 {
1036         void *va;
1037         uint64_t gpa, off;
1038         int error, i, n;
1039
1040         for (i = 0; i < iovcnt; i++) {
1041                 iov[i].iov_base = 0;
1042                 iov[i].iov_len = 0;
1043         }
1044
1045         while (len) {
1046                 assert(iovcnt > 0);
1047                 error = vm_gla2gpa(vcpu, paging, gla, prot, &gpa, fault);
1048                 if (error || *fault)
1049                         return (error);
1050
1051                 off = gpa & PAGE_MASK;
1052                 n = MIN(len, PAGE_SIZE - off);
1053
1054                 va = vm_map_gpa(vcpu->ctx, gpa, n);
1055                 if (va == NULL)
1056                         return (EFAULT);
1057
1058                 iov->iov_base = va;
1059                 iov->iov_len = n;
1060                 iov++;
1061                 iovcnt--;
1062
1063                 gla += n;
1064                 len -= n;
1065         }
1066         return (0);
1067 }
1068
1069 void
1070 vm_copy_teardown(struct iovec *iov __unused, int iovcnt __unused)
1071 {
1072         /*
1073          * Intentionally empty.  This is used by the instruction
1074          * emulation code shared with the kernel.  The in-kernel
1075          * version of this is non-empty.
1076          */
1077 }
1078
1079 void
1080 vm_copyin(struct iovec *iov, void *vp, size_t len)
1081 {
1082         const char *src;
1083         char *dst;
1084         size_t n;
1085
1086         dst = vp;
1087         while (len) {
1088                 assert(iov->iov_len);
1089                 n = min(len, iov->iov_len);
1090                 src = iov->iov_base;
1091                 bcopy(src, dst, n);
1092
1093                 iov++;
1094                 dst += n;
1095                 len -= n;
1096         }
1097 }
1098
1099 void
1100 vm_copyout(const void *vp, struct iovec *iov, size_t len)
1101 {
1102         const char *src;
1103         char *dst;
1104         size_t n;
1105
1106         src = vp;
1107         while (len) {
1108                 assert(iov->iov_len);
1109                 n = min(len, iov->iov_len);
1110                 dst = iov->iov_base;
1111                 bcopy(src, dst, n);
1112
1113                 iov++;
1114                 src += n;
1115                 len -= n;
1116         }
1117 }
1118
1119 static int
1120 vm_get_cpus(struct vmctx *ctx, int which, cpuset_t *cpus)
1121 {
1122         struct vm_cpuset vm_cpuset;
1123         int error;
1124
1125         bzero(&vm_cpuset, sizeof(struct vm_cpuset));
1126         vm_cpuset.which = which;
1127         vm_cpuset.cpusetsize = sizeof(cpuset_t);
1128         vm_cpuset.cpus = cpus;
1129
1130         error = ioctl(ctx->fd, VM_GET_CPUS, &vm_cpuset);
1131         return (error);
1132 }
1133
1134 int
1135 vm_active_cpus(struct vmctx *ctx, cpuset_t *cpus)
1136 {
1137
1138         return (vm_get_cpus(ctx, VM_ACTIVE_CPUS, cpus));
1139 }
1140
1141 int
1142 vm_suspended_cpus(struct vmctx *ctx, cpuset_t *cpus)
1143 {
1144
1145         return (vm_get_cpus(ctx, VM_SUSPENDED_CPUS, cpus));
1146 }
1147
1148 int
1149 vm_debug_cpus(struct vmctx *ctx, cpuset_t *cpus)
1150 {
1151
1152         return (vm_get_cpus(ctx, VM_DEBUG_CPUS, cpus));
1153 }
1154
1155 int
1156 vm_activate_cpu(struct vcpu *vcpu)
1157 {
1158         struct vm_activate_cpu ac;
1159         int error;
1160
1161         bzero(&ac, sizeof(struct vm_activate_cpu));
1162         error = vcpu_ioctl(vcpu, VM_ACTIVATE_CPU, &ac);
1163         return (error);
1164 }
1165
1166 int
1167 vm_suspend_all_cpus(struct vmctx *ctx)
1168 {
1169         struct vm_activate_cpu ac;
1170         int error;
1171
1172         bzero(&ac, sizeof(struct vm_activate_cpu));
1173         ac.vcpuid = -1;
1174         error = ioctl(ctx->fd, VM_SUSPEND_CPU, &ac);
1175         return (error);
1176 }
1177
1178 int
1179 vm_suspend_cpu(struct vcpu *vcpu)
1180 {
1181         struct vm_activate_cpu ac;
1182         int error;
1183
1184         bzero(&ac, sizeof(struct vm_activate_cpu));
1185         error = vcpu_ioctl(vcpu, VM_SUSPEND_CPU, &ac);
1186         return (error);
1187 }
1188
1189 int
1190 vm_resume_cpu(struct vcpu *vcpu)
1191 {
1192         struct vm_activate_cpu ac;
1193         int error;
1194
1195         bzero(&ac, sizeof(struct vm_activate_cpu));
1196         error = vcpu_ioctl(vcpu, VM_RESUME_CPU, &ac);
1197         return (error);
1198 }
1199
1200 int
1201 vm_resume_all_cpus(struct vmctx *ctx)
1202 {
1203         struct vm_activate_cpu ac;
1204         int error;
1205
1206         bzero(&ac, sizeof(struct vm_activate_cpu));
1207         ac.vcpuid = -1;
1208         error = ioctl(ctx->fd, VM_RESUME_CPU, &ac);
1209         return (error);
1210 }
1211
1212 int
1213 vm_get_intinfo(struct vcpu *vcpu, uint64_t *info1, uint64_t *info2)
1214 {
1215         struct vm_intinfo vmii;
1216         int error;
1217
1218         bzero(&vmii, sizeof(struct vm_intinfo));
1219         error = vcpu_ioctl(vcpu, VM_GET_INTINFO, &vmii);
1220         if (error == 0) {
1221                 *info1 = vmii.info1;
1222                 *info2 = vmii.info2;
1223         }
1224         return (error);
1225 }
1226
1227 int
1228 vm_set_intinfo(struct vcpu *vcpu, uint64_t info1)
1229 {
1230         struct vm_intinfo vmii;
1231         int error;
1232
1233         bzero(&vmii, sizeof(struct vm_intinfo));
1234         vmii.info1 = info1;
1235         error = vcpu_ioctl(vcpu, VM_SET_INTINFO, &vmii);
1236         return (error);
1237 }
1238
1239 int
1240 vm_rtc_write(struct vmctx *ctx, int offset, uint8_t value)
1241 {
1242         struct vm_rtc_data rtcdata;
1243         int error;
1244
1245         bzero(&rtcdata, sizeof(struct vm_rtc_data));
1246         rtcdata.offset = offset;
1247         rtcdata.value = value;
1248         error = ioctl(ctx->fd, VM_RTC_WRITE, &rtcdata);
1249         return (error);
1250 }
1251
1252 int
1253 vm_rtc_read(struct vmctx *ctx, int offset, uint8_t *retval)
1254 {
1255         struct vm_rtc_data rtcdata;
1256         int error;
1257
1258         bzero(&rtcdata, sizeof(struct vm_rtc_data));
1259         rtcdata.offset = offset;
1260         error = ioctl(ctx->fd, VM_RTC_READ, &rtcdata);
1261         if (error == 0)
1262                 *retval = rtcdata.value;
1263         return (error);
1264 }
1265
1266 int
1267 vm_rtc_settime(struct vmctx *ctx, time_t secs)
1268 {
1269         struct vm_rtc_time rtctime;
1270         int error;
1271
1272         bzero(&rtctime, sizeof(struct vm_rtc_time));
1273         rtctime.secs = secs;
1274         error = ioctl(ctx->fd, VM_RTC_SETTIME, &rtctime);
1275         return (error);
1276 }
1277
1278 int
1279 vm_rtc_gettime(struct vmctx *ctx, time_t *secs)
1280 {
1281         struct vm_rtc_time rtctime;
1282         int error;
1283
1284         bzero(&rtctime, sizeof(struct vm_rtc_time));
1285         error = ioctl(ctx->fd, VM_RTC_GETTIME, &rtctime);
1286         if (error == 0)
1287                 *secs = rtctime.secs;
1288         return (error);
1289 }
1290
1291 int
1292 vm_restart_instruction(struct vcpu *vcpu)
1293 {
1294         int arg;
1295
1296         return (vcpu_ioctl(vcpu, VM_RESTART_INSTRUCTION, &arg));
1297 }
1298
1299 int
1300 vm_snapshot_req(struct vmctx *ctx, struct vm_snapshot_meta *meta)
1301 {
1302
1303         if (ioctl(ctx->fd, VM_SNAPSHOT_REQ, meta) == -1) {
1304 #ifdef SNAPSHOT_DEBUG
1305                 fprintf(stderr, "%s: snapshot failed for %s: %d\r\n",
1306                     __func__, meta->dev_name, errno);
1307 #endif
1308                 return (-1);
1309         }
1310         return (0);
1311 }
1312
1313 int
1314 vm_restore_time(struct vmctx *ctx)
1315 {
1316         int dummy;
1317
1318         dummy = 0;
1319         return (ioctl(ctx->fd, VM_RESTORE_TIME, &dummy));
1320 }
1321
1322 int
1323 vm_set_topology(struct vmctx *ctx,
1324     uint16_t sockets, uint16_t cores, uint16_t threads, uint16_t maxcpus)
1325 {
1326         struct vm_cpu_topology topology;
1327
1328         bzero(&topology, sizeof (struct vm_cpu_topology));
1329         topology.sockets = sockets;
1330         topology.cores = cores;
1331         topology.threads = threads;
1332         topology.maxcpus = maxcpus;
1333         return (ioctl(ctx->fd, VM_SET_TOPOLOGY, &topology));
1334 }
1335
1336 int
1337 vm_get_topology(struct vmctx *ctx,
1338     uint16_t *sockets, uint16_t *cores, uint16_t *threads, uint16_t *maxcpus)
1339 {
1340         struct vm_cpu_topology topology;
1341         int error;
1342
1343         bzero(&topology, sizeof (struct vm_cpu_topology));
1344         error = ioctl(ctx->fd, VM_GET_TOPOLOGY, &topology);
1345         if (error == 0) {
1346                 *sockets = topology.sockets;
1347                 *cores = topology.cores;
1348                 *threads = topology.threads;
1349                 *maxcpus = topology.maxcpus;
1350         }
1351         return (error);
1352 }
1353
1354 int
1355 vm_limit_rights(struct vmctx *ctx)
1356 {
1357         cap_rights_t rights;
1358
1359         cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
1360         if (caph_rights_limit(ctx->fd, &rights) != 0)
1361                 return (-1);
1362         if (caph_ioctls_limit(ctx->fd, vm_ioctl_cmds, vm_ioctl_ncmds) != 0)
1363                 return (-1);
1364         return (0);
1365 }
1366
1367 /*
1368  * Avoid using in new code.  Operations on the fd should be wrapped here so that
1369  * capability rights can be kept in sync.
1370  */
1371 int
1372 vm_get_device_fd(struct vmctx *ctx)
1373 {
1374
1375         return (ctx->fd);
1376 }
1377
1378 /* Legacy interface, do not use. */
1379 const cap_ioctl_t *
1380 vm_get_ioctls(size_t *len)
1381 {
1382         cap_ioctl_t *cmds;
1383         size_t sz;
1384
1385         if (len == NULL) {
1386                 sz = vm_ioctl_ncmds * sizeof(vm_ioctl_cmds[0]);
1387                 cmds = malloc(sz);
1388                 if (cmds == NULL)
1389                         return (NULL);
1390                 bcopy(vm_ioctl_cmds, cmds, sz);
1391                 return (cmds);
1392         }
1393
1394         *len = vm_ioctl_ncmds;
1395         return (NULL);
1396 }