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