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