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