xref: /freebsd/sys/amd64/vmm/vmm.c (revision 7937bfbc0ca53fe7cdd0d54414f9296e273a518e)
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/cdefs.h>
30 #include "opt_bhyve_snapshot.h"
31 
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/module.h>
36 #include <sys/sysctl.h>
37 #include <sys/malloc.h>
38 #include <sys/pcpu.h>
39 #include <sys/lock.h>
40 #include <sys/mutex.h>
41 #include <sys/proc.h>
42 #include <sys/rwlock.h>
43 #include <sys/sched.h>
44 #include <sys/smp.h>
45 #include <sys/sx.h>
46 #include <sys/vnode.h>
47 
48 #include <vm/vm.h>
49 #include <vm/vm_param.h>
50 #include <vm/vm_extern.h>
51 #include <vm/vm_object.h>
52 #include <vm/vm_page.h>
53 #include <vm/pmap.h>
54 #include <vm/vm_map.h>
55 #include <vm/vm_pager.h>
56 #include <vm/vm_kern.h>
57 #include <vm/vnode_pager.h>
58 #include <vm/swap_pager.h>
59 #include <vm/uma.h>
60 
61 #include <machine/cpu.h>
62 #include <machine/pcb.h>
63 #include <machine/smp.h>
64 #include <machine/md_var.h>
65 #include <x86/psl.h>
66 #include <x86/apicreg.h>
67 #include <x86/ifunc.h>
68 
69 #include <machine/vmm.h>
70 #include <machine/vmm_instruction_emul.h>
71 #include <machine/vmm_snapshot.h>
72 
73 #include <dev/vmm/vmm_dev.h>
74 #include <dev/vmm/vmm_ktr.h>
75 
76 #include "vmm_ioport.h"
77 #include "vmm_host.h"
78 #include "vmm_mem.h"
79 #include "vmm_util.h"
80 #include "vatpic.h"
81 #include "vatpit.h"
82 #include "vhpet.h"
83 #include "vioapic.h"
84 #include "vlapic.h"
85 #include "vpmtmr.h"
86 #include "vrtc.h"
87 #include "vmm_stat.h"
88 #include "vmm_lapic.h"
89 
90 #include "io/ppt.h"
91 #include "io/iommu.h"
92 
93 struct vlapic;
94 
95 /*
96  * Initialization:
97  * (a) allocated when vcpu is created
98  * (i) initialized when vcpu is created and when it is reinitialized
99  * (o) initialized the first time the vcpu is created
100  * (x) initialized before use
101  */
102 struct vcpu {
103 	struct mtx 	mtx;		/* (o) protects 'state' and 'hostcpu' */
104 	enum vcpu_state	state;		/* (o) vcpu state */
105 	int		vcpuid;		/* (o) */
106 	int		hostcpu;	/* (o) vcpu's host cpu */
107 	int		reqidle;	/* (i) request vcpu to idle */
108 	struct vm	*vm;		/* (o) */
109 	void		*cookie;	/* (i) cpu-specific data */
110 	struct vlapic	*vlapic;	/* (i) APIC device model */
111 	enum x2apic_state x2apic_state;	/* (i) APIC mode */
112 	uint64_t	exitintinfo;	/* (i) events pending at VM exit */
113 	int		nmi_pending;	/* (i) NMI pending */
114 	int		extint_pending;	/* (i) INTR pending */
115 	int	exception_pending;	/* (i) exception pending */
116 	int	exc_vector;		/* (x) exception collateral */
117 	int	exc_errcode_valid;
118 	uint32_t exc_errcode;
119 	struct savefpu	*guestfpu;	/* (a,i) guest fpu state */
120 	uint64_t	guest_xcr0;	/* (i) guest %xcr0 register */
121 	void		*stats;		/* (a,i) statistics */
122 	struct vm_exit	exitinfo;	/* (x) exit reason and collateral */
123 	cpuset_t	exitinfo_cpuset; /* (x) storage for vmexit handlers */
124 	uint64_t	nextrip;	/* (x) next instruction to execute */
125 	uint64_t	tsc_offset;	/* (o) TSC offsetting */
126 };
127 
128 #define	vcpu_lock_init(v)	mtx_init(&((v)->mtx), "vcpu lock", 0, MTX_SPIN)
129 #define	vcpu_lock_destroy(v)	mtx_destroy(&((v)->mtx))
130 #define	vcpu_lock(v)		mtx_lock_spin(&((v)->mtx))
131 #define	vcpu_unlock(v)		mtx_unlock_spin(&((v)->mtx))
132 #define	vcpu_assert_locked(v)	mtx_assert(&((v)->mtx), MA_OWNED)
133 
134 struct mem_seg {
135 	size_t	len;
136 	bool	sysmem;
137 	struct vm_object *object;
138 };
139 #define	VM_MAX_MEMSEGS	4
140 
141 struct mem_map {
142 	vm_paddr_t	gpa;
143 	size_t		len;
144 	vm_ooffset_t	segoff;
145 	int		segid;
146 	int		prot;
147 	int		flags;
148 };
149 #define	VM_MAX_MEMMAPS	8
150 
151 /*
152  * Initialization:
153  * (o) initialized the first time the VM is created
154  * (i) initialized when VM is created and when it is reinitialized
155  * (x) initialized before use
156  *
157  * Locking:
158  * [m] mem_segs_lock
159  * [r] rendezvous_mtx
160  * [v] reads require one frozen vcpu, writes require freezing all vcpus
161  */
162 struct vm {
163 	void		*cookie;		/* (i) cpu-specific data */
164 	void		*iommu;			/* (x) iommu-specific data */
165 	struct vhpet	*vhpet;			/* (i) virtual HPET */
166 	struct vioapic	*vioapic;		/* (i) virtual ioapic */
167 	struct vatpic	*vatpic;		/* (i) virtual atpic */
168 	struct vatpit	*vatpit;		/* (i) virtual atpit */
169 	struct vpmtmr	*vpmtmr;		/* (i) virtual ACPI PM timer */
170 	struct vrtc	*vrtc;			/* (o) virtual RTC */
171 	volatile cpuset_t active_cpus;		/* (i) active vcpus */
172 	volatile cpuset_t debug_cpus;		/* (i) vcpus stopped for debug */
173 	cpuset_t	startup_cpus;		/* (i) [r] waiting for startup */
174 	int		suspend;		/* (i) stop VM execution */
175 	bool		dying;			/* (o) is dying */
176 	volatile cpuset_t suspended_cpus; 	/* (i) suspended vcpus */
177 	volatile cpuset_t halted_cpus;		/* (x) cpus in a hard halt */
178 	cpuset_t	rendezvous_req_cpus;	/* (x) [r] rendezvous requested */
179 	cpuset_t	rendezvous_done_cpus;	/* (x) [r] rendezvous finished */
180 	void		*rendezvous_arg;	/* (x) [r] rendezvous func/arg */
181 	vm_rendezvous_func_t rendezvous_func;
182 	struct mtx	rendezvous_mtx;		/* (o) rendezvous lock */
183 	struct mem_map	mem_maps[VM_MAX_MEMMAPS]; /* (i) [m+v] guest address space */
184 	struct mem_seg	mem_segs[VM_MAX_MEMSEGS]; /* (o) [m+v] guest memory regions */
185 	struct vmspace	*vmspace;		/* (o) guest's address space */
186 	char		name[VM_MAX_NAMELEN+1];	/* (o) virtual machine name */
187 	struct vcpu	**vcpu;			/* (o) guest vcpus */
188 	/* The following describe the vm cpu topology */
189 	uint16_t	sockets;		/* (o) num of sockets */
190 	uint16_t	cores;			/* (o) num of cores/socket */
191 	uint16_t	threads;		/* (o) num of threads/core */
192 	uint16_t	maxcpus;		/* (o) max pluggable cpus */
193 	struct sx	mem_segs_lock;		/* (o) */
194 	struct sx	vcpus_init_lock;	/* (o) */
195 };
196 
197 #define	VMM_CTR0(vcpu, format)						\
198 	VCPU_CTR0((vcpu)->vm, (vcpu)->vcpuid, format)
199 
200 #define	VMM_CTR1(vcpu, format, p1)					\
201 	VCPU_CTR1((vcpu)->vm, (vcpu)->vcpuid, format, p1)
202 
203 #define	VMM_CTR2(vcpu, format, p1, p2)					\
204 	VCPU_CTR2((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2)
205 
206 #define	VMM_CTR3(vcpu, format, p1, p2, p3)				\
207 	VCPU_CTR3((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2, p3)
208 
209 #define	VMM_CTR4(vcpu, format, p1, p2, p3, p4)				\
210 	VCPU_CTR4((vcpu)->vm, (vcpu)->vcpuid, format, p1, p2, p3, p4)
211 
212 static int vmm_initialized;
213 
214 static void	vmmops_panic(void);
215 
216 static void
217 vmmops_panic(void)
218 {
219 	panic("vmm_ops func called when !vmm_is_intel() && !vmm_is_svm()");
220 }
221 
222 #define	DEFINE_VMMOPS_IFUNC(ret_type, opname, args)			\
223     DEFINE_IFUNC(static, ret_type, vmmops_##opname, args)		\
224     {									\
225     	if (vmm_is_intel())						\
226     		return (vmm_ops_intel.opname);				\
227     	else if (vmm_is_svm())						\
228     		return (vmm_ops_amd.opname);				\
229     	else								\
230     		return ((ret_type (*)args)vmmops_panic);		\
231     }
232 
233 DEFINE_VMMOPS_IFUNC(int, modinit, (int ipinum))
234 DEFINE_VMMOPS_IFUNC(int, modcleanup, (void))
235 DEFINE_VMMOPS_IFUNC(void, modresume, (void))
236 DEFINE_VMMOPS_IFUNC(void *, init, (struct vm *vm, struct pmap *pmap))
237 DEFINE_VMMOPS_IFUNC(int, run, (void *vcpui, register_t rip, struct pmap *pmap,
238     struct vm_eventinfo *info))
239 DEFINE_VMMOPS_IFUNC(void, cleanup, (void *vmi))
240 DEFINE_VMMOPS_IFUNC(void *, vcpu_init, (void *vmi, struct vcpu *vcpu,
241     int vcpu_id))
242 DEFINE_VMMOPS_IFUNC(void, vcpu_cleanup, (void *vcpui))
243 DEFINE_VMMOPS_IFUNC(int, getreg, (void *vcpui, int num, uint64_t *retval))
244 DEFINE_VMMOPS_IFUNC(int, setreg, (void *vcpui, int num, uint64_t val))
245 DEFINE_VMMOPS_IFUNC(int, getdesc, (void *vcpui, int num, struct seg_desc *desc))
246 DEFINE_VMMOPS_IFUNC(int, setdesc, (void *vcpui, int num, struct seg_desc *desc))
247 DEFINE_VMMOPS_IFUNC(int, getcap, (void *vcpui, int num, int *retval))
248 DEFINE_VMMOPS_IFUNC(int, setcap, (void *vcpui, int num, int val))
249 DEFINE_VMMOPS_IFUNC(struct vmspace *, vmspace_alloc, (vm_offset_t min,
250     vm_offset_t max))
251 DEFINE_VMMOPS_IFUNC(void, vmspace_free, (struct vmspace *vmspace))
252 DEFINE_VMMOPS_IFUNC(struct vlapic *, vlapic_init, (void *vcpui))
253 DEFINE_VMMOPS_IFUNC(void, vlapic_cleanup, (struct vlapic *vlapic))
254 #ifdef BHYVE_SNAPSHOT
255 DEFINE_VMMOPS_IFUNC(int, vcpu_snapshot, (void *vcpui,
256     struct vm_snapshot_meta *meta))
257 DEFINE_VMMOPS_IFUNC(int, restore_tsc, (void *vcpui, uint64_t now))
258 #endif
259 
260 SDT_PROVIDER_DEFINE(vmm);
261 
262 static MALLOC_DEFINE(M_VM, "vm", "vm");
263 
264 /* statistics */
265 static VMM_STAT(VCPU_TOTAL_RUNTIME, "vcpu total runtime");
266 
267 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
268     NULL);
269 
270 /*
271  * Halt the guest if all vcpus are executing a HLT instruction with
272  * interrupts disabled.
273  */
274 static int halt_detection_enabled = 1;
275 SYSCTL_INT(_hw_vmm, OID_AUTO, halt_detection, CTLFLAG_RDTUN,
276     &halt_detection_enabled, 0,
277     "Halt VM if all vcpus execute HLT with interrupts disabled");
278 
279 static int vmm_ipinum;
280 SYSCTL_INT(_hw_vmm, OID_AUTO, ipinum, CTLFLAG_RD, &vmm_ipinum, 0,
281     "IPI vector used for vcpu notifications");
282 
283 static int trace_guest_exceptions;
284 SYSCTL_INT(_hw_vmm, OID_AUTO, trace_guest_exceptions, CTLFLAG_RDTUN,
285     &trace_guest_exceptions, 0,
286     "Trap into hypervisor on all guest exceptions and reflect them back");
287 
288 static int trap_wbinvd;
289 SYSCTL_INT(_hw_vmm, OID_AUTO, trap_wbinvd, CTLFLAG_RDTUN, &trap_wbinvd, 0,
290     "WBINVD triggers a VM-exit");
291 
292 u_int vm_maxcpu;
293 SYSCTL_UINT(_hw_vmm, OID_AUTO, maxcpu, CTLFLAG_RDTUN | CTLFLAG_NOFETCH,
294     &vm_maxcpu, 0, "Maximum number of vCPUs");
295 
296 static void vm_free_memmap(struct vm *vm, int ident);
297 static bool sysmem_mapping(struct vm *vm, struct mem_map *mm);
298 static void vcpu_notify_event_locked(struct vcpu *vcpu, bool lapic_intr);
299 
300 /* global statistics */
301 VMM_STAT(VCPU_MIGRATIONS, "vcpu migration across host cpus");
302 VMM_STAT(VMEXIT_COUNT, "total number of vm exits");
303 VMM_STAT(VMEXIT_EXTINT, "vm exits due to external interrupt");
304 VMM_STAT(VMEXIT_HLT, "number of times hlt was intercepted");
305 VMM_STAT(VMEXIT_CR_ACCESS, "number of times %cr access was intercepted");
306 VMM_STAT(VMEXIT_RDMSR, "number of times rdmsr was intercepted");
307 VMM_STAT(VMEXIT_WRMSR, "number of times wrmsr was intercepted");
308 VMM_STAT(VMEXIT_MTRAP, "number of monitor trap exits");
309 VMM_STAT(VMEXIT_PAUSE, "number of times pause was intercepted");
310 VMM_STAT(VMEXIT_INTR_WINDOW, "vm exits due to interrupt window opening");
311 VMM_STAT(VMEXIT_NMI_WINDOW, "vm exits due to nmi window opening");
312 VMM_STAT(VMEXIT_INOUT, "number of times in/out was intercepted");
313 VMM_STAT(VMEXIT_CPUID, "number of times cpuid was intercepted");
314 VMM_STAT(VMEXIT_NESTED_FAULT, "vm exits due to nested page fault");
315 VMM_STAT(VMEXIT_INST_EMUL, "vm exits for instruction emulation");
316 VMM_STAT(VMEXIT_UNKNOWN, "number of vm exits for unknown reason");
317 VMM_STAT(VMEXIT_ASTPENDING, "number of times astpending at exit");
318 VMM_STAT(VMEXIT_REQIDLE, "number of times idle requested at exit");
319 VMM_STAT(VMEXIT_USERSPACE, "number of vm exits handled in userspace");
320 VMM_STAT(VMEXIT_RENDEZVOUS, "number of times rendezvous pending at exit");
321 VMM_STAT(VMEXIT_EXCEPTION, "number of vm exits due to exceptions");
322 
323 /*
324  * Upper limit on vm_maxcpu.  Limited by use of uint16_t types for CPU
325  * counts as well as range of vpid values for VT-x and by the capacity
326  * of cpuset_t masks.  The call to new_unrhdr() in vpid_init() in
327  * vmx.c requires 'vm_maxcpu + 1 <= 0xffff', hence the '- 1' below.
328  */
329 #define	VM_MAXCPU	MIN(0xffff - 1, CPU_SETSIZE)
330 
331 #ifdef KTR
332 static const char *
333 vcpu_state2str(enum vcpu_state state)
334 {
335 
336 	switch (state) {
337 	case VCPU_IDLE:
338 		return ("idle");
339 	case VCPU_FROZEN:
340 		return ("frozen");
341 	case VCPU_RUNNING:
342 		return ("running");
343 	case VCPU_SLEEPING:
344 		return ("sleeping");
345 	default:
346 		return ("unknown");
347 	}
348 }
349 #endif
350 
351 static void
352 vcpu_cleanup(struct vcpu *vcpu, bool destroy)
353 {
354 	vmmops_vlapic_cleanup(vcpu->vlapic);
355 	vmmops_vcpu_cleanup(vcpu->cookie);
356 	vcpu->cookie = NULL;
357 	if (destroy) {
358 		vmm_stat_free(vcpu->stats);
359 		fpu_save_area_free(vcpu->guestfpu);
360 		vcpu_lock_destroy(vcpu);
361 		free(vcpu, M_VM);
362 	}
363 }
364 
365 static struct vcpu *
366 vcpu_alloc(struct vm *vm, int vcpu_id)
367 {
368 	struct vcpu *vcpu;
369 
370 	KASSERT(vcpu_id >= 0 && vcpu_id < vm->maxcpus,
371 	    ("vcpu_init: invalid vcpu %d", vcpu_id));
372 
373 	vcpu = malloc(sizeof(*vcpu), M_VM, M_WAITOK | M_ZERO);
374 	vcpu_lock_init(vcpu);
375 	vcpu->state = VCPU_IDLE;
376 	vcpu->hostcpu = NOCPU;
377 	vcpu->vcpuid = vcpu_id;
378 	vcpu->vm = vm;
379 	vcpu->guestfpu = fpu_save_area_alloc();
380 	vcpu->stats = vmm_stat_alloc();
381 	vcpu->tsc_offset = 0;
382 	return (vcpu);
383 }
384 
385 static void
386 vcpu_init(struct vcpu *vcpu)
387 {
388 	vcpu->cookie = vmmops_vcpu_init(vcpu->vm->cookie, vcpu, vcpu->vcpuid);
389 	vcpu->vlapic = vmmops_vlapic_init(vcpu->cookie);
390 	vm_set_x2apic_state(vcpu, X2APIC_DISABLED);
391 	vcpu->reqidle = 0;
392 	vcpu->exitintinfo = 0;
393 	vcpu->nmi_pending = 0;
394 	vcpu->extint_pending = 0;
395 	vcpu->exception_pending = 0;
396 	vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
397 	fpu_save_area_reset(vcpu->guestfpu);
398 	vmm_stat_init(vcpu->stats);
399 }
400 
401 int
402 vcpu_trace_exceptions(struct vcpu *vcpu)
403 {
404 
405 	return (trace_guest_exceptions);
406 }
407 
408 int
409 vcpu_trap_wbinvd(struct vcpu *vcpu)
410 {
411 	return (trap_wbinvd);
412 }
413 
414 struct vm_exit *
415 vm_exitinfo(struct vcpu *vcpu)
416 {
417 	return (&vcpu->exitinfo);
418 }
419 
420 cpuset_t *
421 vm_exitinfo_cpuset(struct vcpu *vcpu)
422 {
423 	return (&vcpu->exitinfo_cpuset);
424 }
425 
426 static int
427 vmm_init(void)
428 {
429 	int error;
430 
431 	if (!vmm_is_hw_supported())
432 		return (ENXIO);
433 
434 	vm_maxcpu = mp_ncpus;
435 	TUNABLE_INT_FETCH("hw.vmm.maxcpu", &vm_maxcpu);
436 
437 	if (vm_maxcpu > VM_MAXCPU) {
438 		printf("vmm: vm_maxcpu clamped to %u\n", VM_MAXCPU);
439 		vm_maxcpu = VM_MAXCPU;
440 	}
441 	if (vm_maxcpu == 0)
442 		vm_maxcpu = 1;
443 
444 	vmm_host_state_init();
445 
446 	vmm_ipinum = lapic_ipi_alloc(pti ? &IDTVEC(justreturn1_pti) :
447 	    &IDTVEC(justreturn));
448 	if (vmm_ipinum < 0)
449 		vmm_ipinum = IPI_AST;
450 
451 	error = vmm_mem_init();
452 	if (error)
453 		return (error);
454 
455 	vmm_resume_p = vmmops_modresume;
456 
457 	return (vmmops_modinit(vmm_ipinum));
458 }
459 
460 static int
461 vmm_handler(module_t mod, int what, void *arg)
462 {
463 	int error;
464 
465 	switch (what) {
466 	case MOD_LOAD:
467 		if (vmm_is_hw_supported()) {
468 			vmmdev_init();
469 			error = vmm_init();
470 			if (error == 0)
471 				vmm_initialized = 1;
472 		} else {
473 			error = ENXIO;
474 		}
475 		break;
476 	case MOD_UNLOAD:
477 		if (vmm_is_hw_supported()) {
478 			error = vmmdev_cleanup();
479 			if (error == 0) {
480 				vmm_resume_p = NULL;
481 				iommu_cleanup();
482 				if (vmm_ipinum != IPI_AST)
483 					lapic_ipi_free(vmm_ipinum);
484 				error = vmmops_modcleanup();
485 				/*
486 				 * Something bad happened - prevent new
487 				 * VMs from being created
488 				 */
489 				if (error)
490 					vmm_initialized = 0;
491 			}
492 		} else {
493 			error = 0;
494 		}
495 		break;
496 	default:
497 		error = 0;
498 		break;
499 	}
500 	return (error);
501 }
502 
503 static moduledata_t vmm_kmod = {
504 	"vmm",
505 	vmm_handler,
506 	NULL
507 };
508 
509 /*
510  * vmm initialization has the following dependencies:
511  *
512  * - VT-x initialization requires smp_rendezvous() and therefore must happen
513  *   after SMP is fully functional (after SI_SUB_SMP).
514  */
515 DECLARE_MODULE(vmm, vmm_kmod, SI_SUB_SMP + 1, SI_ORDER_ANY);
516 MODULE_VERSION(vmm, 1);
517 
518 static void
519 vm_init(struct vm *vm, bool create)
520 {
521 	vm->cookie = vmmops_init(vm, vmspace_pmap(vm->vmspace));
522 	vm->iommu = NULL;
523 	vm->vioapic = vioapic_init(vm);
524 	vm->vhpet = vhpet_init(vm);
525 	vm->vatpic = vatpic_init(vm);
526 	vm->vatpit = vatpit_init(vm);
527 	vm->vpmtmr = vpmtmr_init(vm);
528 	if (create)
529 		vm->vrtc = vrtc_init(vm);
530 
531 	CPU_ZERO(&vm->active_cpus);
532 	CPU_ZERO(&vm->debug_cpus);
533 	CPU_ZERO(&vm->startup_cpus);
534 
535 	vm->suspend = 0;
536 	CPU_ZERO(&vm->suspended_cpus);
537 
538 	if (!create) {
539 		for (int i = 0; i < vm->maxcpus; i++) {
540 			if (vm->vcpu[i] != NULL)
541 				vcpu_init(vm->vcpu[i]);
542 		}
543 	}
544 }
545 
546 void
547 vm_disable_vcpu_creation(struct vm *vm)
548 {
549 	sx_xlock(&vm->vcpus_init_lock);
550 	vm->dying = true;
551 	sx_xunlock(&vm->vcpus_init_lock);
552 }
553 
554 struct vcpu *
555 vm_alloc_vcpu(struct vm *vm, int vcpuid)
556 {
557 	struct vcpu *vcpu;
558 
559 	if (vcpuid < 0 || vcpuid >= vm_get_maxcpus(vm))
560 		return (NULL);
561 
562 	vcpu = atomic_load_ptr(&vm->vcpu[vcpuid]);
563 	if (__predict_true(vcpu != NULL))
564 		return (vcpu);
565 
566 	sx_xlock(&vm->vcpus_init_lock);
567 	vcpu = vm->vcpu[vcpuid];
568 	if (vcpu == NULL && !vm->dying) {
569 		vcpu = vcpu_alloc(vm, vcpuid);
570 		vcpu_init(vcpu);
571 
572 		/*
573 		 * Ensure vCPU is fully created before updating pointer
574 		 * to permit unlocked reads above.
575 		 */
576 		atomic_store_rel_ptr((uintptr_t *)&vm->vcpu[vcpuid],
577 		    (uintptr_t)vcpu);
578 	}
579 	sx_xunlock(&vm->vcpus_init_lock);
580 	return (vcpu);
581 }
582 
583 void
584 vm_slock_vcpus(struct vm *vm)
585 {
586 	sx_slock(&vm->vcpus_init_lock);
587 }
588 
589 void
590 vm_unlock_vcpus(struct vm *vm)
591 {
592 	sx_unlock(&vm->vcpus_init_lock);
593 }
594 
595 /*
596  * The default CPU topology is a single thread per package.
597  */
598 u_int cores_per_package = 1;
599 u_int threads_per_core = 1;
600 
601 int
602 vm_create(const char *name, struct vm **retvm)
603 {
604 	struct vm *vm;
605 	struct vmspace *vmspace;
606 
607 	/*
608 	 * If vmm.ko could not be successfully initialized then don't attempt
609 	 * to create the virtual machine.
610 	 */
611 	if (!vmm_initialized)
612 		return (ENXIO);
613 
614 	if (name == NULL || strnlen(name, VM_MAX_NAMELEN + 1) ==
615 	    VM_MAX_NAMELEN + 1)
616 		return (EINVAL);
617 
618 	vmspace = vmmops_vmspace_alloc(0, VM_MAXUSER_ADDRESS_LA48);
619 	if (vmspace == NULL)
620 		return (ENOMEM);
621 
622 	vm = malloc(sizeof(struct vm), M_VM, M_WAITOK | M_ZERO);
623 	strcpy(vm->name, name);
624 	vm->vmspace = vmspace;
625 	mtx_init(&vm->rendezvous_mtx, "vm rendezvous lock", 0, MTX_DEF);
626 	sx_init(&vm->mem_segs_lock, "vm mem_segs");
627 	sx_init(&vm->vcpus_init_lock, "vm vcpus");
628 	vm->vcpu = malloc(sizeof(*vm->vcpu) * vm_maxcpu, M_VM, M_WAITOK |
629 	    M_ZERO);
630 
631 	vm->sockets = 1;
632 	vm->cores = cores_per_package;	/* XXX backwards compatibility */
633 	vm->threads = threads_per_core;	/* XXX backwards compatibility */
634 	vm->maxcpus = vm_maxcpu;
635 
636 	vm_init(vm, true);
637 
638 	*retvm = vm;
639 	return (0);
640 }
641 
642 void
643 vm_get_topology(struct vm *vm, uint16_t *sockets, uint16_t *cores,
644     uint16_t *threads, uint16_t *maxcpus)
645 {
646 	*sockets = vm->sockets;
647 	*cores = vm->cores;
648 	*threads = vm->threads;
649 	*maxcpus = vm->maxcpus;
650 }
651 
652 uint16_t
653 vm_get_maxcpus(struct vm *vm)
654 {
655 	return (vm->maxcpus);
656 }
657 
658 int
659 vm_set_topology(struct vm *vm, uint16_t sockets, uint16_t cores,
660     uint16_t threads, uint16_t maxcpus __unused)
661 {
662 	/* Ignore maxcpus. */
663 	if ((sockets * cores * threads) > vm->maxcpus)
664 		return (EINVAL);
665 	vm->sockets = sockets;
666 	vm->cores = cores;
667 	vm->threads = threads;
668 	return(0);
669 }
670 
671 static void
672 vm_cleanup(struct vm *vm, bool destroy)
673 {
674 	struct mem_map *mm;
675 	int i;
676 
677 	if (destroy)
678 		vm_xlock_memsegs(vm);
679 
680 	ppt_unassign_all(vm);
681 
682 	if (vm->iommu != NULL)
683 		iommu_destroy_domain(vm->iommu);
684 
685 	if (destroy)
686 		vrtc_cleanup(vm->vrtc);
687 	else
688 		vrtc_reset(vm->vrtc);
689 	vpmtmr_cleanup(vm->vpmtmr);
690 	vatpit_cleanup(vm->vatpit);
691 	vhpet_cleanup(vm->vhpet);
692 	vatpic_cleanup(vm->vatpic);
693 	vioapic_cleanup(vm->vioapic);
694 
695 	for (i = 0; i < vm->maxcpus; i++) {
696 		if (vm->vcpu[i] != NULL)
697 			vcpu_cleanup(vm->vcpu[i], destroy);
698 	}
699 
700 	vmmops_cleanup(vm->cookie);
701 
702 	/*
703 	 * System memory is removed from the guest address space only when
704 	 * the VM is destroyed. This is because the mapping remains the same
705 	 * across VM reset.
706 	 *
707 	 * Device memory can be relocated by the guest (e.g. using PCI BARs)
708 	 * so those mappings are removed on a VM reset.
709 	 */
710 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
711 		mm = &vm->mem_maps[i];
712 		if (destroy || !sysmem_mapping(vm, mm))
713 			vm_free_memmap(vm, i);
714 	}
715 
716 	if (destroy) {
717 		for (i = 0; i < VM_MAX_MEMSEGS; i++)
718 			vm_free_memseg(vm, i);
719 		vm_unlock_memsegs(vm);
720 
721 		vmmops_vmspace_free(vm->vmspace);
722 		vm->vmspace = NULL;
723 
724 		free(vm->vcpu, M_VM);
725 		sx_destroy(&vm->vcpus_init_lock);
726 		sx_destroy(&vm->mem_segs_lock);
727 		mtx_destroy(&vm->rendezvous_mtx);
728 	}
729 }
730 
731 void
732 vm_destroy(struct vm *vm)
733 {
734 	vm_cleanup(vm, true);
735 	free(vm, M_VM);
736 }
737 
738 int
739 vm_reinit(struct vm *vm)
740 {
741 	int error;
742 
743 	/*
744 	 * A virtual machine can be reset only if all vcpus are suspended.
745 	 */
746 	if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
747 		vm_cleanup(vm, false);
748 		vm_init(vm, false);
749 		error = 0;
750 	} else {
751 		error = EBUSY;
752 	}
753 
754 	return (error);
755 }
756 
757 const char *
758 vm_name(struct vm *vm)
759 {
760 	return (vm->name);
761 }
762 
763 void
764 vm_slock_memsegs(struct vm *vm)
765 {
766 	sx_slock(&vm->mem_segs_lock);
767 }
768 
769 void
770 vm_xlock_memsegs(struct vm *vm)
771 {
772 	sx_xlock(&vm->mem_segs_lock);
773 }
774 
775 void
776 vm_unlock_memsegs(struct vm *vm)
777 {
778 	sx_unlock(&vm->mem_segs_lock);
779 }
780 
781 int
782 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
783 {
784 	vm_object_t obj;
785 
786 	if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
787 		return (ENOMEM);
788 	else
789 		return (0);
790 }
791 
792 int
793 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
794 {
795 
796 	vmm_mmio_free(vm->vmspace, gpa, len);
797 	return (0);
798 }
799 
800 /*
801  * Return 'true' if 'gpa' is allocated in the guest address space.
802  *
803  * This function is called in the context of a running vcpu which acts as
804  * an implicit lock on 'vm->mem_maps[]'.
805  */
806 bool
807 vm_mem_allocated(struct vcpu *vcpu, vm_paddr_t gpa)
808 {
809 	struct vm *vm = vcpu->vm;
810 	struct mem_map *mm;
811 	int i;
812 
813 #ifdef INVARIANTS
814 	int hostcpu, state;
815 	state = vcpu_get_state(vcpu, &hostcpu);
816 	KASSERT(state == VCPU_RUNNING && hostcpu == curcpu,
817 	    ("%s: invalid vcpu state %d/%d", __func__, state, hostcpu));
818 #endif
819 
820 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
821 		mm = &vm->mem_maps[i];
822 		if (mm->len != 0 && gpa >= mm->gpa && gpa < mm->gpa + mm->len)
823 			return (true);		/* 'gpa' is sysmem or devmem */
824 	}
825 
826 	if (ppt_is_mmio(vm, gpa))
827 		return (true);			/* 'gpa' is pci passthru mmio */
828 
829 	return (false);
830 }
831 
832 int
833 vm_alloc_memseg(struct vm *vm, int ident, size_t len, bool sysmem)
834 {
835 	struct mem_seg *seg;
836 	vm_object_t obj;
837 
838 	sx_assert(&vm->mem_segs_lock, SX_XLOCKED);
839 
840 	if (ident < 0 || ident >= VM_MAX_MEMSEGS)
841 		return (EINVAL);
842 
843 	if (len == 0 || (len & PAGE_MASK))
844 		return (EINVAL);
845 
846 	seg = &vm->mem_segs[ident];
847 	if (seg->object != NULL) {
848 		if (seg->len == len && seg->sysmem == sysmem)
849 			return (EEXIST);
850 		else
851 			return (EINVAL);
852 	}
853 
854 	obj = vm_object_allocate(OBJT_SWAP, len >> PAGE_SHIFT);
855 	if (obj == NULL)
856 		return (ENOMEM);
857 
858 	seg->len = len;
859 	seg->object = obj;
860 	seg->sysmem = sysmem;
861 	return (0);
862 }
863 
864 int
865 vm_get_memseg(struct vm *vm, int ident, size_t *len, bool *sysmem,
866     vm_object_t *objptr)
867 {
868 	struct mem_seg *seg;
869 
870 	sx_assert(&vm->mem_segs_lock, SX_LOCKED);
871 
872 	if (ident < 0 || ident >= VM_MAX_MEMSEGS)
873 		return (EINVAL);
874 
875 	seg = &vm->mem_segs[ident];
876 	if (len)
877 		*len = seg->len;
878 	if (sysmem)
879 		*sysmem = seg->sysmem;
880 	if (objptr)
881 		*objptr = seg->object;
882 	return (0);
883 }
884 
885 void
886 vm_free_memseg(struct vm *vm, int ident)
887 {
888 	struct mem_seg *seg;
889 
890 	KASSERT(ident >= 0 && ident < VM_MAX_MEMSEGS,
891 	    ("%s: invalid memseg ident %d", __func__, ident));
892 
893 	seg = &vm->mem_segs[ident];
894 	if (seg->object != NULL) {
895 		vm_object_deallocate(seg->object);
896 		bzero(seg, sizeof(struct mem_seg));
897 	}
898 }
899 
900 int
901 vm_mmap_memseg(struct vm *vm, vm_paddr_t gpa, int segid, vm_ooffset_t first,
902     size_t len, int prot, int flags)
903 {
904 	struct mem_seg *seg;
905 	struct mem_map *m, *map;
906 	vm_ooffset_t last;
907 	int i, error;
908 
909 	if (prot == 0 || (prot & ~(VM_PROT_ALL)) != 0)
910 		return (EINVAL);
911 
912 	if (flags & ~VM_MEMMAP_F_WIRED)
913 		return (EINVAL);
914 
915 	if (segid < 0 || segid >= VM_MAX_MEMSEGS)
916 		return (EINVAL);
917 
918 	seg = &vm->mem_segs[segid];
919 	if (seg->object == NULL)
920 		return (EINVAL);
921 
922 	last = first + len;
923 	if (first < 0 || first >= last || last > seg->len)
924 		return (EINVAL);
925 
926 	if ((gpa | first | last) & PAGE_MASK)
927 		return (EINVAL);
928 
929 	map = NULL;
930 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
931 		m = &vm->mem_maps[i];
932 		if (m->len == 0) {
933 			map = m;
934 			break;
935 		}
936 	}
937 
938 	if (map == NULL)
939 		return (ENOSPC);
940 
941 	error = vm_map_find(&vm->vmspace->vm_map, seg->object, first, &gpa,
942 	    len, 0, VMFS_NO_SPACE, prot, prot, 0);
943 	if (error != KERN_SUCCESS)
944 		return (EFAULT);
945 
946 	vm_object_reference(seg->object);
947 
948 	if (flags & VM_MEMMAP_F_WIRED) {
949 		error = vm_map_wire(&vm->vmspace->vm_map, gpa, gpa + len,
950 		    VM_MAP_WIRE_USER | VM_MAP_WIRE_NOHOLES);
951 		if (error != KERN_SUCCESS) {
952 			vm_map_remove(&vm->vmspace->vm_map, gpa, gpa + len);
953 			return (error == KERN_RESOURCE_SHORTAGE ? ENOMEM :
954 			    EFAULT);
955 		}
956 	}
957 
958 	map->gpa = gpa;
959 	map->len = len;
960 	map->segoff = first;
961 	map->segid = segid;
962 	map->prot = prot;
963 	map->flags = flags;
964 	return (0);
965 }
966 
967 int
968 vm_munmap_memseg(struct vm *vm, vm_paddr_t gpa, size_t len)
969 {
970 	struct mem_map *m;
971 	int i;
972 
973 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
974 		m = &vm->mem_maps[i];
975 		if (m->gpa == gpa && m->len == len &&
976 		    (m->flags & VM_MEMMAP_F_IOMMU) == 0) {
977 			vm_free_memmap(vm, i);
978 			return (0);
979 		}
980 	}
981 
982 	return (EINVAL);
983 }
984 
985 int
986 vm_mmap_getnext(struct vm *vm, vm_paddr_t *gpa, int *segid,
987     vm_ooffset_t *segoff, size_t *len, int *prot, int *flags)
988 {
989 	struct mem_map *mm, *mmnext;
990 	int i;
991 
992 	mmnext = NULL;
993 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
994 		mm = &vm->mem_maps[i];
995 		if (mm->len == 0 || mm->gpa < *gpa)
996 			continue;
997 		if (mmnext == NULL || mm->gpa < mmnext->gpa)
998 			mmnext = mm;
999 	}
1000 
1001 	if (mmnext != NULL) {
1002 		*gpa = mmnext->gpa;
1003 		if (segid)
1004 			*segid = mmnext->segid;
1005 		if (segoff)
1006 			*segoff = mmnext->segoff;
1007 		if (len)
1008 			*len = mmnext->len;
1009 		if (prot)
1010 			*prot = mmnext->prot;
1011 		if (flags)
1012 			*flags = mmnext->flags;
1013 		return (0);
1014 	} else {
1015 		return (ENOENT);
1016 	}
1017 }
1018 
1019 static void
1020 vm_free_memmap(struct vm *vm, int ident)
1021 {
1022 	struct mem_map *mm;
1023 	int error __diagused;
1024 
1025 	mm = &vm->mem_maps[ident];
1026 	if (mm->len) {
1027 		error = vm_map_remove(&vm->vmspace->vm_map, mm->gpa,
1028 		    mm->gpa + mm->len);
1029 		KASSERT(error == KERN_SUCCESS, ("%s: vm_map_remove error %d",
1030 		    __func__, error));
1031 		bzero(mm, sizeof(struct mem_map));
1032 	}
1033 }
1034 
1035 static __inline bool
1036 sysmem_mapping(struct vm *vm, struct mem_map *mm)
1037 {
1038 
1039 	if (mm->len != 0 && vm->mem_segs[mm->segid].sysmem)
1040 		return (true);
1041 	else
1042 		return (false);
1043 }
1044 
1045 vm_paddr_t
1046 vmm_sysmem_maxaddr(struct vm *vm)
1047 {
1048 	struct mem_map *mm;
1049 	vm_paddr_t maxaddr;
1050 	int i;
1051 
1052 	maxaddr = 0;
1053 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1054 		mm = &vm->mem_maps[i];
1055 		if (sysmem_mapping(vm, mm)) {
1056 			if (maxaddr < mm->gpa + mm->len)
1057 				maxaddr = mm->gpa + mm->len;
1058 		}
1059 	}
1060 	return (maxaddr);
1061 }
1062 
1063 static void
1064 vm_iommu_map(struct vm *vm)
1065 {
1066 	vm_paddr_t gpa, hpa;
1067 	struct mem_map *mm;
1068 	int i;
1069 
1070 	sx_assert(&vm->mem_segs_lock, SX_LOCKED);
1071 
1072 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1073 		mm = &vm->mem_maps[i];
1074 		if (!sysmem_mapping(vm, mm))
1075 			continue;
1076 
1077 		KASSERT((mm->flags & VM_MEMMAP_F_IOMMU) == 0,
1078 		    ("iommu map found invalid memmap %#lx/%#lx/%#x",
1079 		    mm->gpa, mm->len, mm->flags));
1080 		if ((mm->flags & VM_MEMMAP_F_WIRED) == 0)
1081 			continue;
1082 		mm->flags |= VM_MEMMAP_F_IOMMU;
1083 
1084 		for (gpa = mm->gpa; gpa < mm->gpa + mm->len; gpa += PAGE_SIZE) {
1085 			hpa = pmap_extract(vmspace_pmap(vm->vmspace), gpa);
1086 
1087 			/*
1088 			 * All mappings in the vmm vmspace must be
1089 			 * present since they are managed by vmm in this way.
1090 			 * Because we are in pass-through mode, the
1091 			 * mappings must also be wired.  This implies
1092 			 * that all pages must be mapped and wired,
1093 			 * allowing to use pmap_extract() and avoiding the
1094 			 * need to use vm_gpa_hold_global().
1095 			 *
1096 			 * This could change if/when we start
1097 			 * supporting page faults on IOMMU maps.
1098 			 */
1099 			KASSERT(vm_page_wired(PHYS_TO_VM_PAGE(hpa)),
1100 			    ("vm_iommu_map: vm %p gpa %jx hpa %jx not wired",
1101 			    vm, (uintmax_t)gpa, (uintmax_t)hpa));
1102 
1103 			iommu_create_mapping(vm->iommu, gpa, hpa, PAGE_SIZE);
1104 		}
1105 	}
1106 
1107 	iommu_invalidate_tlb(iommu_host_domain());
1108 }
1109 
1110 static void
1111 vm_iommu_unmap(struct vm *vm)
1112 {
1113 	vm_paddr_t gpa;
1114 	struct mem_map *mm;
1115 	int i;
1116 
1117 	sx_assert(&vm->mem_segs_lock, SX_LOCKED);
1118 
1119 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1120 		mm = &vm->mem_maps[i];
1121 		if (!sysmem_mapping(vm, mm))
1122 			continue;
1123 
1124 		if ((mm->flags & VM_MEMMAP_F_IOMMU) == 0)
1125 			continue;
1126 		mm->flags &= ~VM_MEMMAP_F_IOMMU;
1127 		KASSERT((mm->flags & VM_MEMMAP_F_WIRED) != 0,
1128 		    ("iommu unmap found invalid memmap %#lx/%#lx/%#x",
1129 		    mm->gpa, mm->len, mm->flags));
1130 
1131 		for (gpa = mm->gpa; gpa < mm->gpa + mm->len; gpa += PAGE_SIZE) {
1132 			KASSERT(vm_page_wired(PHYS_TO_VM_PAGE(pmap_extract(
1133 			    vmspace_pmap(vm->vmspace), gpa))),
1134 			    ("vm_iommu_unmap: vm %p gpa %jx not wired",
1135 			    vm, (uintmax_t)gpa));
1136 			iommu_remove_mapping(vm->iommu, gpa, PAGE_SIZE);
1137 		}
1138 	}
1139 
1140 	/*
1141 	 * Invalidate the cached translations associated with the domain
1142 	 * from which pages were removed.
1143 	 */
1144 	iommu_invalidate_tlb(vm->iommu);
1145 }
1146 
1147 int
1148 vm_unassign_pptdev(struct vm *vm, int bus, int slot, int func)
1149 {
1150 	int error;
1151 
1152 	error = ppt_unassign_device(vm, bus, slot, func);
1153 	if (error)
1154 		return (error);
1155 
1156 	if (ppt_assigned_devices(vm) == 0)
1157 		vm_iommu_unmap(vm);
1158 
1159 	return (0);
1160 }
1161 
1162 int
1163 vm_assign_pptdev(struct vm *vm, int bus, int slot, int func)
1164 {
1165 	int error;
1166 	vm_paddr_t maxaddr;
1167 
1168 	/* Set up the IOMMU to do the 'gpa' to 'hpa' translation */
1169 	if (ppt_assigned_devices(vm) == 0) {
1170 		KASSERT(vm->iommu == NULL,
1171 		    ("vm_assign_pptdev: iommu must be NULL"));
1172 		maxaddr = vmm_sysmem_maxaddr(vm);
1173 		vm->iommu = iommu_create_domain(maxaddr);
1174 		if (vm->iommu == NULL)
1175 			return (ENXIO);
1176 		vm_iommu_map(vm);
1177 	}
1178 
1179 	error = ppt_assign_device(vm, bus, slot, func);
1180 	return (error);
1181 }
1182 
1183 static void *
1184 _vm_gpa_hold(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
1185     void **cookie)
1186 {
1187 	int i, count, pageoff;
1188 	struct mem_map *mm;
1189 	vm_page_t m;
1190 
1191 	pageoff = gpa & PAGE_MASK;
1192 	if (len > PAGE_SIZE - pageoff)
1193 		panic("vm_gpa_hold: invalid gpa/len: 0x%016lx/%lu", gpa, len);
1194 
1195 	count = 0;
1196 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1197 		mm = &vm->mem_maps[i];
1198 		if (gpa >= mm->gpa && gpa < mm->gpa + mm->len) {
1199 			count = vm_fault_quick_hold_pages(&vm->vmspace->vm_map,
1200 			    trunc_page(gpa), PAGE_SIZE, reqprot, &m, 1);
1201 			break;
1202 		}
1203 	}
1204 
1205 	if (count == 1) {
1206 		*cookie = m;
1207 		return ((void *)(PHYS_TO_DMAP(VM_PAGE_TO_PHYS(m)) + pageoff));
1208 	} else {
1209 		*cookie = NULL;
1210 		return (NULL);
1211 	}
1212 }
1213 
1214 void *
1215 vm_gpa_hold(struct vcpu *vcpu, vm_paddr_t gpa, size_t len, int reqprot,
1216     void **cookie)
1217 {
1218 #ifdef INVARIANTS
1219 	/*
1220 	 * The current vcpu should be frozen to ensure 'vm_memmap[]'
1221 	 * stability.
1222 	 */
1223 	int state = vcpu_get_state(vcpu, NULL);
1224 	KASSERT(state == VCPU_FROZEN, ("%s: invalid vcpu state %d",
1225 	    __func__, state));
1226 #endif
1227 	return (_vm_gpa_hold(vcpu->vm, gpa, len, reqprot, cookie));
1228 }
1229 
1230 void *
1231 vm_gpa_hold_global(struct vm *vm, vm_paddr_t gpa, size_t len, int reqprot,
1232     void **cookie)
1233 {
1234 	sx_assert(&vm->mem_segs_lock, SX_LOCKED);
1235 	return (_vm_gpa_hold(vm, gpa, len, reqprot, cookie));
1236 }
1237 
1238 void
1239 vm_gpa_release(void *cookie)
1240 {
1241 	vm_page_t m = cookie;
1242 
1243 	vm_page_unwire(m, PQ_ACTIVE);
1244 }
1245 
1246 int
1247 vm_get_register(struct vcpu *vcpu, int reg, uint64_t *retval)
1248 {
1249 
1250 	if (reg >= VM_REG_LAST)
1251 		return (EINVAL);
1252 
1253 	return (vmmops_getreg(vcpu->cookie, reg, retval));
1254 }
1255 
1256 int
1257 vm_set_register(struct vcpu *vcpu, int reg, uint64_t val)
1258 {
1259 	int error;
1260 
1261 	if (reg >= VM_REG_LAST)
1262 		return (EINVAL);
1263 
1264 	error = vmmops_setreg(vcpu->cookie, reg, val);
1265 	if (error || reg != VM_REG_GUEST_RIP)
1266 		return (error);
1267 
1268 	/* Set 'nextrip' to match the value of %rip */
1269 	VMM_CTR1(vcpu, "Setting nextrip to %#lx", val);
1270 	vcpu->nextrip = val;
1271 	return (0);
1272 }
1273 
1274 static bool
1275 is_descriptor_table(int reg)
1276 {
1277 
1278 	switch (reg) {
1279 	case VM_REG_GUEST_IDTR:
1280 	case VM_REG_GUEST_GDTR:
1281 		return (true);
1282 	default:
1283 		return (false);
1284 	}
1285 }
1286 
1287 static bool
1288 is_segment_register(int reg)
1289 {
1290 
1291 	switch (reg) {
1292 	case VM_REG_GUEST_ES:
1293 	case VM_REG_GUEST_CS:
1294 	case VM_REG_GUEST_SS:
1295 	case VM_REG_GUEST_DS:
1296 	case VM_REG_GUEST_FS:
1297 	case VM_REG_GUEST_GS:
1298 	case VM_REG_GUEST_TR:
1299 	case VM_REG_GUEST_LDTR:
1300 		return (true);
1301 	default:
1302 		return (false);
1303 	}
1304 }
1305 
1306 int
1307 vm_get_seg_desc(struct vcpu *vcpu, int reg, struct seg_desc *desc)
1308 {
1309 
1310 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
1311 		return (EINVAL);
1312 
1313 	return (vmmops_getdesc(vcpu->cookie, reg, desc));
1314 }
1315 
1316 int
1317 vm_set_seg_desc(struct vcpu *vcpu, int reg, struct seg_desc *desc)
1318 {
1319 
1320 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
1321 		return (EINVAL);
1322 
1323 	return (vmmops_setdesc(vcpu->cookie, reg, desc));
1324 }
1325 
1326 static void
1327 restore_guest_fpustate(struct vcpu *vcpu)
1328 {
1329 
1330 	/* flush host state to the pcb */
1331 	fpuexit(curthread);
1332 
1333 	/* restore guest FPU state */
1334 	fpu_enable();
1335 	fpurestore(vcpu->guestfpu);
1336 
1337 	/* restore guest XCR0 if XSAVE is enabled in the host */
1338 	if (rcr4() & CR4_XSAVE)
1339 		load_xcr(0, vcpu->guest_xcr0);
1340 
1341 	/*
1342 	 * The FPU is now "dirty" with the guest's state so disable
1343 	 * the FPU to trap any access by the host.
1344 	 */
1345 	fpu_disable();
1346 }
1347 
1348 static void
1349 save_guest_fpustate(struct vcpu *vcpu)
1350 {
1351 
1352 	if ((rcr0() & CR0_TS) == 0)
1353 		panic("fpu emulation not enabled in host!");
1354 
1355 	/* save guest XCR0 and restore host XCR0 */
1356 	if (rcr4() & CR4_XSAVE) {
1357 		vcpu->guest_xcr0 = rxcr(0);
1358 		load_xcr(0, vmm_get_host_xcr0());
1359 	}
1360 
1361 	/* save guest FPU state */
1362 	fpu_enable();
1363 	fpusave(vcpu->guestfpu);
1364 	fpu_disable();
1365 }
1366 
1367 static VMM_STAT(VCPU_IDLE_TICKS, "number of ticks vcpu was idle");
1368 
1369 static int
1370 vcpu_set_state_locked(struct vcpu *vcpu, enum vcpu_state newstate,
1371     bool from_idle)
1372 {
1373 	int error;
1374 
1375 	vcpu_assert_locked(vcpu);
1376 
1377 	/*
1378 	 * State transitions from the vmmdev_ioctl() must always begin from
1379 	 * the VCPU_IDLE state. This guarantees that there is only a single
1380 	 * ioctl() operating on a vcpu at any point.
1381 	 */
1382 	if (from_idle) {
1383 		while (vcpu->state != VCPU_IDLE) {
1384 			vcpu->reqidle = 1;
1385 			vcpu_notify_event_locked(vcpu, false);
1386 			VMM_CTR1(vcpu, "vcpu state change from %s to "
1387 			    "idle requested", vcpu_state2str(vcpu->state));
1388 			msleep_spin(&vcpu->state, &vcpu->mtx, "vmstat", hz);
1389 		}
1390 	} else {
1391 		KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
1392 		    "vcpu idle state"));
1393 	}
1394 
1395 	if (vcpu->state == VCPU_RUNNING) {
1396 		KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
1397 		    "mismatch for running vcpu", curcpu, vcpu->hostcpu));
1398 	} else {
1399 		KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
1400 		    "vcpu that is not running", vcpu->hostcpu));
1401 	}
1402 
1403 	/*
1404 	 * The following state transitions are allowed:
1405 	 * IDLE -> FROZEN -> IDLE
1406 	 * FROZEN -> RUNNING -> FROZEN
1407 	 * FROZEN -> SLEEPING -> FROZEN
1408 	 */
1409 	switch (vcpu->state) {
1410 	case VCPU_IDLE:
1411 	case VCPU_RUNNING:
1412 	case VCPU_SLEEPING:
1413 		error = (newstate != VCPU_FROZEN);
1414 		break;
1415 	case VCPU_FROZEN:
1416 		error = (newstate == VCPU_FROZEN);
1417 		break;
1418 	default:
1419 		error = 1;
1420 		break;
1421 	}
1422 
1423 	if (error)
1424 		return (EBUSY);
1425 
1426 	VMM_CTR2(vcpu, "vcpu state changed from %s to %s",
1427 	    vcpu_state2str(vcpu->state), vcpu_state2str(newstate));
1428 
1429 	vcpu->state = newstate;
1430 	if (newstate == VCPU_RUNNING)
1431 		vcpu->hostcpu = curcpu;
1432 	else
1433 		vcpu->hostcpu = NOCPU;
1434 
1435 	if (newstate == VCPU_IDLE)
1436 		wakeup(&vcpu->state);
1437 
1438 	return (0);
1439 }
1440 
1441 static void
1442 vcpu_require_state(struct vcpu *vcpu, enum vcpu_state newstate)
1443 {
1444 	int error;
1445 
1446 	if ((error = vcpu_set_state(vcpu, newstate, false)) != 0)
1447 		panic("Error %d setting state to %d\n", error, newstate);
1448 }
1449 
1450 static void
1451 vcpu_require_state_locked(struct vcpu *vcpu, enum vcpu_state newstate)
1452 {
1453 	int error;
1454 
1455 	if ((error = vcpu_set_state_locked(vcpu, newstate, false)) != 0)
1456 		panic("Error %d setting state to %d", error, newstate);
1457 }
1458 
1459 static int
1460 vm_handle_rendezvous(struct vcpu *vcpu)
1461 {
1462 	struct vm *vm = vcpu->vm;
1463 	struct thread *td;
1464 	int error, vcpuid;
1465 
1466 	error = 0;
1467 	vcpuid = vcpu->vcpuid;
1468 	td = curthread;
1469 	mtx_lock(&vm->rendezvous_mtx);
1470 	while (vm->rendezvous_func != NULL) {
1471 		/* 'rendezvous_req_cpus' must be a subset of 'active_cpus' */
1472 		CPU_AND(&vm->rendezvous_req_cpus, &vm->rendezvous_req_cpus, &vm->active_cpus);
1473 
1474 		if (CPU_ISSET(vcpuid, &vm->rendezvous_req_cpus) &&
1475 		    !CPU_ISSET(vcpuid, &vm->rendezvous_done_cpus)) {
1476 			VMM_CTR0(vcpu, "Calling rendezvous func");
1477 			(*vm->rendezvous_func)(vcpu, vm->rendezvous_arg);
1478 			CPU_SET(vcpuid, &vm->rendezvous_done_cpus);
1479 		}
1480 		if (CPU_CMP(&vm->rendezvous_req_cpus,
1481 		    &vm->rendezvous_done_cpus) == 0) {
1482 			VMM_CTR0(vcpu, "Rendezvous completed");
1483 			CPU_ZERO(&vm->rendezvous_req_cpus);
1484 			vm->rendezvous_func = NULL;
1485 			wakeup(&vm->rendezvous_func);
1486 			break;
1487 		}
1488 		VMM_CTR0(vcpu, "Wait for rendezvous completion");
1489 		mtx_sleep(&vm->rendezvous_func, &vm->rendezvous_mtx, 0,
1490 		    "vmrndv", hz);
1491 		if (td_ast_pending(td, TDA_SUSPEND)) {
1492 			mtx_unlock(&vm->rendezvous_mtx);
1493 			error = thread_check_susp(td, true);
1494 			if (error != 0)
1495 				return (error);
1496 			mtx_lock(&vm->rendezvous_mtx);
1497 		}
1498 	}
1499 	mtx_unlock(&vm->rendezvous_mtx);
1500 	return (0);
1501 }
1502 
1503 /*
1504  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1505  */
1506 static int
1507 vm_handle_hlt(struct vcpu *vcpu, bool intr_disabled, bool *retu)
1508 {
1509 	struct vm *vm = vcpu->vm;
1510 	const char *wmesg;
1511 	struct thread *td;
1512 	int error, t, vcpuid, vcpu_halted, vm_halted;
1513 
1514 	vcpuid = vcpu->vcpuid;
1515 	vcpu_halted = 0;
1516 	vm_halted = 0;
1517 	error = 0;
1518 	td = curthread;
1519 
1520 	KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1521 
1522 	vcpu_lock(vcpu);
1523 	while (1) {
1524 		/*
1525 		 * Do a final check for pending NMI or interrupts before
1526 		 * really putting this thread to sleep. Also check for
1527 		 * software events that would cause this vcpu to wakeup.
1528 		 *
1529 		 * These interrupts/events could have happened after the
1530 		 * vcpu returned from vmmops_run() and before it acquired the
1531 		 * vcpu lock above.
1532 		 */
1533 		if (vm->rendezvous_func != NULL || vm->suspend || vcpu->reqidle)
1534 			break;
1535 		if (vm_nmi_pending(vcpu))
1536 			break;
1537 		if (!intr_disabled) {
1538 			if (vm_extint_pending(vcpu) ||
1539 			    vlapic_pending_intr(vcpu->vlapic, NULL)) {
1540 				break;
1541 			}
1542 		}
1543 
1544 		/* Don't go to sleep if the vcpu thread needs to yield */
1545 		if (vcpu_should_yield(vcpu))
1546 			break;
1547 
1548 		if (vcpu_debugged(vcpu))
1549 			break;
1550 
1551 		/*
1552 		 * Some Linux guests implement "halt" by having all vcpus
1553 		 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1554 		 * track of the vcpus that have entered this state. When all
1555 		 * vcpus enter the halted state the virtual machine is halted.
1556 		 */
1557 		if (intr_disabled) {
1558 			wmesg = "vmhalt";
1559 			VMM_CTR0(vcpu, "Halted");
1560 			if (!vcpu_halted && halt_detection_enabled) {
1561 				vcpu_halted = 1;
1562 				CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1563 			}
1564 			if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1565 				vm_halted = 1;
1566 				break;
1567 			}
1568 		} else {
1569 			wmesg = "vmidle";
1570 		}
1571 
1572 		t = ticks;
1573 		vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1574 		/*
1575 		 * XXX msleep_spin() cannot be interrupted by signals so
1576 		 * wake up periodically to check pending signals.
1577 		 */
1578 		msleep_spin(vcpu, &vcpu->mtx, wmesg, hz);
1579 		vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1580 		vmm_stat_incr(vcpu, VCPU_IDLE_TICKS, ticks - t);
1581 		if (td_ast_pending(td, TDA_SUSPEND)) {
1582 			vcpu_unlock(vcpu);
1583 			error = thread_check_susp(td, false);
1584 			if (error != 0) {
1585 				if (vcpu_halted) {
1586 					CPU_CLR_ATOMIC(vcpuid,
1587 					    &vm->halted_cpus);
1588 				}
1589 				return (error);
1590 			}
1591 			vcpu_lock(vcpu);
1592 		}
1593 	}
1594 
1595 	if (vcpu_halted)
1596 		CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1597 
1598 	vcpu_unlock(vcpu);
1599 
1600 	if (vm_halted)
1601 		vm_suspend(vm, VM_SUSPEND_HALT);
1602 
1603 	return (0);
1604 }
1605 
1606 static int
1607 vm_handle_paging(struct vcpu *vcpu, bool *retu)
1608 {
1609 	struct vm *vm = vcpu->vm;
1610 	int rv, ftype;
1611 	struct vm_map *map;
1612 	struct vm_exit *vme;
1613 
1614 	vme = &vcpu->exitinfo;
1615 
1616 	KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1617 	    __func__, vme->inst_length));
1618 
1619 	ftype = vme->u.paging.fault_type;
1620 	KASSERT(ftype == VM_PROT_READ ||
1621 	    ftype == VM_PROT_WRITE || ftype == VM_PROT_EXECUTE,
1622 	    ("vm_handle_paging: invalid fault_type %d", ftype));
1623 
1624 	if (ftype == VM_PROT_READ || ftype == VM_PROT_WRITE) {
1625 		rv = pmap_emulate_accessed_dirty(vmspace_pmap(vm->vmspace),
1626 		    vme->u.paging.gpa, ftype);
1627 		if (rv == 0) {
1628 			VMM_CTR2(vcpu, "%s bit emulation for gpa %#lx",
1629 			    ftype == VM_PROT_READ ? "accessed" : "dirty",
1630 			    vme->u.paging.gpa);
1631 			goto done;
1632 		}
1633 	}
1634 
1635 	map = &vm->vmspace->vm_map;
1636 	rv = vm_fault(map, vme->u.paging.gpa, ftype, VM_FAULT_NORMAL, NULL);
1637 
1638 	VMM_CTR3(vcpu, "vm_handle_paging rv = %d, gpa = %#lx, "
1639 	    "ftype = %d", rv, vme->u.paging.gpa, ftype);
1640 
1641 	if (rv != KERN_SUCCESS)
1642 		return (EFAULT);
1643 done:
1644 	return (0);
1645 }
1646 
1647 static int
1648 vm_handle_inst_emul(struct vcpu *vcpu, bool *retu)
1649 {
1650 	struct vie *vie;
1651 	struct vm_exit *vme;
1652 	uint64_t gla, gpa, cs_base;
1653 	struct vm_guest_paging *paging;
1654 	mem_region_read_t mread;
1655 	mem_region_write_t mwrite;
1656 	enum vm_cpu_mode cpu_mode;
1657 	int cs_d, error, fault;
1658 
1659 	vme = &vcpu->exitinfo;
1660 
1661 	KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1662 	    __func__, vme->inst_length));
1663 
1664 	gla = vme->u.inst_emul.gla;
1665 	gpa = vme->u.inst_emul.gpa;
1666 	cs_base = vme->u.inst_emul.cs_base;
1667 	cs_d = vme->u.inst_emul.cs_d;
1668 	vie = &vme->u.inst_emul.vie;
1669 	paging = &vme->u.inst_emul.paging;
1670 	cpu_mode = paging->cpu_mode;
1671 
1672 	VMM_CTR1(vcpu, "inst_emul fault accessing gpa %#lx", gpa);
1673 
1674 	/* Fetch, decode and emulate the faulting instruction */
1675 	if (vie->num_valid == 0) {
1676 		error = vmm_fetch_instruction(vcpu, paging, vme->rip + cs_base,
1677 		    VIE_INST_SIZE, vie, &fault);
1678 	} else {
1679 		/*
1680 		 * The instruction bytes have already been copied into 'vie'
1681 		 */
1682 		error = fault = 0;
1683 	}
1684 	if (error || fault)
1685 		return (error);
1686 
1687 	if (vmm_decode_instruction(vcpu, gla, cpu_mode, cs_d, vie) != 0) {
1688 		VMM_CTR1(vcpu, "Error decoding instruction at %#lx",
1689 		    vme->rip + cs_base);
1690 		*retu = true;	    /* dump instruction bytes in userspace */
1691 		return (0);
1692 	}
1693 
1694 	/*
1695 	 * Update 'nextrip' based on the length of the emulated instruction.
1696 	 */
1697 	vme->inst_length = vie->num_processed;
1698 	vcpu->nextrip += vie->num_processed;
1699 	VMM_CTR1(vcpu, "nextrip updated to %#lx after instruction decoding",
1700 	    vcpu->nextrip);
1701 
1702 	/* return to userland unless this is an in-kernel emulated device */
1703 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1704 		mread = lapic_mmio_read;
1705 		mwrite = lapic_mmio_write;
1706 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1707 		mread = vioapic_mmio_read;
1708 		mwrite = vioapic_mmio_write;
1709 	} else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1710 		mread = vhpet_mmio_read;
1711 		mwrite = vhpet_mmio_write;
1712 	} else {
1713 		*retu = true;
1714 		return (0);
1715 	}
1716 
1717 	error = vmm_emulate_instruction(vcpu, gpa, vie, paging, mread, mwrite,
1718 	    retu);
1719 
1720 	return (error);
1721 }
1722 
1723 static int
1724 vm_handle_suspend(struct vcpu *vcpu, bool *retu)
1725 {
1726 	struct vm *vm = vcpu->vm;
1727 	int error, i;
1728 	struct thread *td;
1729 
1730 	error = 0;
1731 	td = curthread;
1732 
1733 	CPU_SET_ATOMIC(vcpu->vcpuid, &vm->suspended_cpus);
1734 
1735 	/*
1736 	 * Wait until all 'active_cpus' have suspended themselves.
1737 	 *
1738 	 * Since a VM may be suspended at any time including when one or
1739 	 * more vcpus are doing a rendezvous we need to call the rendezvous
1740 	 * handler while we are waiting to prevent a deadlock.
1741 	 */
1742 	vcpu_lock(vcpu);
1743 	while (error == 0) {
1744 		if (CPU_CMP(&vm->suspended_cpus, &vm->active_cpus) == 0) {
1745 			VMM_CTR0(vcpu, "All vcpus suspended");
1746 			break;
1747 		}
1748 
1749 		if (vm->rendezvous_func == NULL) {
1750 			VMM_CTR0(vcpu, "Sleeping during suspend");
1751 			vcpu_require_state_locked(vcpu, VCPU_SLEEPING);
1752 			msleep_spin(vcpu, &vcpu->mtx, "vmsusp", hz);
1753 			vcpu_require_state_locked(vcpu, VCPU_FROZEN);
1754 			if (td_ast_pending(td, TDA_SUSPEND)) {
1755 				vcpu_unlock(vcpu);
1756 				error = thread_check_susp(td, false);
1757 				vcpu_lock(vcpu);
1758 			}
1759 		} else {
1760 			VMM_CTR0(vcpu, "Rendezvous during suspend");
1761 			vcpu_unlock(vcpu);
1762 			error = vm_handle_rendezvous(vcpu);
1763 			vcpu_lock(vcpu);
1764 		}
1765 	}
1766 	vcpu_unlock(vcpu);
1767 
1768 	/*
1769 	 * Wakeup the other sleeping vcpus and return to userspace.
1770 	 */
1771 	for (i = 0; i < vm->maxcpus; i++) {
1772 		if (CPU_ISSET(i, &vm->suspended_cpus)) {
1773 			vcpu_notify_event(vm_vcpu(vm, i), false);
1774 		}
1775 	}
1776 
1777 	*retu = true;
1778 	return (error);
1779 }
1780 
1781 static int
1782 vm_handle_reqidle(struct vcpu *vcpu, bool *retu)
1783 {
1784 	vcpu_lock(vcpu);
1785 	KASSERT(vcpu->reqidle, ("invalid vcpu reqidle %d", vcpu->reqidle));
1786 	vcpu->reqidle = 0;
1787 	vcpu_unlock(vcpu);
1788 	*retu = true;
1789 	return (0);
1790 }
1791 
1792 static int
1793 vm_handle_db(struct vcpu *vcpu, struct vm_exit *vme, bool *retu)
1794 {
1795 	int error, fault;
1796 	uint64_t rsp;
1797 	uint64_t rflags;
1798 	struct vm_copyinfo copyinfo[2];
1799 
1800 	*retu = true;
1801 	if (!vme->u.dbg.pushf_intercept || vme->u.dbg.tf_shadow_val != 0) {
1802 		return (0);
1803 	}
1804 
1805 	vm_get_register(vcpu, VM_REG_GUEST_RSP, &rsp);
1806 	error = vm_copy_setup(vcpu, &vme->u.dbg.paging, rsp, sizeof(uint64_t),
1807 	    VM_PROT_RW, copyinfo, nitems(copyinfo), &fault);
1808 	if (error != 0 || fault != 0) {
1809 		*retu = false;
1810 		return (EINVAL);
1811 	}
1812 
1813 	/* Read pushed rflags value from top of stack. */
1814 	vm_copyin(copyinfo, &rflags, sizeof(uint64_t));
1815 
1816 	/* Clear TF bit. */
1817 	rflags &= ~(PSL_T);
1818 
1819 	/* Write updated value back to memory. */
1820 	vm_copyout(&rflags, copyinfo, sizeof(uint64_t));
1821 	vm_copy_teardown(copyinfo, nitems(copyinfo));
1822 
1823 	return (0);
1824 }
1825 
1826 int
1827 vm_suspend(struct vm *vm, enum vm_suspend_how how)
1828 {
1829 	int i;
1830 
1831 	if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST)
1832 		return (EINVAL);
1833 
1834 	if (atomic_cmpset_int(&vm->suspend, 0, how) == 0) {
1835 		VM_CTR2(vm, "virtual machine already suspended %d/%d",
1836 		    vm->suspend, how);
1837 		return (EALREADY);
1838 	}
1839 
1840 	VM_CTR1(vm, "virtual machine successfully suspended %d", how);
1841 
1842 	/*
1843 	 * Notify all active vcpus that they are now suspended.
1844 	 */
1845 	for (i = 0; i < vm->maxcpus; i++) {
1846 		if (CPU_ISSET(i, &vm->active_cpus))
1847 			vcpu_notify_event(vm_vcpu(vm, i), false);
1848 	}
1849 
1850 	return (0);
1851 }
1852 
1853 void
1854 vm_exit_suspended(struct vcpu *vcpu, uint64_t rip)
1855 {
1856 	struct vm *vm = vcpu->vm;
1857 	struct vm_exit *vmexit;
1858 
1859 	KASSERT(vm->suspend > VM_SUSPEND_NONE && vm->suspend < VM_SUSPEND_LAST,
1860 	    ("vm_exit_suspended: invalid suspend type %d", vm->suspend));
1861 
1862 	vmexit = vm_exitinfo(vcpu);
1863 	vmexit->rip = rip;
1864 	vmexit->inst_length = 0;
1865 	vmexit->exitcode = VM_EXITCODE_SUSPENDED;
1866 	vmexit->u.suspended.how = vm->suspend;
1867 }
1868 
1869 void
1870 vm_exit_debug(struct vcpu *vcpu, uint64_t rip)
1871 {
1872 	struct vm_exit *vmexit;
1873 
1874 	vmexit = vm_exitinfo(vcpu);
1875 	vmexit->rip = rip;
1876 	vmexit->inst_length = 0;
1877 	vmexit->exitcode = VM_EXITCODE_DEBUG;
1878 }
1879 
1880 void
1881 vm_exit_rendezvous(struct vcpu *vcpu, uint64_t rip)
1882 {
1883 	struct vm_exit *vmexit;
1884 
1885 	vmexit = vm_exitinfo(vcpu);
1886 	vmexit->rip = rip;
1887 	vmexit->inst_length = 0;
1888 	vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1889 	vmm_stat_incr(vcpu, VMEXIT_RENDEZVOUS, 1);
1890 }
1891 
1892 void
1893 vm_exit_reqidle(struct vcpu *vcpu, uint64_t rip)
1894 {
1895 	struct vm_exit *vmexit;
1896 
1897 	vmexit = vm_exitinfo(vcpu);
1898 	vmexit->rip = rip;
1899 	vmexit->inst_length = 0;
1900 	vmexit->exitcode = VM_EXITCODE_REQIDLE;
1901 	vmm_stat_incr(vcpu, VMEXIT_REQIDLE, 1);
1902 }
1903 
1904 void
1905 vm_exit_astpending(struct vcpu *vcpu, uint64_t rip)
1906 {
1907 	struct vm_exit *vmexit;
1908 
1909 	vmexit = vm_exitinfo(vcpu);
1910 	vmexit->rip = rip;
1911 	vmexit->inst_length = 0;
1912 	vmexit->exitcode = VM_EXITCODE_BOGUS;
1913 	vmm_stat_incr(vcpu, VMEXIT_ASTPENDING, 1);
1914 }
1915 
1916 int
1917 vm_run(struct vcpu *vcpu)
1918 {
1919 	struct vm *vm = vcpu->vm;
1920 	struct vm_eventinfo evinfo;
1921 	int error, vcpuid;
1922 	struct pcb *pcb;
1923 	uint64_t tscval;
1924 	struct vm_exit *vme;
1925 	bool retu, intr_disabled;
1926 	pmap_t pmap;
1927 
1928 	vcpuid = vcpu->vcpuid;
1929 
1930 	if (!CPU_ISSET(vcpuid, &vm->active_cpus))
1931 		return (EINVAL);
1932 
1933 	if (CPU_ISSET(vcpuid, &vm->suspended_cpus))
1934 		return (EINVAL);
1935 
1936 	pmap = vmspace_pmap(vm->vmspace);
1937 	vme = &vcpu->exitinfo;
1938 	evinfo.rptr = &vm->rendezvous_req_cpus;
1939 	evinfo.sptr = &vm->suspend;
1940 	evinfo.iptr = &vcpu->reqidle;
1941 restart:
1942 	critical_enter();
1943 
1944 	KASSERT(!CPU_ISSET(curcpu, &pmap->pm_active),
1945 	    ("vm_run: absurd pm_active"));
1946 
1947 	tscval = rdtsc();
1948 
1949 	pcb = PCPU_GET(curpcb);
1950 	set_pcb_flags(pcb, PCB_FULL_IRET);
1951 
1952 	restore_guest_fpustate(vcpu);
1953 
1954 	vcpu_require_state(vcpu, VCPU_RUNNING);
1955 	error = vmmops_run(vcpu->cookie, vcpu->nextrip, pmap, &evinfo);
1956 	vcpu_require_state(vcpu, VCPU_FROZEN);
1957 
1958 	save_guest_fpustate(vcpu);
1959 
1960 	vmm_stat_incr(vcpu, VCPU_TOTAL_RUNTIME, rdtsc() - tscval);
1961 
1962 	critical_exit();
1963 
1964 	if (error == 0) {
1965 		retu = false;
1966 		vcpu->nextrip = vme->rip + vme->inst_length;
1967 		switch (vme->exitcode) {
1968 		case VM_EXITCODE_REQIDLE:
1969 			error = vm_handle_reqidle(vcpu, &retu);
1970 			break;
1971 		case VM_EXITCODE_SUSPENDED:
1972 			error = vm_handle_suspend(vcpu, &retu);
1973 			break;
1974 		case VM_EXITCODE_IOAPIC_EOI:
1975 			vioapic_process_eoi(vm, vme->u.ioapic_eoi.vector);
1976 			break;
1977 		case VM_EXITCODE_RENDEZVOUS:
1978 			error = vm_handle_rendezvous(vcpu);
1979 			break;
1980 		case VM_EXITCODE_HLT:
1981 			intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
1982 			error = vm_handle_hlt(vcpu, intr_disabled, &retu);
1983 			break;
1984 		case VM_EXITCODE_PAGING:
1985 			error = vm_handle_paging(vcpu, &retu);
1986 			break;
1987 		case VM_EXITCODE_INST_EMUL:
1988 			error = vm_handle_inst_emul(vcpu, &retu);
1989 			break;
1990 		case VM_EXITCODE_INOUT:
1991 		case VM_EXITCODE_INOUT_STR:
1992 			error = vm_handle_inout(vcpu, vme, &retu);
1993 			break;
1994 		case VM_EXITCODE_DB:
1995 			error = vm_handle_db(vcpu, vme, &retu);
1996 			break;
1997 		case VM_EXITCODE_MONITOR:
1998 		case VM_EXITCODE_MWAIT:
1999 		case VM_EXITCODE_VMINSN:
2000 			vm_inject_ud(vcpu);
2001 			break;
2002 		default:
2003 			retu = true;	/* handled in userland */
2004 			break;
2005 		}
2006 	}
2007 
2008 	/*
2009 	 * VM_EXITCODE_INST_EMUL could access the apic which could transform the
2010 	 * exit code into VM_EXITCODE_IPI.
2011 	 */
2012 	if (error == 0 && vme->exitcode == VM_EXITCODE_IPI)
2013 		error = vm_handle_ipi(vcpu, vme, &retu);
2014 
2015 	if (error == 0 && retu == false)
2016 		goto restart;
2017 
2018 	vmm_stat_incr(vcpu, VMEXIT_USERSPACE, 1);
2019 	VMM_CTR2(vcpu, "retu %d/%d", error, vme->exitcode);
2020 
2021 	return (error);
2022 }
2023 
2024 int
2025 vm_restart_instruction(struct vcpu *vcpu)
2026 {
2027 	enum vcpu_state state;
2028 	uint64_t rip;
2029 	int error __diagused;
2030 
2031 	state = vcpu_get_state(vcpu, NULL);
2032 	if (state == VCPU_RUNNING) {
2033 		/*
2034 		 * When a vcpu is "running" the next instruction is determined
2035 		 * by adding 'rip' and 'inst_length' in the vcpu's 'exitinfo'.
2036 		 * Thus setting 'inst_length' to zero will cause the current
2037 		 * instruction to be restarted.
2038 		 */
2039 		vcpu->exitinfo.inst_length = 0;
2040 		VMM_CTR1(vcpu, "restarting instruction at %#lx by "
2041 		    "setting inst_length to zero", vcpu->exitinfo.rip);
2042 	} else if (state == VCPU_FROZEN) {
2043 		/*
2044 		 * When a vcpu is "frozen" it is outside the critical section
2045 		 * around vmmops_run() and 'nextrip' points to the next
2046 		 * instruction. Thus instruction restart is achieved by setting
2047 		 * 'nextrip' to the vcpu's %rip.
2048 		 */
2049 		error = vm_get_register(vcpu, VM_REG_GUEST_RIP, &rip);
2050 		KASSERT(!error, ("%s: error %d getting rip", __func__, error));
2051 		VMM_CTR2(vcpu, "restarting instruction by updating "
2052 		    "nextrip from %#lx to %#lx", vcpu->nextrip, rip);
2053 		vcpu->nextrip = rip;
2054 	} else {
2055 		panic("%s: invalid state %d", __func__, state);
2056 	}
2057 	return (0);
2058 }
2059 
2060 int
2061 vm_exit_intinfo(struct vcpu *vcpu, uint64_t info)
2062 {
2063 	int type, vector;
2064 
2065 	if (info & VM_INTINFO_VALID) {
2066 		type = info & VM_INTINFO_TYPE;
2067 		vector = info & 0xff;
2068 		if (type == VM_INTINFO_NMI && vector != IDT_NMI)
2069 			return (EINVAL);
2070 		if (type == VM_INTINFO_HWEXCEPTION && vector >= 32)
2071 			return (EINVAL);
2072 		if (info & VM_INTINFO_RSVD)
2073 			return (EINVAL);
2074 	} else {
2075 		info = 0;
2076 	}
2077 	VMM_CTR2(vcpu, "%s: info1(%#lx)", __func__, info);
2078 	vcpu->exitintinfo = info;
2079 	return (0);
2080 }
2081 
2082 enum exc_class {
2083 	EXC_BENIGN,
2084 	EXC_CONTRIBUTORY,
2085 	EXC_PAGEFAULT
2086 };
2087 
2088 #define	IDT_VE	20	/* Virtualization Exception (Intel specific) */
2089 
2090 static enum exc_class
2091 exception_class(uint64_t info)
2092 {
2093 	int type, vector;
2094 
2095 	KASSERT(info & VM_INTINFO_VALID, ("intinfo must be valid: %#lx", info));
2096 	type = info & VM_INTINFO_TYPE;
2097 	vector = info & 0xff;
2098 
2099 	/* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
2100 	switch (type) {
2101 	case VM_INTINFO_HWINTR:
2102 	case VM_INTINFO_SWINTR:
2103 	case VM_INTINFO_NMI:
2104 		return (EXC_BENIGN);
2105 	default:
2106 		/*
2107 		 * Hardware exception.
2108 		 *
2109 		 * SVM and VT-x use identical type values to represent NMI,
2110 		 * hardware interrupt and software interrupt.
2111 		 *
2112 		 * SVM uses type '3' for all exceptions. VT-x uses type '3'
2113 		 * for exceptions except #BP and #OF. #BP and #OF use a type
2114 		 * value of '5' or '6'. Therefore we don't check for explicit
2115 		 * values of 'type' to classify 'intinfo' into a hardware
2116 		 * exception.
2117 		 */
2118 		break;
2119 	}
2120 
2121 	switch (vector) {
2122 	case IDT_PF:
2123 	case IDT_VE:
2124 		return (EXC_PAGEFAULT);
2125 	case IDT_DE:
2126 	case IDT_TS:
2127 	case IDT_NP:
2128 	case IDT_SS:
2129 	case IDT_GP:
2130 		return (EXC_CONTRIBUTORY);
2131 	default:
2132 		return (EXC_BENIGN);
2133 	}
2134 }
2135 
2136 static int
2137 nested_fault(struct vcpu *vcpu, uint64_t info1, uint64_t info2,
2138     uint64_t *retinfo)
2139 {
2140 	enum exc_class exc1, exc2;
2141 	int type1, vector1;
2142 
2143 	KASSERT(info1 & VM_INTINFO_VALID, ("info1 %#lx is not valid", info1));
2144 	KASSERT(info2 & VM_INTINFO_VALID, ("info2 %#lx is not valid", info2));
2145 
2146 	/*
2147 	 * If an exception occurs while attempting to call the double-fault
2148 	 * handler the processor enters shutdown mode (aka triple fault).
2149 	 */
2150 	type1 = info1 & VM_INTINFO_TYPE;
2151 	vector1 = info1 & 0xff;
2152 	if (type1 == VM_INTINFO_HWEXCEPTION && vector1 == IDT_DF) {
2153 		VMM_CTR2(vcpu, "triple fault: info1(%#lx), info2(%#lx)",
2154 		    info1, info2);
2155 		vm_suspend(vcpu->vm, VM_SUSPEND_TRIPLEFAULT);
2156 		*retinfo = 0;
2157 		return (0);
2158 	}
2159 
2160 	/*
2161 	 * Table 6-5 "Conditions for Generating a Double Fault", Intel SDM, Vol3
2162 	 */
2163 	exc1 = exception_class(info1);
2164 	exc2 = exception_class(info2);
2165 	if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
2166 	    (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
2167 		/* Convert nested fault into a double fault. */
2168 		*retinfo = IDT_DF;
2169 		*retinfo |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
2170 		*retinfo |= VM_INTINFO_DEL_ERRCODE;
2171 	} else {
2172 		/* Handle exceptions serially */
2173 		*retinfo = info2;
2174 	}
2175 	return (1);
2176 }
2177 
2178 static uint64_t
2179 vcpu_exception_intinfo(struct vcpu *vcpu)
2180 {
2181 	uint64_t info = 0;
2182 
2183 	if (vcpu->exception_pending) {
2184 		info = vcpu->exc_vector & 0xff;
2185 		info |= VM_INTINFO_VALID | VM_INTINFO_HWEXCEPTION;
2186 		if (vcpu->exc_errcode_valid) {
2187 			info |= VM_INTINFO_DEL_ERRCODE;
2188 			info |= (uint64_t)vcpu->exc_errcode << 32;
2189 		}
2190 	}
2191 	return (info);
2192 }
2193 
2194 int
2195 vm_entry_intinfo(struct vcpu *vcpu, uint64_t *retinfo)
2196 {
2197 	uint64_t info1, info2;
2198 	int valid;
2199 
2200 	info1 = vcpu->exitintinfo;
2201 	vcpu->exitintinfo = 0;
2202 
2203 	info2 = 0;
2204 	if (vcpu->exception_pending) {
2205 		info2 = vcpu_exception_intinfo(vcpu);
2206 		vcpu->exception_pending = 0;
2207 		VMM_CTR2(vcpu, "Exception %d delivered: %#lx",
2208 		    vcpu->exc_vector, info2);
2209 	}
2210 
2211 	if ((info1 & VM_INTINFO_VALID) && (info2 & VM_INTINFO_VALID)) {
2212 		valid = nested_fault(vcpu, info1, info2, retinfo);
2213 	} else if (info1 & VM_INTINFO_VALID) {
2214 		*retinfo = info1;
2215 		valid = 1;
2216 	} else if (info2 & VM_INTINFO_VALID) {
2217 		*retinfo = info2;
2218 		valid = 1;
2219 	} else {
2220 		valid = 0;
2221 	}
2222 
2223 	if (valid) {
2224 		VMM_CTR4(vcpu, "%s: info1(%#lx), info2(%#lx), "
2225 		    "retinfo(%#lx)", __func__, info1, info2, *retinfo);
2226 	}
2227 
2228 	return (valid);
2229 }
2230 
2231 int
2232 vm_get_intinfo(struct vcpu *vcpu, uint64_t *info1, uint64_t *info2)
2233 {
2234 	*info1 = vcpu->exitintinfo;
2235 	*info2 = vcpu_exception_intinfo(vcpu);
2236 	return (0);
2237 }
2238 
2239 int
2240 vm_inject_exception(struct vcpu *vcpu, int vector, int errcode_valid,
2241     uint32_t errcode, int restart_instruction)
2242 {
2243 	uint64_t regval;
2244 	int error __diagused;
2245 
2246 	if (vector < 0 || vector >= 32)
2247 		return (EINVAL);
2248 
2249 	/*
2250 	 * A double fault exception should never be injected directly into
2251 	 * the guest. It is a derived exception that results from specific
2252 	 * combinations of nested faults.
2253 	 */
2254 	if (vector == IDT_DF)
2255 		return (EINVAL);
2256 
2257 	if (vcpu->exception_pending) {
2258 		VMM_CTR2(vcpu, "Unable to inject exception %d due to "
2259 		    "pending exception %d", vector, vcpu->exc_vector);
2260 		return (EBUSY);
2261 	}
2262 
2263 	if (errcode_valid) {
2264 		/*
2265 		 * Exceptions don't deliver an error code in real mode.
2266 		 */
2267 		error = vm_get_register(vcpu, VM_REG_GUEST_CR0, &regval);
2268 		KASSERT(!error, ("%s: error %d getting CR0", __func__, error));
2269 		if (!(regval & CR0_PE))
2270 			errcode_valid = 0;
2271 	}
2272 
2273 	/*
2274 	 * From section 26.6.1 "Interruptibility State" in Intel SDM:
2275 	 *
2276 	 * Event blocking by "STI" or "MOV SS" is cleared after guest executes
2277 	 * one instruction or incurs an exception.
2278 	 */
2279 	error = vm_set_register(vcpu, VM_REG_GUEST_INTR_SHADOW, 0);
2280 	KASSERT(error == 0, ("%s: error %d clearing interrupt shadow",
2281 	    __func__, error));
2282 
2283 	if (restart_instruction)
2284 		vm_restart_instruction(vcpu);
2285 
2286 	vcpu->exception_pending = 1;
2287 	vcpu->exc_vector = vector;
2288 	vcpu->exc_errcode = errcode;
2289 	vcpu->exc_errcode_valid = errcode_valid;
2290 	VMM_CTR1(vcpu, "Exception %d pending", vector);
2291 	return (0);
2292 }
2293 
2294 void
2295 vm_inject_fault(struct vcpu *vcpu, int vector, int errcode_valid, int errcode)
2296 {
2297 	int error __diagused, restart_instruction;
2298 
2299 	restart_instruction = 1;
2300 
2301 	error = vm_inject_exception(vcpu, vector, errcode_valid,
2302 	    errcode, restart_instruction);
2303 	KASSERT(error == 0, ("vm_inject_exception error %d", error));
2304 }
2305 
2306 void
2307 vm_inject_pf(struct vcpu *vcpu, int error_code, uint64_t cr2)
2308 {
2309 	int error __diagused;
2310 
2311 	VMM_CTR2(vcpu, "Injecting page fault: error_code %#x, cr2 %#lx",
2312 	    error_code, cr2);
2313 
2314 	error = vm_set_register(vcpu, VM_REG_GUEST_CR2, cr2);
2315 	KASSERT(error == 0, ("vm_set_register(cr2) error %d", error));
2316 
2317 	vm_inject_fault(vcpu, IDT_PF, 1, error_code);
2318 }
2319 
2320 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
2321 
2322 int
2323 vm_inject_nmi(struct vcpu *vcpu)
2324 {
2325 
2326 	vcpu->nmi_pending = 1;
2327 	vcpu_notify_event(vcpu, false);
2328 	return (0);
2329 }
2330 
2331 int
2332 vm_nmi_pending(struct vcpu *vcpu)
2333 {
2334 	return (vcpu->nmi_pending);
2335 }
2336 
2337 void
2338 vm_nmi_clear(struct vcpu *vcpu)
2339 {
2340 	if (vcpu->nmi_pending == 0)
2341 		panic("vm_nmi_clear: inconsistent nmi_pending state");
2342 
2343 	vcpu->nmi_pending = 0;
2344 	vmm_stat_incr(vcpu, VCPU_NMI_COUNT, 1);
2345 }
2346 
2347 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
2348 
2349 int
2350 vm_inject_extint(struct vcpu *vcpu)
2351 {
2352 
2353 	vcpu->extint_pending = 1;
2354 	vcpu_notify_event(vcpu, false);
2355 	return (0);
2356 }
2357 
2358 int
2359 vm_extint_pending(struct vcpu *vcpu)
2360 {
2361 	return (vcpu->extint_pending);
2362 }
2363 
2364 void
2365 vm_extint_clear(struct vcpu *vcpu)
2366 {
2367 	if (vcpu->extint_pending == 0)
2368 		panic("vm_extint_clear: inconsistent extint_pending state");
2369 
2370 	vcpu->extint_pending = 0;
2371 	vmm_stat_incr(vcpu, VCPU_EXTINT_COUNT, 1);
2372 }
2373 
2374 int
2375 vm_get_capability(struct vcpu *vcpu, int type, int *retval)
2376 {
2377 	if (type < 0 || type >= VM_CAP_MAX)
2378 		return (EINVAL);
2379 
2380 	return (vmmops_getcap(vcpu->cookie, type, retval));
2381 }
2382 
2383 int
2384 vm_set_capability(struct vcpu *vcpu, int type, int val)
2385 {
2386 	if (type < 0 || type >= VM_CAP_MAX)
2387 		return (EINVAL);
2388 
2389 	return (vmmops_setcap(vcpu->cookie, type, val));
2390 }
2391 
2392 struct vm *
2393 vcpu_vm(struct vcpu *vcpu)
2394 {
2395 	return (vcpu->vm);
2396 }
2397 
2398 int
2399 vcpu_vcpuid(struct vcpu *vcpu)
2400 {
2401 	return (vcpu->vcpuid);
2402 }
2403 
2404 struct vcpu *
2405 vm_vcpu(struct vm *vm, int vcpuid)
2406 {
2407 	return (vm->vcpu[vcpuid]);
2408 }
2409 
2410 struct vlapic *
2411 vm_lapic(struct vcpu *vcpu)
2412 {
2413 	return (vcpu->vlapic);
2414 }
2415 
2416 struct vioapic *
2417 vm_ioapic(struct vm *vm)
2418 {
2419 
2420 	return (vm->vioapic);
2421 }
2422 
2423 struct vhpet *
2424 vm_hpet(struct vm *vm)
2425 {
2426 
2427 	return (vm->vhpet);
2428 }
2429 
2430 bool
2431 vmm_is_pptdev(int bus, int slot, int func)
2432 {
2433 	int b, f, i, n, s;
2434 	char *val, *cp, *cp2;
2435 	bool found;
2436 
2437 	/*
2438 	 * XXX
2439 	 * The length of an environment variable is limited to 128 bytes which
2440 	 * puts an upper limit on the number of passthru devices that may be
2441 	 * specified using a single environment variable.
2442 	 *
2443 	 * Work around this by scanning multiple environment variable
2444 	 * names instead of a single one - yuck!
2445 	 */
2446 	const char *names[] = { "pptdevs", "pptdevs2", "pptdevs3", NULL };
2447 
2448 	/* set pptdevs="1/2/3 4/5/6 7/8/9 10/11/12" */
2449 	found = false;
2450 	for (i = 0; names[i] != NULL && !found; i++) {
2451 		cp = val = kern_getenv(names[i]);
2452 		while (cp != NULL && *cp != '\0') {
2453 			if ((cp2 = strchr(cp, ' ')) != NULL)
2454 				*cp2 = '\0';
2455 
2456 			n = sscanf(cp, "%d/%d/%d", &b, &s, &f);
2457 			if (n == 3 && bus == b && slot == s && func == f) {
2458 				found = true;
2459 				break;
2460 			}
2461 
2462 			if (cp2 != NULL)
2463 				*cp2++ = ' ';
2464 
2465 			cp = cp2;
2466 		}
2467 		freeenv(val);
2468 	}
2469 	return (found);
2470 }
2471 
2472 void *
2473 vm_iommu_domain(struct vm *vm)
2474 {
2475 
2476 	return (vm->iommu);
2477 }
2478 
2479 int
2480 vcpu_set_state(struct vcpu *vcpu, enum vcpu_state newstate, bool from_idle)
2481 {
2482 	int error;
2483 
2484 	vcpu_lock(vcpu);
2485 	error = vcpu_set_state_locked(vcpu, newstate, from_idle);
2486 	vcpu_unlock(vcpu);
2487 
2488 	return (error);
2489 }
2490 
2491 enum vcpu_state
2492 vcpu_get_state(struct vcpu *vcpu, int *hostcpu)
2493 {
2494 	enum vcpu_state state;
2495 
2496 	vcpu_lock(vcpu);
2497 	state = vcpu->state;
2498 	if (hostcpu != NULL)
2499 		*hostcpu = vcpu->hostcpu;
2500 	vcpu_unlock(vcpu);
2501 
2502 	return (state);
2503 }
2504 
2505 int
2506 vm_activate_cpu(struct vcpu *vcpu)
2507 {
2508 	struct vm *vm = vcpu->vm;
2509 
2510 	if (CPU_ISSET(vcpu->vcpuid, &vm->active_cpus))
2511 		return (EBUSY);
2512 
2513 	VMM_CTR0(vcpu, "activated");
2514 	CPU_SET_ATOMIC(vcpu->vcpuid, &vm->active_cpus);
2515 	return (0);
2516 }
2517 
2518 int
2519 vm_suspend_cpu(struct vm *vm, struct vcpu *vcpu)
2520 {
2521 	if (vcpu == NULL) {
2522 		vm->debug_cpus = vm->active_cpus;
2523 		for (int i = 0; i < vm->maxcpus; i++) {
2524 			if (CPU_ISSET(i, &vm->active_cpus))
2525 				vcpu_notify_event(vm_vcpu(vm, i), false);
2526 		}
2527 	} else {
2528 		if (!CPU_ISSET(vcpu->vcpuid, &vm->active_cpus))
2529 			return (EINVAL);
2530 
2531 		CPU_SET_ATOMIC(vcpu->vcpuid, &vm->debug_cpus);
2532 		vcpu_notify_event(vcpu, false);
2533 	}
2534 	return (0);
2535 }
2536 
2537 int
2538 vm_resume_cpu(struct vm *vm, struct vcpu *vcpu)
2539 {
2540 
2541 	if (vcpu == NULL) {
2542 		CPU_ZERO(&vm->debug_cpus);
2543 	} else {
2544 		if (!CPU_ISSET(vcpu->vcpuid, &vm->debug_cpus))
2545 			return (EINVAL);
2546 
2547 		CPU_CLR_ATOMIC(vcpu->vcpuid, &vm->debug_cpus);
2548 	}
2549 	return (0);
2550 }
2551 
2552 int
2553 vcpu_debugged(struct vcpu *vcpu)
2554 {
2555 
2556 	return (CPU_ISSET(vcpu->vcpuid, &vcpu->vm->debug_cpus));
2557 }
2558 
2559 cpuset_t
2560 vm_active_cpus(struct vm *vm)
2561 {
2562 
2563 	return (vm->active_cpus);
2564 }
2565 
2566 cpuset_t
2567 vm_debug_cpus(struct vm *vm)
2568 {
2569 
2570 	return (vm->debug_cpus);
2571 }
2572 
2573 cpuset_t
2574 vm_suspended_cpus(struct vm *vm)
2575 {
2576 
2577 	return (vm->suspended_cpus);
2578 }
2579 
2580 /*
2581  * Returns the subset of vCPUs in tostart that are awaiting startup.
2582  * These vCPUs are also marked as no longer awaiting startup.
2583  */
2584 cpuset_t
2585 vm_start_cpus(struct vm *vm, const cpuset_t *tostart)
2586 {
2587 	cpuset_t set;
2588 
2589 	mtx_lock(&vm->rendezvous_mtx);
2590 	CPU_AND(&set, &vm->startup_cpus, tostart);
2591 	CPU_ANDNOT(&vm->startup_cpus, &vm->startup_cpus, &set);
2592 	mtx_unlock(&vm->rendezvous_mtx);
2593 	return (set);
2594 }
2595 
2596 void
2597 vm_await_start(struct vm *vm, const cpuset_t *waiting)
2598 {
2599 	mtx_lock(&vm->rendezvous_mtx);
2600 	CPU_OR(&vm->startup_cpus, &vm->startup_cpus, waiting);
2601 	mtx_unlock(&vm->rendezvous_mtx);
2602 }
2603 
2604 void *
2605 vcpu_stats(struct vcpu *vcpu)
2606 {
2607 
2608 	return (vcpu->stats);
2609 }
2610 
2611 int
2612 vm_get_x2apic_state(struct vcpu *vcpu, enum x2apic_state *state)
2613 {
2614 	*state = vcpu->x2apic_state;
2615 
2616 	return (0);
2617 }
2618 
2619 int
2620 vm_set_x2apic_state(struct vcpu *vcpu, enum x2apic_state state)
2621 {
2622 	if (state >= X2APIC_STATE_LAST)
2623 		return (EINVAL);
2624 
2625 	vcpu->x2apic_state = state;
2626 
2627 	vlapic_set_x2apic_state(vcpu, state);
2628 
2629 	return (0);
2630 }
2631 
2632 /*
2633  * This function is called to ensure that a vcpu "sees" a pending event
2634  * as soon as possible:
2635  * - If the vcpu thread is sleeping then it is woken up.
2636  * - If the vcpu is running on a different host_cpu then an IPI will be directed
2637  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
2638  */
2639 static void
2640 vcpu_notify_event_locked(struct vcpu *vcpu, bool lapic_intr)
2641 {
2642 	int hostcpu;
2643 
2644 	hostcpu = vcpu->hostcpu;
2645 	if (vcpu->state == VCPU_RUNNING) {
2646 		KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
2647 		if (hostcpu != curcpu) {
2648 			if (lapic_intr) {
2649 				vlapic_post_intr(vcpu->vlapic, hostcpu,
2650 				    vmm_ipinum);
2651 			} else {
2652 				ipi_cpu(hostcpu, vmm_ipinum);
2653 			}
2654 		} else {
2655 			/*
2656 			 * If the 'vcpu' is running on 'curcpu' then it must
2657 			 * be sending a notification to itself (e.g. SELF_IPI).
2658 			 * The pending event will be picked up when the vcpu
2659 			 * transitions back to guest context.
2660 			 */
2661 		}
2662 	} else {
2663 		KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
2664 		    "with hostcpu %d", vcpu->state, hostcpu));
2665 		if (vcpu->state == VCPU_SLEEPING)
2666 			wakeup_one(vcpu);
2667 	}
2668 }
2669 
2670 void
2671 vcpu_notify_event(struct vcpu *vcpu, bool lapic_intr)
2672 {
2673 	vcpu_lock(vcpu);
2674 	vcpu_notify_event_locked(vcpu, lapic_intr);
2675 	vcpu_unlock(vcpu);
2676 }
2677 
2678 struct vmspace *
2679 vm_get_vmspace(struct vm *vm)
2680 {
2681 
2682 	return (vm->vmspace);
2683 }
2684 
2685 int
2686 vm_apicid2vcpuid(struct vm *vm, int apicid)
2687 {
2688 	/*
2689 	 * XXX apic id is assumed to be numerically identical to vcpu id
2690 	 */
2691 	return (apicid);
2692 }
2693 
2694 int
2695 vm_smp_rendezvous(struct vcpu *vcpu, cpuset_t dest,
2696     vm_rendezvous_func_t func, void *arg)
2697 {
2698 	struct vm *vm = vcpu->vm;
2699 	int error, i;
2700 
2701 	/*
2702 	 * Enforce that this function is called without any locks
2703 	 */
2704 	WITNESS_WARN(WARN_PANIC, NULL, "vm_smp_rendezvous");
2705 
2706 restart:
2707 	mtx_lock(&vm->rendezvous_mtx);
2708 	if (vm->rendezvous_func != NULL) {
2709 		/*
2710 		 * If a rendezvous is already in progress then we need to
2711 		 * call the rendezvous handler in case this 'vcpu' is one
2712 		 * of the targets of the rendezvous.
2713 		 */
2714 		VMM_CTR0(vcpu, "Rendezvous already in progress");
2715 		mtx_unlock(&vm->rendezvous_mtx);
2716 		error = vm_handle_rendezvous(vcpu);
2717 		if (error != 0)
2718 			return (error);
2719 		goto restart;
2720 	}
2721 	KASSERT(vm->rendezvous_func == NULL, ("vm_smp_rendezvous: previous "
2722 	    "rendezvous is still in progress"));
2723 
2724 	VMM_CTR0(vcpu, "Initiating rendezvous");
2725 	vm->rendezvous_req_cpus = dest;
2726 	CPU_ZERO(&vm->rendezvous_done_cpus);
2727 	vm->rendezvous_arg = arg;
2728 	vm->rendezvous_func = func;
2729 	mtx_unlock(&vm->rendezvous_mtx);
2730 
2731 	/*
2732 	 * Wake up any sleeping vcpus and trigger a VM-exit in any running
2733 	 * vcpus so they handle the rendezvous as soon as possible.
2734 	 */
2735 	for (i = 0; i < vm->maxcpus; i++) {
2736 		if (CPU_ISSET(i, &dest))
2737 			vcpu_notify_event(vm_vcpu(vm, i), false);
2738 	}
2739 
2740 	return (vm_handle_rendezvous(vcpu));
2741 }
2742 
2743 struct vatpic *
2744 vm_atpic(struct vm *vm)
2745 {
2746 	return (vm->vatpic);
2747 }
2748 
2749 struct vatpit *
2750 vm_atpit(struct vm *vm)
2751 {
2752 	return (vm->vatpit);
2753 }
2754 
2755 struct vpmtmr *
2756 vm_pmtmr(struct vm *vm)
2757 {
2758 
2759 	return (vm->vpmtmr);
2760 }
2761 
2762 struct vrtc *
2763 vm_rtc(struct vm *vm)
2764 {
2765 
2766 	return (vm->vrtc);
2767 }
2768 
2769 enum vm_reg_name
2770 vm_segment_name(int seg)
2771 {
2772 	static enum vm_reg_name seg_names[] = {
2773 		VM_REG_GUEST_ES,
2774 		VM_REG_GUEST_CS,
2775 		VM_REG_GUEST_SS,
2776 		VM_REG_GUEST_DS,
2777 		VM_REG_GUEST_FS,
2778 		VM_REG_GUEST_GS
2779 	};
2780 
2781 	KASSERT(seg >= 0 && seg < nitems(seg_names),
2782 	    ("%s: invalid segment encoding %d", __func__, seg));
2783 	return (seg_names[seg]);
2784 }
2785 
2786 void
2787 vm_copy_teardown(struct vm_copyinfo *copyinfo, int num_copyinfo)
2788 {
2789 	int idx;
2790 
2791 	for (idx = 0; idx < num_copyinfo; idx++) {
2792 		if (copyinfo[idx].cookie != NULL)
2793 			vm_gpa_release(copyinfo[idx].cookie);
2794 	}
2795 	bzero(copyinfo, num_copyinfo * sizeof(struct vm_copyinfo));
2796 }
2797 
2798 int
2799 vm_copy_setup(struct vcpu *vcpu, struct vm_guest_paging *paging,
2800     uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
2801     int num_copyinfo, int *fault)
2802 {
2803 	int error, idx, nused;
2804 	size_t n, off, remaining;
2805 	void *hva, *cookie;
2806 	uint64_t gpa;
2807 
2808 	bzero(copyinfo, sizeof(struct vm_copyinfo) * num_copyinfo);
2809 
2810 	nused = 0;
2811 	remaining = len;
2812 	while (remaining > 0) {
2813 		if (nused >= num_copyinfo)
2814 			return (EFAULT);
2815 		error = vm_gla2gpa(vcpu, paging, gla, prot, &gpa, fault);
2816 		if (error || *fault)
2817 			return (error);
2818 		off = gpa & PAGE_MASK;
2819 		n = min(remaining, PAGE_SIZE - off);
2820 		copyinfo[nused].gpa = gpa;
2821 		copyinfo[nused].len = n;
2822 		remaining -= n;
2823 		gla += n;
2824 		nused++;
2825 	}
2826 
2827 	for (idx = 0; idx < nused; idx++) {
2828 		hva = vm_gpa_hold(vcpu, copyinfo[idx].gpa,
2829 		    copyinfo[idx].len, prot, &cookie);
2830 		if (hva == NULL)
2831 			break;
2832 		copyinfo[idx].hva = hva;
2833 		copyinfo[idx].cookie = cookie;
2834 	}
2835 
2836 	if (idx != nused) {
2837 		vm_copy_teardown(copyinfo, num_copyinfo);
2838 		return (EFAULT);
2839 	} else {
2840 		*fault = 0;
2841 		return (0);
2842 	}
2843 }
2844 
2845 void
2846 vm_copyin(struct vm_copyinfo *copyinfo, void *kaddr, size_t len)
2847 {
2848 	char *dst;
2849 	int idx;
2850 
2851 	dst = kaddr;
2852 	idx = 0;
2853 	while (len > 0) {
2854 		bcopy(copyinfo[idx].hva, dst, copyinfo[idx].len);
2855 		len -= copyinfo[idx].len;
2856 		dst += copyinfo[idx].len;
2857 		idx++;
2858 	}
2859 }
2860 
2861 void
2862 vm_copyout(const void *kaddr, struct vm_copyinfo *copyinfo, size_t len)
2863 {
2864 	const char *src;
2865 	int idx;
2866 
2867 	src = kaddr;
2868 	idx = 0;
2869 	while (len > 0) {
2870 		bcopy(src, copyinfo[idx].hva, copyinfo[idx].len);
2871 		len -= copyinfo[idx].len;
2872 		src += copyinfo[idx].len;
2873 		idx++;
2874 	}
2875 }
2876 
2877 /*
2878  * Return the amount of in-use and wired memory for the VM. Since
2879  * these are global stats, only return the values with for vCPU 0
2880  */
2881 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
2882 VMM_STAT_DECLARE(VMM_MEM_WIRED);
2883 
2884 static void
2885 vm_get_rescnt(struct vcpu *vcpu, struct vmm_stat_type *stat)
2886 {
2887 
2888 	if (vcpu->vcpuid == 0) {
2889 		vmm_stat_set(vcpu, VMM_MEM_RESIDENT, PAGE_SIZE *
2890 		    vmspace_resident_count(vcpu->vm->vmspace));
2891 	}
2892 }
2893 
2894 static void
2895 vm_get_wiredcnt(struct vcpu *vcpu, struct vmm_stat_type *stat)
2896 {
2897 
2898 	if (vcpu->vcpuid == 0) {
2899 		vmm_stat_set(vcpu, VMM_MEM_WIRED, PAGE_SIZE *
2900 		    pmap_wired_count(vmspace_pmap(vcpu->vm->vmspace)));
2901 	}
2902 }
2903 
2904 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
2905 VMM_STAT_FUNC(VMM_MEM_WIRED, "Wired memory", vm_get_wiredcnt);
2906 
2907 #ifdef BHYVE_SNAPSHOT
2908 static int
2909 vm_snapshot_vcpus(struct vm *vm, struct vm_snapshot_meta *meta)
2910 {
2911 	uint64_t tsc, now;
2912 	int ret;
2913 	struct vcpu *vcpu;
2914 	uint16_t i, maxcpus;
2915 
2916 	now = rdtsc();
2917 	maxcpus = vm_get_maxcpus(vm);
2918 	for (i = 0; i < maxcpus; i++) {
2919 		vcpu = vm->vcpu[i];
2920 		if (vcpu == NULL)
2921 			continue;
2922 
2923 		SNAPSHOT_VAR_OR_LEAVE(vcpu->x2apic_state, meta, ret, done);
2924 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exitintinfo, meta, ret, done);
2925 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exc_vector, meta, ret, done);
2926 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exc_errcode_valid, meta, ret, done);
2927 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exc_errcode, meta, ret, done);
2928 		SNAPSHOT_VAR_OR_LEAVE(vcpu->guest_xcr0, meta, ret, done);
2929 		SNAPSHOT_VAR_OR_LEAVE(vcpu->exitinfo, meta, ret, done);
2930 		SNAPSHOT_VAR_OR_LEAVE(vcpu->nextrip, meta, ret, done);
2931 
2932 		/*
2933 		 * Save the absolute TSC value by adding now to tsc_offset.
2934 		 *
2935 		 * It will be turned turned back into an actual offset when the
2936 		 * TSC restore function is called
2937 		 */
2938 		tsc = now + vcpu->tsc_offset;
2939 		SNAPSHOT_VAR_OR_LEAVE(tsc, meta, ret, done);
2940 		if (meta->op == VM_SNAPSHOT_RESTORE)
2941 			vcpu->tsc_offset = tsc;
2942 	}
2943 
2944 done:
2945 	return (ret);
2946 }
2947 
2948 static int
2949 vm_snapshot_vm(struct vm *vm, struct vm_snapshot_meta *meta)
2950 {
2951 	int ret;
2952 
2953 	ret = vm_snapshot_vcpus(vm, meta);
2954 	if (ret != 0)
2955 		goto done;
2956 
2957 	SNAPSHOT_VAR_OR_LEAVE(vm->startup_cpus, meta, ret, done);
2958 done:
2959 	return (ret);
2960 }
2961 
2962 static int
2963 vm_snapshot_vcpu(struct vm *vm, struct vm_snapshot_meta *meta)
2964 {
2965 	int error;
2966 	struct vcpu *vcpu;
2967 	uint16_t i, maxcpus;
2968 
2969 	error = 0;
2970 
2971 	maxcpus = vm_get_maxcpus(vm);
2972 	for (i = 0; i < maxcpus; i++) {
2973 		vcpu = vm->vcpu[i];
2974 		if (vcpu == NULL)
2975 			continue;
2976 
2977 		error = vmmops_vcpu_snapshot(vcpu->cookie, meta);
2978 		if (error != 0) {
2979 			printf("%s: failed to snapshot vmcs/vmcb data for "
2980 			       "vCPU: %d; error: %d\n", __func__, i, error);
2981 			goto done;
2982 		}
2983 	}
2984 
2985 done:
2986 	return (error);
2987 }
2988 
2989 /*
2990  * Save kernel-side structures to user-space for snapshotting.
2991  */
2992 int
2993 vm_snapshot_req(struct vm *vm, struct vm_snapshot_meta *meta)
2994 {
2995 	int ret = 0;
2996 
2997 	switch (meta->dev_req) {
2998 	case STRUCT_VMCX:
2999 		ret = vm_snapshot_vcpu(vm, meta);
3000 		break;
3001 	case STRUCT_VM:
3002 		ret = vm_snapshot_vm(vm, meta);
3003 		break;
3004 	case STRUCT_VIOAPIC:
3005 		ret = vioapic_snapshot(vm_ioapic(vm), meta);
3006 		break;
3007 	case STRUCT_VLAPIC:
3008 		ret = vlapic_snapshot(vm, meta);
3009 		break;
3010 	case STRUCT_VHPET:
3011 		ret = vhpet_snapshot(vm_hpet(vm), meta);
3012 		break;
3013 	case STRUCT_VATPIC:
3014 		ret = vatpic_snapshot(vm_atpic(vm), meta);
3015 		break;
3016 	case STRUCT_VATPIT:
3017 		ret = vatpit_snapshot(vm_atpit(vm), meta);
3018 		break;
3019 	case STRUCT_VPMTMR:
3020 		ret = vpmtmr_snapshot(vm_pmtmr(vm), meta);
3021 		break;
3022 	case STRUCT_VRTC:
3023 		ret = vrtc_snapshot(vm_rtc(vm), meta);
3024 		break;
3025 	default:
3026 		printf("%s: failed to find the requested type %#x\n",
3027 		       __func__, meta->dev_req);
3028 		ret = (EINVAL);
3029 	}
3030 	return (ret);
3031 }
3032 
3033 void
3034 vm_set_tsc_offset(struct vcpu *vcpu, uint64_t offset)
3035 {
3036 	vcpu->tsc_offset = offset;
3037 }
3038 
3039 int
3040 vm_restore_time(struct vm *vm)
3041 {
3042 	int error;
3043 	uint64_t now;
3044 	struct vcpu *vcpu;
3045 	uint16_t i, maxcpus;
3046 
3047 	now = rdtsc();
3048 
3049 	error = vhpet_restore_time(vm_hpet(vm));
3050 	if (error)
3051 		return (error);
3052 
3053 	maxcpus = vm_get_maxcpus(vm);
3054 	for (i = 0; i < maxcpus; i++) {
3055 		vcpu = vm->vcpu[i];
3056 		if (vcpu == NULL)
3057 			continue;
3058 
3059 		error = vmmops_restore_tsc(vcpu->cookie,
3060 		    vcpu->tsc_offset - now);
3061 		if (error)
3062 			return (error);
3063 	}
3064 
3065 	return (0);
3066 }
3067 #endif
3068