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