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