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