xref: /freebsd/lib/libvmmapi/vmmapi.c (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
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  * $FreeBSD$
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/param.h>
35 #include <sys/capsicum.h>
36 #include <sys/sysctl.h>
37 #include <sys/ioctl.h>
38 #include <sys/linker.h>
39 #include <sys/mman.h>
40 #include <sys/module.h>
41 #include <sys/_iovec.h>
42 #include <sys/cpuset.h>
43 
44 #include <x86/segments.h>
45 #include <machine/specialreg.h>
46 
47 #include <capsicum_helpers.h>
48 #include <errno.h>
49 #include <stdbool.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <assert.h>
53 #include <string.h>
54 #include <fcntl.h>
55 #include <unistd.h>
56 
57 #include <libutil.h>
58 
59 #include <vm/vm.h>
60 #include <machine/vmm.h>
61 #include <machine/vmm_dev.h>
62 #include <machine/vmm_snapshot.h>
63 
64 #include "vmmapi.h"
65 #include "internal.h"
66 
67 #define	MB	(1024 * 1024UL)
68 #define	GB	(1024 * 1024 * 1024UL)
69 
70 /*
71  * Size of the guard region before and after the virtual address space
72  * mapping the guest physical memory. This must be a multiple of the
73  * superpage size for performance reasons.
74  */
75 #define	VM_MMAP_GUARD_SIZE	(4 * MB)
76 
77 #define	PROT_RW		(PROT_READ | PROT_WRITE)
78 #define	PROT_ALL	(PROT_READ | PROT_WRITE | PROT_EXEC)
79 
80 struct vmctx {
81 	int	fd;
82 	uint32_t lowmem_limit;
83 	int	memflags;
84 	size_t	lowmem;
85 	size_t	highmem;
86 	char	*baseaddr;
87 	char	*name;
88 };
89 
90 #define	CREATE(x)  sysctlbyname("hw.vmm.create", NULL, NULL, (x), strlen((x)))
91 #define	DESTROY(x) sysctlbyname("hw.vmm.destroy", NULL, NULL, (x), strlen((x)))
92 
93 static int
94 vm_device_open(const char *name)
95 {
96 	int fd, len;
97 	char *vmfile;
98 
99 	len = strlen("/dev/vmm/") + strlen(name) + 1;
100 	vmfile = malloc(len);
101 	assert(vmfile != NULL);
102 	snprintf(vmfile, len, "/dev/vmm/%s", name);
103 
104 	/* Open the device file */
105 	fd = open(vmfile, O_RDWR, 0);
106 
107 	free(vmfile);
108 	return (fd);
109 }
110 
111 int
112 vm_create(const char *name)
113 {
114 	/* Try to load vmm(4) module before creating a guest. */
115 	if (modfind("vmm") < 0)
116 		kldload("vmm");
117 	return (CREATE(name));
118 }
119 
120 struct vmctx *
121 vm_open(const char *name)
122 {
123 	struct vmctx *vm;
124 	int saved_errno;
125 
126 	vm = malloc(sizeof(struct vmctx) + strlen(name) + 1);
127 	assert(vm != NULL);
128 
129 	vm->fd = -1;
130 	vm->memflags = 0;
131 	vm->lowmem_limit = 3 * GB;
132 	vm->name = (char *)(vm + 1);
133 	strcpy(vm->name, name);
134 
135 	if ((vm->fd = vm_device_open(vm->name)) < 0)
136 		goto err;
137 
138 	return (vm);
139 err:
140 	saved_errno = errno;
141 	free(vm);
142 	errno = saved_errno;
143 	return (NULL);
144 }
145 
146 void
147 vm_close(struct vmctx *vm)
148 {
149 	assert(vm != NULL);
150 
151 	close(vm->fd);
152 	free(vm);
153 }
154 
155 void
156 vm_destroy(struct vmctx *vm)
157 {
158 	assert(vm != NULL);
159 
160 	if (vm->fd >= 0)
161 		close(vm->fd);
162 	DESTROY(vm->name);
163 
164 	free(vm);
165 }
166 
167 struct vcpu *
168 vm_vcpu_open(struct vmctx *ctx, int vcpuid)
169 {
170 	struct vcpu *vcpu;
171 
172 	vcpu = malloc(sizeof(*vcpu));
173 	vcpu->ctx = ctx;
174 	vcpu->vcpuid = vcpuid;
175 	return (vcpu);
176 }
177 
178 void
179 vm_vcpu_close(struct vcpu *vcpu)
180 {
181 	free(vcpu);
182 }
183 
184 int
185 vcpu_id(struct vcpu *vcpu)
186 {
187 	return (vcpu->vcpuid);
188 }
189 
190 int
191 vm_parse_memsize(const char *opt, size_t *ret_memsize)
192 {
193 	char *endptr;
194 	size_t optval;
195 	int error;
196 
197 	optval = strtoul(opt, &endptr, 0);
198 	if (*opt != '\0' && *endptr == '\0') {
199 		/*
200 		 * For the sake of backward compatibility if the memory size
201 		 * specified on the command line is less than a megabyte then
202 		 * it is interpreted as being in units of MB.
203 		 */
204 		if (optval < MB)
205 			optval *= MB;
206 		*ret_memsize = optval;
207 		error = 0;
208 	} else
209 		error = expand_number(opt, ret_memsize);
210 
211 	return (error);
212 }
213 
214 uint32_t
215 vm_get_lowmem_limit(struct vmctx *ctx)
216 {
217 
218 	return (ctx->lowmem_limit);
219 }
220 
221 void
222 vm_set_lowmem_limit(struct vmctx *ctx, uint32_t limit)
223 {
224 
225 	ctx->lowmem_limit = limit;
226 }
227 
228 void
229 vm_set_memflags(struct vmctx *ctx, int flags)
230 {
231 
232 	ctx->memflags = flags;
233 }
234 
235 int
236 vm_get_memflags(struct vmctx *ctx)
237 {
238 
239 	return (ctx->memflags);
240 }
241 
242 /*
243  * Map segment 'segid' starting at 'off' into guest address range [gpa,gpa+len).
244  */
245 int
246 vm_mmap_memseg(struct vmctx *ctx, vm_paddr_t gpa, int segid, vm_ooffset_t off,
247     size_t len, int prot)
248 {
249 	struct vm_memmap memmap;
250 	int error, flags;
251 
252 	memmap.gpa = gpa;
253 	memmap.segid = segid;
254 	memmap.segoff = off;
255 	memmap.len = len;
256 	memmap.prot = prot;
257 	memmap.flags = 0;
258 
259 	if (ctx->memflags & VM_MEM_F_WIRED)
260 		memmap.flags |= VM_MEMMAP_F_WIRED;
261 
262 	/*
263 	 * If this mapping already exists then don't create it again. This
264 	 * is the common case for SYSMEM mappings created by bhyveload(8).
265 	 */
266 	error = vm_mmap_getnext(ctx, &gpa, &segid, &off, &len, &prot, &flags);
267 	if (error == 0 && gpa == memmap.gpa) {
268 		if (segid != memmap.segid || off != memmap.segoff ||
269 		    prot != memmap.prot || flags != memmap.flags) {
270 			errno = EEXIST;
271 			return (-1);
272 		} else {
273 			return (0);
274 		}
275 	}
276 
277 	error = ioctl(ctx->fd, VM_MMAP_MEMSEG, &memmap);
278 	return (error);
279 }
280 
281 int
282 vm_get_guestmem_from_ctx(struct vmctx *ctx, char **guest_baseaddr,
283     size_t *lowmem_size, size_t *highmem_size)
284 {
285 
286 	*guest_baseaddr = ctx->baseaddr;
287 	*lowmem_size = ctx->lowmem;
288 	*highmem_size = ctx->highmem;
289 	return (0);
290 }
291 
292 int
293 vm_munmap_memseg(struct vmctx *ctx, vm_paddr_t gpa, size_t len)
294 {
295 	struct vm_munmap munmap;
296 	int error;
297 
298 	munmap.gpa = gpa;
299 	munmap.len = len;
300 
301 	error = ioctl(ctx->fd, VM_MUNMAP_MEMSEG, &munmap);
302 	return (error);
303 }
304 
305 int
306 vm_mmap_getnext(struct vmctx *ctx, vm_paddr_t *gpa, int *segid,
307     vm_ooffset_t *segoff, size_t *len, int *prot, int *flags)
308 {
309 	struct vm_memmap memmap;
310 	int error;
311 
312 	bzero(&memmap, sizeof(struct vm_memmap));
313 	memmap.gpa = *gpa;
314 	error = ioctl(ctx->fd, VM_MMAP_GETNEXT, &memmap);
315 	if (error == 0) {
316 		*gpa = memmap.gpa;
317 		*segid = memmap.segid;
318 		*segoff = memmap.segoff;
319 		*len = memmap.len;
320 		*prot = memmap.prot;
321 		*flags = memmap.flags;
322 	}
323 	return (error);
324 }
325 
326 /*
327  * Return 0 if the segments are identical and non-zero otherwise.
328  *
329  * This is slightly complicated by the fact that only device memory segments
330  * are named.
331  */
332 static int
333 cmpseg(size_t len, const char *str, size_t len2, const char *str2)
334 {
335 
336 	if (len == len2) {
337 		if ((!str && !str2) || (str && str2 && !strcmp(str, str2)))
338 			return (0);
339 	}
340 	return (-1);
341 }
342 
343 static int
344 vm_alloc_memseg(struct vmctx *ctx, int segid, size_t len, const char *name)
345 {
346 	struct vm_memseg memseg;
347 	size_t n;
348 	int error;
349 
350 	/*
351 	 * If the memory segment has already been created then just return.
352 	 * This is the usual case for the SYSMEM segment created by userspace
353 	 * loaders like bhyveload(8).
354 	 */
355 	error = vm_get_memseg(ctx, segid, &memseg.len, memseg.name,
356 	    sizeof(memseg.name));
357 	if (error)
358 		return (error);
359 
360 	if (memseg.len != 0) {
361 		if (cmpseg(len, name, memseg.len, VM_MEMSEG_NAME(&memseg))) {
362 			errno = EINVAL;
363 			return (-1);
364 		} else {
365 			return (0);
366 		}
367 	}
368 
369 	bzero(&memseg, sizeof(struct vm_memseg));
370 	memseg.segid = segid;
371 	memseg.len = len;
372 	if (name != NULL) {
373 		n = strlcpy(memseg.name, name, sizeof(memseg.name));
374 		if (n >= sizeof(memseg.name)) {
375 			errno = ENAMETOOLONG;
376 			return (-1);
377 		}
378 	}
379 
380 	error = ioctl(ctx->fd, VM_ALLOC_MEMSEG, &memseg);
381 	return (error);
382 }
383 
384 int
385 vm_get_memseg(struct vmctx *ctx, int segid, size_t *lenp, char *namebuf,
386     size_t bufsize)
387 {
388 	struct vm_memseg memseg;
389 	size_t n;
390 	int error;
391 
392 	memseg.segid = segid;
393 	error = ioctl(ctx->fd, VM_GET_MEMSEG, &memseg);
394 	if (error == 0) {
395 		*lenp = memseg.len;
396 		n = strlcpy(namebuf, memseg.name, bufsize);
397 		if (n >= bufsize) {
398 			errno = ENAMETOOLONG;
399 			error = -1;
400 		}
401 	}
402 	return (error);
403 }
404 
405 static int
406 setup_memory_segment(struct vmctx *ctx, vm_paddr_t gpa, size_t len, char *base)
407 {
408 	char *ptr;
409 	int error, flags;
410 
411 	/* Map 'len' bytes starting at 'gpa' in the guest address space */
412 	error = vm_mmap_memseg(ctx, gpa, VM_SYSMEM, gpa, len, PROT_ALL);
413 	if (error)
414 		return (error);
415 
416 	flags = MAP_SHARED | MAP_FIXED;
417 	if ((ctx->memflags & VM_MEM_F_INCORE) == 0)
418 		flags |= MAP_NOCORE;
419 
420 	/* mmap into the process address space on the host */
421 	ptr = mmap(base + gpa, len, PROT_RW, flags, ctx->fd, gpa);
422 	if (ptr == MAP_FAILED)
423 		return (-1);
424 
425 	return (0);
426 }
427 
428 int
429 vm_setup_memory(struct vmctx *ctx, size_t memsize, enum vm_mmap_style vms)
430 {
431 	size_t objsize, len;
432 	vm_paddr_t gpa;
433 	char *baseaddr, *ptr;
434 	int error;
435 
436 	assert(vms == VM_MMAP_ALL);
437 
438 	/*
439 	 * If 'memsize' cannot fit entirely in the 'lowmem' segment then
440 	 * create another 'highmem' segment above 4GB for the remainder.
441 	 */
442 	if (memsize > ctx->lowmem_limit) {
443 		ctx->lowmem = ctx->lowmem_limit;
444 		ctx->highmem = memsize - ctx->lowmem_limit;
445 		objsize = 4*GB + ctx->highmem;
446 	} else {
447 		ctx->lowmem = memsize;
448 		ctx->highmem = 0;
449 		objsize = ctx->lowmem;
450 	}
451 
452 	error = vm_alloc_memseg(ctx, VM_SYSMEM, objsize, NULL);
453 	if (error)
454 		return (error);
455 
456 	/*
457 	 * Stake out a contiguous region covering the guest physical memory
458 	 * and the adjoining guard regions.
459 	 */
460 	len = VM_MMAP_GUARD_SIZE + objsize + VM_MMAP_GUARD_SIZE;
461 	ptr = mmap(NULL, len, PROT_NONE, MAP_GUARD | MAP_ALIGNED_SUPER, -1, 0);
462 	if (ptr == MAP_FAILED)
463 		return (-1);
464 
465 	baseaddr = ptr + VM_MMAP_GUARD_SIZE;
466 	if (ctx->highmem > 0) {
467 		gpa = 4*GB;
468 		len = ctx->highmem;
469 		error = setup_memory_segment(ctx, gpa, len, baseaddr);
470 		if (error)
471 			return (error);
472 	}
473 
474 	if (ctx->lowmem > 0) {
475 		gpa = 0;
476 		len = ctx->lowmem;
477 		error = setup_memory_segment(ctx, gpa, len, baseaddr);
478 		if (error)
479 			return (error);
480 	}
481 
482 	ctx->baseaddr = baseaddr;
483 
484 	return (0);
485 }
486 
487 /*
488  * Returns a non-NULL pointer if [gaddr, gaddr+len) is entirely contained in
489  * the lowmem or highmem regions.
490  *
491  * In particular return NULL if [gaddr, gaddr+len) falls in guest MMIO region.
492  * The instruction emulation code depends on this behavior.
493  */
494 void *
495 vm_map_gpa(struct vmctx *ctx, vm_paddr_t gaddr, size_t len)
496 {
497 
498 	if (ctx->lowmem > 0) {
499 		if (gaddr < ctx->lowmem && len <= ctx->lowmem &&
500 		    gaddr + len <= ctx->lowmem)
501 			return (ctx->baseaddr + gaddr);
502 	}
503 
504 	if (ctx->highmem > 0) {
505                 if (gaddr >= 4*GB) {
506 			if (gaddr < 4*GB + ctx->highmem &&
507 			    len <= ctx->highmem &&
508 			    gaddr + len <= 4*GB + ctx->highmem)
509 				return (ctx->baseaddr + gaddr);
510 		}
511 	}
512 
513 	return (NULL);
514 }
515 
516 vm_paddr_t
517 vm_rev_map_gpa(struct vmctx *ctx, void *addr)
518 {
519 	vm_paddr_t offaddr;
520 
521 	offaddr = (char *)addr - ctx->baseaddr;
522 
523 	if (ctx->lowmem > 0)
524 		if (offaddr <= ctx->lowmem)
525 			return (offaddr);
526 
527 	if (ctx->highmem > 0)
528 		if (offaddr >= 4*GB && offaddr < 4*GB + ctx->highmem)
529 			return (offaddr);
530 
531 	return ((vm_paddr_t)-1);
532 }
533 
534 const char *
535 vm_get_name(struct vmctx *ctx)
536 {
537 
538 	return (ctx->name);
539 }
540 
541 size_t
542 vm_get_lowmem_size(struct vmctx *ctx)
543 {
544 
545 	return (ctx->lowmem);
546 }
547 
548 size_t
549 vm_get_highmem_size(struct vmctx *ctx)
550 {
551 
552 	return (ctx->highmem);
553 }
554 
555 void *
556 vm_create_devmem(struct vmctx *ctx, int segid, const char *name, size_t len)
557 {
558 	char pathname[MAXPATHLEN];
559 	size_t len2;
560 	char *base, *ptr;
561 	int fd, error, flags;
562 
563 	fd = -1;
564 	ptr = MAP_FAILED;
565 	if (name == NULL || strlen(name) == 0) {
566 		errno = EINVAL;
567 		goto done;
568 	}
569 
570 	error = vm_alloc_memseg(ctx, segid, len, name);
571 	if (error)
572 		goto done;
573 
574 	strlcpy(pathname, "/dev/vmm.io/", sizeof(pathname));
575 	strlcat(pathname, ctx->name, sizeof(pathname));
576 	strlcat(pathname, ".", sizeof(pathname));
577 	strlcat(pathname, name, sizeof(pathname));
578 
579 	fd = open(pathname, O_RDWR);
580 	if (fd < 0)
581 		goto done;
582 
583 	/*
584 	 * Stake out a contiguous region covering the device memory and the
585 	 * adjoining guard regions.
586 	 */
587 	len2 = VM_MMAP_GUARD_SIZE + len + VM_MMAP_GUARD_SIZE;
588 	base = mmap(NULL, len2, PROT_NONE, MAP_GUARD | MAP_ALIGNED_SUPER, -1,
589 	    0);
590 	if (base == MAP_FAILED)
591 		goto done;
592 
593 	flags = MAP_SHARED | MAP_FIXED;
594 	if ((ctx->memflags & VM_MEM_F_INCORE) == 0)
595 		flags |= MAP_NOCORE;
596 
597 	/* mmap the devmem region in the host address space */
598 	ptr = mmap(base + VM_MMAP_GUARD_SIZE, len, PROT_RW, flags, fd, 0);
599 done:
600 	if (fd >= 0)
601 		close(fd);
602 	return (ptr);
603 }
604 
605 static int
606 vcpu_ioctl(struct vcpu *vcpu, u_long cmd, void *arg)
607 {
608 	/*
609 	 * XXX: fragile, handle with care
610 	 * Assumes that the first field of the ioctl data
611 	 * is the vcpuid.
612 	 */
613 	*(int *)arg = vcpu->vcpuid;
614 	return (ioctl(vcpu->ctx->fd, cmd, arg));
615 }
616 
617 int
618 vm_set_desc(struct vcpu *vcpu, int reg,
619 	    uint64_t base, uint32_t limit, uint32_t access)
620 {
621 	int error;
622 	struct vm_seg_desc vmsegdesc;
623 
624 	bzero(&vmsegdesc, sizeof(vmsegdesc));
625 	vmsegdesc.regnum = reg;
626 	vmsegdesc.desc.base = base;
627 	vmsegdesc.desc.limit = limit;
628 	vmsegdesc.desc.access = access;
629 
630 	error = vcpu_ioctl(vcpu, VM_SET_SEGMENT_DESCRIPTOR, &vmsegdesc);
631 	return (error);
632 }
633 
634 int
635 vm_get_desc(struct vcpu *vcpu, int reg, uint64_t *base, uint32_t *limit,
636     uint32_t *access)
637 {
638 	int error;
639 	struct vm_seg_desc vmsegdesc;
640 
641 	bzero(&vmsegdesc, sizeof(vmsegdesc));
642 	vmsegdesc.regnum = reg;
643 
644 	error = vcpu_ioctl(vcpu, VM_GET_SEGMENT_DESCRIPTOR, &vmsegdesc);
645 	if (error == 0) {
646 		*base = vmsegdesc.desc.base;
647 		*limit = vmsegdesc.desc.limit;
648 		*access = vmsegdesc.desc.access;
649 	}
650 	return (error);
651 }
652 
653 int
654 vm_get_seg_desc(struct vcpu *vcpu, int reg, struct seg_desc *seg_desc)
655 {
656 	int error;
657 
658 	error = vm_get_desc(vcpu, reg, &seg_desc->base, &seg_desc->limit,
659 	    &seg_desc->access);
660 	return (error);
661 }
662 
663 int
664 vm_set_register(struct vcpu *vcpu, int reg, uint64_t val)
665 {
666 	int error;
667 	struct vm_register vmreg;
668 
669 	bzero(&vmreg, sizeof(vmreg));
670 	vmreg.regnum = reg;
671 	vmreg.regval = val;
672 
673 	error = vcpu_ioctl(vcpu, VM_SET_REGISTER, &vmreg);
674 	return (error);
675 }
676 
677 int
678 vm_get_register(struct vcpu *vcpu, int reg, uint64_t *ret_val)
679 {
680 	int error;
681 	struct vm_register vmreg;
682 
683 	bzero(&vmreg, sizeof(vmreg));
684 	vmreg.regnum = reg;
685 
686 	error = vcpu_ioctl(vcpu, VM_GET_REGISTER, &vmreg);
687 	*ret_val = vmreg.regval;
688 	return (error);
689 }
690 
691 int
692 vm_set_register_set(struct vcpu *vcpu, unsigned int count,
693     const int *regnums, uint64_t *regvals)
694 {
695 	int error;
696 	struct vm_register_set vmregset;
697 
698 	bzero(&vmregset, sizeof(vmregset));
699 	vmregset.count = count;
700 	vmregset.regnums = regnums;
701 	vmregset.regvals = regvals;
702 
703 	error = vcpu_ioctl(vcpu, VM_SET_REGISTER_SET, &vmregset);
704 	return (error);
705 }
706 
707 int
708 vm_get_register_set(struct vcpu *vcpu, unsigned int count,
709     const int *regnums, uint64_t *regvals)
710 {
711 	int error;
712 	struct vm_register_set vmregset;
713 
714 	bzero(&vmregset, sizeof(vmregset));
715 	vmregset.count = count;
716 	vmregset.regnums = regnums;
717 	vmregset.regvals = regvals;
718 
719 	error = vcpu_ioctl(vcpu, VM_GET_REGISTER_SET, &vmregset);
720 	return (error);
721 }
722 
723 int
724 vm_run(struct vcpu *vcpu, struct vm_run *vmrun)
725 {
726 	return (vcpu_ioctl(vcpu, VM_RUN, vmrun));
727 }
728 
729 int
730 vm_suspend(struct vmctx *ctx, enum vm_suspend_how how)
731 {
732 	struct vm_suspend vmsuspend;
733 
734 	bzero(&vmsuspend, sizeof(vmsuspend));
735 	vmsuspend.how = how;
736 	return (ioctl(ctx->fd, VM_SUSPEND, &vmsuspend));
737 }
738 
739 int
740 vm_reinit(struct vmctx *ctx)
741 {
742 
743 	return (ioctl(ctx->fd, VM_REINIT, 0));
744 }
745 
746 int
747 vm_inject_exception(struct vcpu *vcpu, int vector, int errcode_valid,
748     uint32_t errcode, int restart_instruction)
749 {
750 	struct vm_exception exc;
751 
752 	exc.vector = vector;
753 	exc.error_code = errcode;
754 	exc.error_code_valid = errcode_valid;
755 	exc.restart_instruction = restart_instruction;
756 
757 	return (vcpu_ioctl(vcpu, VM_INJECT_EXCEPTION, &exc));
758 }
759 
760 int
761 vm_apicid2vcpu(struct vmctx *ctx __unused, int apicid)
762 {
763 	/*
764 	 * The apic id associated with the 'vcpu' has the same numerical value
765 	 * as the 'vcpu' itself.
766 	 */
767 	return (apicid);
768 }
769 
770 int
771 vm_lapic_irq(struct vcpu *vcpu, int vector)
772 {
773 	struct vm_lapic_irq vmirq;
774 
775 	bzero(&vmirq, sizeof(vmirq));
776 	vmirq.vector = vector;
777 
778 	return (vcpu_ioctl(vcpu, VM_LAPIC_IRQ, &vmirq));
779 }
780 
781 int
782 vm_lapic_local_irq(struct vcpu *vcpu, int vector)
783 {
784 	struct vm_lapic_irq vmirq;
785 
786 	bzero(&vmirq, sizeof(vmirq));
787 	vmirq.vector = vector;
788 
789 	return (vcpu_ioctl(vcpu, VM_LAPIC_LOCAL_IRQ, &vmirq));
790 }
791 
792 int
793 vm_lapic_msi(struct vmctx *ctx, uint64_t addr, uint64_t msg)
794 {
795 	struct vm_lapic_msi vmmsi;
796 
797 	bzero(&vmmsi, sizeof(vmmsi));
798 	vmmsi.addr = addr;
799 	vmmsi.msg = msg;
800 
801 	return (ioctl(ctx->fd, VM_LAPIC_MSI, &vmmsi));
802 }
803 
804 int
805 vm_ioapic_assert_irq(struct vmctx *ctx, int irq)
806 {
807 	struct vm_ioapic_irq ioapic_irq;
808 
809 	bzero(&ioapic_irq, sizeof(struct vm_ioapic_irq));
810 	ioapic_irq.irq = irq;
811 
812 	return (ioctl(ctx->fd, VM_IOAPIC_ASSERT_IRQ, &ioapic_irq));
813 }
814 
815 int
816 vm_ioapic_deassert_irq(struct vmctx *ctx, int irq)
817 {
818 	struct vm_ioapic_irq ioapic_irq;
819 
820 	bzero(&ioapic_irq, sizeof(struct vm_ioapic_irq));
821 	ioapic_irq.irq = irq;
822 
823 	return (ioctl(ctx->fd, VM_IOAPIC_DEASSERT_IRQ, &ioapic_irq));
824 }
825 
826 int
827 vm_ioapic_pulse_irq(struct vmctx *ctx, int irq)
828 {
829 	struct vm_ioapic_irq ioapic_irq;
830 
831 	bzero(&ioapic_irq, sizeof(struct vm_ioapic_irq));
832 	ioapic_irq.irq = irq;
833 
834 	return (ioctl(ctx->fd, VM_IOAPIC_PULSE_IRQ, &ioapic_irq));
835 }
836 
837 int
838 vm_ioapic_pincount(struct vmctx *ctx, int *pincount)
839 {
840 
841 	return (ioctl(ctx->fd, VM_IOAPIC_PINCOUNT, pincount));
842 }
843 
844 int
845 vm_readwrite_kernemu_device(struct vcpu *vcpu, vm_paddr_t gpa,
846     bool write, int size, uint64_t *value)
847 {
848 	struct vm_readwrite_kernemu_device irp = {
849 		.access_width = fls(size) - 1,
850 		.gpa = gpa,
851 		.value = write ? *value : ~0ul,
852 	};
853 	long cmd = (write ? VM_SET_KERNEMU_DEV : VM_GET_KERNEMU_DEV);
854 	int rc;
855 
856 	rc = vcpu_ioctl(vcpu, cmd, &irp);
857 	if (rc == 0 && !write)
858 		*value = irp.value;
859 	return (rc);
860 }
861 
862 int
863 vm_isa_assert_irq(struct vmctx *ctx, int atpic_irq, int ioapic_irq)
864 {
865 	struct vm_isa_irq isa_irq;
866 
867 	bzero(&isa_irq, sizeof(struct vm_isa_irq));
868 	isa_irq.atpic_irq = atpic_irq;
869 	isa_irq.ioapic_irq = ioapic_irq;
870 
871 	return (ioctl(ctx->fd, VM_ISA_ASSERT_IRQ, &isa_irq));
872 }
873 
874 int
875 vm_isa_deassert_irq(struct vmctx *ctx, int atpic_irq, int ioapic_irq)
876 {
877 	struct vm_isa_irq isa_irq;
878 
879 	bzero(&isa_irq, sizeof(struct vm_isa_irq));
880 	isa_irq.atpic_irq = atpic_irq;
881 	isa_irq.ioapic_irq = ioapic_irq;
882 
883 	return (ioctl(ctx->fd, VM_ISA_DEASSERT_IRQ, &isa_irq));
884 }
885 
886 int
887 vm_isa_pulse_irq(struct vmctx *ctx, int atpic_irq, int ioapic_irq)
888 {
889 	struct vm_isa_irq isa_irq;
890 
891 	bzero(&isa_irq, sizeof(struct vm_isa_irq));
892 	isa_irq.atpic_irq = atpic_irq;
893 	isa_irq.ioapic_irq = ioapic_irq;
894 
895 	return (ioctl(ctx->fd, VM_ISA_PULSE_IRQ, &isa_irq));
896 }
897 
898 int
899 vm_isa_set_irq_trigger(struct vmctx *ctx, int atpic_irq,
900     enum vm_intr_trigger trigger)
901 {
902 	struct vm_isa_irq_trigger isa_irq_trigger;
903 
904 	bzero(&isa_irq_trigger, sizeof(struct vm_isa_irq_trigger));
905 	isa_irq_trigger.atpic_irq = atpic_irq;
906 	isa_irq_trigger.trigger = trigger;
907 
908 	return (ioctl(ctx->fd, VM_ISA_SET_IRQ_TRIGGER, &isa_irq_trigger));
909 }
910 
911 int
912 vm_inject_nmi(struct vcpu *vcpu)
913 {
914 	struct vm_nmi vmnmi;
915 
916 	bzero(&vmnmi, sizeof(vmnmi));
917 
918 	return (vcpu_ioctl(vcpu, VM_INJECT_NMI, &vmnmi));
919 }
920 
921 static const char *capstrmap[] = {
922 	[VM_CAP_HALT_EXIT]  = "hlt_exit",
923 	[VM_CAP_MTRAP_EXIT] = "mtrap_exit",
924 	[VM_CAP_PAUSE_EXIT] = "pause_exit",
925 	[VM_CAP_UNRESTRICTED_GUEST] = "unrestricted_guest",
926 	[VM_CAP_ENABLE_INVPCID] = "enable_invpcid",
927 	[VM_CAP_BPT_EXIT] = "bpt_exit",
928 };
929 
930 int
931 vm_capability_name2type(const char *capname)
932 {
933 	int i;
934 
935 	for (i = 0; i < (int)nitems(capstrmap); i++) {
936 		if (strcmp(capstrmap[i], capname) == 0)
937 			return (i);
938 	}
939 
940 	return (-1);
941 }
942 
943 const char *
944 vm_capability_type2name(int type)
945 {
946 	if (type >= 0 && type < (int)nitems(capstrmap))
947 		return (capstrmap[type]);
948 
949 	return (NULL);
950 }
951 
952 int
953 vm_get_capability(struct vcpu *vcpu, enum vm_cap_type cap, int *retval)
954 {
955 	int error;
956 	struct vm_capability vmcap;
957 
958 	bzero(&vmcap, sizeof(vmcap));
959 	vmcap.captype = cap;
960 
961 	error = vcpu_ioctl(vcpu, VM_GET_CAPABILITY, &vmcap);
962 	*retval = vmcap.capval;
963 	return (error);
964 }
965 
966 int
967 vm_set_capability(struct vcpu *vcpu, enum vm_cap_type cap, int val)
968 {
969 	struct vm_capability vmcap;
970 
971 	bzero(&vmcap, sizeof(vmcap));
972 	vmcap.captype = cap;
973 	vmcap.capval = val;
974 
975 	return (vcpu_ioctl(vcpu, VM_SET_CAPABILITY, &vmcap));
976 }
977 
978 int
979 vm_assign_pptdev(struct vmctx *ctx, int bus, int slot, int func)
980 {
981 	struct vm_pptdev pptdev;
982 
983 	bzero(&pptdev, sizeof(pptdev));
984 	pptdev.bus = bus;
985 	pptdev.slot = slot;
986 	pptdev.func = func;
987 
988 	return (ioctl(ctx->fd, VM_BIND_PPTDEV, &pptdev));
989 }
990 
991 int
992 vm_unassign_pptdev(struct vmctx *ctx, int bus, int slot, int func)
993 {
994 	struct vm_pptdev pptdev;
995 
996 	bzero(&pptdev, sizeof(pptdev));
997 	pptdev.bus = bus;
998 	pptdev.slot = slot;
999 	pptdev.func = func;
1000 
1001 	return (ioctl(ctx->fd, VM_UNBIND_PPTDEV, &pptdev));
1002 }
1003 
1004 int
1005 vm_map_pptdev_mmio(struct vmctx *ctx, int bus, int slot, int func,
1006 		   vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
1007 {
1008 	struct vm_pptdev_mmio pptmmio;
1009 
1010 	bzero(&pptmmio, sizeof(pptmmio));
1011 	pptmmio.bus = bus;
1012 	pptmmio.slot = slot;
1013 	pptmmio.func = func;
1014 	pptmmio.gpa = gpa;
1015 	pptmmio.len = len;
1016 	pptmmio.hpa = hpa;
1017 
1018 	return (ioctl(ctx->fd, VM_MAP_PPTDEV_MMIO, &pptmmio));
1019 }
1020 
1021 int
1022 vm_unmap_pptdev_mmio(struct vmctx *ctx, int bus, int slot, int func,
1023 		     vm_paddr_t gpa, size_t len)
1024 {
1025 	struct vm_pptdev_mmio pptmmio;
1026 
1027 	bzero(&pptmmio, sizeof(pptmmio));
1028 	pptmmio.bus = bus;
1029 	pptmmio.slot = slot;
1030 	pptmmio.func = func;
1031 	pptmmio.gpa = gpa;
1032 	pptmmio.len = len;
1033 
1034 	return (ioctl(ctx->fd, VM_UNMAP_PPTDEV_MMIO, &pptmmio));
1035 }
1036 
1037 int
1038 vm_setup_pptdev_msi(struct vmctx *ctx, int bus, int slot, int func,
1039     uint64_t addr, uint64_t msg, int numvec)
1040 {
1041 	struct vm_pptdev_msi pptmsi;
1042 
1043 	bzero(&pptmsi, sizeof(pptmsi));
1044 	pptmsi.bus = bus;
1045 	pptmsi.slot = slot;
1046 	pptmsi.func = func;
1047 	pptmsi.msg = msg;
1048 	pptmsi.addr = addr;
1049 	pptmsi.numvec = numvec;
1050 
1051 	return (ioctl(ctx->fd, VM_PPTDEV_MSI, &pptmsi));
1052 }
1053 
1054 int
1055 vm_setup_pptdev_msix(struct vmctx *ctx, int bus, int slot, int func,
1056     int idx, uint64_t addr, uint64_t msg, uint32_t vector_control)
1057 {
1058 	struct vm_pptdev_msix pptmsix;
1059 
1060 	bzero(&pptmsix, sizeof(pptmsix));
1061 	pptmsix.bus = bus;
1062 	pptmsix.slot = slot;
1063 	pptmsix.func = func;
1064 	pptmsix.idx = idx;
1065 	pptmsix.msg = msg;
1066 	pptmsix.addr = addr;
1067 	pptmsix.vector_control = vector_control;
1068 
1069 	return ioctl(ctx->fd, VM_PPTDEV_MSIX, &pptmsix);
1070 }
1071 
1072 int
1073 vm_disable_pptdev_msix(struct vmctx *ctx, int bus, int slot, int func)
1074 {
1075 	struct vm_pptdev ppt;
1076 
1077 	bzero(&ppt, sizeof(ppt));
1078 	ppt.bus = bus;
1079 	ppt.slot = slot;
1080 	ppt.func = func;
1081 
1082 	return ioctl(ctx->fd, VM_PPTDEV_DISABLE_MSIX, &ppt);
1083 }
1084 
1085 uint64_t *
1086 vm_get_stats(struct vcpu *vcpu, struct timeval *ret_tv,
1087 	     int *ret_entries)
1088 {
1089 	static _Thread_local uint64_t *stats_buf;
1090 	static _Thread_local u_int stats_count;
1091 	uint64_t *new_stats;
1092 	struct vm_stats vmstats;
1093 	u_int count, index;
1094 	bool have_stats;
1095 
1096 	have_stats = false;
1097 	count = 0;
1098 	for (index = 0;; index += nitems(vmstats.statbuf)) {
1099 		vmstats.index = index;
1100 		if (vcpu_ioctl(vcpu, VM_STATS, &vmstats) != 0)
1101 			break;
1102 		if (stats_count < index + vmstats.num_entries) {
1103 			new_stats = realloc(stats_buf,
1104 			    (index + vmstats.num_entries) * sizeof(uint64_t));
1105 			if (new_stats == NULL) {
1106 				errno = ENOMEM;
1107 				return (NULL);
1108 			}
1109 			stats_count = index + vmstats.num_entries;
1110 			stats_buf = new_stats;
1111 		}
1112 		memcpy(stats_buf + index, vmstats.statbuf,
1113 		    vmstats.num_entries * sizeof(uint64_t));
1114 		count += vmstats.num_entries;
1115 		have_stats = true;
1116 
1117 		if (vmstats.num_entries != nitems(vmstats.statbuf))
1118 			break;
1119 	}
1120 	if (have_stats) {
1121 		if (ret_entries)
1122 			*ret_entries = count;
1123 		if (ret_tv)
1124 			*ret_tv = vmstats.tv;
1125 		return (stats_buf);
1126 	} else
1127 		return (NULL);
1128 }
1129 
1130 const char *
1131 vm_get_stat_desc(struct vmctx *ctx, int index)
1132 {
1133 	static struct vm_stat_desc statdesc;
1134 
1135 	statdesc.index = index;
1136 	if (ioctl(ctx->fd, VM_STAT_DESC, &statdesc) == 0)
1137 		return (statdesc.desc);
1138 	else
1139 		return (NULL);
1140 }
1141 
1142 int
1143 vm_get_x2apic_state(struct vcpu *vcpu, enum x2apic_state *state)
1144 {
1145 	int error;
1146 	struct vm_x2apic x2apic;
1147 
1148 	bzero(&x2apic, sizeof(x2apic));
1149 
1150 	error = vcpu_ioctl(vcpu, VM_GET_X2APIC_STATE, &x2apic);
1151 	*state = x2apic.state;
1152 	return (error);
1153 }
1154 
1155 int
1156 vm_set_x2apic_state(struct vcpu *vcpu, enum x2apic_state state)
1157 {
1158 	int error;
1159 	struct vm_x2apic x2apic;
1160 
1161 	bzero(&x2apic, sizeof(x2apic));
1162 	x2apic.state = state;
1163 
1164 	error = vcpu_ioctl(vcpu, VM_SET_X2APIC_STATE, &x2apic);
1165 
1166 	return (error);
1167 }
1168 
1169 /*
1170  * From Intel Vol 3a:
1171  * Table 9-1. IA-32 Processor States Following Power-up, Reset or INIT
1172  */
1173 int
1174 vcpu_reset(struct vcpu *vcpu)
1175 {
1176 	int error;
1177 	uint64_t rflags, rip, cr0, cr4, zero, desc_base, rdx;
1178 	uint32_t desc_access, desc_limit;
1179 	uint16_t sel;
1180 
1181 	zero = 0;
1182 
1183 	rflags = 0x2;
1184 	error = vm_set_register(vcpu, VM_REG_GUEST_RFLAGS, rflags);
1185 	if (error)
1186 		goto done;
1187 
1188 	rip = 0xfff0;
1189 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_RIP, rip)) != 0)
1190 		goto done;
1191 
1192 	/*
1193 	 * According to Intels Software Developer Manual CR0 should be
1194 	 * initialized with CR0_ET | CR0_NW | CR0_CD but that crashes some
1195 	 * guests like Windows.
1196 	 */
1197 	cr0 = CR0_NE;
1198 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_CR0, cr0)) != 0)
1199 		goto done;
1200 
1201 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_CR2, zero)) != 0)
1202 		goto done;
1203 
1204 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_CR3, zero)) != 0)
1205 		goto done;
1206 
1207 	cr4 = 0;
1208 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_CR4, cr4)) != 0)
1209 		goto done;
1210 
1211 	/*
1212 	 * CS: present, r/w, accessed, 16-bit, byte granularity, usable
1213 	 */
1214 	desc_base = 0xffff0000;
1215 	desc_limit = 0xffff;
1216 	desc_access = 0x0093;
1217 	error = vm_set_desc(vcpu, VM_REG_GUEST_CS,
1218 			    desc_base, desc_limit, desc_access);
1219 	if (error)
1220 		goto done;
1221 
1222 	sel = 0xf000;
1223 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_CS, sel)) != 0)
1224 		goto done;
1225 
1226 	/*
1227 	 * SS,DS,ES,FS,GS: present, r/w, accessed, 16-bit, byte granularity
1228 	 */
1229 	desc_base = 0;
1230 	desc_limit = 0xffff;
1231 	desc_access = 0x0093;
1232 	error = vm_set_desc(vcpu, VM_REG_GUEST_SS,
1233 			    desc_base, desc_limit, desc_access);
1234 	if (error)
1235 		goto done;
1236 
1237 	error = vm_set_desc(vcpu, VM_REG_GUEST_DS,
1238 			    desc_base, desc_limit, desc_access);
1239 	if (error)
1240 		goto done;
1241 
1242 	error = vm_set_desc(vcpu, VM_REG_GUEST_ES,
1243 			    desc_base, desc_limit, desc_access);
1244 	if (error)
1245 		goto done;
1246 
1247 	error = vm_set_desc(vcpu, VM_REG_GUEST_FS,
1248 			    desc_base, desc_limit, desc_access);
1249 	if (error)
1250 		goto done;
1251 
1252 	error = vm_set_desc(vcpu, VM_REG_GUEST_GS,
1253 			    desc_base, desc_limit, desc_access);
1254 	if (error)
1255 		goto done;
1256 
1257 	sel = 0;
1258 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_SS, sel)) != 0)
1259 		goto done;
1260 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_DS, sel)) != 0)
1261 		goto done;
1262 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_ES, sel)) != 0)
1263 		goto done;
1264 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_FS, sel)) != 0)
1265 		goto done;
1266 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_GS, sel)) != 0)
1267 		goto done;
1268 
1269 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_EFER, zero)) != 0)
1270 		goto done;
1271 
1272 	/* General purpose registers */
1273 	rdx = 0xf00;
1274 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_RAX, zero)) != 0)
1275 		goto done;
1276 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_RBX, zero)) != 0)
1277 		goto done;
1278 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_RCX, zero)) != 0)
1279 		goto done;
1280 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_RDX, rdx)) != 0)
1281 		goto done;
1282 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_RSI, zero)) != 0)
1283 		goto done;
1284 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_RDI, zero)) != 0)
1285 		goto done;
1286 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_RBP, zero)) != 0)
1287 		goto done;
1288 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_RSP, zero)) != 0)
1289 		goto done;
1290 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_R8, zero)) != 0)
1291 		goto done;
1292 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_R9, zero)) != 0)
1293 		goto done;
1294 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_R10, zero)) != 0)
1295 		goto done;
1296 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_R11, zero)) != 0)
1297 		goto done;
1298 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_R12, zero)) != 0)
1299 		goto done;
1300 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_R13, zero)) != 0)
1301 		goto done;
1302 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_R14, zero)) != 0)
1303 		goto done;
1304 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_R15, zero)) != 0)
1305 		goto done;
1306 
1307 	/* GDTR, IDTR */
1308 	desc_base = 0;
1309 	desc_limit = 0xffff;
1310 	desc_access = 0;
1311 	error = vm_set_desc(vcpu, VM_REG_GUEST_GDTR,
1312 			    desc_base, desc_limit, desc_access);
1313 	if (error != 0)
1314 		goto done;
1315 
1316 	error = vm_set_desc(vcpu, VM_REG_GUEST_IDTR,
1317 			    desc_base, desc_limit, desc_access);
1318 	if (error != 0)
1319 		goto done;
1320 
1321 	/* TR */
1322 	desc_base = 0;
1323 	desc_limit = 0xffff;
1324 	desc_access = 0x0000008b;
1325 	error = vm_set_desc(vcpu, VM_REG_GUEST_TR, 0, 0, desc_access);
1326 	if (error)
1327 		goto done;
1328 
1329 	sel = 0;
1330 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_TR, sel)) != 0)
1331 		goto done;
1332 
1333 	/* LDTR */
1334 	desc_base = 0;
1335 	desc_limit = 0xffff;
1336 	desc_access = 0x00000082;
1337 	error = vm_set_desc(vcpu, VM_REG_GUEST_LDTR, desc_base,
1338 			    desc_limit, desc_access);
1339 	if (error)
1340 		goto done;
1341 
1342 	sel = 0;
1343 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_LDTR, 0)) != 0)
1344 		goto done;
1345 
1346 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_DR6,
1347 		 0xffff0ff0)) != 0)
1348 		goto done;
1349 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_DR7, 0x400)) !=
1350 	    0)
1351 		goto done;
1352 
1353 	if ((error = vm_set_register(vcpu, VM_REG_GUEST_INTR_SHADOW,
1354 		 zero)) != 0)
1355 		goto done;
1356 
1357 	error = 0;
1358 done:
1359 	return (error);
1360 }
1361 
1362 int
1363 vm_get_gpa_pmap(struct vmctx *ctx, uint64_t gpa, uint64_t *pte, int *num)
1364 {
1365 	int error, i;
1366 	struct vm_gpa_pte gpapte;
1367 
1368 	bzero(&gpapte, sizeof(gpapte));
1369 	gpapte.gpa = gpa;
1370 
1371 	error = ioctl(ctx->fd, VM_GET_GPA_PMAP, &gpapte);
1372 
1373 	if (error == 0) {
1374 		*num = gpapte.ptenum;
1375 		for (i = 0; i < gpapte.ptenum; i++)
1376 			pte[i] = gpapte.pte[i];
1377 	}
1378 
1379 	return (error);
1380 }
1381 
1382 int
1383 vm_get_hpet_capabilities(struct vmctx *ctx, uint32_t *capabilities)
1384 {
1385 	int error;
1386 	struct vm_hpet_cap cap;
1387 
1388 	bzero(&cap, sizeof(struct vm_hpet_cap));
1389 	error = ioctl(ctx->fd, VM_GET_HPET_CAPABILITIES, &cap);
1390 	if (capabilities != NULL)
1391 		*capabilities = cap.capabilities;
1392 	return (error);
1393 }
1394 
1395 int
1396 vm_gla2gpa(struct vcpu *vcpu, struct vm_guest_paging *paging,
1397     uint64_t gla, int prot, uint64_t *gpa, int *fault)
1398 {
1399 	struct vm_gla2gpa gg;
1400 	int error;
1401 
1402 	bzero(&gg, sizeof(struct vm_gla2gpa));
1403 	gg.prot = prot;
1404 	gg.gla = gla;
1405 	gg.paging = *paging;
1406 
1407 	error = vcpu_ioctl(vcpu, VM_GLA2GPA, &gg);
1408 	if (error == 0) {
1409 		*fault = gg.fault;
1410 		*gpa = gg.gpa;
1411 	}
1412 	return (error);
1413 }
1414 
1415 int
1416 vm_gla2gpa_nofault(struct vcpu *vcpu, struct vm_guest_paging *paging,
1417     uint64_t gla, int prot, uint64_t *gpa, int *fault)
1418 {
1419 	struct vm_gla2gpa gg;
1420 	int error;
1421 
1422 	bzero(&gg, sizeof(struct vm_gla2gpa));
1423 	gg.prot = prot;
1424 	gg.gla = gla;
1425 	gg.paging = *paging;
1426 
1427 	error = vcpu_ioctl(vcpu, VM_GLA2GPA_NOFAULT, &gg);
1428 	if (error == 0) {
1429 		*fault = gg.fault;
1430 		*gpa = gg.gpa;
1431 	}
1432 	return (error);
1433 }
1434 
1435 #ifndef min
1436 #define	min(a,b)	(((a) < (b)) ? (a) : (b))
1437 #endif
1438 
1439 int
1440 vm_copy_setup(struct vcpu *vcpu, struct vm_guest_paging *paging,
1441     uint64_t gla, size_t len, int prot, struct iovec *iov, int iovcnt,
1442     int *fault)
1443 {
1444 	void *va;
1445 	uint64_t gpa, off;
1446 	int error, i, n;
1447 
1448 	for (i = 0; i < iovcnt; i++) {
1449 		iov[i].iov_base = 0;
1450 		iov[i].iov_len = 0;
1451 	}
1452 
1453 	while (len) {
1454 		assert(iovcnt > 0);
1455 		error = vm_gla2gpa(vcpu, paging, gla, prot, &gpa, fault);
1456 		if (error || *fault)
1457 			return (error);
1458 
1459 		off = gpa & PAGE_MASK;
1460 		n = MIN(len, PAGE_SIZE - off);
1461 
1462 		va = vm_map_gpa(vcpu->ctx, gpa, n);
1463 		if (va == NULL)
1464 			return (EFAULT);
1465 
1466 		iov->iov_base = va;
1467 		iov->iov_len = n;
1468 		iov++;
1469 		iovcnt--;
1470 
1471 		gla += n;
1472 		len -= n;
1473 	}
1474 	return (0);
1475 }
1476 
1477 void
1478 vm_copy_teardown(struct iovec *iov __unused, int iovcnt __unused)
1479 {
1480 	/*
1481 	 * Intentionally empty.  This is used by the instruction
1482 	 * emulation code shared with the kernel.  The in-kernel
1483 	 * version of this is non-empty.
1484 	 */
1485 }
1486 
1487 void
1488 vm_copyin(struct iovec *iov, void *vp, size_t len)
1489 {
1490 	const char *src;
1491 	char *dst;
1492 	size_t n;
1493 
1494 	dst = vp;
1495 	while (len) {
1496 		assert(iov->iov_len);
1497 		n = min(len, iov->iov_len);
1498 		src = iov->iov_base;
1499 		bcopy(src, dst, n);
1500 
1501 		iov++;
1502 		dst += n;
1503 		len -= n;
1504 	}
1505 }
1506 
1507 void
1508 vm_copyout(const void *vp, struct iovec *iov, size_t len)
1509 {
1510 	const char *src;
1511 	char *dst;
1512 	size_t n;
1513 
1514 	src = vp;
1515 	while (len) {
1516 		assert(iov->iov_len);
1517 		n = min(len, iov->iov_len);
1518 		dst = iov->iov_base;
1519 		bcopy(src, dst, n);
1520 
1521 		iov++;
1522 		src += n;
1523 		len -= n;
1524 	}
1525 }
1526 
1527 static int
1528 vm_get_cpus(struct vmctx *ctx, int which, cpuset_t *cpus)
1529 {
1530 	struct vm_cpuset vm_cpuset;
1531 	int error;
1532 
1533 	bzero(&vm_cpuset, sizeof(struct vm_cpuset));
1534 	vm_cpuset.which = which;
1535 	vm_cpuset.cpusetsize = sizeof(cpuset_t);
1536 	vm_cpuset.cpus = cpus;
1537 
1538 	error = ioctl(ctx->fd, VM_GET_CPUS, &vm_cpuset);
1539 	return (error);
1540 }
1541 
1542 int
1543 vm_active_cpus(struct vmctx *ctx, cpuset_t *cpus)
1544 {
1545 
1546 	return (vm_get_cpus(ctx, VM_ACTIVE_CPUS, cpus));
1547 }
1548 
1549 int
1550 vm_suspended_cpus(struct vmctx *ctx, cpuset_t *cpus)
1551 {
1552 
1553 	return (vm_get_cpus(ctx, VM_SUSPENDED_CPUS, cpus));
1554 }
1555 
1556 int
1557 vm_debug_cpus(struct vmctx *ctx, cpuset_t *cpus)
1558 {
1559 
1560 	return (vm_get_cpus(ctx, VM_DEBUG_CPUS, cpus));
1561 }
1562 
1563 int
1564 vm_activate_cpu(struct vcpu *vcpu)
1565 {
1566 	struct vm_activate_cpu ac;
1567 	int error;
1568 
1569 	bzero(&ac, sizeof(struct vm_activate_cpu));
1570 	error = vcpu_ioctl(vcpu, VM_ACTIVATE_CPU, &ac);
1571 	return (error);
1572 }
1573 
1574 int
1575 vm_suspend_all_cpus(struct vmctx *ctx)
1576 {
1577 	struct vm_activate_cpu ac;
1578 	int error;
1579 
1580 	bzero(&ac, sizeof(struct vm_activate_cpu));
1581 	ac.vcpuid = -1;
1582 	error = ioctl(ctx->fd, VM_SUSPEND_CPU, &ac);
1583 	return (error);
1584 }
1585 
1586 int
1587 vm_suspend_cpu(struct vcpu *vcpu)
1588 {
1589 	struct vm_activate_cpu ac;
1590 	int error;
1591 
1592 	bzero(&ac, sizeof(struct vm_activate_cpu));
1593 	error = vcpu_ioctl(vcpu, VM_SUSPEND_CPU, &ac);
1594 	return (error);
1595 }
1596 
1597 int
1598 vm_resume_cpu(struct vcpu *vcpu)
1599 {
1600 	struct vm_activate_cpu ac;
1601 	int error;
1602 
1603 	bzero(&ac, sizeof(struct vm_activate_cpu));
1604 	error = vcpu_ioctl(vcpu, VM_RESUME_CPU, &ac);
1605 	return (error);
1606 }
1607 
1608 int
1609 vm_resume_all_cpus(struct vmctx *ctx)
1610 {
1611 	struct vm_activate_cpu ac;
1612 	int error;
1613 
1614 	bzero(&ac, sizeof(struct vm_activate_cpu));
1615 	ac.vcpuid = -1;
1616 	error = ioctl(ctx->fd, VM_RESUME_CPU, &ac);
1617 	return (error);
1618 }
1619 
1620 int
1621 vm_get_intinfo(struct vcpu *vcpu, uint64_t *info1, uint64_t *info2)
1622 {
1623 	struct vm_intinfo vmii;
1624 	int error;
1625 
1626 	bzero(&vmii, sizeof(struct vm_intinfo));
1627 	error = vcpu_ioctl(vcpu, VM_GET_INTINFO, &vmii);
1628 	if (error == 0) {
1629 		*info1 = vmii.info1;
1630 		*info2 = vmii.info2;
1631 	}
1632 	return (error);
1633 }
1634 
1635 int
1636 vm_set_intinfo(struct vcpu *vcpu, uint64_t info1)
1637 {
1638 	struct vm_intinfo vmii;
1639 	int error;
1640 
1641 	bzero(&vmii, sizeof(struct vm_intinfo));
1642 	vmii.info1 = info1;
1643 	error = vcpu_ioctl(vcpu, VM_SET_INTINFO, &vmii);
1644 	return (error);
1645 }
1646 
1647 int
1648 vm_rtc_write(struct vmctx *ctx, int offset, uint8_t value)
1649 {
1650 	struct vm_rtc_data rtcdata;
1651 	int error;
1652 
1653 	bzero(&rtcdata, sizeof(struct vm_rtc_data));
1654 	rtcdata.offset = offset;
1655 	rtcdata.value = value;
1656 	error = ioctl(ctx->fd, VM_RTC_WRITE, &rtcdata);
1657 	return (error);
1658 }
1659 
1660 int
1661 vm_rtc_read(struct vmctx *ctx, int offset, uint8_t *retval)
1662 {
1663 	struct vm_rtc_data rtcdata;
1664 	int error;
1665 
1666 	bzero(&rtcdata, sizeof(struct vm_rtc_data));
1667 	rtcdata.offset = offset;
1668 	error = ioctl(ctx->fd, VM_RTC_READ, &rtcdata);
1669 	if (error == 0)
1670 		*retval = rtcdata.value;
1671 	return (error);
1672 }
1673 
1674 int
1675 vm_rtc_settime(struct vmctx *ctx, time_t secs)
1676 {
1677 	struct vm_rtc_time rtctime;
1678 	int error;
1679 
1680 	bzero(&rtctime, sizeof(struct vm_rtc_time));
1681 	rtctime.secs = secs;
1682 	error = ioctl(ctx->fd, VM_RTC_SETTIME, &rtctime);
1683 	return (error);
1684 }
1685 
1686 int
1687 vm_rtc_gettime(struct vmctx *ctx, time_t *secs)
1688 {
1689 	struct vm_rtc_time rtctime;
1690 	int error;
1691 
1692 	bzero(&rtctime, sizeof(struct vm_rtc_time));
1693 	error = ioctl(ctx->fd, VM_RTC_GETTIME, &rtctime);
1694 	if (error == 0)
1695 		*secs = rtctime.secs;
1696 	return (error);
1697 }
1698 
1699 int
1700 vm_restart_instruction(struct vcpu *vcpu)
1701 {
1702 	int arg;
1703 
1704 	return (vcpu_ioctl(vcpu, VM_RESTART_INSTRUCTION, &arg));
1705 }
1706 
1707 int
1708 vm_snapshot_req(struct vmctx *ctx, struct vm_snapshot_meta *meta)
1709 {
1710 
1711 	if (ioctl(ctx->fd, VM_SNAPSHOT_REQ, meta) == -1) {
1712 #ifdef SNAPSHOT_DEBUG
1713 		fprintf(stderr, "%s: snapshot failed for %s: %d\r\n",
1714 		    __func__, meta->dev_name, errno);
1715 #endif
1716 		return (-1);
1717 	}
1718 	return (0);
1719 }
1720 
1721 int
1722 vm_restore_time(struct vmctx *ctx)
1723 {
1724 	int dummy;
1725 
1726 	dummy = 0;
1727 	return (ioctl(ctx->fd, VM_RESTORE_TIME, &dummy));
1728 }
1729 
1730 int
1731 vm_set_topology(struct vmctx *ctx,
1732     uint16_t sockets, uint16_t cores, uint16_t threads, uint16_t maxcpus)
1733 {
1734 	struct vm_cpu_topology topology;
1735 
1736 	bzero(&topology, sizeof (struct vm_cpu_topology));
1737 	topology.sockets = sockets;
1738 	topology.cores = cores;
1739 	topology.threads = threads;
1740 	topology.maxcpus = maxcpus;
1741 	return (ioctl(ctx->fd, VM_SET_TOPOLOGY, &topology));
1742 }
1743 
1744 int
1745 vm_get_topology(struct vmctx *ctx,
1746     uint16_t *sockets, uint16_t *cores, uint16_t *threads, uint16_t *maxcpus)
1747 {
1748 	struct vm_cpu_topology topology;
1749 	int error;
1750 
1751 	bzero(&topology, sizeof (struct vm_cpu_topology));
1752 	error = ioctl(ctx->fd, VM_GET_TOPOLOGY, &topology);
1753 	if (error == 0) {
1754 		*sockets = topology.sockets;
1755 		*cores = topology.cores;
1756 		*threads = topology.threads;
1757 		*maxcpus = topology.maxcpus;
1758 	}
1759 	return (error);
1760 }
1761 
1762 /* Keep in sync with machine/vmm_dev.h. */
1763 static const cap_ioctl_t vm_ioctl_cmds[] = { VM_RUN, VM_SUSPEND, VM_REINIT,
1764     VM_ALLOC_MEMSEG, VM_GET_MEMSEG, VM_MMAP_MEMSEG, VM_MMAP_MEMSEG,
1765     VM_MMAP_GETNEXT, VM_MUNMAP_MEMSEG, VM_SET_REGISTER, VM_GET_REGISTER,
1766     VM_SET_SEGMENT_DESCRIPTOR, VM_GET_SEGMENT_DESCRIPTOR,
1767     VM_SET_REGISTER_SET, VM_GET_REGISTER_SET,
1768     VM_SET_KERNEMU_DEV, VM_GET_KERNEMU_DEV,
1769     VM_INJECT_EXCEPTION, VM_LAPIC_IRQ, VM_LAPIC_LOCAL_IRQ,
1770     VM_LAPIC_MSI, VM_IOAPIC_ASSERT_IRQ, VM_IOAPIC_DEASSERT_IRQ,
1771     VM_IOAPIC_PULSE_IRQ, VM_IOAPIC_PINCOUNT, VM_ISA_ASSERT_IRQ,
1772     VM_ISA_DEASSERT_IRQ, VM_ISA_PULSE_IRQ, VM_ISA_SET_IRQ_TRIGGER,
1773     VM_SET_CAPABILITY, VM_GET_CAPABILITY, VM_BIND_PPTDEV,
1774     VM_UNBIND_PPTDEV, VM_MAP_PPTDEV_MMIO, VM_PPTDEV_MSI,
1775     VM_PPTDEV_MSIX, VM_UNMAP_PPTDEV_MMIO, VM_PPTDEV_DISABLE_MSIX,
1776     VM_INJECT_NMI, VM_STATS, VM_STAT_DESC,
1777     VM_SET_X2APIC_STATE, VM_GET_X2APIC_STATE,
1778     VM_GET_HPET_CAPABILITIES, VM_GET_GPA_PMAP, VM_GLA2GPA,
1779     VM_GLA2GPA_NOFAULT,
1780     VM_ACTIVATE_CPU, VM_GET_CPUS, VM_SUSPEND_CPU, VM_RESUME_CPU,
1781     VM_SET_INTINFO, VM_GET_INTINFO,
1782     VM_RTC_WRITE, VM_RTC_READ, VM_RTC_SETTIME, VM_RTC_GETTIME,
1783     VM_RESTART_INSTRUCTION, VM_SET_TOPOLOGY, VM_GET_TOPOLOGY,
1784     VM_SNAPSHOT_REQ, VM_RESTORE_TIME
1785 };
1786 
1787 int
1788 vm_limit_rights(struct vmctx *ctx)
1789 {
1790 	cap_rights_t rights;
1791 	size_t ncmds;
1792 
1793 	cap_rights_init(&rights, CAP_IOCTL, CAP_MMAP_RW);
1794 	if (caph_rights_limit(ctx->fd, &rights) != 0)
1795 		return (-1);
1796 	ncmds = nitems(vm_ioctl_cmds);
1797 	if (caph_ioctls_limit(ctx->fd, vm_ioctl_cmds, ncmds) != 0)
1798 		return (-1);
1799 	return (0);
1800 }
1801 
1802 /*
1803  * Avoid using in new code.  Operations on the fd should be wrapped here so that
1804  * capability rights can be kept in sync.
1805  */
1806 int
1807 vm_get_device_fd(struct vmctx *ctx)
1808 {
1809 
1810 	return (ctx->fd);
1811 }
1812 
1813 /* Legacy interface, do not use. */
1814 const cap_ioctl_t *
1815 vm_get_ioctls(size_t *len)
1816 {
1817 	cap_ioctl_t *cmds;
1818 
1819 	if (len == NULL) {
1820 		cmds = malloc(sizeof(vm_ioctl_cmds));
1821 		if (cmds == NULL)
1822 			return (NULL);
1823 		bcopy(vm_ioctl_cmds, cmds, sizeof(vm_ioctl_cmds));
1824 		return (cmds);
1825 	}
1826 
1827 	*len = nitems(vm_ioctl_cmds);
1828 	return (NULL);
1829 }
1830