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