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