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