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