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