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