xref: /illumos-gate/usr/src/uts/intel/io/vmm/vmm.c (revision 50fe091cff3f2dccec5f588584a3ccb4f9933570)
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  * This file and its contents are supplied under the terms of the
30  * Common Development and Distribution License ("CDDL"), version 1.0.
31  * You may only use this file in accordance with the terms of version
32  * 1.0 of the CDDL.
33  *
34  * A full copy of the text of the CDDL should have accompanied this
35  * source.  A copy of the CDDL is also available via the Internet at
36  * http://www.illumos.org/license/CDDL.
37  */
38 /* This file is dual-licensed; see usr/src/contrib/bhyve/LICENSE */
39 
40 /*
41  * Copyright 2015 Pluribus Networks Inc.
42  * Copyright 2018 Joyent, Inc.
43  * Copyright 2025 Oxide Computer Company
44  * Copyright 2021 OmniOS Community Edition (OmniOSce) Association.
45  */
46 
47 
48 #include <sys/cdefs.h>
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/module.h>
54 #include <sys/sysctl.h>
55 #include <sys/kmem.h>
56 #include <sys/pcpu.h>
57 #include <sys/mutex.h>
58 #include <sys/proc.h>
59 #include <sys/rwlock.h>
60 #include <sys/sched.h>
61 #include <sys/systm.h>
62 #include <sys/sunddi.h>
63 #include <sys/hma.h>
64 #include <sys/archsystm.h>
65 
66 #include <machine/md_var.h>
67 #include <x86/psl.h>
68 #include <x86/apicreg.h>
69 
70 #include <machine/specialreg.h>
71 #include <machine/vmm.h>
72 #include <machine/vmm_dev.h>
73 #include <machine/vmparam.h>
74 #include <sys/vmm_instruction_emul.h>
75 #include <sys/vmm_vm.h>
76 #include <sys/vmm_gpt.h>
77 #include <sys/vmm_data.h>
78 
79 #include "vmm_ioport.h"
80 #include "vmm_host.h"
81 #include "vmm_util.h"
82 #include "vatpic.h"
83 #include "vatpit.h"
84 #include "vhpet.h"
85 #include "vioapic.h"
86 #include "vlapic.h"
87 #include "vpmtmr.h"
88 #include "vrtc.h"
89 #include "vmm_stat.h"
90 #include "vmm_lapic.h"
91 
92 #include "io/ppt.h"
93 #include "io/iommu.h"
94 
95 struct vlapic;
96 
97 /* Flags for vtc_status */
98 #define	VTCS_FPU_RESTORED	1 /* guest FPU restored, host FPU saved */
99 #define	VTCS_FPU_CTX_CRITICAL	2 /* in ctx where FPU restore cannot be lazy */
100 
101 typedef struct vm_thread_ctx {
102 	struct vm	*vtc_vm;
103 	int		vtc_vcpuid;
104 	uint_t		vtc_status;
105 	enum vcpu_ustate vtc_ustate;
106 } vm_thread_ctx_t;
107 
108 #define	VMM_MTRR_VAR_MAX 10
109 #define	VMM_MTRR_DEF_MASK \
110 	(MTRR_DEF_ENABLE | MTRR_DEF_FIXED_ENABLE | MTRR_DEF_TYPE)
111 #define	VMM_MTRR_PHYSBASE_MASK (MTRR_PHYSBASE_PHYSBASE | MTRR_PHYSBASE_TYPE)
112 #define	VMM_MTRR_PHYSMASK_MASK (MTRR_PHYSMASK_PHYSMASK | MTRR_PHYSMASK_VALID)
113 struct vm_mtrr {
114 	uint64_t def_type;
115 	uint64_t fixed4k[8];
116 	uint64_t fixed16k[2];
117 	uint64_t fixed64k;
118 	struct {
119 		uint64_t base;
120 		uint64_t mask;
121 	} var[VMM_MTRR_VAR_MAX];
122 };
123 
124 /*
125  * Initialization:
126  * (a) allocated when vcpu is created
127  * (i) initialized when vcpu is created and when it is reinitialized
128  * (o) initialized the first time the vcpu is created
129  * (x) initialized before use
130  */
131 struct vcpu {
132 	/* (o) protects state, run_state, hostcpu, sipi_vector */
133 	kmutex_t	lock;
134 
135 	enum vcpu_state	state;		/* (o) vcpu state */
136 	enum vcpu_run_state run_state;	/* (i) vcpu init/sipi/run state */
137 	kcondvar_t	vcpu_cv;	/* (o) cpu waiter cv */
138 	kcondvar_t	state_cv;	/* (o) IDLE-transition cv */
139 	int		hostcpu;	/* (o) vcpu's current host cpu */
140 	int		lastloccpu;	/* (o) last host cpu localized to */
141 	bool		reqidle;	/* (i) request vcpu to idle */
142 	bool		reqconsist;	/* (i) req. vcpu exit when consistent */
143 	bool		reqbarrier;	/* (i) request vcpu exit barrier */
144 	struct vlapic	*vlapic;	/* (i) APIC device model */
145 	enum x2apic_state x2apic_state;	/* (i) APIC mode */
146 	uint64_t	exit_intinfo;	/* (i) events pending at VM exit */
147 	uint64_t	exc_pending;	/* (i) exception pending */
148 	bool		nmi_pending;	/* (i) NMI pending */
149 	bool		extint_pending;	/* (i) INTR pending */
150 
151 	uint8_t		sipi_vector;	/* (i) SIPI vector */
152 	hma_fpu_t	*guestfpu;	/* (a,i) guest fpu state */
153 	uint64_t	guest_xcr0;	/* (i) guest %xcr0 register */
154 	void		*stats;		/* (a,i) statistics */
155 	struct vm_exit	exitinfo;	/* (x) exit reason and collateral */
156 	uint64_t	nextrip;	/* (x) next instruction to execute */
157 	struct vie	*vie_ctx;	/* (x) instruction emulation context */
158 	vm_client_t	*vmclient;	/* (a) VM-system client */
159 	uint64_t	tsc_offset;	/* (x) vCPU TSC offset */
160 	struct vm_mtrr	mtrr;		/* (i) vcpu's MTRR */
161 	vcpu_cpuid_config_t cpuid_cfg;	/* (x) cpuid configuration */
162 
163 	enum vcpu_ustate ustate;	/* (i) microstate for the vcpu */
164 	hrtime_t	ustate_when;	/* (i) time of last ustate change */
165 	uint64_t ustate_total[VU_MAX];	/* (o) total time spent in ustates */
166 	vm_thread_ctx_t	vtc;		/* (o) thread state for ctxops */
167 	struct ctxop	*ctxop;		/* (o) ctxop storage for vcpu */
168 };
169 
170 #define	vcpu_lock(v)		mutex_enter(&((v)->lock))
171 #define	vcpu_unlock(v)		mutex_exit(&((v)->lock))
172 #define	vcpu_assert_locked(v)	ASSERT(MUTEX_HELD(&((v)->lock)))
173 
174 struct mem_seg {
175 	size_t	len;
176 	bool	sysmem;
177 	vm_object_t *object;
178 };
179 #define	VM_MAX_MEMSEGS	5
180 
181 struct mem_map {
182 	vm_paddr_t	gpa;
183 	size_t		len;
184 	uintptr_t	segoff;
185 	int		segid;
186 	int		prot;
187 	int		flags;
188 };
189 #define	VM_MAX_MEMMAPS	8
190 
191 /*
192  * Initialization:
193  * (o) initialized the first time the VM is created
194  * (i) initialized when VM is created and when it is reinitialized
195  * (x) initialized before use
196  */
197 struct vm {
198 	void		*cookie;		/* (i) cpu-specific data */
199 	void		*iommu;			/* (x) iommu-specific data */
200 	struct vhpet	*vhpet;			/* (i) virtual HPET */
201 	struct vioapic	*vioapic;		/* (i) virtual ioapic */
202 	struct vatpic	*vatpic;		/* (i) virtual atpic */
203 	struct vatpit	*vatpit;		/* (i) virtual atpit */
204 	struct vpmtmr	*vpmtmr;		/* (i) virtual ACPI PM timer */
205 	struct vrtc	*vrtc;			/* (o) virtual RTC */
206 	volatile cpuset_t active_cpus;		/* (i) active vcpus */
207 	volatile cpuset_t debug_cpus;		/* (i) vcpus stopped for dbg */
208 	volatile cpuset_t halted_cpus;		/* (x) cpus in a hard halt */
209 	int		suspend_how;		/* (i) stop VM execution */
210 	int		suspend_source;		/* (i) src vcpuid of suspend */
211 	hrtime_t	suspend_when;		/* (i) time suspend asserted */
212 	struct mem_map	mem_maps[VM_MAX_MEMMAPS]; /* (i) guest address space */
213 	struct mem_seg	mem_segs[VM_MAX_MEMSEGS]; /* (o) guest memory regions */
214 	struct vmspace	*vmspace;		/* (o) guest's address space */
215 	struct vcpu	vcpu[VM_MAXCPU];	/* (i) guest vcpus */
216 	/* The following describe the vm cpu topology */
217 	uint16_t	sockets;		/* (o) num of sockets */
218 	uint16_t	cores;			/* (o) num of cores/socket */
219 	uint16_t	threads;		/* (o) num of threads/core */
220 	uint16_t	maxcpus;		/* (o) max pluggable cpus */
221 
222 	hrtime_t	boot_hrtime;		/* (i) hrtime at VM boot */
223 
224 	/* TSC and TSC scaling related values */
225 	uint64_t	tsc_offset;		/* (i) VM-wide TSC offset */
226 	uint64_t	guest_freq;		/* (i) guest TSC Frequency */
227 	uint64_t	freq_multiplier;	/* (i) guest/host TSC Ratio */
228 
229 	struct ioport_config ioports;		/* (o) ioport handling */
230 
231 	bool		mem_transient;		/* (o) alloc transient memory */
232 	bool		is_paused;		/* (i) instance is paused */
233 };
234 
235 static int vmm_initialized;
236 static uint64_t vmm_host_freq;
237 
238 
239 static void
nullop_panic(void)240 nullop_panic(void)
241 {
242 	panic("null vmm operation call");
243 }
244 
245 /* Do not allow use of an un-set `ops` to do anything but panic */
246 static struct vmm_ops vmm_ops_null = {
247 	.init		= (vmm_init_func_t)nullop_panic,
248 	.resume		= (vmm_resume_func_t)nullop_panic,
249 	.vminit		= (vmi_init_func_t)nullop_panic,
250 	.vmrun		= (vmi_run_func_t)nullop_panic,
251 	.vmcleanup	= (vmi_cleanup_func_t)nullop_panic,
252 	.vmgetreg	= (vmi_get_register_t)nullop_panic,
253 	.vmsetreg	= (vmi_set_register_t)nullop_panic,
254 	.vmgetdesc	= (vmi_get_desc_t)nullop_panic,
255 	.vmsetdesc	= (vmi_set_desc_t)nullop_panic,
256 	.vmgetcap	= (vmi_get_cap_t)nullop_panic,
257 	.vmsetcap	= (vmi_set_cap_t)nullop_panic,
258 	.vlapic_init	= (vmi_vlapic_init)nullop_panic,
259 	.vlapic_cleanup	= (vmi_vlapic_cleanup)nullop_panic,
260 	.vmpause	= (vmi_pause_t)nullop_panic,
261 	.vmsavectx	= (vmi_savectx)nullop_panic,
262 	.vmrestorectx	= (vmi_restorectx)nullop_panic,
263 	.vmgetmsr	= (vmi_get_msr_t)nullop_panic,
264 	.vmsetmsr	= (vmi_set_msr_t)nullop_panic,
265 	.vmfreqratio	= (vmi_freqratio_t)nullop_panic,
266 	.fr_fracsize	= 0,
267 	.fr_intsize	= 0,
268 };
269 
270 static struct vmm_ops *ops = &vmm_ops_null;
271 
272 #define	VMM_INIT()			((*ops->init)())
273 #define	VMM_RESUME()			((*ops->resume)())
274 
275 #define	VMINIT(vm)		((*ops->vminit)(vm))
276 #define	VMRUN(vmi, vcpu, rip)	((*ops->vmrun)(vmi, vcpu, rip))
277 #define	VMCLEANUP(vmi)			((*ops->vmcleanup)(vmi))
278 
279 #define	VMGETREG(vmi, vcpu, num, rv)	((*ops->vmgetreg)(vmi, vcpu, num, rv))
280 #define	VMSETREG(vmi, vcpu, num, val)	((*ops->vmsetreg)(vmi, vcpu, num, val))
281 #define	VMGETDESC(vmi, vcpu, num, dsc)	((*ops->vmgetdesc)(vmi, vcpu, num, dsc))
282 #define	VMSETDESC(vmi, vcpu, num, dsc)	((*ops->vmsetdesc)(vmi, vcpu, num, dsc))
283 #define	VMGETCAP(vmi, vcpu, num, rv)	((*ops->vmgetcap)(vmi, vcpu, num, rv))
284 #define	VMSETCAP(vmi, vcpu, num, val)	((*ops->vmsetcap)(vmi, vcpu, num, val))
285 #define	VLAPIC_INIT(vmi, vcpu)		((*ops->vlapic_init)(vmi, vcpu))
286 #define	VLAPIC_CLEANUP(vmi, vlapic)	((*ops->vlapic_cleanup)(vmi, vlapic))
287 
288 #define	fpu_start_emulating()	load_cr0(rcr0() | CR0_TS)
289 #define	fpu_stop_emulating()	clts()
290 
291 SDT_PROVIDER_DEFINE(vmm);
292 
293 SYSCTL_NODE(_hw, OID_AUTO, vmm, CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
294     NULL);
295 
296 /*
297  * Halt the guest if all vcpus are executing a HLT instruction with
298  * interrupts disabled.
299  */
300 int halt_detection_enabled = 1;
301 
302 /* Trap into hypervisor on all guest exceptions and reflect them back */
303 int trace_guest_exceptions;
304 
305 /* Trap WBINVD and ignore it */
306 int trap_wbinvd = 1;
307 
308 static void vm_free_memmap(struct vm *vm, int ident);
309 static bool sysmem_mapping(struct vm *vm, struct mem_map *mm);
310 static void vcpu_notify_event_locked(struct vcpu *vcpu, vcpu_notify_t);
311 static bool vcpu_sleep_bailout_checks(struct vm *vm, int vcpuid);
312 static int vcpu_vector_sipi(struct vm *vm, int vcpuid, uint8_t vector);
313 static bool vm_is_suspended(struct vm *, struct vm_exit *);
314 
315 static void vmm_savectx(void *);
316 static void vmm_restorectx(void *);
317 static const struct ctxop_template vmm_ctxop_tpl = {
318 	.ct_rev		= CTXOP_TPL_REV,
319 	.ct_save	= vmm_savectx,
320 	.ct_restore	= vmm_restorectx,
321 };
322 
323 static uint64_t calc_tsc_offset(uint64_t base_host_tsc, uint64_t base_guest_tsc,
324     uint64_t mult);
325 static uint64_t calc_guest_tsc(uint64_t host_tsc, uint64_t mult,
326     uint64_t offset);
327 
328 /* functions implemented in vmm_time_support.S */
329 uint64_t calc_freq_multiplier(uint64_t guest_hz, uint64_t host_hz,
330     uint32_t frac_size);
331 uint64_t scale_tsc(uint64_t tsc, uint64_t multiplier, uint32_t frac_size);
332 
333 #ifdef KTR
334 static const char *
vcpu_state2str(enum vcpu_state state)335 vcpu_state2str(enum vcpu_state state)
336 {
337 
338 	switch (state) {
339 	case VCPU_IDLE:
340 		return ("idle");
341 	case VCPU_FROZEN:
342 		return ("frozen");
343 	case VCPU_RUNNING:
344 		return ("running");
345 	case VCPU_SLEEPING:
346 		return ("sleeping");
347 	default:
348 		return ("unknown");
349 	}
350 }
351 #endif
352 
353 static void
vcpu_cleanup(struct vm * vm,int i,bool destroy)354 vcpu_cleanup(struct vm *vm, int i, bool destroy)
355 {
356 	struct vcpu *vcpu = &vm->vcpu[i];
357 
358 	VLAPIC_CLEANUP(vm->cookie, vcpu->vlapic);
359 	if (destroy) {
360 		vmm_stat_free(vcpu->stats);
361 
362 		vcpu_cpuid_cleanup(&vcpu->cpuid_cfg);
363 
364 		hma_fpu_free(vcpu->guestfpu);
365 		vcpu->guestfpu = NULL;
366 
367 		vie_free(vcpu->vie_ctx);
368 		vcpu->vie_ctx = NULL;
369 
370 		vmc_destroy(vcpu->vmclient);
371 		vcpu->vmclient = NULL;
372 
373 		ctxop_free(vcpu->ctxop);
374 		mutex_destroy(&vcpu->lock);
375 	}
376 }
377 
378 static void
vcpu_init(struct vm * vm,int vcpu_id,bool create)379 vcpu_init(struct vm *vm, int vcpu_id, bool create)
380 {
381 	struct vcpu *vcpu;
382 
383 	KASSERT(vcpu_id >= 0 && vcpu_id < vm->maxcpus,
384 	    ("vcpu_init: invalid vcpu %d", vcpu_id));
385 
386 	vcpu = &vm->vcpu[vcpu_id];
387 
388 	if (create) {
389 		mutex_init(&vcpu->lock, NULL, MUTEX_ADAPTIVE, NULL);
390 
391 		vcpu->state = VCPU_IDLE;
392 		vcpu->hostcpu = NOCPU;
393 		vcpu->lastloccpu = NOCPU;
394 		vcpu->guestfpu = hma_fpu_alloc(KM_SLEEP);
395 		vcpu->stats = vmm_stat_alloc();
396 		vcpu->vie_ctx = vie_alloc();
397 		vcpu_cpuid_init(&vcpu->cpuid_cfg);
398 
399 		vcpu->ustate = VU_INIT;
400 		vcpu->ustate_when = gethrtime();
401 
402 		vcpu->vtc.vtc_vm = vm;
403 		vcpu->vtc.vtc_vcpuid = vcpu_id;
404 		vcpu->ctxop = ctxop_allocate(&vmm_ctxop_tpl, &vcpu->vtc);
405 	} else {
406 		vie_reset(vcpu->vie_ctx);
407 		bzero(&vcpu->exitinfo, sizeof (vcpu->exitinfo));
408 		vcpu_ustate_change(vm, vcpu_id, VU_INIT);
409 		bzero(&vcpu->mtrr, sizeof (vcpu->mtrr));
410 	}
411 
412 	vcpu->run_state = VRS_HALT;
413 	vcpu->vlapic = VLAPIC_INIT(vm->cookie, vcpu_id);
414 	(void) vm_set_x2apic_state(vm, vcpu_id, X2APIC_DISABLED);
415 	vcpu->reqidle = false;
416 	vcpu->reqconsist = false;
417 	vcpu->reqbarrier = false;
418 	vcpu->exit_intinfo = 0;
419 	vcpu->nmi_pending = false;
420 	vcpu->extint_pending = false;
421 	vcpu->exc_pending = 0;
422 	vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
423 	(void) hma_fpu_init(vcpu->guestfpu);
424 	vmm_stat_init(vcpu->stats);
425 	vcpu->tsc_offset = 0;
426 }
427 
428 int
vcpu_trace_exceptions(struct vm * vm,int vcpuid)429 vcpu_trace_exceptions(struct vm *vm, int vcpuid)
430 {
431 	return (trace_guest_exceptions);
432 }
433 
434 int
vcpu_trap_wbinvd(struct vm * vm,int vcpuid)435 vcpu_trap_wbinvd(struct vm *vm, int vcpuid)
436 {
437 	return (trap_wbinvd);
438 }
439 
440 struct vm_exit *
vm_exitinfo(struct vm * vm,int cpuid)441 vm_exitinfo(struct vm *vm, int cpuid)
442 {
443 	struct vcpu *vcpu;
444 
445 	if (cpuid < 0 || cpuid >= vm->maxcpus)
446 		panic("vm_exitinfo: invalid cpuid %d", cpuid);
447 
448 	vcpu = &vm->vcpu[cpuid];
449 
450 	return (&vcpu->exitinfo);
451 }
452 
453 struct vie *
vm_vie_ctx(struct vm * vm,int cpuid)454 vm_vie_ctx(struct vm *vm, int cpuid)
455 {
456 	if (cpuid < 0 || cpuid >= vm->maxcpus)
457 		panic("vm_vie_ctx: invalid cpuid %d", cpuid);
458 
459 	return (vm->vcpu[cpuid].vie_ctx);
460 }
461 
462 static int
vmm_init(void)463 vmm_init(void)
464 {
465 	vmm_host_state_init();
466 	vmm_host_freq = unscalehrtime(NANOSEC);
467 
468 	if (vmm_is_intel()) {
469 		ops = &vmm_ops_intel;
470 	} else if (vmm_is_svm()) {
471 		ops = &vmm_ops_amd;
472 	} else {
473 		return (ENXIO);
474 	}
475 
476 	if (!vmm_vm_init()) {
477 		return (ENXIO);
478 	}
479 	const int err = VMM_INIT();
480 	if (err != 0) {
481 		vmm_vm_fini();
482 		ops = &vmm_ops_null;
483 		return (err);
484 	}
485 
486 	return (0);
487 }
488 
489 int
vmm_mod_load()490 vmm_mod_load()
491 {
492 	VERIFY(vmm_initialized == 0);
493 
494 	const int err = vmm_init();
495 	if (err == 0) {
496 		vmm_initialized = 1;
497 	}
498 
499 	return (err);
500 }
501 
502 void
vmm_mod_unload()503 vmm_mod_unload()
504 {
505 	VERIFY(vmm_initialized == 1);
506 
507 	vmm_vm_fini();
508 
509 	vmm_initialized = 0;
510 }
511 
512 /*
513  * Create a test IOMMU domain to see if the host system has necessary hardware
514  * and drivers to do so.
515  */
516 bool
vmm_check_iommu(void)517 vmm_check_iommu(void)
518 {
519 	void *domain;
520 	const size_t arb_test_sz = (1UL << 32);
521 
522 	domain = iommu_create_domain(arb_test_sz);
523 	if (domain == NULL) {
524 		return (false);
525 	}
526 	iommu_destroy_domain(domain);
527 	return (true);
528 }
529 
530 static void
vm_init(struct vm * vm,bool create)531 vm_init(struct vm *vm, bool create)
532 {
533 	int i;
534 
535 	vm->cookie = VMINIT(vm);
536 	vm->iommu = NULL;
537 	vm->vioapic = vioapic_init(vm);
538 	vm->vhpet = vhpet_init(vm);
539 	vm->vatpic = vatpic_init(vm);
540 	vm->vatpit = vatpit_init(vm);
541 	vm->vpmtmr = vpmtmr_init(vm);
542 	if (create)
543 		vm->vrtc = vrtc_init(vm);
544 
545 	vm_inout_init(vm, &vm->ioports);
546 
547 	CPU_ZERO(&vm->active_cpus);
548 	CPU_ZERO(&vm->debug_cpus);
549 
550 	vm->suspend_how = 0;
551 	vm->suspend_source = 0;
552 	vm->suspend_when = 0;
553 
554 	for (i = 0; i < vm->maxcpus; i++)
555 		vcpu_init(vm, i, create);
556 
557 	/*
558 	 * Configure VM time-related data, including:
559 	 * - VM-wide TSC offset
560 	 * - boot_hrtime
561 	 * - guest_freq (same as host at boot time)
562 	 * - freq_multiplier (used for scaling)
563 	 *
564 	 * This data is configured such that the call to vm_init() represents
565 	 * the boot time (when the TSC(s) read 0).  Each vCPU will have its own
566 	 * offset from this, which is altered if/when the guest writes to
567 	 * MSR_TSC.
568 	 *
569 	 * Further changes to this data may occur if userspace writes to the
570 	 * time data.
571 	 */
572 	const uint64_t boot_tsc = rdtsc_offset();
573 
574 	/* Convert the boot TSC reading to hrtime */
575 	vm->boot_hrtime = (hrtime_t)boot_tsc;
576 	scalehrtime(&vm->boot_hrtime);
577 
578 	/* Guest frequency is the same as the host at boot time */
579 	vm->guest_freq = vmm_host_freq;
580 
581 	/* no scaling needed if guest_freq == host_freq */
582 	vm->freq_multiplier = VM_TSCM_NOSCALE;
583 
584 	/* configure VM-wide offset: initial guest TSC is 0 at boot */
585 	vm->tsc_offset = calc_tsc_offset(boot_tsc, 0, vm->freq_multiplier);
586 }
587 
588 /*
589  * The default CPU topology is a single thread per package.
590  */
591 uint_t cores_per_package = 1;
592 uint_t threads_per_core = 1;
593 
594 int
vm_create(uint64_t flags,struct vm ** retvm)595 vm_create(uint64_t flags, struct vm **retvm)
596 {
597 	struct vm *vm;
598 	struct vmspace *vmspace;
599 
600 	/*
601 	 * If vmm.ko could not be successfully initialized then don't attempt
602 	 * to create the virtual machine.
603 	 */
604 	if (!vmm_initialized)
605 		return (ENXIO);
606 
607 	vmspace = vmspace_alloc(VM_MAXUSER_ADDRESS);
608 	if (vmspace == NULL) {
609 		return (ENOMEM);
610 	}
611 
612 	if ((flags & VCF_TRACK_DIRTY) != 0) {
613 		if (vmspace_set_tracking(vmspace, true) != 0) {
614 			vmspace_destroy(vmspace);
615 			return (ENOTSUP);
616 		}
617 	}
618 
619 	vm = kmem_zalloc(sizeof (struct vm), KM_SLEEP);
620 
621 	vm->vmspace = vmspace;
622 	vm->mem_transient = (flags & VCF_RESERVOIR_MEM) == 0;
623 	for (uint_t i = 0; i < VM_MAXCPU; i++) {
624 		vm->vcpu[i].vmclient = vmspace_client_alloc(vmspace);
625 	}
626 
627 	vm->sockets = 1;
628 	vm->cores = cores_per_package;	/* XXX backwards compatibility */
629 	vm->threads = threads_per_core;	/* XXX backwards compatibility */
630 	vm->maxcpus = VM_MAXCPU;	/* XXX temp to keep code working */
631 
632 	vm_init(vm, true);
633 
634 	*retvm = vm;
635 	return (0);
636 }
637 
638 void
vm_get_topology(struct vm * vm,uint16_t * sockets,uint16_t * cores,uint16_t * threads,uint16_t * maxcpus)639 vm_get_topology(struct vm *vm, uint16_t *sockets, uint16_t *cores,
640     uint16_t *threads, uint16_t *maxcpus)
641 {
642 	*sockets = vm->sockets;
643 	*cores = vm->cores;
644 	*threads = vm->threads;
645 	*maxcpus = vm->maxcpus;
646 }
647 
648 uint16_t
vm_get_maxcpus(struct vm * vm)649 vm_get_maxcpus(struct vm *vm)
650 {
651 	return (vm->maxcpus);
652 }
653 
654 int
vm_set_topology(struct vm * vm,uint16_t sockets,uint16_t cores,uint16_t threads,uint16_t maxcpus)655 vm_set_topology(struct vm *vm, uint16_t sockets, uint16_t cores,
656     uint16_t threads, uint16_t maxcpus)
657 {
658 	if (maxcpus != 0)
659 		return (EINVAL);	/* XXX remove when supported */
660 	if ((sockets * cores * threads) > vm->maxcpus)
661 		return (EINVAL);
662 	/* XXX need to check sockets * cores * threads == vCPU, how? */
663 	vm->sockets = sockets;
664 	vm->cores = cores;
665 	vm->threads = threads;
666 	vm->maxcpus = VM_MAXCPU;	/* XXX temp to keep code working */
667 	return (0);
668 }
669 
670 static void
vm_cleanup(struct vm * vm,bool destroy)671 vm_cleanup(struct vm *vm, bool destroy)
672 {
673 	struct mem_map *mm;
674 	int i;
675 
676 	ppt_unassign_all(vm);
677 
678 	if (vm->iommu != NULL)
679 		iommu_destroy_domain(vm->iommu);
680 
681 	/*
682 	 * Devices which attach their own ioport hooks should be cleaned up
683 	 * first so they can tear down those registrations.
684 	 */
685 	vpmtmr_cleanup(vm->vpmtmr);
686 
687 	vm_inout_cleanup(vm, &vm->ioports);
688 
689 	if (destroy)
690 		vrtc_cleanup(vm->vrtc);
691 	else
692 		vrtc_reset(vm->vrtc);
693 
694 	vatpit_cleanup(vm->vatpit);
695 	vhpet_cleanup(vm->vhpet);
696 	vatpic_cleanup(vm->vatpic);
697 	vioapic_cleanup(vm->vioapic);
698 
699 	for (i = 0; i < vm->maxcpus; i++)
700 		vcpu_cleanup(vm, i, destroy);
701 
702 	VMCLEANUP(vm->cookie);
703 
704 	/*
705 	 * System memory is removed from the guest address space only when
706 	 * the VM is destroyed. This is because the mapping remains the same
707 	 * across VM reset.
708 	 *
709 	 * Device memory can be relocated by the guest (e.g. using PCI BARs)
710 	 * so those mappings are removed on a VM reset.
711 	 */
712 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
713 		mm = &vm->mem_maps[i];
714 		if (destroy || !sysmem_mapping(vm, mm)) {
715 			vm_free_memmap(vm, i);
716 		} else {
717 			/*
718 			 * We need to reset the IOMMU flag so this mapping can
719 			 * be reused when a VM is rebooted. Since the IOMMU
720 			 * domain has already been destroyed we can just reset
721 			 * the flag here.
722 			 */
723 			mm->flags &= ~VM_MEMMAP_F_IOMMU;
724 		}
725 	}
726 
727 	if (destroy) {
728 		for (i = 0; i < VM_MAX_MEMSEGS; i++)
729 			vm_free_memseg(vm, i);
730 
731 		vmspace_destroy(vm->vmspace);
732 		vm->vmspace = NULL;
733 	}
734 }
735 
736 void
vm_destroy(struct vm * vm)737 vm_destroy(struct vm *vm)
738 {
739 	vm_cleanup(vm, true);
740 	kmem_free(vm, sizeof (*vm));
741 }
742 
743 int
vm_reinit(struct vm * vm,uint64_t flags)744 vm_reinit(struct vm *vm, uint64_t flags)
745 {
746 	vm_cleanup(vm, false);
747 	vm_init(vm, false);
748 	return (0);
749 }
750 
751 bool
vm_is_paused(struct vm * vm)752 vm_is_paused(struct vm *vm)
753 {
754 	return (vm->is_paused);
755 }
756 
757 int
vm_pause_instance(struct vm * vm)758 vm_pause_instance(struct vm *vm)
759 {
760 	if (vm->is_paused) {
761 		return (EALREADY);
762 	}
763 	vm->is_paused = true;
764 
765 	for (uint_t i = 0; i < vm->maxcpus; i++) {
766 		struct vcpu *vcpu = &vm->vcpu[i];
767 
768 		if (!CPU_ISSET(i, &vm->active_cpus)) {
769 			continue;
770 		}
771 		vlapic_pause(vcpu->vlapic);
772 
773 		/*
774 		 * vCPU-specific pause logic includes stashing any
775 		 * to-be-injected events in exit_intinfo where it can be
776 		 * accessed in a manner generic to the backend.
777 		 */
778 		ops->vmpause(vm->cookie, i);
779 	}
780 	vhpet_pause(vm->vhpet);
781 	vatpit_pause(vm->vatpit);
782 	vrtc_pause(vm->vrtc);
783 
784 	return (0);
785 }
786 
787 int
vm_resume_instance(struct vm * vm)788 vm_resume_instance(struct vm *vm)
789 {
790 	if (!vm->is_paused) {
791 		return (EALREADY);
792 	}
793 	vm->is_paused = false;
794 
795 	vrtc_resume(vm->vrtc);
796 	vatpit_resume(vm->vatpit);
797 	vhpet_resume(vm->vhpet);
798 	for (uint_t i = 0; i < vm->maxcpus; i++) {
799 		struct vcpu *vcpu = &vm->vcpu[i];
800 
801 		if (!CPU_ISSET(i, &vm->active_cpus)) {
802 			continue;
803 		}
804 		vlapic_resume(vcpu->vlapic);
805 	}
806 
807 	return (0);
808 }
809 
810 int
vm_map_mmio(struct vm * vm,vm_paddr_t gpa,size_t len,vm_paddr_t hpa)811 vm_map_mmio(struct vm *vm, vm_paddr_t gpa, size_t len, vm_paddr_t hpa)
812 {
813 	vm_object_t *obj;
814 
815 	if ((obj = vmm_mmio_alloc(vm->vmspace, gpa, len, hpa)) == NULL)
816 		return (ENOMEM);
817 	else
818 		return (0);
819 }
820 
821 int
vm_unmap_mmio(struct vm * vm,vm_paddr_t gpa,size_t len)822 vm_unmap_mmio(struct vm *vm, vm_paddr_t gpa, size_t len)
823 {
824 	return (vmspace_unmap(vm->vmspace, gpa, len));
825 }
826 
827 /*
828  * Return 'true' if 'gpa' is allocated in the guest address space.
829  *
830  * This function is called in the context of a running vcpu which acts as
831  * an implicit lock on 'vm->mem_maps[]'.
832  */
833 bool
vm_mem_allocated(struct vm * vm,int vcpuid,vm_paddr_t gpa)834 vm_mem_allocated(struct vm *vm, int vcpuid, vm_paddr_t gpa)
835 {
836 	struct mem_map *mm;
837 	int i;
838 
839 #ifdef INVARIANTS
840 	int hostcpu, state;
841 	state = vcpu_get_state(vm, vcpuid, &hostcpu);
842 	KASSERT(state == VCPU_RUNNING && hostcpu == curcpu,
843 	    ("%s: invalid vcpu state %d/%d", __func__, state, hostcpu));
844 #endif
845 
846 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
847 		mm = &vm->mem_maps[i];
848 		if (mm->len != 0 && gpa >= mm->gpa && gpa < mm->gpa + mm->len)
849 			return (true);		/* 'gpa' is sysmem or devmem */
850 	}
851 
852 	if (ppt_is_mmio(vm, gpa))
853 		return (true);			/* 'gpa' is pci passthru mmio */
854 
855 	return (false);
856 }
857 
858 int
vm_alloc_memseg(struct vm * vm,int ident,size_t len,bool sysmem)859 vm_alloc_memseg(struct vm *vm, int ident, size_t len, bool sysmem)
860 {
861 	struct mem_seg *seg;
862 	vm_object_t *obj;
863 
864 	if (ident < 0 || ident >= VM_MAX_MEMSEGS)
865 		return (EINVAL);
866 
867 	if (len == 0 || (len & PAGEOFFSET))
868 		return (EINVAL);
869 
870 	seg = &vm->mem_segs[ident];
871 	if (seg->object != NULL) {
872 		if (seg->len == len && seg->sysmem == sysmem)
873 			return (EEXIST);
874 		else
875 			return (EINVAL);
876 	}
877 
878 	obj = vm_object_mem_allocate(len, vm->mem_transient);
879 	if (obj == NULL)
880 		return (ENOMEM);
881 
882 	seg->len = len;
883 	seg->object = obj;
884 	seg->sysmem = sysmem;
885 	return (0);
886 }
887 
888 int
vm_get_memseg(struct vm * vm,int ident,size_t * len,bool * sysmem,vm_object_t ** objptr)889 vm_get_memseg(struct vm *vm, int ident, size_t *len, bool *sysmem,
890     vm_object_t **objptr)
891 {
892 	struct mem_seg *seg;
893 
894 	if (ident < 0 || ident >= VM_MAX_MEMSEGS)
895 		return (EINVAL);
896 
897 	seg = &vm->mem_segs[ident];
898 	if (len)
899 		*len = seg->len;
900 	if (sysmem)
901 		*sysmem = seg->sysmem;
902 	if (objptr)
903 		*objptr = seg->object;
904 	return (0);
905 }
906 
907 void
vm_free_memseg(struct vm * vm,int ident)908 vm_free_memseg(struct vm *vm, int ident)
909 {
910 	struct mem_seg *seg;
911 
912 	KASSERT(ident >= 0 && ident < VM_MAX_MEMSEGS,
913 	    ("%s: invalid memseg ident %d", __func__, ident));
914 
915 	seg = &vm->mem_segs[ident];
916 	if (seg->object != NULL) {
917 		vm_object_release(seg->object);
918 		bzero(seg, sizeof (struct mem_seg));
919 	}
920 }
921 
922 int
vm_mmap_memseg(struct vm * vm,vm_paddr_t gpa,int segid,uintptr_t off,size_t len,int prot,int flags)923 vm_mmap_memseg(struct vm *vm, vm_paddr_t gpa, int segid, uintptr_t off,
924     size_t len, int prot, int flags)
925 {
926 	if (prot == 0 || (prot & ~(PROT_ALL)) != 0)
927 		return (EINVAL);
928 
929 	if (flags & ~VM_MEMMAP_F_WIRED)
930 		return (EINVAL);
931 
932 	if (segid < 0 || segid >= VM_MAX_MEMSEGS)
933 		return (EINVAL);
934 	const struct mem_seg *seg = &vm->mem_segs[segid];
935 	if (seg->object == NULL)
936 		return (EINVAL);
937 
938 	const uintptr_t end = off + len;
939 	if (((gpa | off | end) & PAGEOFFSET) != 0)
940 		return (EINVAL);
941 	if (end < off || end > seg->len)
942 		return (EINVAL);
943 
944 	struct mem_map *map = NULL;
945 	for (int i = 0; i < VM_MAX_MEMMAPS; i++) {
946 		struct mem_map *m = &vm->mem_maps[i];
947 		if (m->len == 0) {
948 			map = m;
949 			break;
950 		}
951 	}
952 	if (map == NULL)
953 		return (ENOSPC);
954 
955 	int error = vmspace_map(vm->vmspace, seg->object, off, gpa, len, prot);
956 	if (error != 0)
957 		return (EFAULT);
958 
959 	vm_object_reference(seg->object);
960 
961 	if ((flags & VM_MEMMAP_F_WIRED) != 0) {
962 		error = vmspace_populate(vm->vmspace, gpa, len);
963 		if (error != 0) {
964 			VERIFY0(vmspace_unmap(vm->vmspace, gpa, len));
965 			return (EFAULT);
966 		}
967 	}
968 
969 	map->gpa = gpa;
970 	map->len = len;
971 	map->segoff = off;
972 	map->segid = segid;
973 	map->prot = prot;
974 	map->flags = flags;
975 	return (0);
976 }
977 
978 int
vm_munmap_memseg(struct vm * vm,vm_paddr_t gpa,size_t len)979 vm_munmap_memseg(struct vm *vm, vm_paddr_t gpa, size_t len)
980 {
981 	struct mem_map *m;
982 	int i;
983 
984 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
985 		m = &vm->mem_maps[i];
986 		if (m->gpa == gpa && m->len == len &&
987 		    (m->flags & VM_MEMMAP_F_IOMMU) == 0) {
988 			vm_free_memmap(vm, i);
989 			return (0);
990 		}
991 	}
992 
993 	return (EINVAL);
994 }
995 
996 int
vm_mmap_getnext(struct vm * vm,vm_paddr_t * gpa,int * segid,uintptr_t * segoff,size_t * len,int * prot,int * flags)997 vm_mmap_getnext(struct vm *vm, vm_paddr_t *gpa, int *segid,
998     uintptr_t *segoff, size_t *len, int *prot, int *flags)
999 {
1000 	struct mem_map *mm, *mmnext;
1001 	int i;
1002 
1003 	mmnext = NULL;
1004 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1005 		mm = &vm->mem_maps[i];
1006 		if (mm->len == 0 || mm->gpa < *gpa)
1007 			continue;
1008 		if (mmnext == NULL || mm->gpa < mmnext->gpa)
1009 			mmnext = mm;
1010 	}
1011 
1012 	if (mmnext != NULL) {
1013 		*gpa = mmnext->gpa;
1014 		if (segid)
1015 			*segid = mmnext->segid;
1016 		if (segoff)
1017 			*segoff = mmnext->segoff;
1018 		if (len)
1019 			*len = mmnext->len;
1020 		if (prot)
1021 			*prot = mmnext->prot;
1022 		if (flags)
1023 			*flags = mmnext->flags;
1024 		return (0);
1025 	} else {
1026 		return (ENOENT);
1027 	}
1028 }
1029 
1030 static void
vm_free_memmap(struct vm * vm,int ident)1031 vm_free_memmap(struct vm *vm, int ident)
1032 {
1033 	struct mem_map *mm;
1034 	int error;
1035 
1036 	mm = &vm->mem_maps[ident];
1037 	if (mm->len) {
1038 		error = vmspace_unmap(vm->vmspace, mm->gpa, mm->len);
1039 		VERIFY0(error);
1040 		bzero(mm, sizeof (struct mem_map));
1041 	}
1042 }
1043 
1044 static __inline bool
sysmem_mapping(struct vm * vm,struct mem_map * mm)1045 sysmem_mapping(struct vm *vm, struct mem_map *mm)
1046 {
1047 
1048 	if (mm->len != 0 && vm->mem_segs[mm->segid].sysmem)
1049 		return (true);
1050 	else
1051 		return (false);
1052 }
1053 
1054 vm_paddr_t
vmm_sysmem_maxaddr(struct vm * vm)1055 vmm_sysmem_maxaddr(struct vm *vm)
1056 {
1057 	struct mem_map *mm;
1058 	vm_paddr_t maxaddr;
1059 	int i;
1060 
1061 	maxaddr = 0;
1062 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1063 		mm = &vm->mem_maps[i];
1064 		if (sysmem_mapping(vm, mm)) {
1065 			if (maxaddr < mm->gpa + mm->len)
1066 				maxaddr = mm->gpa + mm->len;
1067 		}
1068 	}
1069 	return (maxaddr);
1070 }
1071 
1072 static void
vm_iommu_modify(struct vm * vm,bool map)1073 vm_iommu_modify(struct vm *vm, bool map)
1074 {
1075 	int i, sz;
1076 	vm_paddr_t gpa, hpa;
1077 	struct mem_map *mm;
1078 	vm_client_t *vmc;
1079 
1080 	sz = PAGE_SIZE;
1081 	vmc = vmspace_client_alloc(vm->vmspace);
1082 
1083 	for (i = 0; i < VM_MAX_MEMMAPS; i++) {
1084 		mm = &vm->mem_maps[i];
1085 		if (!sysmem_mapping(vm, mm))
1086 			continue;
1087 
1088 		if (map) {
1089 			KASSERT((mm->flags & VM_MEMMAP_F_IOMMU) == 0,
1090 			    ("iommu map found invalid memmap %lx/%lx/%x",
1091 			    mm->gpa, mm->len, mm->flags));
1092 			if ((mm->flags & VM_MEMMAP_F_WIRED) == 0)
1093 				continue;
1094 			mm->flags |= VM_MEMMAP_F_IOMMU;
1095 		} else {
1096 			if ((mm->flags & VM_MEMMAP_F_IOMMU) == 0)
1097 				continue;
1098 			mm->flags &= ~VM_MEMMAP_F_IOMMU;
1099 			KASSERT((mm->flags & VM_MEMMAP_F_WIRED) != 0,
1100 			    ("iommu unmap found invalid memmap %lx/%lx/%x",
1101 			    mm->gpa, mm->len, mm->flags));
1102 		}
1103 
1104 		gpa = mm->gpa;
1105 		while (gpa < mm->gpa + mm->len) {
1106 			vm_page_t *vmp;
1107 
1108 			vmp = vmc_hold(vmc, gpa, PROT_WRITE);
1109 			ASSERT(vmp != NULL);
1110 			hpa = ((uintptr_t)vmp_get_pfn(vmp) << PAGESHIFT);
1111 			(void) vmp_release(vmp);
1112 
1113 			/*
1114 			 * When originally ported from FreeBSD, the logic for
1115 			 * adding memory to the guest domain would
1116 			 * simultaneously remove it from the host domain.  The
1117 			 * justification for that is not clear, and FreeBSD has
1118 			 * subsequently changed the behavior to not remove the
1119 			 * memory from the host domain.
1120 			 *
1121 			 * Leaving the guest memory in the host domain for the
1122 			 * life of the VM is necessary to make it available for
1123 			 * DMA, such as through viona in the TX path.
1124 			 */
1125 			if (map) {
1126 				iommu_create_mapping(vm->iommu, gpa, hpa, sz);
1127 			} else {
1128 				iommu_remove_mapping(vm->iommu, gpa, sz);
1129 			}
1130 
1131 			gpa += PAGE_SIZE;
1132 		}
1133 	}
1134 	vmc_destroy(vmc);
1135 
1136 	/*
1137 	 * Invalidate the cached translations associated with the domain
1138 	 * from which pages were removed.
1139 	 */
1140 	iommu_invalidate_tlb(vm->iommu);
1141 }
1142 
1143 int
vm_unassign_pptdev(struct vm * vm,int pptfd)1144 vm_unassign_pptdev(struct vm *vm, int pptfd)
1145 {
1146 	int error;
1147 
1148 	error = ppt_unassign_device(vm, pptfd);
1149 	if (error)
1150 		return (error);
1151 
1152 	if (ppt_assigned_devices(vm) == 0)
1153 		vm_iommu_modify(vm, false);
1154 
1155 	return (0);
1156 }
1157 
1158 int
vm_assign_pptdev(struct vm * vm,int pptfd)1159 vm_assign_pptdev(struct vm *vm, int pptfd)
1160 {
1161 	int error;
1162 	vm_paddr_t maxaddr;
1163 
1164 	/* Set up the IOMMU to do the 'gpa' to 'hpa' translation */
1165 	if (ppt_assigned_devices(vm) == 0) {
1166 		KASSERT(vm->iommu == NULL,
1167 		    ("vm_assign_pptdev: iommu must be NULL"));
1168 		maxaddr = vmm_sysmem_maxaddr(vm);
1169 		vm->iommu = iommu_create_domain(maxaddr);
1170 		if (vm->iommu == NULL)
1171 			return (ENXIO);
1172 		vm_iommu_modify(vm, true);
1173 	}
1174 
1175 	error = ppt_assign_device(vm, pptfd);
1176 	return (error);
1177 }
1178 
1179 int
vm_get_register(struct vm * vm,int vcpuid,int reg,uint64_t * retval)1180 vm_get_register(struct vm *vm, int vcpuid, int reg, uint64_t *retval)
1181 {
1182 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
1183 		return (EINVAL);
1184 
1185 	if (reg >= VM_REG_LAST)
1186 		return (EINVAL);
1187 
1188 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
1189 	switch (reg) {
1190 	case VM_REG_GUEST_XCR0:
1191 		*retval = vcpu->guest_xcr0;
1192 		return (0);
1193 	default:
1194 		return (VMGETREG(vm->cookie, vcpuid, reg, retval));
1195 	}
1196 }
1197 
1198 int
vm_set_register(struct vm * vm,int vcpuid,int reg,uint64_t val)1199 vm_set_register(struct vm *vm, int vcpuid, int reg, uint64_t val)
1200 {
1201 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
1202 		return (EINVAL);
1203 
1204 	if (reg >= VM_REG_LAST)
1205 		return (EINVAL);
1206 
1207 	int error;
1208 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
1209 	switch (reg) {
1210 	case VM_REG_GUEST_RIP:
1211 		error = VMSETREG(vm->cookie, vcpuid, reg, val);
1212 		if (error == 0) {
1213 			vcpu->nextrip = val;
1214 		}
1215 		return (error);
1216 	case VM_REG_GUEST_XCR0:
1217 		if (!validate_guest_xcr0(val, vmm_get_host_xcr0())) {
1218 			return (EINVAL);
1219 		}
1220 		vcpu->guest_xcr0 = val;
1221 		return (0);
1222 	default:
1223 		return (VMSETREG(vm->cookie, vcpuid, reg, val));
1224 	}
1225 }
1226 
1227 static bool
is_descriptor_table(int reg)1228 is_descriptor_table(int reg)
1229 {
1230 	switch (reg) {
1231 	case VM_REG_GUEST_IDTR:
1232 	case VM_REG_GUEST_GDTR:
1233 		return (true);
1234 	default:
1235 		return (false);
1236 	}
1237 }
1238 
1239 static bool
is_segment_register(int reg)1240 is_segment_register(int reg)
1241 {
1242 	switch (reg) {
1243 	case VM_REG_GUEST_ES:
1244 	case VM_REG_GUEST_CS:
1245 	case VM_REG_GUEST_SS:
1246 	case VM_REG_GUEST_DS:
1247 	case VM_REG_GUEST_FS:
1248 	case VM_REG_GUEST_GS:
1249 	case VM_REG_GUEST_TR:
1250 	case VM_REG_GUEST_LDTR:
1251 		return (true);
1252 	default:
1253 		return (false);
1254 	}
1255 }
1256 
1257 int
vm_get_seg_desc(struct vm * vm,int vcpu,int reg,struct seg_desc * desc)1258 vm_get_seg_desc(struct vm *vm, int vcpu, int reg, struct seg_desc *desc)
1259 {
1260 
1261 	if (vcpu < 0 || vcpu >= vm->maxcpus)
1262 		return (EINVAL);
1263 
1264 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
1265 		return (EINVAL);
1266 
1267 	return (VMGETDESC(vm->cookie, vcpu, reg, desc));
1268 }
1269 
1270 int
vm_set_seg_desc(struct vm * vm,int vcpu,int reg,const struct seg_desc * desc)1271 vm_set_seg_desc(struct vm *vm, int vcpu, int reg, const struct seg_desc *desc)
1272 {
1273 	if (vcpu < 0 || vcpu >= vm->maxcpus)
1274 		return (EINVAL);
1275 
1276 	if (!is_segment_register(reg) && !is_descriptor_table(reg))
1277 		return (EINVAL);
1278 
1279 	return (VMSETDESC(vm->cookie, vcpu, reg, desc));
1280 }
1281 
1282 static int
translate_hma_xsave_result(hma_fpu_xsave_result_t res)1283 translate_hma_xsave_result(hma_fpu_xsave_result_t res)
1284 {
1285 	switch (res) {
1286 	case HFXR_OK:
1287 		return (0);
1288 	case HFXR_NO_SPACE:
1289 		return (ENOSPC);
1290 	case HFXR_BAD_ALIGN:
1291 	case HFXR_UNSUP_FMT:
1292 	case HFXR_UNSUP_FEAT:
1293 	case HFXR_INVALID_DATA:
1294 		return (EINVAL);
1295 	default:
1296 		panic("unexpected xsave result");
1297 	}
1298 }
1299 
1300 int
vm_get_fpu(struct vm * vm,int vcpuid,void * buf,size_t len)1301 vm_get_fpu(struct vm *vm, int vcpuid, void *buf, size_t len)
1302 {
1303 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
1304 		return (EINVAL);
1305 
1306 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
1307 	hma_fpu_xsave_result_t res;
1308 
1309 	res = hma_fpu_get_xsave_state(vcpu->guestfpu, buf, len);
1310 	return (translate_hma_xsave_result(res));
1311 }
1312 
1313 int
vm_set_fpu(struct vm * vm,int vcpuid,void * buf,size_t len)1314 vm_set_fpu(struct vm *vm, int vcpuid, void *buf, size_t len)
1315 {
1316 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
1317 		return (EINVAL);
1318 
1319 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
1320 	hma_fpu_xsave_result_t res;
1321 
1322 	res = hma_fpu_set_xsave_state(vcpu->guestfpu, buf, len);
1323 	return (translate_hma_xsave_result(res));
1324 }
1325 
1326 int
vm_get_run_state(struct vm * vm,int vcpuid,uint32_t * state,uint8_t * sipi_vec)1327 vm_get_run_state(struct vm *vm, int vcpuid, uint32_t *state, uint8_t *sipi_vec)
1328 {
1329 	struct vcpu *vcpu;
1330 
1331 	if (vcpuid < 0 || vcpuid >= vm->maxcpus) {
1332 		return (EINVAL);
1333 	}
1334 
1335 	vcpu = &vm->vcpu[vcpuid];
1336 
1337 	vcpu_lock(vcpu);
1338 	*state = vcpu->run_state;
1339 	*sipi_vec = vcpu->sipi_vector;
1340 	vcpu_unlock(vcpu);
1341 
1342 	return (0);
1343 }
1344 
1345 int
vm_set_run_state(struct vm * vm,int vcpuid,uint32_t state,uint8_t sipi_vec)1346 vm_set_run_state(struct vm *vm, int vcpuid, uint32_t state, uint8_t sipi_vec)
1347 {
1348 	struct vcpu *vcpu;
1349 
1350 	if (vcpuid < 0 || vcpuid >= vm->maxcpus) {
1351 		return (EINVAL);
1352 	}
1353 	if (!VRS_IS_VALID(state)) {
1354 		return (EINVAL);
1355 	}
1356 
1357 	vcpu = &vm->vcpu[vcpuid];
1358 
1359 	vcpu_lock(vcpu);
1360 	vcpu->run_state = state;
1361 	vcpu->sipi_vector = sipi_vec;
1362 	vcpu_notify_event_locked(vcpu, VCPU_NOTIFY_EXIT);
1363 	vcpu_unlock(vcpu);
1364 
1365 	return (0);
1366 }
1367 
1368 int
vm_track_dirty_pages(struct vm * vm,uint64_t gpa,size_t len,uint8_t * bitmap)1369 vm_track_dirty_pages(struct vm *vm, uint64_t gpa, size_t len, uint8_t *bitmap)
1370 {
1371 	ASSERT0(gpa & PAGEOFFSET);
1372 	ASSERT0(len & PAGEOFFSET);
1373 
1374 	/*
1375 	 * The only difference in expectations between this legacy interface and
1376 	 * an equivalent call to vm_npt_do_operation() is the check for
1377 	 * dirty-page-tracking being enabled on the vmspace.
1378 	 */
1379 	if (!vmspace_get_tracking(vm->vmspace)) {
1380 		return (EPERM);
1381 	}
1382 
1383 	vmspace_bits_operate(vm->vmspace, gpa, len,
1384 	    VBO_RESET_DIRTY | VBO_FLAG_BITMAP_OUT, bitmap);
1385 	return (0);
1386 }
1387 
1388 int
vm_npt_do_operation(struct vm * vm,uint64_t gpa,size_t len,uint32_t oper,uint8_t * bitmap,int * rvalp)1389 vm_npt_do_operation(struct vm *vm, uint64_t gpa, size_t len, uint32_t oper,
1390     uint8_t *bitmap, int *rvalp)
1391 {
1392 	ASSERT0(gpa & PAGEOFFSET);
1393 	ASSERT0(len & PAGEOFFSET);
1394 
1395 	/*
1396 	 * For now, the bits defined in vmm_dev.h are meant to match up 1:1 with
1397 	 * those in vmm_vm.h
1398 	 */
1399 	CTASSERT(VNO_OP_RESET_DIRTY == VBO_RESET_DIRTY);
1400 	CTASSERT(VNO_OP_SET_DIRTY == VBO_SET_DIRTY);
1401 	CTASSERT(VNO_OP_GET_DIRTY == VBO_GET_DIRTY);
1402 	CTASSERT(VNO_FLAG_BITMAP_IN == VBO_FLAG_BITMAP_IN);
1403 	CTASSERT(VNO_FLAG_BITMAP_OUT == VBO_FLAG_BITMAP_OUT);
1404 
1405 	const uint32_t oper_only =
1406 	    oper & ~(VNO_FLAG_BITMAP_IN | VNO_FLAG_BITMAP_OUT);
1407 	switch (oper_only) {
1408 	case VNO_OP_RESET_DIRTY:
1409 	case VNO_OP_SET_DIRTY:
1410 	case VNO_OP_GET_DIRTY:
1411 		if (len == 0) {
1412 			break;
1413 		}
1414 		vmspace_bits_operate(vm->vmspace, gpa, len, oper, bitmap);
1415 		break;
1416 	case VNO_OP_GET_TRACK_DIRTY:
1417 		ASSERT3P(rvalp, !=, NULL);
1418 		*rvalp = vmspace_get_tracking(vm->vmspace) ? 1 : 0;
1419 		break;
1420 	case VNO_OP_EN_TRACK_DIRTY:
1421 		return (vmspace_set_tracking(vm->vmspace, true));
1422 	case VNO_OP_DIS_TRACK_DIRTY:
1423 		return (vmspace_set_tracking(vm->vmspace, false));
1424 	default:
1425 		return (EINVAL);
1426 	}
1427 	return (0);
1428 }
1429 
1430 static void
restore_guest_fpustate(struct vcpu * vcpu)1431 restore_guest_fpustate(struct vcpu *vcpu)
1432 {
1433 	/* Save host FPU and restore guest FPU */
1434 	fpu_stop_emulating();
1435 	hma_fpu_start_guest(vcpu->guestfpu);
1436 
1437 	/* restore guest XCR0 if XSAVE is enabled in the host */
1438 	if (rcr4() & CR4_XSAVE)
1439 		load_xcr(0, vcpu->guest_xcr0);
1440 
1441 	/*
1442 	 * The FPU is now "dirty" with the guest's state so turn on emulation
1443 	 * to trap any access to the FPU by the host.
1444 	 */
1445 	fpu_start_emulating();
1446 }
1447 
1448 static void
save_guest_fpustate(struct vcpu * vcpu)1449 save_guest_fpustate(struct vcpu *vcpu)
1450 {
1451 
1452 	if ((rcr0() & CR0_TS) == 0)
1453 		panic("fpu emulation not enabled in host!");
1454 
1455 	/* save guest XCR0 and restore host XCR0 */
1456 	if (rcr4() & CR4_XSAVE) {
1457 		vcpu->guest_xcr0 = rxcr(0);
1458 		load_xcr(0, vmm_get_host_xcr0());
1459 	}
1460 
1461 	/* save guest FPU and restore host FPU */
1462 	fpu_stop_emulating();
1463 	hma_fpu_stop_guest(vcpu->guestfpu);
1464 	/*
1465 	 * When the host state has been restored, we should not re-enable
1466 	 * CR0.TS on illumos for eager FPU.
1467 	 */
1468 }
1469 
1470 static int
vcpu_set_state_locked(struct vm * vm,int vcpuid,enum vcpu_state newstate,bool from_idle)1471 vcpu_set_state_locked(struct vm *vm, int vcpuid, enum vcpu_state newstate,
1472     bool from_idle)
1473 {
1474 	struct vcpu *vcpu;
1475 	int error;
1476 
1477 	vcpu = &vm->vcpu[vcpuid];
1478 	vcpu_assert_locked(vcpu);
1479 
1480 	/*
1481 	 * State transitions from the vmmdev_ioctl() must always begin from
1482 	 * the VCPU_IDLE state. This guarantees that there is only a single
1483 	 * ioctl() operating on a vcpu at any point.
1484 	 */
1485 	if (from_idle) {
1486 		while (vcpu->state != VCPU_IDLE) {
1487 			vcpu->reqidle = true;
1488 			vcpu_notify_event_locked(vcpu, VCPU_NOTIFY_EXIT);
1489 			cv_wait(&vcpu->state_cv, &vcpu->lock);
1490 			vcpu->reqidle = false;
1491 		}
1492 	} else {
1493 		KASSERT(vcpu->state != VCPU_IDLE, ("invalid transition from "
1494 		    "vcpu idle state"));
1495 	}
1496 
1497 	if (vcpu->state == VCPU_RUNNING) {
1498 		KASSERT(vcpu->hostcpu == curcpu, ("curcpu %d and hostcpu %d "
1499 		    "mismatch for running vcpu", curcpu, vcpu->hostcpu));
1500 	} else {
1501 		KASSERT(vcpu->hostcpu == NOCPU, ("Invalid hostcpu %d for a "
1502 		    "vcpu that is not running", vcpu->hostcpu));
1503 	}
1504 
1505 	/*
1506 	 * The following state transitions are allowed:
1507 	 * IDLE -> FROZEN -> IDLE
1508 	 * FROZEN -> RUNNING -> FROZEN
1509 	 * FROZEN -> SLEEPING -> FROZEN
1510 	 */
1511 	switch (vcpu->state) {
1512 	case VCPU_IDLE:
1513 	case VCPU_RUNNING:
1514 	case VCPU_SLEEPING:
1515 		error = (newstate != VCPU_FROZEN);
1516 		break;
1517 	case VCPU_FROZEN:
1518 		error = (newstate == VCPU_FROZEN);
1519 		break;
1520 	default:
1521 		error = 1;
1522 		break;
1523 	}
1524 
1525 	if (error)
1526 		return (EBUSY);
1527 
1528 	vcpu->state = newstate;
1529 	if (newstate == VCPU_RUNNING)
1530 		vcpu->hostcpu = curcpu;
1531 	else
1532 		vcpu->hostcpu = NOCPU;
1533 
1534 	if (newstate == VCPU_IDLE) {
1535 		cv_broadcast(&vcpu->state_cv);
1536 	}
1537 
1538 	return (0);
1539 }
1540 
1541 static void
vcpu_require_state(struct vm * vm,int vcpuid,enum vcpu_state newstate)1542 vcpu_require_state(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1543 {
1544 	int error;
1545 
1546 	if ((error = vcpu_set_state(vm, vcpuid, newstate, false)) != 0)
1547 		panic("Error %d setting state to %d\n", error, newstate);
1548 }
1549 
1550 static void
vcpu_require_state_locked(struct vm * vm,int vcpuid,enum vcpu_state newstate)1551 vcpu_require_state_locked(struct vm *vm, int vcpuid, enum vcpu_state newstate)
1552 {
1553 	int error;
1554 
1555 	if ((error = vcpu_set_state_locked(vm, vcpuid, newstate, false)) != 0)
1556 		panic("Error %d setting state to %d", error, newstate);
1557 }
1558 
1559 /*
1560  * Emulate a guest 'hlt' by sleeping until the vcpu is ready to run.
1561  */
1562 static int
vm_handle_hlt(struct vm * vm,int vcpuid,bool intr_disabled)1563 vm_handle_hlt(struct vm *vm, int vcpuid, bool intr_disabled)
1564 {
1565 	struct vcpu *vcpu;
1566 	int vcpu_halted, vm_halted;
1567 	bool userspace_exit = false;
1568 
1569 	KASSERT(!CPU_ISSET(vcpuid, &vm->halted_cpus), ("vcpu already halted"));
1570 
1571 	vcpu = &vm->vcpu[vcpuid];
1572 	vcpu_halted = 0;
1573 	vm_halted = 0;
1574 
1575 	vcpu_lock(vcpu);
1576 	while (1) {
1577 		/*
1578 		 * Do a final check for pending interrupts (including NMI and
1579 		 * INIT) before putting this thread to sleep.
1580 		 */
1581 		if (vm_nmi_pending(vm, vcpuid))
1582 			break;
1583 		if (vcpu_run_state_pending(vm, vcpuid))
1584 			break;
1585 		if (!intr_disabled) {
1586 			if (vm_extint_pending(vm, vcpuid) ||
1587 			    vlapic_pending_intr(vcpu->vlapic, NULL)) {
1588 				break;
1589 			}
1590 		}
1591 
1592 		/*
1593 		 * Also check for software events which would cause a wake-up.
1594 		 * This will set the appropriate exitcode directly, rather than
1595 		 * requiring a trip through VM_RUN().
1596 		 */
1597 		if (vcpu_sleep_bailout_checks(vm, vcpuid)) {
1598 			userspace_exit = true;
1599 			break;
1600 		}
1601 
1602 		/*
1603 		 * Some Linux guests implement "halt" by having all vcpus
1604 		 * execute HLT with interrupts disabled. 'halted_cpus' keeps
1605 		 * track of the vcpus that have entered this state. When all
1606 		 * vcpus enter the halted state the virtual machine is halted.
1607 		 */
1608 		if (intr_disabled) {
1609 			if (!vcpu_halted && halt_detection_enabled) {
1610 				vcpu_halted = 1;
1611 				CPU_SET_ATOMIC(vcpuid, &vm->halted_cpus);
1612 			}
1613 			if (CPU_CMP(&vm->halted_cpus, &vm->active_cpus) == 0) {
1614 				vm_halted = 1;
1615 				break;
1616 			}
1617 		}
1618 
1619 		vcpu_ustate_change(vm, vcpuid, VU_IDLE);
1620 		vcpu_require_state_locked(vm, vcpuid, VCPU_SLEEPING);
1621 		(void) cv_wait_sig(&vcpu->vcpu_cv, &vcpu->lock);
1622 		vcpu_require_state_locked(vm, vcpuid, VCPU_FROZEN);
1623 		vcpu_ustate_change(vm, vcpuid, VU_EMU_KERN);
1624 	}
1625 
1626 	if (vcpu_halted)
1627 		CPU_CLR_ATOMIC(vcpuid, &vm->halted_cpus);
1628 
1629 	vcpu_unlock(vcpu);
1630 
1631 	if (vm_halted) {
1632 		(void) vm_suspend(vm, VM_SUSPEND_HALT, -1);
1633 	}
1634 
1635 	return (userspace_exit ? -1 : 0);
1636 }
1637 
1638 static int
vm_handle_paging(struct vm * vm,int vcpuid)1639 vm_handle_paging(struct vm *vm, int vcpuid)
1640 {
1641 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
1642 	vm_client_t *vmc = vcpu->vmclient;
1643 	struct vm_exit *vme = &vcpu->exitinfo;
1644 	const int ftype = vme->u.paging.fault_type;
1645 
1646 	ASSERT0(vme->inst_length);
1647 	ASSERT(ftype == PROT_READ || ftype == PROT_WRITE || ftype == PROT_EXEC);
1648 
1649 	if (vmc_fault(vmc, vme->u.paging.gpa, ftype) != 0) {
1650 		/*
1651 		 * If the fault cannot be serviced, kick it out to userspace for
1652 		 * handling (or more likely, halting the instance).
1653 		 */
1654 		return (-1);
1655 	}
1656 
1657 	return (0);
1658 }
1659 
1660 int
vm_service_mmio_read(struct vm * vm,int cpuid,uint64_t gpa,uint64_t * rval,int rsize)1661 vm_service_mmio_read(struct vm *vm, int cpuid, uint64_t gpa, uint64_t *rval,
1662     int rsize)
1663 {
1664 	int err = ESRCH;
1665 
1666 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1667 		struct vlapic *vlapic = vm_lapic(vm, cpuid);
1668 
1669 		err = vlapic_mmio_read(vlapic, gpa, rval, rsize);
1670 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1671 		err = vioapic_mmio_read(vm, cpuid, gpa, rval, rsize);
1672 	} else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1673 		err = vhpet_mmio_read(vm, cpuid, gpa, rval, rsize);
1674 	}
1675 
1676 	return (err);
1677 }
1678 
1679 int
vm_service_mmio_write(struct vm * vm,int cpuid,uint64_t gpa,uint64_t wval,int wsize)1680 vm_service_mmio_write(struct vm *vm, int cpuid, uint64_t gpa, uint64_t wval,
1681     int wsize)
1682 {
1683 	int err = ESRCH;
1684 
1685 	if (gpa >= DEFAULT_APIC_BASE && gpa < DEFAULT_APIC_BASE + PAGE_SIZE) {
1686 		struct vlapic *vlapic = vm_lapic(vm, cpuid);
1687 
1688 		err = vlapic_mmio_write(vlapic, gpa, wval, wsize);
1689 	} else if (gpa >= VIOAPIC_BASE && gpa < VIOAPIC_BASE + VIOAPIC_SIZE) {
1690 		err = vioapic_mmio_write(vm, cpuid, gpa, wval, wsize);
1691 	} else if (gpa >= VHPET_BASE && gpa < VHPET_BASE + VHPET_SIZE) {
1692 		err = vhpet_mmio_write(vm, cpuid, gpa, wval, wsize);
1693 	}
1694 
1695 	return (err);
1696 }
1697 
1698 static int
vm_handle_mmio_emul(struct vm * vm,int vcpuid)1699 vm_handle_mmio_emul(struct vm *vm, int vcpuid)
1700 {
1701 	struct vie *vie;
1702 	struct vcpu *vcpu;
1703 	struct vm_exit *vme;
1704 	uint64_t inst_addr;
1705 	int error, fault, cs_d;
1706 
1707 	vcpu = &vm->vcpu[vcpuid];
1708 	vme = &vcpu->exitinfo;
1709 	vie = vcpu->vie_ctx;
1710 
1711 	KASSERT(vme->inst_length == 0, ("%s: invalid inst_length %d",
1712 	    __func__, vme->inst_length));
1713 
1714 	inst_addr = vme->rip + vme->u.mmio_emul.cs_base;
1715 	cs_d = vme->u.mmio_emul.cs_d;
1716 
1717 	/* Fetch the faulting instruction */
1718 	if (vie_needs_fetch(vie)) {
1719 		error = vie_fetch_instruction(vie, vm, vcpuid, inst_addr,
1720 		    &fault);
1721 		if (error != 0) {
1722 			return (error);
1723 		} else if (fault) {
1724 			/*
1725 			 * If a fault during instruction fetch was encountered,
1726 			 * it will have asserted that the appropriate exception
1727 			 * be injected at next entry.
1728 			 * No further work is required.
1729 			 */
1730 			return (0);
1731 		}
1732 	}
1733 
1734 	if (vie_decode_instruction(vie, vm, vcpuid, cs_d) != 0) {
1735 		/* Dump (unrecognized) instruction bytes in userspace */
1736 		vie_fallback_exitinfo(vie, vme);
1737 		return (-1);
1738 	}
1739 	if (vme->u.mmio_emul.gla != VIE_INVALID_GLA &&
1740 	    vie_verify_gla(vie, vm, vcpuid, vme->u.mmio_emul.gla) != 0) {
1741 		/* Decoded GLA does not match GLA from VM exit state */
1742 		vie_fallback_exitinfo(vie, vme);
1743 		return (-1);
1744 	}
1745 
1746 repeat:
1747 	error = vie_emulate_mmio(vie, vm, vcpuid);
1748 	if (error < 0) {
1749 		/*
1750 		 * MMIO not handled by any of the in-kernel-emulated devices, so
1751 		 * make a trip out to userspace for it.
1752 		 */
1753 		vie_exitinfo(vie, vme);
1754 	} else if (error == EAGAIN) {
1755 		/*
1756 		 * Continue emulating the rep-prefixed instruction, which has
1757 		 * not completed its iterations.
1758 		 *
1759 		 * In case this can be emulated in-kernel and has a high
1760 		 * repetition count (causing a tight spin), it should be
1761 		 * deferential to yield conditions.
1762 		 */
1763 		if (!vcpu_should_yield(vm, vcpuid)) {
1764 			goto repeat;
1765 		} else {
1766 			/*
1767 			 * Defer to the contending load by making a trip to
1768 			 * userspace with a no-op (BOGUS) exit reason.
1769 			 */
1770 			vie_reset(vie);
1771 			vme->exitcode = VM_EXITCODE_BOGUS;
1772 			return (-1);
1773 		}
1774 	} else if (error == 0) {
1775 		/* Update %rip now that instruction has been emulated */
1776 		vie_advance_pc(vie, &vcpu->nextrip);
1777 	}
1778 	return (error);
1779 }
1780 
1781 static int
vm_handle_inout(struct vm * vm,int vcpuid,struct vm_exit * vme)1782 vm_handle_inout(struct vm *vm, int vcpuid, struct vm_exit *vme)
1783 {
1784 	struct vcpu *vcpu;
1785 	struct vie *vie;
1786 	int err;
1787 
1788 	vcpu = &vm->vcpu[vcpuid];
1789 	vie = vcpu->vie_ctx;
1790 
1791 repeat:
1792 	err = vie_emulate_inout(vie, vm, vcpuid);
1793 
1794 	if (err < 0) {
1795 		/*
1796 		 * In/out not handled by any of the in-kernel-emulated devices,
1797 		 * so make a trip out to userspace for it.
1798 		 */
1799 		vie_exitinfo(vie, vme);
1800 		return (err);
1801 	} else if (err == EAGAIN) {
1802 		/*
1803 		 * Continue emulating the rep-prefixed ins/outs, which has not
1804 		 * completed its iterations.
1805 		 *
1806 		 * In case this can be emulated in-kernel and has a high
1807 		 * repetition count (causing a tight spin), it should be
1808 		 * deferential to yield conditions.
1809 		 */
1810 		if (!vcpu_should_yield(vm, vcpuid)) {
1811 			goto repeat;
1812 		} else {
1813 			/*
1814 			 * Defer to the contending load by making a trip to
1815 			 * userspace with a no-op (BOGUS) exit reason.
1816 			 */
1817 			vie_reset(vie);
1818 			vme->exitcode = VM_EXITCODE_BOGUS;
1819 			return (-1);
1820 		}
1821 	} else if (err != 0) {
1822 		/* Emulation failure.  Bail all the way out to userspace. */
1823 		vme->exitcode = VM_EXITCODE_INST_EMUL;
1824 		bzero(&vme->u.inst_emul, sizeof (vme->u.inst_emul));
1825 		return (-1);
1826 	}
1827 
1828 	vie_advance_pc(vie, &vcpu->nextrip);
1829 	return (0);
1830 }
1831 
1832 static int
vm_handle_inst_emul(struct vm * vm,int vcpuid)1833 vm_handle_inst_emul(struct vm *vm, int vcpuid)
1834 {
1835 	struct vie *vie;
1836 	struct vcpu *vcpu;
1837 	struct vm_exit *vme;
1838 	uint64_t cs_base;
1839 	int error, fault, cs_d;
1840 
1841 	vcpu = &vm->vcpu[vcpuid];
1842 	vme = &vcpu->exitinfo;
1843 	vie = vcpu->vie_ctx;
1844 
1845 	vie_cs_info(vie, vm, vcpuid, &cs_base, &cs_d);
1846 
1847 	/* Fetch the faulting instruction */
1848 	ASSERT(vie_needs_fetch(vie));
1849 	error = vie_fetch_instruction(vie, vm, vcpuid, vme->rip + cs_base,
1850 	    &fault);
1851 	if (error != 0) {
1852 		return (error);
1853 	} else if (fault) {
1854 		/*
1855 		 * If a fault during instruction fetch was encounted, it will
1856 		 * have asserted that the appropriate exception be injected at
1857 		 * next entry.  No further work is required.
1858 		 */
1859 		return (0);
1860 	}
1861 
1862 	if (vie_decode_instruction(vie, vm, vcpuid, cs_d) != 0) {
1863 		/* Dump (unrecognized) instruction bytes in userspace */
1864 		vie_fallback_exitinfo(vie, vme);
1865 		return (-1);
1866 	}
1867 
1868 	error = vie_emulate_other(vie, vm, vcpuid);
1869 	if (error != 0) {
1870 		/*
1871 		 * Instruction emulation was unable to complete successfully, so
1872 		 * kick it out to userspace for handling.
1873 		 */
1874 		vie_fallback_exitinfo(vie, vme);
1875 	} else {
1876 		/* Update %rip now that instruction has been emulated */
1877 		vie_advance_pc(vie, &vcpu->nextrip);
1878 	}
1879 	return (error);
1880 }
1881 
1882 static int
vm_handle_run_state(struct vm * vm,int vcpuid)1883 vm_handle_run_state(struct vm *vm, int vcpuid)
1884 {
1885 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
1886 	bool handled = false;
1887 
1888 	vcpu_lock(vcpu);
1889 	while (1) {
1890 		if ((vcpu->run_state & VRS_PEND_INIT) != 0) {
1891 			vcpu_unlock(vcpu);
1892 			VERIFY0(vcpu_arch_reset(vm, vcpuid, true));
1893 			vcpu_lock(vcpu);
1894 
1895 			vcpu->run_state &= ~(VRS_RUN | VRS_PEND_INIT);
1896 			vcpu->run_state |= VRS_INIT;
1897 		}
1898 
1899 		if ((vcpu->run_state & (VRS_INIT | VRS_RUN | VRS_PEND_SIPI)) ==
1900 		    (VRS_INIT | VRS_PEND_SIPI)) {
1901 			const uint8_t vector = vcpu->sipi_vector;
1902 
1903 			vcpu_unlock(vcpu);
1904 			VERIFY0(vcpu_vector_sipi(vm, vcpuid, vector));
1905 			vcpu_lock(vcpu);
1906 
1907 			vcpu->run_state &= ~VRS_PEND_SIPI;
1908 			vcpu->run_state |= VRS_RUN;
1909 		}
1910 
1911 		/*
1912 		 * If the vCPU is now in the running state, there is no need to
1913 		 * wait for anything prior to re-entry.
1914 		 */
1915 		if ((vcpu->run_state & VRS_RUN) != 0) {
1916 			handled = true;
1917 			break;
1918 		}
1919 
1920 		/*
1921 		 * Also check for software events which would cause a wake-up.
1922 		 * This will set the appropriate exitcode directly, rather than
1923 		 * requiring a trip through VM_RUN().
1924 		 */
1925 		if (vcpu_sleep_bailout_checks(vm, vcpuid)) {
1926 			break;
1927 		}
1928 
1929 		vcpu_ustate_change(vm, vcpuid, VU_IDLE);
1930 		vcpu_require_state_locked(vm, vcpuid, VCPU_SLEEPING);
1931 		(void) cv_wait_sig(&vcpu->vcpu_cv, &vcpu->lock);
1932 		vcpu_require_state_locked(vm, vcpuid, VCPU_FROZEN);
1933 		vcpu_ustate_change(vm, vcpuid, VU_EMU_KERN);
1934 	}
1935 	vcpu_unlock(vcpu);
1936 
1937 	return (handled ? 0 : -1);
1938 }
1939 
1940 static int
vm_rdmtrr(const struct vm_mtrr * mtrr,uint32_t num,uint64_t * val)1941 vm_rdmtrr(const struct vm_mtrr *mtrr, uint32_t num, uint64_t *val)
1942 {
1943 	switch (num) {
1944 	case MSR_MTRRcap:
1945 		*val = MTRR_CAP_WC | MTRR_CAP_FIXED | VMM_MTRR_VAR_MAX;
1946 		break;
1947 	case MSR_MTRRdefType:
1948 		*val = mtrr->def_type;
1949 		break;
1950 	case MSR_MTRR4kBase ... MSR_MTRR4kBase + 7:
1951 		*val = mtrr->fixed4k[num - MSR_MTRR4kBase];
1952 		break;
1953 	case MSR_MTRR16kBase ... MSR_MTRR16kBase + 1:
1954 		*val = mtrr->fixed16k[num - MSR_MTRR16kBase];
1955 		break;
1956 	case MSR_MTRR64kBase:
1957 		*val = mtrr->fixed64k;
1958 		break;
1959 	case MSR_MTRRVarBase ... MSR_MTRRVarBase + (VMM_MTRR_VAR_MAX * 2) - 1: {
1960 		uint_t offset = num - MSR_MTRRVarBase;
1961 		if (offset % 2 == 0) {
1962 			*val = mtrr->var[offset / 2].base;
1963 		} else {
1964 			*val = mtrr->var[offset / 2].mask;
1965 		}
1966 		break;
1967 	}
1968 	default:
1969 		return (EINVAL);
1970 	}
1971 
1972 	return (0);
1973 }
1974 
1975 static int
vm_wrmtrr(struct vm_mtrr * mtrr,uint32_t num,uint64_t val)1976 vm_wrmtrr(struct vm_mtrr *mtrr, uint32_t num, uint64_t val)
1977 {
1978 	switch (num) {
1979 	case MSR_MTRRcap:
1980 		/* MTRRCAP is read only */
1981 		return (EPERM);
1982 	case MSR_MTRRdefType:
1983 		if (val & ~VMM_MTRR_DEF_MASK) {
1984 			/* generate #GP on writes to reserved fields */
1985 			return (EINVAL);
1986 		}
1987 		mtrr->def_type = val;
1988 		break;
1989 	case MSR_MTRR4kBase ... MSR_MTRR4kBase + 7:
1990 		mtrr->fixed4k[num - MSR_MTRR4kBase] = val;
1991 		break;
1992 	case MSR_MTRR16kBase ... MSR_MTRR16kBase + 1:
1993 		mtrr->fixed16k[num - MSR_MTRR16kBase] = val;
1994 		break;
1995 	case MSR_MTRR64kBase:
1996 		mtrr->fixed64k = val;
1997 		break;
1998 	case MSR_MTRRVarBase ... MSR_MTRRVarBase + (VMM_MTRR_VAR_MAX * 2) - 1: {
1999 		uint_t offset = num - MSR_MTRRVarBase;
2000 		if (offset % 2 == 0) {
2001 			if (val & ~VMM_MTRR_PHYSBASE_MASK) {
2002 				/* generate #GP on writes to reserved fields */
2003 				return (EINVAL);
2004 			}
2005 			mtrr->var[offset / 2].base = val;
2006 		} else {
2007 			if (val & ~VMM_MTRR_PHYSMASK_MASK) {
2008 				/* generate #GP on writes to reserved fields */
2009 				return (EINVAL);
2010 			}
2011 			mtrr->var[offset / 2].mask = val;
2012 		}
2013 		break;
2014 	}
2015 	default:
2016 		return (EINVAL);
2017 	}
2018 
2019 	return (0);
2020 }
2021 
2022 static bool
is_mtrr_msr(uint32_t msr)2023 is_mtrr_msr(uint32_t msr)
2024 {
2025 	switch (msr) {
2026 	case MSR_MTRRcap:
2027 	case MSR_MTRRdefType:
2028 	case MSR_MTRR4kBase ... MSR_MTRR4kBase + 7:
2029 	case MSR_MTRR16kBase ... MSR_MTRR16kBase + 1:
2030 	case MSR_MTRR64kBase:
2031 	case MSR_MTRRVarBase ... MSR_MTRRVarBase + (VMM_MTRR_VAR_MAX * 2) - 1:
2032 		return (true);
2033 	default:
2034 		return (false);
2035 	}
2036 }
2037 
2038 static int
vm_handle_rdmsr(struct vm * vm,int vcpuid,struct vm_exit * vme)2039 vm_handle_rdmsr(struct vm *vm, int vcpuid, struct vm_exit *vme)
2040 {
2041 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
2042 	const uint32_t code = vme->u.msr.code;
2043 	uint64_t val = 0;
2044 
2045 	switch (code) {
2046 	case MSR_MCG_CAP:
2047 	case MSR_MCG_STATUS:
2048 		val = 0;
2049 		break;
2050 
2051 	case MSR_MTRRcap:
2052 	case MSR_MTRRdefType:
2053 	case MSR_MTRR4kBase ... MSR_MTRR4kBase + 7:
2054 	case MSR_MTRR16kBase ... MSR_MTRR16kBase + 1:
2055 	case MSR_MTRR64kBase:
2056 	case MSR_MTRRVarBase ... MSR_MTRRVarBase + (VMM_MTRR_VAR_MAX * 2) - 1:
2057 		if (vm_rdmtrr(&vcpu->mtrr, code, &val) != 0)
2058 			vm_inject_gp(vm, vcpuid);
2059 		break;
2060 
2061 	case MSR_TSC:
2062 		/*
2063 		 * Get the guest TSC, applying necessary vCPU offsets.
2064 		 *
2065 		 * In all likelihood, this should always be handled in guest
2066 		 * context by VMX/SVM rather than taking an exit.  (Both VMX and
2067 		 * SVM pass through read-only access to MSR_TSC to the guest.)
2068 		 *
2069 		 * The VM-wide TSC offset and per-vCPU offset are included in
2070 		 * the calculations of vcpu_tsc_offset(), so this is sufficient
2071 		 * to use as the offset in our calculations.
2072 		 *
2073 		 * No physical offset is requested of vcpu_tsc_offset() since
2074 		 * rdtsc_offset() takes care of that instead.
2075 		 */
2076 		val = calc_guest_tsc(rdtsc_offset(), vm->freq_multiplier,
2077 		    vcpu_tsc_offset(vm, vcpuid, false));
2078 		break;
2079 
2080 	default:
2081 		/*
2082 		 * Anything not handled at this point will be kicked out to
2083 		 * userspace for attempted processing there.
2084 		 */
2085 		return (-1);
2086 	}
2087 
2088 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_RAX,
2089 	    val & 0xffffffff));
2090 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_RDX,
2091 	    val >> 32));
2092 	return (0);
2093 }
2094 
2095 static int
vm_handle_wrmsr(struct vm * vm,int vcpuid,struct vm_exit * vme)2096 vm_handle_wrmsr(struct vm *vm, int vcpuid, struct vm_exit *vme)
2097 {
2098 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
2099 	const uint32_t code = vme->u.msr.code;
2100 	const uint64_t val = vme->u.msr.wval;
2101 
2102 	switch (code) {
2103 	case MSR_MCG_CAP:
2104 	case MSR_MCG_STATUS:
2105 		/* Ignore writes */
2106 		break;
2107 
2108 	case MSR_MTRRcap:
2109 	case MSR_MTRRdefType:
2110 	case MSR_MTRR4kBase ... MSR_MTRR4kBase + 7:
2111 	case MSR_MTRR16kBase ... MSR_MTRR16kBase + 1:
2112 	case MSR_MTRR64kBase:
2113 	case MSR_MTRRVarBase ... MSR_MTRRVarBase + (VMM_MTRR_VAR_MAX * 2) - 1:
2114 		if (vm_wrmtrr(&vcpu->mtrr, code, val) != 0)
2115 			vm_inject_gp(vm, vcpuid);
2116 		break;
2117 
2118 	case MSR_TSC:
2119 		/*
2120 		 * The effect of writing the TSC MSR is that a subsequent read
2121 		 * of the TSC would report that value written (plus any time
2122 		 * elapsed between the write and the read).
2123 		 *
2124 		 * To calculate that per-vCPU offset, we can work backwards from
2125 		 * the guest TSC at the time of write:
2126 		 *
2127 		 * value = current guest TSC + vCPU offset
2128 		 *
2129 		 * so therefore:
2130 		 *
2131 		 * value - current guest TSC = vCPU offset
2132 		 */
2133 		vcpu->tsc_offset = val - calc_guest_tsc(rdtsc_offset(),
2134 		    vm->freq_multiplier, vm->tsc_offset);
2135 		break;
2136 
2137 	default:
2138 		/*
2139 		 * Anything not handled at this point will be kicked out to
2140 		 * userspace for attempted processing there.
2141 		 */
2142 		return (-1);
2143 	}
2144 
2145 	return (0);
2146 }
2147 
2148 /*
2149  * Has a suspend event been asserted on the VM?
2150  *
2151  * The reason and (in the case of a triple-fault) source vcpuid are optionally
2152  * returned if such a state is present.
2153  */
2154 static bool
vm_is_suspended(struct vm * vm,struct vm_exit * vme)2155 vm_is_suspended(struct vm *vm, struct vm_exit *vme)
2156 {
2157 	const int val = vm->suspend_how;
2158 	if (val == 0) {
2159 		return (false);
2160 	} else {
2161 		if (vme != NULL) {
2162 			vme->exitcode = VM_EXITCODE_SUSPENDED;
2163 			vme->u.suspended.how = val;
2164 			vme->u.suspended.source = vm->suspend_source;
2165 			/*
2166 			 * Normalize suspend event time and, on the off chance
2167 			 * that it was recorded as occuring prior to VM boot,
2168 			 * clamp it to a minimum of 0.
2169 			 */
2170 			vme->u.suspended.when = (uint64_t)
2171 			    MAX(vm_normalize_hrtime(vm, vm->suspend_when), 0);
2172 		}
2173 		return (true);
2174 	}
2175 }
2176 
2177 int
vm_suspend(struct vm * vm,enum vm_suspend_how how,int source)2178 vm_suspend(struct vm *vm, enum vm_suspend_how how, int source)
2179 {
2180 	if (how <= VM_SUSPEND_NONE || how >= VM_SUSPEND_LAST) {
2181 		return (EINVAL);
2182 	}
2183 
2184 	/*
2185 	 * Although the common case of calling vm_suspend() is via
2186 	 * ioctl(VM_SUSPEND), where all the vCPUs will be held in the frozen
2187 	 * state, it can also be called by a running vCPU to indicate a
2188 	 * triple-fault.  In the latter case, there is no exclusion from a
2189 	 * racing vm_suspend() from a different vCPU, so assertion of the
2190 	 * suspended state must be performed carefully.
2191 	 *
2192 	 * The `suspend_when` is set first via atomic cmpset to pick a "winner"
2193 	 * of the suspension race, followed by population of 'suspend_source'.
2194 	 * Only after those are done, and a membar is emitted will 'suspend_how'
2195 	 * be set, which makes the suspended state visible to any vCPU checking
2196 	 * for it.  That order will prevent an incomplete suspend state (between
2197 	 * 'how', 'source', and 'when') from being observed.
2198 	 */
2199 	const hrtime_t now = gethrtime();
2200 	if (atomic_cmpset_long((ulong_t *)&vm->suspend_when, 0, now) == 0) {
2201 		return (EALREADY);
2202 	}
2203 	vm->suspend_source = source;
2204 	membar_producer();
2205 	vm->suspend_how = how;
2206 
2207 	/* Notify all active vcpus that they are now suspended. */
2208 	for (uint_t i = 0; i < vm->maxcpus; i++) {
2209 		struct vcpu *vcpu = &vm->vcpu[i];
2210 
2211 		vcpu_lock(vcpu);
2212 
2213 		if (!CPU_ISSET(i, &vm->active_cpus)) {
2214 			/*
2215 			 * vCPUs not already marked as active can be ignored,
2216 			 * since they cannot become marked as active unless the
2217 			 * VM is reinitialized, clearing the suspended state.
2218 			 */
2219 			vcpu_unlock(vcpu);
2220 			continue;
2221 		}
2222 
2223 		switch (vcpu->state) {
2224 		case VCPU_IDLE:
2225 		case VCPU_FROZEN:
2226 			/*
2227 			 * vCPUs not locked by in-kernel activity can be
2228 			 * immediately marked as suspended: The ustate is moved
2229 			 * back to VU_INIT, since no further guest work will
2230 			 * occur while the VM is in this state.
2231 			 *
2232 			 * A FROZEN vCPU may still change its ustate on the way
2233 			 * out of the kernel, but a subsequent check at the end
2234 			 * of vm_run() should be adequate to fix it up.
2235 			 */
2236 			vcpu_ustate_change(vm, i, VU_INIT);
2237 			break;
2238 		default:
2239 			/*
2240 			 * Any vCPUs which are running or waiting in-kernel
2241 			 * (such as in HLT) are notified to pick up the newly
2242 			 * suspended state.
2243 			 */
2244 			vcpu_notify_event_locked(vcpu, VCPU_NOTIFY_EXIT);
2245 			break;
2246 		}
2247 		vcpu_unlock(vcpu);
2248 	}
2249 	return (0);
2250 }
2251 
2252 void
vm_exit_run_state(struct vm * vm,int vcpuid,uint64_t rip)2253 vm_exit_run_state(struct vm *vm, int vcpuid, uint64_t rip)
2254 {
2255 	struct vm_exit *vmexit;
2256 
2257 	vmexit = vm_exitinfo(vm, vcpuid);
2258 	vmexit->rip = rip;
2259 	vmexit->inst_length = 0;
2260 	vmexit->exitcode = VM_EXITCODE_RUN_STATE;
2261 	vmm_stat_incr(vm, vcpuid, VMEXIT_RUN_STATE, 1);
2262 }
2263 
2264 /*
2265  * Some vmm resources, such as the lapic, may have CPU-specific resources
2266  * allocated to them which would benefit from migration onto the host CPU which
2267  * is processing the vcpu state.
2268  */
2269 static void
vm_localize_resources(struct vm * vm,struct vcpu * vcpu)2270 vm_localize_resources(struct vm *vm, struct vcpu *vcpu)
2271 {
2272 	/*
2273 	 * Localizing cyclic resources requires acquisition of cpu_lock, and
2274 	 * doing so with kpreempt disabled is a recipe for deadlock disaster.
2275 	 */
2276 	VERIFY(curthread->t_preempt == 0);
2277 
2278 	/*
2279 	 * Do not bother with localization if this vCPU is about to return to
2280 	 * the host CPU it was last localized to.
2281 	 */
2282 	if (vcpu->lastloccpu == curcpu)
2283 		return;
2284 
2285 	/*
2286 	 * Localize system-wide resources to the primary boot vCPU.  While any
2287 	 * of the other vCPUs may access them, it keeps the potential interrupt
2288 	 * footprint constrained to CPUs involved with this instance.
2289 	 */
2290 	if (vcpu == &vm->vcpu[0]) {
2291 		vhpet_localize_resources(vm->vhpet);
2292 		vrtc_localize_resources(vm->vrtc);
2293 		vatpit_localize_resources(vm->vatpit);
2294 	}
2295 
2296 	vlapic_localize_resources(vcpu->vlapic);
2297 
2298 	vcpu->lastloccpu = curcpu;
2299 }
2300 
2301 static void
vmm_savectx(void * arg)2302 vmm_savectx(void *arg)
2303 {
2304 	vm_thread_ctx_t *vtc = arg;
2305 	struct vm *vm = vtc->vtc_vm;
2306 	const int vcpuid = vtc->vtc_vcpuid;
2307 
2308 	if (ops->vmsavectx != NULL) {
2309 		ops->vmsavectx(vm->cookie, vcpuid);
2310 	}
2311 
2312 	/*
2313 	 * Account for going off-cpu, unless the vCPU is idled, where being
2314 	 * off-cpu is the explicit point.
2315 	 */
2316 	if (vm->vcpu[vcpuid].ustate != VU_IDLE) {
2317 		vtc->vtc_ustate = vm->vcpu[vcpuid].ustate;
2318 		vcpu_ustate_change(vm, vcpuid, VU_SCHED);
2319 	}
2320 
2321 	/*
2322 	 * If the CPU holds the restored guest FPU state, save it and restore
2323 	 * the host FPU state before this thread goes off-cpu.
2324 	 */
2325 	if ((vtc->vtc_status & VTCS_FPU_RESTORED) != 0) {
2326 		struct vcpu *vcpu = &vm->vcpu[vcpuid];
2327 
2328 		save_guest_fpustate(vcpu);
2329 		vtc->vtc_status &= ~VTCS_FPU_RESTORED;
2330 	}
2331 }
2332 
2333 static void
vmm_restorectx(void * arg)2334 vmm_restorectx(void *arg)
2335 {
2336 	vm_thread_ctx_t *vtc = arg;
2337 	struct vm *vm = vtc->vtc_vm;
2338 	const int vcpuid = vtc->vtc_vcpuid;
2339 
2340 	/* Complete microstate accounting for vCPU being off-cpu */
2341 	if (vm->vcpu[vcpuid].ustate != VU_IDLE) {
2342 		vcpu_ustate_change(vm, vcpuid, vtc->vtc_ustate);
2343 	}
2344 
2345 	/*
2346 	 * When coming back on-cpu, only restore the guest FPU status if the
2347 	 * thread is in a context marked as requiring it.  This should be rare,
2348 	 * occurring only when a future logic error results in a voluntary
2349 	 * sleep during the VMRUN critical section.
2350 	 *
2351 	 * The common case will result in elision of the guest FPU state
2352 	 * restoration, deferring that action until it is clearly necessary
2353 	 * during vm_run.
2354 	 */
2355 	VERIFY((vtc->vtc_status & VTCS_FPU_RESTORED) == 0);
2356 	if ((vtc->vtc_status & VTCS_FPU_CTX_CRITICAL) != 0) {
2357 		struct vcpu *vcpu = &vm->vcpu[vcpuid];
2358 
2359 		restore_guest_fpustate(vcpu);
2360 		vtc->vtc_status |= VTCS_FPU_RESTORED;
2361 	}
2362 
2363 	if (ops->vmrestorectx != NULL) {
2364 		ops->vmrestorectx(vm->cookie, vcpuid);
2365 	}
2366 
2367 }
2368 
2369 /* Convenience defines for parsing vm_entry`cmd values */
2370 #define	VEC_MASK_FLAGS	(VEC_FLAG_EXIT_CONSISTENT)
2371 #define	VEC_MASK_CMD	(~VEC_MASK_FLAGS)
2372 
2373 static int
vm_entry_actions(struct vm * vm,int vcpuid,const struct vm_entry * entry,struct vm_exit * vme)2374 vm_entry_actions(struct vm *vm, int vcpuid, const struct vm_entry *entry,
2375     struct vm_exit *vme)
2376 {
2377 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
2378 	struct vie *vie = vcpu->vie_ctx;
2379 	int err = 0;
2380 
2381 	const uint_t cmd = entry->cmd & VEC_MASK_CMD;
2382 	const uint_t flags = entry->cmd & VEC_MASK_FLAGS;
2383 
2384 	switch (cmd) {
2385 	case VEC_DEFAULT:
2386 		break;
2387 	case VEC_DISCARD_INSTR:
2388 		vie_reset(vie);
2389 		break;
2390 	case VEC_FULFILL_MMIO:
2391 		err = vie_fulfill_mmio(vie, &entry->u.mmio);
2392 		if (err == 0) {
2393 			err = vie_emulate_mmio(vie, vm, vcpuid);
2394 			if (err == 0) {
2395 				vie_advance_pc(vie, &vcpu->nextrip);
2396 			} else if (err < 0) {
2397 				vie_exitinfo(vie, vme);
2398 			} else if (err == EAGAIN) {
2399 				/*
2400 				 * Clear the instruction emulation state in
2401 				 * order to re-enter VM context and continue
2402 				 * this 'rep <instruction>'
2403 				 */
2404 				vie_reset(vie);
2405 				err = 0;
2406 			}
2407 		}
2408 		break;
2409 	case VEC_FULFILL_INOUT:
2410 		err = vie_fulfill_inout(vie, &entry->u.inout);
2411 		if (err == 0) {
2412 			err = vie_emulate_inout(vie, vm, vcpuid);
2413 			if (err == 0) {
2414 				vie_advance_pc(vie, &vcpu->nextrip);
2415 			} else if (err < 0) {
2416 				vie_exitinfo(vie, vme);
2417 			} else if (err == EAGAIN) {
2418 				/*
2419 				 * Clear the instruction emulation state in
2420 				 * order to re-enter VM context and continue
2421 				 * this 'rep ins/outs'
2422 				 */
2423 				vie_reset(vie);
2424 				err = 0;
2425 			}
2426 		}
2427 		break;
2428 	default:
2429 		return (EINVAL);
2430 	}
2431 
2432 	/*
2433 	 * Pay heed to requests for exit-when-vCPU-is-consistent requests, at
2434 	 * least when we are not immediately bound for another exit due to
2435 	 * multi-part instruction emulation or related causes.
2436 	 */
2437 	if ((flags & VEC_FLAG_EXIT_CONSISTENT) != 0 && err == 0) {
2438 		vcpu->reqconsist = true;
2439 	}
2440 
2441 	return (err);
2442 }
2443 
2444 static int
vm_loop_checks(struct vm * vm,int vcpuid,struct vm_exit * vme)2445 vm_loop_checks(struct vm *vm, int vcpuid, struct vm_exit *vme)
2446 {
2447 	struct vie *vie;
2448 
2449 	vie = vm->vcpu[vcpuid].vie_ctx;
2450 
2451 	if (vie_pending(vie)) {
2452 		/*
2453 		 * Userspace has not fulfilled the pending needs of the
2454 		 * instruction emulation, so bail back out.
2455 		 */
2456 		vie_exitinfo(vie, vme);
2457 		return (-1);
2458 	}
2459 
2460 	return (0);
2461 }
2462 
2463 int
vm_run(struct vm * vm,int vcpuid,const struct vm_entry * entry)2464 vm_run(struct vm *vm, int vcpuid, const struct vm_entry *entry)
2465 {
2466 	int error;
2467 	struct vcpu *vcpu;
2468 	struct vm_exit *vme;
2469 	bool intr_disabled;
2470 	int affinity_type = CPU_CURRENT;
2471 
2472 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2473 		return (EINVAL);
2474 	if (!CPU_ISSET(vcpuid, &vm->active_cpus))
2475 		return (EINVAL);
2476 	if (vm->is_paused) {
2477 		return (EBUSY);
2478 	}
2479 
2480 	vcpu = &vm->vcpu[vcpuid];
2481 	vme = &vcpu->exitinfo;
2482 
2483 	vcpu_ustate_change(vm, vcpuid, VU_EMU_KERN);
2484 
2485 	vcpu->vtc.vtc_status = 0;
2486 	ctxop_attach(curthread, vcpu->ctxop);
2487 
2488 	error = vm_entry_actions(vm, vcpuid, entry, vme);
2489 	if (error != 0) {
2490 		goto exit;
2491 	}
2492 
2493 restart:
2494 	error = vm_loop_checks(vm, vcpuid, vme);
2495 	if (error != 0) {
2496 		goto exit;
2497 	}
2498 
2499 	thread_affinity_set(curthread, affinity_type);
2500 	/*
2501 	 * Resource localization should happen after the CPU affinity for the
2502 	 * thread has been set to ensure that access from restricted contexts,
2503 	 * such as VMX-accelerated APIC operations, can occur without inducing
2504 	 * cyclic cross-calls.
2505 	 *
2506 	 * This must be done prior to disabling kpreempt via critical_enter().
2507 	 */
2508 	vm_localize_resources(vm, vcpu);
2509 	affinity_type = CPU_CURRENT;
2510 	critical_enter();
2511 
2512 	/* Force a trip through update_sregs to reload %fs/%gs and friends */
2513 	PCB_SET_UPDATE_SEGS(&ttolwp(curthread)->lwp_pcb);
2514 
2515 	if ((vcpu->vtc.vtc_status & VTCS_FPU_RESTORED) == 0) {
2516 		restore_guest_fpustate(vcpu);
2517 		vcpu->vtc.vtc_status |= VTCS_FPU_RESTORED;
2518 	}
2519 	vcpu->vtc.vtc_status |= VTCS_FPU_CTX_CRITICAL;
2520 
2521 	vcpu_require_state(vm, vcpuid, VCPU_RUNNING);
2522 	error = VMRUN(vm->cookie, vcpuid, vcpu->nextrip);
2523 	vcpu_require_state(vm, vcpuid, VCPU_FROZEN);
2524 
2525 	/*
2526 	 * Once clear of the delicate contexts comprising the VM_RUN handler,
2527 	 * thread CPU affinity can be loosened while other processing occurs.
2528 	 */
2529 	vcpu->vtc.vtc_status &= ~VTCS_FPU_CTX_CRITICAL;
2530 	thread_affinity_clear(curthread);
2531 	critical_exit();
2532 
2533 	if (error != 0) {
2534 		/* Communicate out any error from VMRUN() above */
2535 		goto exit;
2536 	}
2537 
2538 	vcpu->nextrip = vme->rip + vme->inst_length;
2539 	switch (vme->exitcode) {
2540 	case VM_EXITCODE_RUN_STATE:
2541 		error = vm_handle_run_state(vm, vcpuid);
2542 		break;
2543 	case VM_EXITCODE_IOAPIC_EOI:
2544 		vioapic_process_eoi(vm, vcpuid,
2545 		    vme->u.ioapic_eoi.vector);
2546 		break;
2547 	case VM_EXITCODE_HLT:
2548 		intr_disabled = ((vme->u.hlt.rflags & PSL_I) == 0);
2549 		error = vm_handle_hlt(vm, vcpuid, intr_disabled);
2550 		break;
2551 	case VM_EXITCODE_PAGING:
2552 		error = vm_handle_paging(vm, vcpuid);
2553 		break;
2554 	case VM_EXITCODE_MMIO_EMUL:
2555 		error = vm_handle_mmio_emul(vm, vcpuid);
2556 		break;
2557 	case VM_EXITCODE_INOUT:
2558 		error = vm_handle_inout(vm, vcpuid, vme);
2559 		break;
2560 	case VM_EXITCODE_INST_EMUL:
2561 		error = vm_handle_inst_emul(vm, vcpuid);
2562 		break;
2563 	case VM_EXITCODE_MONITOR:
2564 	case VM_EXITCODE_MWAIT:
2565 	case VM_EXITCODE_VMINSN:
2566 		vm_inject_ud(vm, vcpuid);
2567 		break;
2568 	case VM_EXITCODE_RDMSR:
2569 		error = vm_handle_rdmsr(vm, vcpuid, vme);
2570 		break;
2571 	case VM_EXITCODE_WRMSR:
2572 		error = vm_handle_wrmsr(vm, vcpuid, vme);
2573 		break;
2574 	case VM_EXITCODE_HT:
2575 		affinity_type = CPU_BEST;
2576 		break;
2577 	case VM_EXITCODE_MTRAP:
2578 		VERIFY0(vm_suspend_cpu(vm, vcpuid));
2579 		error = -1;
2580 		break;
2581 	default:
2582 		/* handled in userland */
2583 		error = -1;
2584 		break;
2585 	}
2586 
2587 	if (error == 0) {
2588 		/* VM exit conditions handled in-kernel, continue running */
2589 		goto restart;
2590 	}
2591 
2592 exit:
2593 	kpreempt_disable();
2594 	ctxop_detach(curthread, vcpu->ctxop);
2595 	/* Make sure all of the needed vCPU context state is saved */
2596 	vmm_savectx(&vcpu->vtc);
2597 	kpreempt_enable();
2598 
2599 	/*
2600 	 * Bill time in userspace against VU_EMU_USER, unless the VM is
2601 	 * suspended, in which case VU_INIT is the choice.
2602 	 */
2603 	vcpu_ustate_change(vm, vcpuid,
2604 	    vm_is_suspended(vm, NULL) ? VU_INIT : VU_EMU_USER);
2605 
2606 	return (error);
2607 }
2608 
2609 int
vm_restart_instruction(void * arg,int vcpuid)2610 vm_restart_instruction(void *arg, int vcpuid)
2611 {
2612 	struct vm *vm;
2613 	struct vcpu *vcpu;
2614 	enum vcpu_state state;
2615 	uint64_t rip;
2616 	int error;
2617 
2618 	vm = arg;
2619 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2620 		return (EINVAL);
2621 
2622 	vcpu = &vm->vcpu[vcpuid];
2623 	state = vcpu_get_state(vm, vcpuid, NULL);
2624 	if (state == VCPU_RUNNING) {
2625 		/*
2626 		 * When a vcpu is "running" the next instruction is determined
2627 		 * by adding 'rip' and 'inst_length' in the vcpu's 'exitinfo'.
2628 		 * Thus setting 'inst_length' to zero will cause the current
2629 		 * instruction to be restarted.
2630 		 */
2631 		vcpu->exitinfo.inst_length = 0;
2632 	} else if (state == VCPU_FROZEN) {
2633 		/*
2634 		 * When a vcpu is "frozen" it is outside the critical section
2635 		 * around VMRUN() and 'nextrip' points to the next instruction.
2636 		 * Thus instruction restart is achieved by setting 'nextrip'
2637 		 * to the vcpu's %rip.
2638 		 */
2639 		error = vm_get_register(vm, vcpuid, VM_REG_GUEST_RIP, &rip);
2640 		KASSERT(!error, ("%s: error %d getting rip", __func__, error));
2641 		vcpu->nextrip = rip;
2642 	} else {
2643 		panic("%s: invalid state %d", __func__, state);
2644 	}
2645 	return (0);
2646 }
2647 
2648 int
vm_exit_intinfo(struct vm * vm,int vcpuid,uint64_t info)2649 vm_exit_intinfo(struct vm *vm, int vcpuid, uint64_t info)
2650 {
2651 	struct vcpu *vcpu;
2652 
2653 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2654 		return (EINVAL);
2655 
2656 	vcpu = &vm->vcpu[vcpuid];
2657 
2658 	if (VM_INTINFO_PENDING(info)) {
2659 		const uint32_t type = VM_INTINFO_TYPE(info);
2660 		const uint8_t vector = VM_INTINFO_VECTOR(info);
2661 
2662 		if (type == VM_INTINFO_NMI && vector != IDT_NMI)
2663 			return (EINVAL);
2664 		if (type == VM_INTINFO_HWEXCP && vector >= 32)
2665 			return (EINVAL);
2666 		if (info & VM_INTINFO_MASK_RSVD)
2667 			return (EINVAL);
2668 	} else {
2669 		info = 0;
2670 	}
2671 	vcpu->exit_intinfo = info;
2672 	return (0);
2673 }
2674 
2675 enum exc_class {
2676 	EXC_BENIGN,
2677 	EXC_CONTRIBUTORY,
2678 	EXC_PAGEFAULT
2679 };
2680 
2681 #define	IDT_VE	20	/* Virtualization Exception (Intel specific) */
2682 
2683 static enum exc_class
exception_class(uint64_t info)2684 exception_class(uint64_t info)
2685 {
2686 	ASSERT(VM_INTINFO_PENDING(info));
2687 
2688 	/* Table 6-4, "Interrupt and Exception Classes", Intel SDM, Vol 3 */
2689 	switch (VM_INTINFO_TYPE(info)) {
2690 	case VM_INTINFO_HWINTR:
2691 	case VM_INTINFO_SWINTR:
2692 	case VM_INTINFO_NMI:
2693 		return (EXC_BENIGN);
2694 	default:
2695 		/*
2696 		 * Hardware exception.
2697 		 *
2698 		 * SVM and VT-x use identical type values to represent NMI,
2699 		 * hardware interrupt and software interrupt.
2700 		 *
2701 		 * SVM uses type '3' for all exceptions. VT-x uses type '3'
2702 		 * for exceptions except #BP and #OF. #BP and #OF use a type
2703 		 * value of '5' or '6'. Therefore we don't check for explicit
2704 		 * values of 'type' to classify 'intinfo' into a hardware
2705 		 * exception.
2706 		 */
2707 		break;
2708 	}
2709 
2710 	switch (VM_INTINFO_VECTOR(info)) {
2711 	case IDT_PF:
2712 	case IDT_VE:
2713 		return (EXC_PAGEFAULT);
2714 	case IDT_DE:
2715 	case IDT_TS:
2716 	case IDT_NP:
2717 	case IDT_SS:
2718 	case IDT_GP:
2719 		return (EXC_CONTRIBUTORY);
2720 	default:
2721 		return (EXC_BENIGN);
2722 	}
2723 }
2724 
2725 /*
2726  * Fetch event pending injection into the guest, if one exists.
2727  *
2728  * Returns true if an event is to be injected (which is placed in `retinfo`).
2729  */
2730 bool
vm_entry_intinfo(struct vm * vm,int vcpuid,uint64_t * retinfo)2731 vm_entry_intinfo(struct vm *vm, int vcpuid, uint64_t *retinfo)
2732 {
2733 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
2734 	const uint64_t info1 = vcpu->exit_intinfo;
2735 	vcpu->exit_intinfo = 0;
2736 	const uint64_t info2 = vcpu->exc_pending;
2737 	vcpu->exc_pending = 0;
2738 
2739 	if (VM_INTINFO_PENDING(info1) && VM_INTINFO_PENDING(info2)) {
2740 		/*
2741 		 * If an exception occurs while attempting to call the
2742 		 * double-fault handler the processor enters shutdown mode
2743 		 * (aka triple fault).
2744 		 */
2745 		if (VM_INTINFO_TYPE(info1) == VM_INTINFO_HWEXCP &&
2746 		    VM_INTINFO_VECTOR(info1) == IDT_DF) {
2747 			(void) vm_suspend(vm, VM_SUSPEND_TRIPLEFAULT, vcpuid);
2748 			*retinfo = 0;
2749 			return (false);
2750 		}
2751 		/*
2752 		 * "Conditions for Generating a Double Fault"
2753 		 *  Intel SDM, Vol3, Table 6-5
2754 		 */
2755 		const enum exc_class exc1 = exception_class(info1);
2756 		const enum exc_class exc2 = exception_class(info2);
2757 		if ((exc1 == EXC_CONTRIBUTORY && exc2 == EXC_CONTRIBUTORY) ||
2758 		    (exc1 == EXC_PAGEFAULT && exc2 != EXC_BENIGN)) {
2759 			/* Convert nested fault into a double fault. */
2760 			*retinfo =
2761 			    VM_INTINFO_VALID |
2762 			    VM_INTINFO_DEL_ERRCODE |
2763 			    VM_INTINFO_HWEXCP |
2764 			    IDT_DF;
2765 		} else {
2766 			/* Handle exceptions serially */
2767 			vcpu->exit_intinfo = info1;
2768 			*retinfo = info2;
2769 		}
2770 		return (true);
2771 	} else if (VM_INTINFO_PENDING(info1)) {
2772 		*retinfo = info1;
2773 		return (true);
2774 	} else if (VM_INTINFO_PENDING(info2)) {
2775 		*retinfo = info2;
2776 		return (true);
2777 	}
2778 
2779 	return (false);
2780 }
2781 
2782 int
vm_get_intinfo(struct vm * vm,int vcpuid,uint64_t * info1,uint64_t * info2)2783 vm_get_intinfo(struct vm *vm, int vcpuid, uint64_t *info1, uint64_t *info2)
2784 {
2785 	struct vcpu *vcpu;
2786 
2787 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2788 		return (EINVAL);
2789 
2790 	vcpu = &vm->vcpu[vcpuid];
2791 	*info1 = vcpu->exit_intinfo;
2792 	*info2 = vcpu->exc_pending;
2793 	return (0);
2794 }
2795 
2796 int
vm_inject_exception(struct vm * vm,int vcpuid,uint8_t vector,bool errcode_valid,uint32_t errcode,bool restart_instruction)2797 vm_inject_exception(struct vm *vm, int vcpuid, uint8_t vector,
2798     bool errcode_valid, uint32_t errcode, bool restart_instruction)
2799 {
2800 	struct vcpu *vcpu;
2801 	uint64_t regval;
2802 	int error;
2803 
2804 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2805 		return (EINVAL);
2806 
2807 	if (vector >= 32)
2808 		return (EINVAL);
2809 
2810 	/*
2811 	 * NMIs are to be injected via their own specialized path using
2812 	 * vm_inject_nmi().
2813 	 */
2814 	if (vector == IDT_NMI) {
2815 		return (EINVAL);
2816 	}
2817 
2818 	/*
2819 	 * A double fault exception should never be injected directly into
2820 	 * the guest. It is a derived exception that results from specific
2821 	 * combinations of nested faults.
2822 	 */
2823 	if (vector == IDT_DF) {
2824 		return (EINVAL);
2825 	}
2826 
2827 	vcpu = &vm->vcpu[vcpuid];
2828 
2829 	if (VM_INTINFO_PENDING(vcpu->exc_pending)) {
2830 		/* Unable to inject exception due to one already pending */
2831 		return (EBUSY);
2832 	}
2833 
2834 	if (errcode_valid) {
2835 		/*
2836 		 * Exceptions don't deliver an error code in real mode.
2837 		 */
2838 		error = vm_get_register(vm, vcpuid, VM_REG_GUEST_CR0, &regval);
2839 		VERIFY0(error);
2840 		if ((regval & CR0_PE) == 0) {
2841 			errcode_valid = false;
2842 		}
2843 	}
2844 
2845 	/*
2846 	 * From section 26.6.1 "Interruptibility State" in Intel SDM:
2847 	 *
2848 	 * Event blocking by "STI" or "MOV SS" is cleared after guest executes
2849 	 * one instruction or incurs an exception.
2850 	 */
2851 	error = vm_set_register(vm, vcpuid, VM_REG_GUEST_INTR_SHADOW, 0);
2852 	VERIFY0(error);
2853 
2854 	if (restart_instruction) {
2855 		VERIFY0(vm_restart_instruction(vm, vcpuid));
2856 	}
2857 
2858 	uint64_t val = VM_INTINFO_VALID | VM_INTINFO_HWEXCP | vector;
2859 	if (errcode_valid) {
2860 		val |= VM_INTINFO_DEL_ERRCODE;
2861 		val |= (uint64_t)errcode << VM_INTINFO_SHIFT_ERRCODE;
2862 	}
2863 	vcpu->exc_pending = val;
2864 	return (0);
2865 }
2866 
2867 void
vm_inject_ud(struct vm * vm,int vcpuid)2868 vm_inject_ud(struct vm *vm, int vcpuid)
2869 {
2870 	VERIFY0(vm_inject_exception(vm, vcpuid, IDT_UD, false, 0, true));
2871 }
2872 
2873 void
vm_inject_gp(struct vm * vm,int vcpuid)2874 vm_inject_gp(struct vm *vm, int vcpuid)
2875 {
2876 	VERIFY0(vm_inject_exception(vm, vcpuid, IDT_GP, true, 0, true));
2877 }
2878 
2879 void
vm_inject_ac(struct vm * vm,int vcpuid,uint32_t errcode)2880 vm_inject_ac(struct vm *vm, int vcpuid, uint32_t errcode)
2881 {
2882 	VERIFY0(vm_inject_exception(vm, vcpuid, IDT_AC, true, errcode, true));
2883 }
2884 
2885 void
vm_inject_ss(struct vm * vm,int vcpuid,uint32_t errcode)2886 vm_inject_ss(struct vm *vm, int vcpuid, uint32_t errcode)
2887 {
2888 	VERIFY0(vm_inject_exception(vm, vcpuid, IDT_SS, true, errcode, true));
2889 }
2890 
2891 void
vm_inject_pf(struct vm * vm,int vcpuid,uint32_t errcode,uint64_t cr2)2892 vm_inject_pf(struct vm *vm, int vcpuid, uint32_t errcode, uint64_t cr2)
2893 {
2894 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_CR2, cr2));
2895 	VERIFY0(vm_inject_exception(vm, vcpuid, IDT_PF, true, errcode, true));
2896 }
2897 
2898 static VMM_STAT(VCPU_NMI_COUNT, "number of NMIs delivered to vcpu");
2899 
2900 int
vm_inject_nmi(struct vm * vm,int vcpuid)2901 vm_inject_nmi(struct vm *vm, int vcpuid)
2902 {
2903 	struct vcpu *vcpu;
2904 
2905 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2906 		return (EINVAL);
2907 
2908 	vcpu = &vm->vcpu[vcpuid];
2909 
2910 	vcpu->nmi_pending = true;
2911 	vcpu_notify_event(vm, vcpuid);
2912 	return (0);
2913 }
2914 
2915 bool
vm_nmi_pending(struct vm * vm,int vcpuid)2916 vm_nmi_pending(struct vm *vm, int vcpuid)
2917 {
2918 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
2919 
2920 	return (vcpu->nmi_pending);
2921 }
2922 
2923 void
vm_nmi_clear(struct vm * vm,int vcpuid)2924 vm_nmi_clear(struct vm *vm, int vcpuid)
2925 {
2926 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
2927 
2928 	ASSERT(vcpu->nmi_pending);
2929 
2930 	vcpu->nmi_pending = false;
2931 	vmm_stat_incr(vm, vcpuid, VCPU_NMI_COUNT, 1);
2932 }
2933 
2934 static VMM_STAT(VCPU_EXTINT_COUNT, "number of ExtINTs delivered to vcpu");
2935 
2936 int
vm_inject_extint(struct vm * vm,int vcpuid)2937 vm_inject_extint(struct vm *vm, int vcpuid)
2938 {
2939 	struct vcpu *vcpu;
2940 
2941 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2942 		return (EINVAL);
2943 
2944 	vcpu = &vm->vcpu[vcpuid];
2945 
2946 	vcpu->extint_pending = true;
2947 	vcpu_notify_event(vm, vcpuid);
2948 	return (0);
2949 }
2950 
2951 bool
vm_extint_pending(struct vm * vm,int vcpuid)2952 vm_extint_pending(struct vm *vm, int vcpuid)
2953 {
2954 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
2955 
2956 	return (vcpu->extint_pending);
2957 }
2958 
2959 void
vm_extint_clear(struct vm * vm,int vcpuid)2960 vm_extint_clear(struct vm *vm, int vcpuid)
2961 {
2962 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
2963 
2964 	ASSERT(vcpu->extint_pending);
2965 
2966 	vcpu->extint_pending = false;
2967 	vmm_stat_incr(vm, vcpuid, VCPU_EXTINT_COUNT, 1);
2968 }
2969 
2970 int
vm_inject_init(struct vm * vm,int vcpuid)2971 vm_inject_init(struct vm *vm, int vcpuid)
2972 {
2973 	struct vcpu *vcpu;
2974 
2975 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
2976 		return (EINVAL);
2977 
2978 	vcpu = &vm->vcpu[vcpuid];
2979 	vcpu_lock(vcpu);
2980 	vcpu->run_state |= VRS_PEND_INIT;
2981 	/*
2982 	 * As part of queuing the INIT request, clear any pending SIPI.  It
2983 	 * would not otherwise survive across the reset of the vCPU when it
2984 	 * undergoes the requested INIT.  We would not want it to linger when it
2985 	 * could be mistaken as a subsequent (after the INIT) SIPI request.
2986 	 */
2987 	vcpu->run_state &= ~VRS_PEND_SIPI;
2988 	vcpu_notify_event_locked(vcpu, VCPU_NOTIFY_EXIT);
2989 
2990 	vcpu_unlock(vcpu);
2991 	return (0);
2992 }
2993 
2994 int
vm_inject_sipi(struct vm * vm,int vcpuid,uint8_t vector)2995 vm_inject_sipi(struct vm *vm, int vcpuid, uint8_t vector)
2996 {
2997 	struct vcpu *vcpu;
2998 
2999 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
3000 		return (EINVAL);
3001 
3002 	vcpu = &vm->vcpu[vcpuid];
3003 	vcpu_lock(vcpu);
3004 	vcpu->run_state |= VRS_PEND_SIPI;
3005 	vcpu->sipi_vector = vector;
3006 	/* SIPI is only actionable if the CPU is waiting in INIT state */
3007 	if ((vcpu->run_state & (VRS_INIT | VRS_RUN)) == VRS_INIT) {
3008 		vcpu_notify_event_locked(vcpu, VCPU_NOTIFY_EXIT);
3009 	}
3010 	vcpu_unlock(vcpu);
3011 	return (0);
3012 }
3013 
3014 bool
vcpu_run_state_pending(struct vm * vm,int vcpuid)3015 vcpu_run_state_pending(struct vm *vm, int vcpuid)
3016 {
3017 	struct vcpu *vcpu;
3018 
3019 	ASSERT(vcpuid >= 0 && vcpuid < vm->maxcpus);
3020 	vcpu = &vm->vcpu[vcpuid];
3021 
3022 	/* Of interest: vCPU not in running state or with pending INIT */
3023 	return ((vcpu->run_state & (VRS_RUN | VRS_PEND_INIT)) != VRS_RUN);
3024 }
3025 
3026 int
vcpu_arch_reset(struct vm * vm,int vcpuid,bool init_only)3027 vcpu_arch_reset(struct vm *vm, int vcpuid, bool init_only)
3028 {
3029 	struct seg_desc desc;
3030 	const enum vm_reg_name clear_regs[] = {
3031 		VM_REG_GUEST_CR2,
3032 		VM_REG_GUEST_CR3,
3033 		VM_REG_GUEST_CR4,
3034 		VM_REG_GUEST_RAX,
3035 		VM_REG_GUEST_RBX,
3036 		VM_REG_GUEST_RCX,
3037 		VM_REG_GUEST_RSI,
3038 		VM_REG_GUEST_RDI,
3039 		VM_REG_GUEST_RBP,
3040 		VM_REG_GUEST_RSP,
3041 		VM_REG_GUEST_R8,
3042 		VM_REG_GUEST_R9,
3043 		VM_REG_GUEST_R10,
3044 		VM_REG_GUEST_R11,
3045 		VM_REG_GUEST_R12,
3046 		VM_REG_GUEST_R13,
3047 		VM_REG_GUEST_R14,
3048 		VM_REG_GUEST_R15,
3049 		VM_REG_GUEST_DR0,
3050 		VM_REG_GUEST_DR1,
3051 		VM_REG_GUEST_DR2,
3052 		VM_REG_GUEST_DR3,
3053 		VM_REG_GUEST_EFER,
3054 	};
3055 	const enum vm_reg_name data_segs[] = {
3056 		VM_REG_GUEST_SS,
3057 		VM_REG_GUEST_DS,
3058 		VM_REG_GUEST_ES,
3059 		VM_REG_GUEST_FS,
3060 		VM_REG_GUEST_GS,
3061 	};
3062 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
3063 
3064 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
3065 		return (EINVAL);
3066 
3067 	for (uint_t i = 0; i < nitems(clear_regs); i++) {
3068 		VERIFY0(vm_set_register(vm, vcpuid, clear_regs[i], 0));
3069 	}
3070 
3071 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_RFLAGS, 2));
3072 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_RIP, 0xfff0));
3073 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_CR0, 0x60000010));
3074 
3075 	/*
3076 	 * The prescribed contents of %rdx differ slightly between the Intel and
3077 	 * AMD architectural definitions.  The former expects the Extended Model
3078 	 * in bits 16-19 where the latter expects all the Family, Model, and
3079 	 * Stepping be there.  Common boot ROMs appear to disregard this
3080 	 * anyways, so we stick with a compromise value similar to what is
3081 	 * spelled out in the Intel SDM.
3082 	 */
3083 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_RDX, 0x600));
3084 
3085 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_DR6, 0xffff0ff0));
3086 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_DR7, 0x400));
3087 
3088 	/* CS: Present, R/W, Accessed */
3089 	desc.access = 0x0093;
3090 	desc.base = 0xffff0000;
3091 	desc.limit = 0xffff;
3092 	VERIFY0(vm_set_seg_desc(vm, vcpuid, VM_REG_GUEST_CS, &desc));
3093 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_CS, 0xf000));
3094 
3095 	/* SS, DS, ES, FS, GS: Present, R/W, Accessed */
3096 	desc.access = 0x0093;
3097 	desc.base = 0;
3098 	desc.limit = 0xffff;
3099 	for (uint_t i = 0; i < nitems(data_segs); i++) {
3100 		VERIFY0(vm_set_seg_desc(vm, vcpuid, data_segs[i], &desc));
3101 		VERIFY0(vm_set_register(vm, vcpuid, data_segs[i], 0));
3102 	}
3103 
3104 	/* GDTR, IDTR */
3105 	desc.base = 0;
3106 	desc.limit = 0xffff;
3107 	VERIFY0(vm_set_seg_desc(vm, vcpuid, VM_REG_GUEST_GDTR, &desc));
3108 	VERIFY0(vm_set_seg_desc(vm, vcpuid, VM_REG_GUEST_IDTR, &desc));
3109 
3110 	/* LDTR: Present, LDT */
3111 	desc.access = 0x0082;
3112 	desc.base = 0;
3113 	desc.limit = 0xffff;
3114 	VERIFY0(vm_set_seg_desc(vm, vcpuid, VM_REG_GUEST_LDTR, &desc));
3115 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_LDTR, 0));
3116 
3117 	/* TR: Present, 32-bit TSS */
3118 	desc.access = 0x008b;
3119 	desc.base = 0;
3120 	desc.limit = 0xffff;
3121 	VERIFY0(vm_set_seg_desc(vm, vcpuid, VM_REG_GUEST_TR, &desc));
3122 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_TR, 0));
3123 
3124 	vlapic_reset(vm_lapic(vm, vcpuid));
3125 
3126 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_INTR_SHADOW, 0));
3127 
3128 	vcpu->exit_intinfo = 0;
3129 	vcpu->exc_pending = 0;
3130 	vcpu->nmi_pending = false;
3131 	vcpu->extint_pending = 0;
3132 
3133 	/*
3134 	 * A CPU reset caused by power-on or system reset clears more state than
3135 	 * one which is trigged from an INIT IPI.
3136 	 */
3137 	if (!init_only) {
3138 		vcpu->guest_xcr0 = XFEATURE_ENABLED_X87;
3139 		(void) hma_fpu_init(vcpu->guestfpu);
3140 
3141 		/* XXX: clear MSRs and other pieces */
3142 		bzero(&vcpu->mtrr, sizeof (vcpu->mtrr));
3143 	}
3144 
3145 	return (0);
3146 }
3147 
3148 static int
vcpu_vector_sipi(struct vm * vm,int vcpuid,uint8_t vector)3149 vcpu_vector_sipi(struct vm *vm, int vcpuid, uint8_t vector)
3150 {
3151 	struct seg_desc desc;
3152 
3153 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
3154 		return (EINVAL);
3155 
3156 	/* CS: Present, R/W, Accessed */
3157 	desc.access = 0x0093;
3158 	desc.base = (uint64_t)vector << 12;
3159 	desc.limit = 0xffff;
3160 	VERIFY0(vm_set_seg_desc(vm, vcpuid, VM_REG_GUEST_CS, &desc));
3161 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_CS,
3162 	    (uint64_t)vector << 8));
3163 
3164 	VERIFY0(vm_set_register(vm, vcpuid, VM_REG_GUEST_RIP, 0));
3165 
3166 	return (0);
3167 }
3168 
3169 int
vm_get_capability(struct vm * vm,int vcpu,int type,int * retval)3170 vm_get_capability(struct vm *vm, int vcpu, int type, int *retval)
3171 {
3172 	if (vcpu < 0 || vcpu >= vm->maxcpus)
3173 		return (EINVAL);
3174 
3175 	if (type < 0 || type >= VM_CAP_MAX)
3176 		return (EINVAL);
3177 
3178 	return (VMGETCAP(vm->cookie, vcpu, type, retval));
3179 }
3180 
3181 int
vm_set_capability(struct vm * vm,int vcpu,int type,int val)3182 vm_set_capability(struct vm *vm, int vcpu, int type, int val)
3183 {
3184 	if (vcpu < 0 || vcpu >= vm->maxcpus)
3185 		return (EINVAL);
3186 
3187 	if (type < 0 || type >= VM_CAP_MAX)
3188 		return (EINVAL);
3189 
3190 	return (VMSETCAP(vm->cookie, vcpu, type, val));
3191 }
3192 
3193 vcpu_cpuid_config_t *
vm_cpuid_config(struct vm * vm,int vcpuid)3194 vm_cpuid_config(struct vm *vm, int vcpuid)
3195 {
3196 	ASSERT3S(vcpuid, >=, 0);
3197 	ASSERT3S(vcpuid, <, VM_MAXCPU);
3198 
3199 	return (&vm->vcpu[vcpuid].cpuid_cfg);
3200 }
3201 
3202 struct vlapic *
vm_lapic(struct vm * vm,int cpu)3203 vm_lapic(struct vm *vm, int cpu)
3204 {
3205 	ASSERT3S(cpu, >=, 0);
3206 	ASSERT3S(cpu, <, VM_MAXCPU);
3207 
3208 	return (vm->vcpu[cpu].vlapic);
3209 }
3210 
3211 struct vioapic *
vm_ioapic(struct vm * vm)3212 vm_ioapic(struct vm *vm)
3213 {
3214 
3215 	return (vm->vioapic);
3216 }
3217 
3218 struct vhpet *
vm_hpet(struct vm * vm)3219 vm_hpet(struct vm *vm)
3220 {
3221 
3222 	return (vm->vhpet);
3223 }
3224 
3225 void *
vm_iommu_domain(struct vm * vm)3226 vm_iommu_domain(struct vm *vm)
3227 {
3228 
3229 	return (vm->iommu);
3230 }
3231 
3232 int
vcpu_set_state(struct vm * vm,int vcpuid,enum vcpu_state newstate,bool from_idle)3233 vcpu_set_state(struct vm *vm, int vcpuid, enum vcpu_state newstate,
3234     bool from_idle)
3235 {
3236 	int error;
3237 	struct vcpu *vcpu;
3238 
3239 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
3240 		panic("vcpu_set_state: invalid vcpuid %d", vcpuid);
3241 
3242 	vcpu = &vm->vcpu[vcpuid];
3243 
3244 	vcpu_lock(vcpu);
3245 	error = vcpu_set_state_locked(vm, vcpuid, newstate, from_idle);
3246 	vcpu_unlock(vcpu);
3247 
3248 	return (error);
3249 }
3250 
3251 enum vcpu_state
vcpu_get_state(struct vm * vm,int vcpuid,int * hostcpu)3252 vcpu_get_state(struct vm *vm, int vcpuid, int *hostcpu)
3253 {
3254 	struct vcpu *vcpu;
3255 	enum vcpu_state state;
3256 
3257 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
3258 		panic("vcpu_get_state: invalid vcpuid %d", vcpuid);
3259 
3260 	vcpu = &vm->vcpu[vcpuid];
3261 
3262 	vcpu_lock(vcpu);
3263 	state = vcpu->state;
3264 	if (hostcpu != NULL)
3265 		*hostcpu = vcpu->hostcpu;
3266 	vcpu_unlock(vcpu);
3267 
3268 	return (state);
3269 }
3270 
3271 /*
3272  * Calculate the TSC offset for a vCPU, applying physical CPU adjustments if
3273  * requested. The offset calculations include the VM-wide TSC offset.
3274  */
3275 uint64_t
vcpu_tsc_offset(struct vm * vm,int vcpuid,bool phys_adj)3276 vcpu_tsc_offset(struct vm *vm, int vcpuid, bool phys_adj)
3277 {
3278 	ASSERT(vcpuid >= 0 && vcpuid < vm->maxcpus);
3279 
3280 	uint64_t vcpu_off = vm->tsc_offset + vm->vcpu[vcpuid].tsc_offset;
3281 
3282 	if (phys_adj) {
3283 		/* Include any offset for the current physical CPU too */
3284 		vcpu_off += vmm_host_tsc_delta();
3285 	}
3286 
3287 	return (vcpu_off);
3288 }
3289 
3290 uint64_t
vm_get_freq_multiplier(struct vm * vm)3291 vm_get_freq_multiplier(struct vm *vm)
3292 {
3293 	return (vm->freq_multiplier);
3294 }
3295 
3296 /* Normalize hrtime against the boot time for a VM */
3297 hrtime_t
vm_normalize_hrtime(struct vm * vm,hrtime_t hrt)3298 vm_normalize_hrtime(struct vm *vm, hrtime_t hrt)
3299 {
3300 	/* To avoid underflow/overflow UB, perform math as unsigned */
3301 	return ((hrtime_t)((uint64_t)hrt - (uint64_t)vm->boot_hrtime));
3302 }
3303 
3304 /* Denormalize hrtime against the boot time for a VM */
3305 hrtime_t
vm_denormalize_hrtime(struct vm * vm,hrtime_t hrt)3306 vm_denormalize_hrtime(struct vm *vm, hrtime_t hrt)
3307 {
3308 	/* To avoid underflow/overflow UB, perform math as unsigned */
3309 	return ((hrtime_t)((uint64_t)hrt + (uint64_t)vm->boot_hrtime));
3310 }
3311 
3312 int
vm_activate_cpu(struct vm * vm,int vcpuid)3313 vm_activate_cpu(struct vm *vm, int vcpuid)
3314 {
3315 
3316 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
3317 		return (EINVAL);
3318 
3319 	if (CPU_ISSET(vcpuid, &vm->active_cpus))
3320 		return (EBUSY);
3321 
3322 	if (vm_is_suspended(vm, NULL)) {
3323 		return (EBUSY);
3324 	}
3325 
3326 	CPU_SET_ATOMIC(vcpuid, &vm->active_cpus);
3327 
3328 	/*
3329 	 * It is possible that this vCPU was undergoing activation at the same
3330 	 * time that the VM was being suspended.
3331 	 */
3332 	if (vm_is_suspended(vm, NULL)) {
3333 		return (EBUSY);
3334 	}
3335 
3336 	return (0);
3337 }
3338 
3339 int
vm_suspend_cpu(struct vm * vm,int vcpuid)3340 vm_suspend_cpu(struct vm *vm, int vcpuid)
3341 {
3342 	int i;
3343 
3344 	if (vcpuid < -1 || vcpuid >= vm->maxcpus)
3345 		return (EINVAL);
3346 
3347 	if (vcpuid == -1) {
3348 		vm->debug_cpus = vm->active_cpus;
3349 		for (i = 0; i < vm->maxcpus; i++) {
3350 			if (CPU_ISSET(i, &vm->active_cpus))
3351 				vcpu_notify_event(vm, i);
3352 		}
3353 	} else {
3354 		if (!CPU_ISSET(vcpuid, &vm->active_cpus))
3355 			return (EINVAL);
3356 
3357 		CPU_SET_ATOMIC(vcpuid, &vm->debug_cpus);
3358 		vcpu_notify_event(vm, vcpuid);
3359 	}
3360 	return (0);
3361 }
3362 
3363 int
vm_resume_cpu(struct vm * vm,int vcpuid)3364 vm_resume_cpu(struct vm *vm, int vcpuid)
3365 {
3366 
3367 	if (vcpuid < -1 || vcpuid >= vm->maxcpus)
3368 		return (EINVAL);
3369 
3370 	if (vcpuid == -1) {
3371 		CPU_ZERO(&vm->debug_cpus);
3372 	} else {
3373 		if (!CPU_ISSET(vcpuid, &vm->debug_cpus))
3374 			return (EINVAL);
3375 
3376 		CPU_CLR_ATOMIC(vcpuid, &vm->debug_cpus);
3377 	}
3378 	return (0);
3379 }
3380 
3381 static bool
vcpu_bailout_checks(struct vm * vm,int vcpuid)3382 vcpu_bailout_checks(struct vm *vm, int vcpuid)
3383 {
3384 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
3385 	struct vm_exit *vme = &vcpu->exitinfo;
3386 
3387 	ASSERT(vcpuid >= 0 && vcpuid < vm->maxcpus);
3388 
3389 	/*
3390 	 * Check if VM is suspended, only passing the 'vm_exit *' to be
3391 	 * populated if this check is being performed as part of entry.
3392 	 */
3393 	if (vm_is_suspended(vm, vme)) {
3394 		/* Confirm exit details are as expected */
3395 		VERIFY3S(vme->exitcode, ==, VM_EXITCODE_SUSPENDED);
3396 		VERIFY(vme->u.suspended.how > VM_SUSPEND_NONE &&
3397 		    vme->u.suspended.how < VM_SUSPEND_LAST);
3398 
3399 		return (true);
3400 	}
3401 	if (vcpu->reqidle) {
3402 		/*
3403 		 * Another thread is trying to lock this vCPU and is waiting for
3404 		 * it to enter the VCPU_IDLE state.  Take a lap with a BOGUS
3405 		 * exit to allow other thread(s) access to this vCPU.
3406 		 */
3407 		vme->exitcode = VM_EXITCODE_BOGUS;
3408 		vmm_stat_incr(vm, vcpuid, VMEXIT_REQIDLE, 1);
3409 		return (true);
3410 	}
3411 	if (vcpu->reqbarrier) {
3412 		/*
3413 		 * Similar to 'reqidle', userspace has requested that this vCPU
3414 		 * be pushed to a barrier by exiting to userspace.  Take that
3415 		 * lap with BOGUS and clear the flag.
3416 		 */
3417 		vme->exitcode = VM_EXITCODE_BOGUS;
3418 		vcpu->reqbarrier = false;
3419 		return (true);
3420 	}
3421 	if (vcpu->reqconsist) {
3422 		/*
3423 		 * We only expect exit-when-consistent requests to be asserted
3424 		 * during entry, not as an otherwise spontaneous condition.  As
3425 		 * such, we do not count it among the exit statistics, and emit
3426 		 * the expected BOGUS exitcode, while clearing the request.
3427 		 */
3428 		vme->exitcode = VM_EXITCODE_BOGUS;
3429 		vcpu->reqconsist = false;
3430 		return (true);
3431 	}
3432 	if (vcpu_should_yield(vm, vcpuid)) {
3433 		vme->exitcode = VM_EXITCODE_BOGUS;
3434 		vmm_stat_incr(vm, vcpuid, VMEXIT_ASTPENDING, 1);
3435 		return (true);
3436 	}
3437 	if (CPU_ISSET(vcpuid, &vm->debug_cpus)) {
3438 		vme->exitcode = VM_EXITCODE_DEBUG;
3439 		return (true);
3440 	}
3441 
3442 	return (false);
3443 }
3444 
3445 static bool
vcpu_sleep_bailout_checks(struct vm * vm,int vcpuid)3446 vcpu_sleep_bailout_checks(struct vm *vm, int vcpuid)
3447 {
3448 	if (vcpu_bailout_checks(vm, vcpuid)) {
3449 		struct vcpu *vcpu = &vm->vcpu[vcpuid];
3450 		struct vm_exit *vme = &vcpu->exitinfo;
3451 
3452 		/*
3453 		 * Bail-out check done prior to sleeping (in vCPU contexts like
3454 		 * HLT or wait-for-SIPI) expect that %rip is already populated
3455 		 * in the vm_exit structure, and we would only modify the
3456 		 * exitcode and clear the inst_length.
3457 		 */
3458 		vme->inst_length = 0;
3459 		return (true);
3460 	}
3461 	return (false);
3462 }
3463 
3464 bool
vcpu_entry_bailout_checks(struct vm * vm,int vcpuid,uint64_t rip)3465 vcpu_entry_bailout_checks(struct vm *vm, int vcpuid, uint64_t rip)
3466 {
3467 	if (vcpu_bailout_checks(vm, vcpuid)) {
3468 		struct vcpu *vcpu = &vm->vcpu[vcpuid];
3469 		struct vm_exit *vme = &vcpu->exitinfo;
3470 
3471 		/*
3472 		 * Bail-out checks done as part of VM entry require an updated
3473 		 * %rip to populate the vm_exit struct if any of the conditions
3474 		 * of interest are matched in the check.
3475 		 */
3476 		vme->rip = rip;
3477 		vme->inst_length = 0;
3478 		return (true);
3479 	}
3480 	return (false);
3481 }
3482 
3483 int
vm_vcpu_barrier(struct vm * vm,int vcpuid)3484 vm_vcpu_barrier(struct vm *vm, int vcpuid)
3485 {
3486 	if (vcpuid >= 0 && vcpuid < vm->maxcpus) {
3487 		struct vcpu *vcpu = &vm->vcpu[vcpuid];
3488 
3489 		/* Push specified vCPU to barrier */
3490 		vcpu_lock(vcpu);
3491 		if (CPU_ISSET(vcpuid, &vm->active_cpus)) {
3492 			vcpu->reqbarrier = true;
3493 			vcpu_notify_event_locked(vcpu, VCPU_NOTIFY_EXIT);
3494 		}
3495 		vcpu_unlock(vcpu);
3496 
3497 		return (0);
3498 	} else if (vcpuid == -1) {
3499 		/* Push all (active) vCPUs to barrier */
3500 		for (int i = 0; i < vm->maxcpus; i++) {
3501 			struct vcpu *vcpu = &vm->vcpu[i];
3502 
3503 			vcpu_lock(vcpu);
3504 			if (CPU_ISSET(vcpuid, &vm->active_cpus)) {
3505 				vcpu->reqbarrier = true;
3506 				vcpu_notify_event_locked(vcpu,
3507 				    VCPU_NOTIFY_EXIT);
3508 			}
3509 			vcpu_unlock(vcpu);
3510 		}
3511 
3512 		return (0);
3513 	} else {
3514 		return (EINVAL);
3515 	}
3516 }
3517 
3518 cpuset_t
vm_active_cpus(struct vm * vm)3519 vm_active_cpus(struct vm *vm)
3520 {
3521 	return (vm->active_cpus);
3522 }
3523 
3524 cpuset_t
vm_debug_cpus(struct vm * vm)3525 vm_debug_cpus(struct vm *vm)
3526 {
3527 	return (vm->debug_cpus);
3528 }
3529 
3530 void *
vcpu_stats(struct vm * vm,int vcpuid)3531 vcpu_stats(struct vm *vm, int vcpuid)
3532 {
3533 
3534 	return (vm->vcpu[vcpuid].stats);
3535 }
3536 
3537 int
vm_get_x2apic_state(struct vm * vm,int vcpuid,enum x2apic_state * state)3538 vm_get_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state *state)
3539 {
3540 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
3541 		return (EINVAL);
3542 
3543 	*state = vm->vcpu[vcpuid].x2apic_state;
3544 
3545 	return (0);
3546 }
3547 
3548 int
vm_set_x2apic_state(struct vm * vm,int vcpuid,enum x2apic_state state)3549 vm_set_x2apic_state(struct vm *vm, int vcpuid, enum x2apic_state state)
3550 {
3551 	if (vcpuid < 0 || vcpuid >= vm->maxcpus)
3552 		return (EINVAL);
3553 
3554 	if (state >= X2APIC_STATE_LAST)
3555 		return (EINVAL);
3556 
3557 	vm->vcpu[vcpuid].x2apic_state = state;
3558 
3559 	vlapic_set_x2apic_state(vm, vcpuid, state);
3560 
3561 	return (0);
3562 }
3563 
3564 /*
3565  * This function is called to ensure that a vcpu "sees" a pending event
3566  * as soon as possible:
3567  * - If the vcpu thread is sleeping then it is woken up.
3568  * - If the vcpu is running on a different host_cpu then an IPI will be directed
3569  *   to the host_cpu to cause the vcpu to trap into the hypervisor.
3570  */
3571 static void
vcpu_notify_event_locked(struct vcpu * vcpu,vcpu_notify_t ntype)3572 vcpu_notify_event_locked(struct vcpu *vcpu, vcpu_notify_t ntype)
3573 {
3574 	int hostcpu;
3575 
3576 	ASSERT(ntype == VCPU_NOTIFY_APIC || VCPU_NOTIFY_EXIT);
3577 
3578 	hostcpu = vcpu->hostcpu;
3579 	if (vcpu->state == VCPU_RUNNING) {
3580 		KASSERT(hostcpu != NOCPU, ("vcpu running on invalid hostcpu"));
3581 		if (hostcpu != curcpu) {
3582 			if (ntype == VCPU_NOTIFY_APIC) {
3583 				vlapic_post_intr(vcpu->vlapic, hostcpu);
3584 			} else {
3585 				poke_cpu(hostcpu);
3586 			}
3587 		} else {
3588 			/*
3589 			 * If the 'vcpu' is running on 'curcpu' then it must
3590 			 * be sending a notification to itself (e.g. SELF_IPI).
3591 			 * The pending event will be picked up when the vcpu
3592 			 * transitions back to guest context.
3593 			 */
3594 		}
3595 	} else {
3596 		KASSERT(hostcpu == NOCPU, ("vcpu state %d not consistent "
3597 		    "with hostcpu %d", vcpu->state, hostcpu));
3598 		if (vcpu->state == VCPU_SLEEPING) {
3599 			cv_signal(&vcpu->vcpu_cv);
3600 		}
3601 	}
3602 }
3603 
3604 void
vcpu_notify_event(struct vm * vm,int vcpuid)3605 vcpu_notify_event(struct vm *vm, int vcpuid)
3606 {
3607 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
3608 
3609 	vcpu_lock(vcpu);
3610 	vcpu_notify_event_locked(vcpu, VCPU_NOTIFY_EXIT);
3611 	vcpu_unlock(vcpu);
3612 }
3613 
3614 void
vcpu_notify_event_type(struct vm * vm,int vcpuid,vcpu_notify_t ntype)3615 vcpu_notify_event_type(struct vm *vm, int vcpuid, vcpu_notify_t ntype)
3616 {
3617 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
3618 
3619 	if (ntype == VCPU_NOTIFY_NONE) {
3620 		return;
3621 	}
3622 
3623 	vcpu_lock(vcpu);
3624 	vcpu_notify_event_locked(vcpu, ntype);
3625 	vcpu_unlock(vcpu);
3626 }
3627 
3628 void
vcpu_ustate_change(struct vm * vm,int vcpuid,enum vcpu_ustate ustate)3629 vcpu_ustate_change(struct vm *vm, int vcpuid, enum vcpu_ustate ustate)
3630 {
3631 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
3632 	const hrtime_t now = gethrtime();
3633 
3634 	ASSERT3S(ustate, <, VU_MAX);
3635 	ASSERT3S(ustate, >=, VU_INIT);
3636 
3637 	if (ustate == vcpu->ustate) {
3638 		return;
3639 	}
3640 
3641 	const hrtime_t delta = now - vcpu->ustate_when;
3642 	vcpu->ustate_total[vcpu->ustate] += delta;
3643 
3644 	membar_producer();
3645 
3646 	vcpu->ustate_when = now;
3647 	vcpu->ustate = ustate;
3648 }
3649 
3650 void *
vm_get_cookie(struct vm * vm)3651 vm_get_cookie(struct vm *vm)
3652 {
3653 	return (vm->cookie);
3654 }
3655 
3656 struct vmspace *
vm_get_vmspace(struct vm * vm)3657 vm_get_vmspace(struct vm *vm)
3658 {
3659 
3660 	return (vm->vmspace);
3661 }
3662 
3663 struct vm_client *
vm_get_vmclient(struct vm * vm,int vcpuid)3664 vm_get_vmclient(struct vm *vm, int vcpuid)
3665 {
3666 	return (vm->vcpu[vcpuid].vmclient);
3667 }
3668 
3669 int
vm_apicid2vcpuid(struct vm * vm,int apicid)3670 vm_apicid2vcpuid(struct vm *vm, int apicid)
3671 {
3672 	/*
3673 	 * XXX apic id is assumed to be numerically identical to vcpu id
3674 	 */
3675 	return (apicid);
3676 }
3677 
3678 struct vatpic *
vm_atpic(struct vm * vm)3679 vm_atpic(struct vm *vm)
3680 {
3681 	return (vm->vatpic);
3682 }
3683 
3684 struct vatpit *
vm_atpit(struct vm * vm)3685 vm_atpit(struct vm *vm)
3686 {
3687 	return (vm->vatpit);
3688 }
3689 
3690 struct vpmtmr *
vm_pmtmr(struct vm * vm)3691 vm_pmtmr(struct vm *vm)
3692 {
3693 
3694 	return (vm->vpmtmr);
3695 }
3696 
3697 struct vrtc *
vm_rtc(struct vm * vm)3698 vm_rtc(struct vm *vm)
3699 {
3700 
3701 	return (vm->vrtc);
3702 }
3703 
3704 enum vm_reg_name
vm_segment_name(int seg)3705 vm_segment_name(int seg)
3706 {
3707 	static enum vm_reg_name seg_names[] = {
3708 		VM_REG_GUEST_ES,
3709 		VM_REG_GUEST_CS,
3710 		VM_REG_GUEST_SS,
3711 		VM_REG_GUEST_DS,
3712 		VM_REG_GUEST_FS,
3713 		VM_REG_GUEST_GS
3714 	};
3715 
3716 	KASSERT(seg >= 0 && seg < nitems(seg_names),
3717 	    ("%s: invalid segment encoding %d", __func__, seg));
3718 	return (seg_names[seg]);
3719 }
3720 
3721 void
vm_copy_teardown(struct vm * vm,int vcpuid,struct vm_copyinfo * copyinfo,uint_t num_copyinfo)3722 vm_copy_teardown(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo,
3723     uint_t num_copyinfo)
3724 {
3725 	for (uint_t idx = 0; idx < num_copyinfo; idx++) {
3726 		if (copyinfo[idx].cookie != NULL) {
3727 			(void) vmp_release((vm_page_t *)copyinfo[idx].cookie);
3728 		}
3729 	}
3730 	bzero(copyinfo, num_copyinfo * sizeof (struct vm_copyinfo));
3731 }
3732 
3733 int
vm_copy_setup(struct vm * vm,int vcpuid,struct vm_guest_paging * paging,uint64_t gla,size_t len,int prot,struct vm_copyinfo * copyinfo,uint_t num_copyinfo,int * fault)3734 vm_copy_setup(struct vm *vm, int vcpuid, struct vm_guest_paging *paging,
3735     uint64_t gla, size_t len, int prot, struct vm_copyinfo *copyinfo,
3736     uint_t num_copyinfo, int *fault)
3737 {
3738 	uint_t idx, nused;
3739 	size_t n, off, remaining;
3740 	vm_client_t *vmc = vm_get_vmclient(vm, vcpuid);
3741 
3742 	bzero(copyinfo, sizeof (struct vm_copyinfo) * num_copyinfo);
3743 
3744 	nused = 0;
3745 	remaining = len;
3746 	while (remaining > 0) {
3747 		uint64_t gpa;
3748 		int error;
3749 
3750 		if (nused >= num_copyinfo)
3751 			return (EFAULT);
3752 		error = vm_gla2gpa(vm, vcpuid, paging, gla, prot, &gpa, fault);
3753 		if (error || *fault)
3754 			return (error);
3755 		off = gpa & PAGEOFFSET;
3756 		n = min(remaining, PAGESIZE - off);
3757 		copyinfo[nused].gpa = gpa;
3758 		copyinfo[nused].len = n;
3759 		remaining -= n;
3760 		gla += n;
3761 		nused++;
3762 	}
3763 
3764 	for (idx = 0; idx < nused; idx++) {
3765 		vm_page_t *vmp;
3766 		caddr_t hva;
3767 
3768 		vmp = vmc_hold(vmc, copyinfo[idx].gpa & PAGEMASK, prot);
3769 		if (vmp == NULL) {
3770 			break;
3771 		}
3772 		if ((prot & PROT_WRITE) != 0) {
3773 			hva = (caddr_t)vmp_get_writable(vmp);
3774 		} else {
3775 			hva = (caddr_t)vmp_get_readable(vmp);
3776 		}
3777 		copyinfo[idx].hva = hva + (copyinfo[idx].gpa & PAGEOFFSET);
3778 		copyinfo[idx].cookie = vmp;
3779 		copyinfo[idx].prot = prot;
3780 	}
3781 
3782 	if (idx != nused) {
3783 		vm_copy_teardown(vm, vcpuid, copyinfo, num_copyinfo);
3784 		return (EFAULT);
3785 	} else {
3786 		*fault = 0;
3787 		return (0);
3788 	}
3789 }
3790 
3791 void
vm_copyin(struct vm * vm,int vcpuid,struct vm_copyinfo * copyinfo,void * kaddr,size_t len)3792 vm_copyin(struct vm *vm, int vcpuid, struct vm_copyinfo *copyinfo, void *kaddr,
3793     size_t len)
3794 {
3795 	char *dst;
3796 	int idx;
3797 
3798 	dst = kaddr;
3799 	idx = 0;
3800 	while (len > 0) {
3801 		ASSERT(copyinfo[idx].prot & PROT_READ);
3802 
3803 		bcopy(copyinfo[idx].hva, dst, copyinfo[idx].len);
3804 		len -= copyinfo[idx].len;
3805 		dst += copyinfo[idx].len;
3806 		idx++;
3807 	}
3808 }
3809 
3810 void
vm_copyout(struct vm * vm,int vcpuid,const void * kaddr,struct vm_copyinfo * copyinfo,size_t len)3811 vm_copyout(struct vm *vm, int vcpuid, const void *kaddr,
3812     struct vm_copyinfo *copyinfo, size_t len)
3813 {
3814 	const char *src;
3815 	int idx;
3816 
3817 	src = kaddr;
3818 	idx = 0;
3819 	while (len > 0) {
3820 		ASSERT(copyinfo[idx].prot & PROT_WRITE);
3821 
3822 		bcopy(src, copyinfo[idx].hva, copyinfo[idx].len);
3823 		len -= copyinfo[idx].len;
3824 		src += copyinfo[idx].len;
3825 		idx++;
3826 	}
3827 }
3828 
3829 /*
3830  * Return the amount of in-use and wired memory for the VM. Since
3831  * these are global stats, only return the values with for vCPU 0
3832  */
3833 VMM_STAT_DECLARE(VMM_MEM_RESIDENT);
3834 
3835 static void
vm_get_rescnt(struct vm * vm,int vcpu,struct vmm_stat_type * stat)3836 vm_get_rescnt(struct vm *vm, int vcpu, struct vmm_stat_type *stat)
3837 {
3838 	if (vcpu == 0) {
3839 		vmm_stat_set(vm, vcpu, VMM_MEM_RESIDENT,
3840 		    PAGE_SIZE * vmspace_resident_count(vm->vmspace));
3841 	}
3842 }
3843 
3844 VMM_STAT_FUNC(VMM_MEM_RESIDENT, "Resident memory", vm_get_rescnt);
3845 
3846 int
vm_ioport_access(struct vm * vm,int vcpuid,bool in,uint16_t port,uint8_t bytes,uint32_t * val)3847 vm_ioport_access(struct vm *vm, int vcpuid, bool in, uint16_t port,
3848     uint8_t bytes, uint32_t *val)
3849 {
3850 	return (vm_inout_access(&vm->ioports, in, port, bytes, val));
3851 }
3852 
3853 /*
3854  * bhyve-internal interfaces to attach or detach IO port handlers.
3855  * Must be called with VM write lock held for safety.
3856  */
3857 int
vm_ioport_attach(struct vm * vm,uint16_t port,ioport_handler_t func,void * arg,void ** cookie)3858 vm_ioport_attach(struct vm *vm, uint16_t port, ioport_handler_t func, void *arg,
3859     void **cookie)
3860 {
3861 	int err;
3862 	err = vm_inout_attach(&vm->ioports, port, IOPF_DEFAULT, func, arg);
3863 	if (err == 0) {
3864 		*cookie = (void *)IOP_GEN_COOKIE(func, arg, port);
3865 	}
3866 	return (err);
3867 }
3868 int
vm_ioport_detach(struct vm * vm,void ** cookie,ioport_handler_t * old_func,void ** old_arg)3869 vm_ioport_detach(struct vm *vm, void **cookie, ioport_handler_t *old_func,
3870     void **old_arg)
3871 {
3872 	uint16_t port = IOP_PORT_FROM_COOKIE((uintptr_t)*cookie);
3873 	int err;
3874 
3875 	err = vm_inout_detach(&vm->ioports, port, false, old_func, old_arg);
3876 	if (err == 0) {
3877 		*cookie = NULL;
3878 	}
3879 	return (err);
3880 }
3881 
3882 /*
3883  * External driver interfaces to attach or detach IO port handlers.
3884  * Must be called with VM write lock held for safety.
3885  */
3886 int
vm_ioport_hook(struct vm * vm,uint16_t port,ioport_handler_t func,void * arg,void ** cookie)3887 vm_ioport_hook(struct vm *vm, uint16_t port, ioport_handler_t func,
3888     void *arg, void **cookie)
3889 {
3890 	int err;
3891 
3892 	if (port == 0) {
3893 		return (EINVAL);
3894 	}
3895 
3896 	err = vm_inout_attach(&vm->ioports, port, IOPF_DRV_HOOK, func, arg);
3897 	if (err == 0) {
3898 		*cookie = (void *)IOP_GEN_COOKIE(func, arg, port);
3899 	}
3900 	return (err);
3901 }
3902 void
vm_ioport_unhook(struct vm * vm,void ** cookie)3903 vm_ioport_unhook(struct vm *vm, void **cookie)
3904 {
3905 	uint16_t port = IOP_PORT_FROM_COOKIE((uintptr_t)*cookie);
3906 	ioport_handler_t old_func;
3907 	void *old_arg;
3908 	int err;
3909 
3910 	err = vm_inout_detach(&vm->ioports, port, true, &old_func, &old_arg);
3911 
3912 	/* ioport-hook-using drivers are expected to be well-behaved */
3913 	VERIFY0(err);
3914 	VERIFY(IOP_GEN_COOKIE(old_func, old_arg, port) == (uintptr_t)*cookie);
3915 
3916 	*cookie = NULL;
3917 }
3918 
3919 int
vmm_kstat_update_vcpu(struct kstat * ksp,int rw)3920 vmm_kstat_update_vcpu(struct kstat *ksp, int rw)
3921 {
3922 	struct vm *vm = ksp->ks_private;
3923 	vmm_vcpu_kstats_t *vvk = ksp->ks_data;
3924 	const int vcpuid = vvk->vvk_vcpu.value.ui32;
3925 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
3926 
3927 	ASSERT3U(vcpuid, <, VM_MAXCPU);
3928 
3929 	vvk->vvk_time_init.value.ui64 = vcpu->ustate_total[VU_INIT];
3930 	vvk->vvk_time_run.value.ui64 = vcpu->ustate_total[VU_RUN];
3931 	vvk->vvk_time_idle.value.ui64 = vcpu->ustate_total[VU_IDLE];
3932 	vvk->vvk_time_emu_kern.value.ui64 = vcpu->ustate_total[VU_EMU_KERN];
3933 	vvk->vvk_time_emu_user.value.ui64 = vcpu->ustate_total[VU_EMU_USER];
3934 	vvk->vvk_time_sched.value.ui64 = vcpu->ustate_total[VU_SCHED];
3935 
3936 	return (0);
3937 }
3938 
3939 SET_DECLARE(vmm_data_version_entries, const vmm_data_version_entry_t);
3940 
3941 static int
vmm_data_find(const vmm_data_req_t * req,const vmm_data_version_entry_t ** resp)3942 vmm_data_find(const vmm_data_req_t *req, const vmm_data_version_entry_t **resp)
3943 {
3944 	const vmm_data_version_entry_t **vdpp, *vdp;
3945 
3946 	ASSERT(resp != NULL);
3947 	ASSERT(req->vdr_result_len != NULL);
3948 
3949 	SET_FOREACH(vdpp, vmm_data_version_entries) {
3950 		vdp = *vdpp;
3951 		if (vdp->vdve_class != req->vdr_class ||
3952 		    vdp->vdve_version != req->vdr_version) {
3953 			continue;
3954 		}
3955 
3956 		/*
3957 		 * Enforce any data length expectation expressed by the provider
3958 		 * for this data.
3959 		 */
3960 		if (vdp->vdve_len_expect != 0 &&
3961 		    vdp->vdve_len_expect > req->vdr_len) {
3962 			*req->vdr_result_len = vdp->vdve_len_expect;
3963 			return (ENOSPC);
3964 		}
3965 
3966 		/*
3967 		 * Make sure that the provided vcpuid is acceptable for the
3968 		 * backend handler.
3969 		 */
3970 		if (vdp->vdve_readf != NULL || vdp->vdve_writef != NULL) {
3971 			/*
3972 			 * While it is tempting to demand the -1 sentinel value
3973 			 * in vcpuid here, that expectation was not established
3974 			 * for early consumers, so it is ignored.
3975 			 */
3976 		} else if (vdp->vdve_vcpu_readf != NULL ||
3977 		    vdp->vdve_vcpu_writef != NULL) {
3978 			/*
3979 			 * Per-vCPU handlers which permit "wildcard" access will
3980 			 * accept a vcpuid of -1 (for VM-wide data), while all
3981 			 * others expect vcpuid [0, VM_MAXCPU).
3982 			 */
3983 			const int llimit = vdp->vdve_vcpu_wildcard ? -1 : 0;
3984 			if (req->vdr_vcpuid < llimit ||
3985 			    req->vdr_vcpuid >= VM_MAXCPU) {
3986 				return (EINVAL);
3987 			}
3988 		} else {
3989 			/*
3990 			 * A provider with neither VM-wide nor per-vCPU handlers
3991 			 * is completely unexpected.  Such a situation should be
3992 			 * made into a compile-time error.  Bail out for now,
3993 			 * rather than punishing the user with a panic.
3994 			 */
3995 			return (EINVAL);
3996 		}
3997 
3998 
3999 		*resp = vdp;
4000 		return (0);
4001 	}
4002 	return (EINVAL);
4003 }
4004 
4005 static void *
vmm_data_from_class(const vmm_data_req_t * req,struct vm * vm)4006 vmm_data_from_class(const vmm_data_req_t *req, struct vm *vm)
4007 {
4008 	switch (req->vdr_class) {
4009 	case VDC_REGISTER:
4010 	case VDC_MSR:
4011 	case VDC_FPU:
4012 	case VDC_LAPIC:
4013 	case VDC_VMM_ARCH:
4014 		/*
4015 		 * These have per-CPU handling which is dispatched outside
4016 		 * vmm_data_version_entries listing.
4017 		 */
4018 		panic("Unexpected per-vcpu class %u", req->vdr_class);
4019 		break;
4020 
4021 	case VDC_IOAPIC:
4022 		return (vm->vioapic);
4023 	case VDC_ATPIT:
4024 		return (vm->vatpit);
4025 	case VDC_ATPIC:
4026 		return (vm->vatpic);
4027 	case VDC_HPET:
4028 		return (vm->vhpet);
4029 	case VDC_PM_TIMER:
4030 		return (vm->vpmtmr);
4031 	case VDC_RTC:
4032 		return (vm->vrtc);
4033 	case VDC_VMM_TIME:
4034 		return (vm);
4035 	case VDC_VERSION:
4036 		/*
4037 		 * Play along with all of the other classes which need backup
4038 		 * data, even though version info does not require it.
4039 		 */
4040 		return (vm);
4041 
4042 	default:
4043 		/* The data class will have been validated by now */
4044 		panic("Unexpected class %u", req->vdr_class);
4045 	}
4046 }
4047 
4048 const uint32_t default_msr_iter[] = {
4049 	/*
4050 	 * Although EFER is also available via the get/set-register interface,
4051 	 * we include it in the default list of emitted MSRs.
4052 	 */
4053 	MSR_EFER,
4054 
4055 	/*
4056 	 * While gsbase and fsbase are accessible via the MSR accessors, they
4057 	 * are not included in MSR iteration since they are covered by the
4058 	 * segment descriptor interface too.
4059 	 */
4060 	MSR_KGSBASE,
4061 
4062 	MSR_STAR,
4063 	MSR_LSTAR,
4064 	MSR_CSTAR,
4065 	MSR_SF_MASK,
4066 
4067 	MSR_SYSENTER_CS_MSR,
4068 	MSR_SYSENTER_ESP_MSR,
4069 	MSR_SYSENTER_EIP_MSR,
4070 
4071 	MSR_PAT,
4072 
4073 	MSR_TSC,
4074 
4075 	MSR_MTRRcap,
4076 	MSR_MTRRdefType,
4077 	MSR_MTRR4kBase, MSR_MTRR4kBase + 1, MSR_MTRR4kBase + 2,
4078 	MSR_MTRR4kBase + 3, MSR_MTRR4kBase + 4, MSR_MTRR4kBase + 5,
4079 	MSR_MTRR4kBase + 6, MSR_MTRR4kBase + 7,
4080 	MSR_MTRR16kBase, MSR_MTRR16kBase + 1,
4081 	MSR_MTRR64kBase,
4082 };
4083 
4084 static int
vmm_data_read_msr(struct vm * vm,int vcpuid,uint32_t msr,uint64_t * value)4085 vmm_data_read_msr(struct vm *vm, int vcpuid, uint32_t msr, uint64_t *value)
4086 {
4087 	int err = 0;
4088 
4089 	switch (msr) {
4090 	case MSR_TSC:
4091 		/*
4092 		 * The vmm-data interface for MSRs provides access to the
4093 		 * per-vCPU offset of the TSC, when reading/writing MSR_TSC.
4094 		 *
4095 		 * The VM-wide offset (and scaling) of the guest TSC is accessed
4096 		 * via the VMM_TIME data class.
4097 		 */
4098 		*value = vm->vcpu[vcpuid].tsc_offset;
4099 		return (0);
4100 
4101 	default:
4102 		if (is_mtrr_msr(msr)) {
4103 			err = vm_rdmtrr(&vm->vcpu[vcpuid].mtrr, msr, value);
4104 		} else {
4105 			err = ops->vmgetmsr(vm->cookie, vcpuid, msr, value);
4106 		}
4107 		break;
4108 	}
4109 
4110 	return (err);
4111 }
4112 
4113 static int
vmm_data_write_msr(struct vm * vm,int vcpuid,uint32_t msr,uint64_t value)4114 vmm_data_write_msr(struct vm *vm, int vcpuid, uint32_t msr, uint64_t value)
4115 {
4116 	int err = 0;
4117 
4118 	switch (msr) {
4119 	case MSR_TSC:
4120 		/* See vmm_data_read_msr() for more detail */
4121 		vm->vcpu[vcpuid].tsc_offset = value;
4122 		return (0);
4123 	case MSR_MTRRcap: {
4124 		/*
4125 		 * MTRRcap is read-only.  If the desired value matches the
4126 		 * existing one, consider it a success.
4127 		 */
4128 		uint64_t comp;
4129 		err = vm_rdmtrr(&vm->vcpu[vcpuid].mtrr, msr, &comp);
4130 		if (err == 0 && comp != value) {
4131 			return (EINVAL);
4132 		}
4133 		break;
4134 	}
4135 	default:
4136 		if (is_mtrr_msr(msr)) {
4137 			/* MTRRcap is already handled above */
4138 			ASSERT3U(msr, !=, MSR_MTRRcap);
4139 
4140 			err = vm_wrmtrr(&vm->vcpu[vcpuid].mtrr, msr, value);
4141 		} else {
4142 			err = ops->vmsetmsr(vm->cookie, vcpuid, msr, value);
4143 		}
4144 		break;
4145 	}
4146 
4147 	return (err);
4148 }
4149 
4150 static int
vmm_data_read_msrs(struct vm * vm,int vcpuid,const vmm_data_req_t * req)4151 vmm_data_read_msrs(struct vm *vm, int vcpuid, const vmm_data_req_t *req)
4152 {
4153 	VERIFY3U(req->vdr_class, ==, VDC_MSR);
4154 	VERIFY3U(req->vdr_version, ==, 1);
4155 
4156 	struct vdi_field_entry_v1 *entryp = req->vdr_data;
4157 
4158 	/* Specific MSRs requested */
4159 	if ((req->vdr_flags & VDX_FLAG_READ_COPYIN) != 0) {
4160 		const uint_t count =
4161 		    req->vdr_len / sizeof (struct vdi_field_entry_v1);
4162 
4163 		for (uint_t i = 0; i < count; i++, entryp++) {
4164 			int err = vmm_data_read_msr(vm, vcpuid,
4165 			    entryp->vfe_ident, &entryp->vfe_value);
4166 
4167 			if (err != 0) {
4168 				return (err);
4169 			}
4170 		}
4171 
4172 		*req->vdr_result_len =
4173 		    count * sizeof (struct vdi_field_entry_v1);
4174 		return (0);
4175 	}
4176 
4177 	/*
4178 	 * If specific MSRs are not requested, try to provide all those which we
4179 	 * know about instead.
4180 	 */
4181 	const uint_t num_msrs = nitems(default_msr_iter) +
4182 	    (VMM_MTRR_VAR_MAX * 2);
4183 	const uint32_t output_len =
4184 	    num_msrs * sizeof (struct vdi_field_entry_v1);
4185 
4186 	*req->vdr_result_len = output_len;
4187 	if (req->vdr_len < output_len) {
4188 		return (ENOSPC);
4189 	}
4190 
4191 	/* Output the MSRs in the default list */
4192 	for (uint_t i = 0; i < nitems(default_msr_iter); i++, entryp++) {
4193 		entryp->vfe_ident = default_msr_iter[i];
4194 
4195 		/* All of these MSRs are expected to work */
4196 		VERIFY0(vmm_data_read_msr(vm, vcpuid, entryp->vfe_ident,
4197 		    &entryp->vfe_value));
4198 	}
4199 
4200 	/* Output the variable MTRRs */
4201 	for (uint_t i = 0; i < (VMM_MTRR_VAR_MAX * 2); i++, entryp++) {
4202 		entryp->vfe_ident = MSR_MTRRVarBase + i;
4203 
4204 		/* All of these MSRs are expected to work */
4205 		VERIFY0(vmm_data_read_msr(vm, vcpuid, entryp->vfe_ident,
4206 		    &entryp->vfe_value));
4207 	}
4208 	return (0);
4209 }
4210 
4211 static int
vmm_data_write_msrs(struct vm * vm,int vcpuid,const vmm_data_req_t * req)4212 vmm_data_write_msrs(struct vm *vm, int vcpuid, const vmm_data_req_t *req)
4213 {
4214 	VERIFY3U(req->vdr_class, ==, VDC_MSR);
4215 	VERIFY3U(req->vdr_version, ==, 1);
4216 
4217 	const struct vdi_field_entry_v1 *entryp = req->vdr_data;
4218 	const uint_t entry_count =
4219 	    req->vdr_len / sizeof (struct vdi_field_entry_v1);
4220 
4221 	/*
4222 	 * First make sure that all of the MSRs can be manipulated.
4223 	 * For now, this check is done by going though the getmsr handler
4224 	 */
4225 	for (uint_t i = 0; i < entry_count; i++, entryp++) {
4226 		const uint64_t msr = entryp->vfe_ident;
4227 		uint64_t val;
4228 
4229 		if (vmm_data_read_msr(vm, vcpuid, msr, &val) != 0) {
4230 			return (EINVAL);
4231 		}
4232 	}
4233 
4234 	/*
4235 	 * Fairly confident that all of the 'set' operations are at least
4236 	 * targeting valid MSRs, continue on.
4237 	 */
4238 	entryp = req->vdr_data;
4239 	for (uint_t i = 0; i < entry_count; i++, entryp++) {
4240 		int err = vmm_data_write_msr(vm, vcpuid, entryp->vfe_ident,
4241 		    entryp->vfe_value);
4242 
4243 		if (err != 0) {
4244 			return (err);
4245 		}
4246 	}
4247 	*req->vdr_result_len = entry_count * sizeof (struct vdi_field_entry_v1);
4248 
4249 	return (0);
4250 }
4251 
4252 static const vmm_data_version_entry_t msr_v1 = {
4253 	.vdve_class = VDC_MSR,
4254 	.vdve_version = 1,
4255 	.vdve_len_per_item = sizeof (struct vdi_field_entry_v1),
4256 	.vdve_vcpu_readf = vmm_data_read_msrs,
4257 	.vdve_vcpu_writef = vmm_data_write_msrs,
4258 };
4259 VMM_DATA_VERSION(msr_v1);
4260 
4261 static const uint32_t vmm_arch_v1_fields[] = {
4262 	VAI_VM_IS_PAUSED,
4263 };
4264 
4265 static const uint32_t vmm_arch_v1_vcpu_fields[] = {
4266 	VAI_PEND_NMI,
4267 	VAI_PEND_EXTINT,
4268 	VAI_PEND_EXCP,
4269 	VAI_PEND_INTINFO,
4270 };
4271 
4272 static bool
vmm_read_arch_field(struct vm * vm,int vcpuid,uint32_t ident,uint64_t * valp)4273 vmm_read_arch_field(struct vm *vm, int vcpuid, uint32_t ident, uint64_t *valp)
4274 {
4275 	ASSERT(valp != NULL);
4276 
4277 	if (vcpuid == -1) {
4278 		switch (ident) {
4279 		case VAI_VM_IS_PAUSED:
4280 			*valp = vm->is_paused ? 1 : 0;
4281 			return (true);
4282 		default:
4283 			break;
4284 		}
4285 	} else {
4286 		VERIFY(vcpuid >= 0 && vcpuid <= VM_MAXCPU);
4287 
4288 		struct vcpu *vcpu = &vm->vcpu[vcpuid];
4289 		switch (ident) {
4290 		case VAI_PEND_NMI:
4291 			*valp = vcpu->nmi_pending != 0 ? 1 : 0;
4292 			return (true);
4293 		case VAI_PEND_EXTINT:
4294 			*valp = vcpu->extint_pending != 0 ? 1 : 0;
4295 			return (true);
4296 		case VAI_PEND_EXCP:
4297 			*valp = vcpu->exc_pending;
4298 			return (true);
4299 		case VAI_PEND_INTINFO:
4300 			*valp = vcpu->exit_intinfo;
4301 			return (true);
4302 		default:
4303 			break;
4304 		}
4305 	}
4306 	return (false);
4307 }
4308 
4309 static int
vmm_data_read_varch(struct vm * vm,int vcpuid,const vmm_data_req_t * req)4310 vmm_data_read_varch(struct vm *vm, int vcpuid, const vmm_data_req_t *req)
4311 {
4312 	VERIFY3U(req->vdr_class, ==, VDC_VMM_ARCH);
4313 	VERIFY3U(req->vdr_version, ==, 1);
4314 
4315 	/* per-vCPU fields are handled separately from VM-wide ones */
4316 	if (vcpuid != -1 && (vcpuid < 0 || vcpuid >= VM_MAXCPU)) {
4317 		return (EINVAL);
4318 	}
4319 
4320 	struct vdi_field_entry_v1 *entryp = req->vdr_data;
4321 
4322 	/* Specific fields requested */
4323 	if ((req->vdr_flags & VDX_FLAG_READ_COPYIN) != 0) {
4324 		const uint_t count =
4325 		    req->vdr_len / sizeof (struct vdi_field_entry_v1);
4326 
4327 		for (uint_t i = 0; i < count; i++, entryp++) {
4328 			if (!vmm_read_arch_field(vm, vcpuid, entryp->vfe_ident,
4329 			    &entryp->vfe_value)) {
4330 				return (EINVAL);
4331 			}
4332 		}
4333 		*req->vdr_result_len =
4334 		    count * sizeof (struct vdi_field_entry_v1);
4335 		return (0);
4336 	}
4337 
4338 	/* Emit all of the possible values */
4339 	const uint32_t *idents;
4340 	uint_t ident_count;
4341 
4342 	if (vcpuid == -1) {
4343 		idents = vmm_arch_v1_fields;
4344 		ident_count = nitems(vmm_arch_v1_fields);
4345 	} else {
4346 		idents = vmm_arch_v1_vcpu_fields;
4347 		ident_count = nitems(vmm_arch_v1_vcpu_fields);
4348 
4349 	}
4350 
4351 	const uint32_t total_size =
4352 	    ident_count * sizeof (struct vdi_field_entry_v1);
4353 
4354 	*req->vdr_result_len = total_size;
4355 	if (req->vdr_len < total_size) {
4356 		return (ENOSPC);
4357 	}
4358 	for (uint_t i = 0; i < ident_count; i++, entryp++) {
4359 		entryp->vfe_ident = idents[i];
4360 		VERIFY(vmm_read_arch_field(vm, vcpuid, entryp->vfe_ident,
4361 		    &entryp->vfe_value));
4362 	}
4363 	return (0);
4364 }
4365 
4366 static int
vmm_data_write_varch_vcpu(struct vm * vm,int vcpuid,const vmm_data_req_t * req)4367 vmm_data_write_varch_vcpu(struct vm *vm, int vcpuid, const vmm_data_req_t *req)
4368 {
4369 	VERIFY3U(req->vdr_class, ==, VDC_VMM_ARCH);
4370 	VERIFY3U(req->vdr_version, ==, 1);
4371 
4372 	if (vcpuid < 0 || vcpuid >= VM_MAXCPU) {
4373 		return (EINVAL);
4374 	}
4375 
4376 	const struct vdi_field_entry_v1 *entryp = req->vdr_data;
4377 	const uint_t entry_count =
4378 	    req->vdr_len / sizeof (struct vdi_field_entry_v1);
4379 	struct vcpu *vcpu = &vm->vcpu[vcpuid];
4380 
4381 	for (uint_t i = 0; i < entry_count; i++, entryp++) {
4382 		const uint64_t val = entryp->vfe_value;
4383 
4384 		switch (entryp->vfe_ident) {
4385 		case VAI_PEND_NMI:
4386 			vcpu->nmi_pending = (val != 0);
4387 			break;
4388 		case VAI_PEND_EXTINT:
4389 			vcpu->extint_pending = (val != 0);
4390 			break;
4391 		case VAI_PEND_EXCP:
4392 			if (!VM_INTINFO_PENDING(val)) {
4393 				vcpu->exc_pending = 0;
4394 			} else if (VM_INTINFO_TYPE(val) != VM_INTINFO_HWEXCP ||
4395 			    (val & VM_INTINFO_MASK_RSVD) != 0) {
4396 				/* reject improperly-formed hw exception */
4397 				return (EINVAL);
4398 			} else {
4399 				vcpu->exc_pending = val;
4400 			}
4401 			break;
4402 		case VAI_PEND_INTINFO:
4403 			if (vm_exit_intinfo(vm, vcpuid, val) != 0) {
4404 				return (EINVAL);
4405 			}
4406 			break;
4407 		default:
4408 			return (EINVAL);
4409 		}
4410 	}
4411 
4412 	*req->vdr_result_len = entry_count * sizeof (struct vdi_field_entry_v1);
4413 	return (0);
4414 }
4415 
4416 static int
vmm_data_write_varch(struct vm * vm,int vcpuid,const vmm_data_req_t * req)4417 vmm_data_write_varch(struct vm *vm, int vcpuid, const vmm_data_req_t *req)
4418 {
4419 	VERIFY3U(req->vdr_class, ==, VDC_VMM_ARCH);
4420 	VERIFY3U(req->vdr_version, ==, 1);
4421 
4422 	/* per-vCPU fields are handled separately from VM-wide ones */
4423 	if (vcpuid != -1) {
4424 		return (vmm_data_write_varch_vcpu(vm, vcpuid, req));
4425 	}
4426 
4427 	const struct vdi_field_entry_v1 *entryp = req->vdr_data;
4428 	const uint_t entry_count =
4429 	    req->vdr_len / sizeof (struct vdi_field_entry_v1);
4430 
4431 	if (entry_count > 0) {
4432 		if (entryp->vfe_ident == VAI_VM_IS_PAUSED) {
4433 			/*
4434 			 * The VM_PAUSE and VM_RESUME ioctls are the officially
4435 			 * sanctioned mechanisms for setting the is-paused state
4436 			 * of the VM.
4437 			 */
4438 			return (EPERM);
4439 		} else {
4440 			/* no other valid arch entries at this time */
4441 			return (EINVAL);
4442 		}
4443 	}
4444 
4445 	*req->vdr_result_len = entry_count * sizeof (struct vdi_field_entry_v1);
4446 	return (0);
4447 }
4448 
4449 static const vmm_data_version_entry_t vmm_arch_v1 = {
4450 	.vdve_class = VDC_VMM_ARCH,
4451 	.vdve_version = 1,
4452 	.vdve_len_per_item = sizeof (struct vdi_field_entry_v1),
4453 	.vdve_vcpu_readf = vmm_data_read_varch,
4454 	.vdve_vcpu_writef = vmm_data_write_varch,
4455 
4456 	/*
4457 	 * Handlers for VMM_ARCH can process VM-wide (vcpuid == -1) entries in
4458 	 * addition to vCPU specific ones.
4459 	 */
4460 	.vdve_vcpu_wildcard = true,
4461 };
4462 VMM_DATA_VERSION(vmm_arch_v1);
4463 
4464 
4465 /*
4466  * GUEST TIME SUPPORT
4467  *
4468  * Broadly, there are two categories of functionality related to time passing in
4469  * the guest: the guest's TSC and timers used by emulated devices.
4470  *
4471  * ---------------------------
4472  * GUEST TSC "VIRTUALIZATION"
4473  * ---------------------------
4474  *
4475  * The TSC can be read either via an instruction (rdtsc/rdtscp) or by reading
4476  * the TSC MSR.
4477  *
4478  * When a guest reads the TSC via its MSR, the guest will exit and we emulate
4479  * the rdmsr. More typically, the guest reads the TSC via a rdtsc(p)
4480  * instruction. Both SVM and VMX support virtualizing the guest TSC in hardware
4481  * -- that is, a guest will not generally exit on a rdtsc instruction.
4482  *
4483  * To support hardware-virtualized guest TSC, both SVM and VMX provide two knobs
4484  * for the hypervisor to adjust the guest's view of the TSC:
4485  * - TSC offset
4486  * - TSC frequency multiplier (also called "frequency ratio")
4487  *
4488  * When a guest calls rdtsc(p), the TSC value it sees is the sum of:
4489  *     guest_tsc = (host TSC, scaled according to frequency multiplier)
4490  *		    + (TSC offset, programmed by hypervisor)
4491  *
4492  * See the discussions of the TSC offset and frequency multiplier below for more
4493  * details on each of these.
4494  *
4495  * --------------------
4496  * TSC OFFSET OVERVIEW
4497  * --------------------
4498  *
4499  * The TSC offset is a value added to the host TSC (which may be scaled first)
4500  * to provide the guest TSC. This offset addition is generally done by hardware,
4501  * but may be used in emulating the TSC if necessary.
4502  *
4503  * Recall that general formula for calculating the guest TSC is:
4504  *
4505  *	guest_tsc = (host TSC, scaled if needed) + TSC offset
4506  *
4507  * Intuitively, the TSC offset is simply an offset of the host's TSC to make the
4508  * guest's view of the TSC appear correct: The guest TSC should be 0 at boot and
4509  * monotonically increase at a roughly constant frequency. Thus in the simplest
4510  * case, the TSC offset is just the negated value of the host TSC when the guest
4511  * was booted, assuming they have the same frequencies.
4512  *
4513  * In practice, there are several factors that can make calculating the TSC
4514  * offset more complicated, including:
4515  *
4516  * (1) the physical CPU the guest is running on
4517  * (2) whether the guest has written to the TSC of that vCPU
4518  * (3) differing host and guest frequencies, like after a live migration
4519  * (4) a guest running on a different system than where it was booted, like
4520  *     after a live migration
4521  *
4522  * We will explore each of these factors individually. See below for a
4523  * summary.
4524  *
4525  *
4526  * (1) Physical CPU offsets
4527  *
4528  * The system maintains a set of per-CPU offsets to the TSC to provide a
4529  * consistent view of the TSC regardless of the CPU a thread is running on.
4530  * These offsets are included automatically as a part of rdtsc_offset().
4531  *
4532  * The per-CPU offset must be included as a part reading the host TSC when
4533  * calculating the offset before running the guest on a given CPU.
4534  *
4535  *
4536  * (2) Guest TSC writes (vCPU offsets)
4537  *
4538  * The TSC is a writable MSR. When a guest writes to the TSC, this operation
4539  * should result in the TSC, when read from that vCPU, shows the value written,
4540  * plus whatever time has elapsed since the read.
4541  *
4542  * To support this, when the guest writes to the TSC, we store an additional
4543  * vCPU offset calculated to make future reads of the TSC map to what the guest
4544  * expects.
4545  *
4546  *
4547  * (3) Differing host and guest frequencies (host TSC scaling)
4548  *
4549  * A guest has the same frequency of its host when it boots, but it may be
4550  * migrated to a machine with a different TSC frequency. Systems expect that
4551  * their TSC frequency does not change. To support this fiction in which a guest
4552  * is running on hardware of a different TSC frequency, the hypervisor  can
4553  * program a "frequency multiplier" that represents the ratio of guest/host
4554  * frequency.
4555  *
4556  * Any time a host TSC is used in calculations for the offset, it should be
4557  * "scaled" according to this multiplier, and the hypervisor should program the
4558  * multiplier before running a guest so that the hardware virtualization of the
4559  * TSC functions properly. Similarly, the multiplier should be used in any TSC
4560  * emulation.
4561  *
4562  * See below for more details about the frequency multiplier.
4563  *
4564  *
4565  * (4) Guest running on a system it did not boot on ("base guest TSC")
4566  *
4567  * When a guest boots, its TSC offset is simply the negated host TSC at the time
4568  * it booted. If a guest is migrated from a source host to a target host, the
4569  * TSC offset from the source host is no longer useful for several reasons:
4570  * - the target host TSC has no relationship to the source host TSC
4571  * - the guest did not boot on the target system, so the TSC of the target host
4572  *   is not sufficient to describe how long the guest has been running prior to
4573  *   migration
4574  * - the target system may have a different TSC frequency than the source system
4575  *
4576  * Ignoring the issue of frequency differences for a moment, let's consider how
4577  * to re-align the guest TSC with the host TSC of the target host. Intuitively,
4578  * for the guest to see the correct TSC, we still want to add some offset to the
4579  * host TSC that offsets how long this guest has been running on
4580  * the system.
4581  *
4582  * An example here might be helpful. Consider a source host and target host,
4583  * both with TSC frequencies of 1GHz. On the source host, the guest and host TSC
4584  * values might look like:
4585  *
4586  *  +----------------------------------------------------------------------+
4587  *  | Event                 | source host TSC  | guest TSC                 |
4588  *  ------------------------------------------------------------------------
4589  *  | guest boot  (t=0s)    | 5000000000       | 5000000000 + -5000000000  |
4590  *  |                       |                  | 0			   |
4591  *  ------------------------------------------------------------------------
4592  *  | guest rdtsc (t=10s))  | 15000000000      | 15000000000 + -5000000000 |
4593  *  |                       |                  | 10000000000		   |
4594  *  ------------------------------------------------------------------------
4595  *  | migration   (t=15s)   | 20000000000      | 20000000000 + -5000000000 |
4596  *  |                       |                  | 15000000000		   |
4597  *  +----------------------------------------------------------------------+
4598  *
4599  * Ignoring the time it takes for a guest to physically migrate machines, on the
4600  * target host, we would expect the TSC to continue functioning as such:
4601  *
4602  *  +----------------------------------------------------------------------+
4603  *  | Event                 | target host TSC  | guest TSC                 |
4604  *  ------------------------------------------------------------------------
4605  *  | guest migrate (t=15s) | 300000000000     | 15000000000		   |
4606  *  ------------------------------------------------------------------------
4607  *  | guest rdtsc (t=20s))  | 305000000000     | 20000000000		   |
4608  *  ------------------------------------------------------------------------
4609  *
4610  * In order to produce a correct TSC value here, we can calculate a new
4611  * "effective" boot TSC that maps to what the host TSC would've been had it been
4612  * booted on the target. We add that to the guest TSC when it began to run on
4613  * this machine, and negate them both to get a new offset. In this example, the
4614  * effective boot TSC is: -(300000000000 - 15000000000) = -285000000000.
4615  *
4616  *  +-------------------------------------------------------------------------+
4617  *  | Event                 | target host TSC  | guest TSC                    |
4618  *  ---------------------------------------------------------------------------
4619  *  | guest "boot" (t=0s)   | 285000000000     | 285000000000 + -285000000000 |
4620  *  |                       |                  | 0			      |
4621  *  ---------------------------------------------------------------------------
4622  *  | guest migrate (t=15s) | 300000000000     | 300000000000 + -285000000000 |
4623  *  |                       |                  | 15000000000		      |
4624  *  ---------------------------------------------------------------------------
4625  *  | guest rdtsc (t=20s))  | 305000000000     | 305000000000 + -285000000000 |
4626  *  |                       |                  | 20000000000		      |
4627  *  --------------------------------------------------------------------------+
4628  *
4629  * To support the offset calculation following a migration, the VMM data time
4630  * interface allows callers to set a "base guest TSC", which is the TSC value of
4631  * the guest when it began running on the host. The current guest TSC can be
4632  * requested via a read of the time data. See below for details on that
4633  * interface.
4634  *
4635  * Frequency differences between the host and the guest are accounted for when
4636  * scaling the host TSC. See below for details on the frequency multiplier.
4637  *
4638  *
4639  * --------------------
4640  * TSC OFFSET SUMMARY
4641  * --------------------
4642  *
4643  * Factoring in all of the components to the TSC above, the TSC offset that is
4644  * programmed by the hypervisor before running a given vCPU is:
4645  *
4646  * offset = -((base host TSC, scaled if needed) - base_guest_tsc) + vCPU offset
4647  *
4648  * This offset is stored in two pieces. Per-vCPU offsets are stored with the
4649  * given vCPU and added in when programming the offset. The rest of the offset
4650  * is stored as a VM-wide offset, and computed either at boot or when the time
4651  * data is written to.
4652  *
4653  * It is safe to add the vCPU offset and the VM-wide offsets together because
4654  * the vCPU offset is in terms of the guest TSC. The host TSC is scaled before
4655  * using it in calculations, so all TSC values are applicable to the same
4656  * frequency.
4657  *
4658  * Note: Though both the VM-wide offset and per-vCPU offsets may be negative, we
4659  * store them as unsigned values and perform all offsetting math unsigned. This
4660  * is to avoid UB from signed overflow.
4661  *
4662  * -------------------------
4663  * TSC FREQUENCY MULTIPLIER
4664  * -------------------------
4665  *
4666  * In order to account for frequency differences between the host and guest, SVM
4667  * and VMX provide an interface to set a "frequency multiplier" (or "frequency
4668  * ratio") representing guest to host frequency. In a hardware-virtualized read
4669  * of the TSC, the host TSC is scaled using this multiplier prior to adding the
4670  * programmed TSC offset.
4671  *
4672  * Both platforms represent the ratio as a fixed point number, where the lower
4673  * bits are used as a fractional component, and some number of the upper bits
4674  * are used as the integer component.
4675  *
4676  * Some example multipliers, for a platform with FRAC fractional bits in the
4677  * multiplier:
4678  * - guest frequency == host: 1 << FRAC
4679  * - guest frequency is 2x host: 1 << (FRAC + 1)
4680  * - guest frequency is 0.5x host: 1 << (FRAC - 1), as the highest-order
4681  *   fractional bit represents 1/2
4682  * - guest frequency is 2.5x host: (1 << FRAC) | (1 << (FRAC - 1))
4683  * and so on.
4684  *
4685  * In general, the frequency multiplier is calculated as follows:
4686  *		(guest_hz * (1 << FRAC_SIZE)) / host_hz
4687  *
4688  * The multiplier should be used any time the host TSC value is used in
4689  * calculations with the guest TSC (and their frequencies differ). The function
4690  * `vmm_scale_tsc` is intended to be used for these purposes, as it will scale
4691  * the host TSC only if needed.
4692  *
4693  * The multiplier should also be programmed by the hypervisor before the guest
4694  * is run.
4695  *
4696  *
4697  * ----------------------------
4698  * DEVICE TIMERS (BOOT_HRTIME)
4699  * ----------------------------
4700  *
4701  * Emulated devices use timers to do things such as scheduling periodic events.
4702  * These timers are scheduled relative to the hrtime of the host. When device
4703  * state is exported or imported, we use boot_hrtime to normalize these timers
4704  * against the host hrtime. The boot_hrtime represents the hrtime of the host
4705  * when the guest was booted.
4706  *
4707  * If a guest is migrated to a different machine, boot_hrtime must be adjusted
4708  * to match the hrtime of when the guest was effectively booted on the target
4709  * host. This allows timers to continue functioning when device state is
4710  * imported on the target.
4711  *
4712  *
4713  * ------------------------
4714  * VMM DATA TIME INTERFACE
4715  * ------------------------
4716  *
4717  * In order to facilitate live migrations of guests, we provide an interface,
4718  * via the VMM data read/write ioctls, for userspace to make changes to the
4719  * guest's view of the TSC and device timers, allowing these features to
4720  * continue functioning after a migration.
4721  *
4722  * The interface was designed to expose the minimal amount of data needed for a
4723  * userspace component to make adjustments to the guest's view of time (e.g., to
4724  * account for time passing in a live migration). At a minimum, such a program
4725  * needs:
4726  * - the current guest TSC
4727  * - guest TSC frequency
4728  * - guest's boot_hrtime
4729  * - timestamps of when this data was taken (hrtime for hrtime calculations, and
4730  *   wall clock time for computing time deltas between machines)
4731  *
4732  * The wall clock time is provided for consumers to make adjustments to the
4733  * guest TSC and boot_hrtime based on deltas observed during migrations. It may
4734  * be prudent for consumers to use this data only in circumstances where the
4735  * source and target have well-synchronized wall clocks, but nothing in the
4736  * interface depends on this assumption.
4737  *
4738  * On writes, consumers write back:
4739  * - the base guest TSC (used for TSC offset calculations)
4740  * - desired boot_hrtime
4741  * - guest_frequency (cannot change)
4742  * - hrtime of when this data was adjusted
4743  * - (wall clock time on writes is ignored)
4744  *
4745  * The interface will adjust the input guest TSC slightly, based on the input
4746  * hrtime, to account for latency between userspace calculations and application
4747  * of the data on the kernel side. This amounts to adding a small amount of
4748  * additional "uptime" for the guest.
4749  *
4750  * After the adjustments, the interface updates the VM-wide TSC offset and
4751  * boot_hrtime. Per-vCPU offsets are not adjusted, as those are already in terms
4752  * of the guest TSC and can be exported/imported via the MSR VMM data interface.
4753  *
4754  *
4755  * --------------------------------
4756  * SUPPORTED PLATFORMS AND CAVEATS
4757  * --------------------------------
4758  *
4759  * While both VMX and SVM offer TSC scaling as a feature, at this time only SVM
4760  * is supported by bhyve.
4761  *
4762  * The time data interface is designed such that Intel support can be added
4763  * easily, and all other aspects of the time interface should work on Intel.
4764  * (Without frequency control though, in practice, doing live migrations of
4765  * guests on Intel will not work for time-related things, as two machines
4766  * rarely have exactly the same frequency).
4767  *
4768  * Additionally, while on both SVM and VMX the frequency multiplier is a fixed
4769  * point number, each uses a different number of fractional and integer bits for
4770  * the multiplier. As such, calculating the multiplier and fractional bit size
4771  * is requested via the vmm_ops.
4772  *
4773  * Care should be taken to set reasonable limits for ratios based on the
4774  * platform, as the difference in fractional bits can lead to slightly different
4775  * tradeoffs in terms of representable ratios and potentially overflowing
4776  * calculations.
4777  */
4778 
4779 /*
4780  * Scales the TSC if needed, based on the input frequency multiplier.
4781  */
4782 static uint64_t
vmm_scale_tsc(uint64_t tsc,uint64_t mult)4783 vmm_scale_tsc(uint64_t tsc, uint64_t mult)
4784 {
4785 	const uint32_t frac_size = ops->fr_fracsize;
4786 
4787 	if (mult != VM_TSCM_NOSCALE) {
4788 		VERIFY3U(frac_size, >, 0);
4789 		return (scale_tsc(tsc, mult, frac_size));
4790 	} else {
4791 		return (tsc);
4792 	}
4793 }
4794 
4795 /*
4796  * Calculate the frequency multiplier, which represents the ratio of
4797  * guest_hz / host_hz. The frequency multiplier is a fixed point number with
4798  * `frac_sz` fractional bits (fractional bits begin at bit 0).
4799  *
4800  * See comment for "calc_freq_multiplier" in "vmm_time_support.S" for more
4801  * information about valid input to this function.
4802  */
4803 uint64_t
vmm_calc_freq_multiplier(uint64_t guest_hz,uint64_t host_hz,uint32_t frac_size)4804 vmm_calc_freq_multiplier(uint64_t guest_hz, uint64_t host_hz,
4805     uint32_t frac_size)
4806 {
4807 	VERIFY3U(guest_hz, !=, 0);
4808 	VERIFY3U(frac_size, >, 0);
4809 	VERIFY3U(frac_size, <, 64);
4810 
4811 	return (calc_freq_multiplier(guest_hz, host_hz, frac_size));
4812 }
4813 
4814 /*
4815  * Calculate the guest VM-wide TSC offset.
4816  *
4817  * offset = - ((base host TSC, scaled if needed) - base_guest_tsc)
4818  *
4819  * The base_host_tsc and the base_guest_tsc are the TSC values of the host
4820  * (read on the system) and the guest (calculated) at the same point in time.
4821  * This allows us to fix the guest TSC at this point in time as a base, either
4822  * following boot (guest TSC = 0), or a change to the guest's time data from
4823  * userspace (such as in the case of a migration).
4824  */
4825 static uint64_t
calc_tsc_offset(uint64_t base_host_tsc,uint64_t base_guest_tsc,uint64_t mult)4826 calc_tsc_offset(uint64_t base_host_tsc, uint64_t base_guest_tsc, uint64_t mult)
4827 {
4828 	const uint64_t htsc_scaled = vmm_scale_tsc(base_host_tsc, mult);
4829 	if (htsc_scaled > base_guest_tsc) {
4830 		return ((uint64_t)(- (int64_t)(htsc_scaled - base_guest_tsc)));
4831 	} else {
4832 		return (base_guest_tsc - htsc_scaled);
4833 	}
4834 }
4835 
4836 /*
4837  * Calculate an estimate of the guest TSC.
4838  *
4839  * guest_tsc = (host TSC, scaled if needed) + offset
4840  */
4841 static uint64_t
calc_guest_tsc(uint64_t host_tsc,uint64_t mult,uint64_t offset)4842 calc_guest_tsc(uint64_t host_tsc, uint64_t mult, uint64_t offset)
4843 {
4844 	return (vmm_scale_tsc(host_tsc, mult) + offset);
4845 }
4846 
4847 /*
4848  * Take a non-atomic "snapshot" of the current:
4849  * - TSC
4850  * - hrtime
4851  * - wall clock time
4852  */
4853 static void
vmm_time_snapshot(uint64_t * tsc,hrtime_t * hrtime,timespec_t * hrestime)4854 vmm_time_snapshot(uint64_t *tsc, hrtime_t *hrtime, timespec_t *hrestime)
4855 {
4856 	/*
4857 	 * Disable interrupts while we take the readings: In the absence of a
4858 	 * mechanism to convert hrtime to hrestime, we want the time between
4859 	 * each of these measurements to be as small as possible.
4860 	 */
4861 	ulong_t iflag = intr_clear();
4862 
4863 	hrtime_t hrt = gethrtimeunscaledf();
4864 	*tsc = (uint64_t)hrt;
4865 	*hrtime = hrt;
4866 	scalehrtime(hrtime);
4867 	gethrestime(hrestime);
4868 
4869 	intr_restore(iflag);
4870 }
4871 
4872 /*
4873  * Read VMM Time data
4874  *
4875  * Provides:
4876  * - the current guest TSC and TSC frequency
4877  * - guest boot_hrtime
4878  * - timestamps of the read (hrtime and wall clock time)
4879  */
4880 static int
vmm_data_read_vmm_time(void * arg,const vmm_data_req_t * req)4881 vmm_data_read_vmm_time(void *arg, const vmm_data_req_t *req)
4882 {
4883 	VERIFY3U(req->vdr_class, ==, VDC_VMM_TIME);
4884 	VERIFY3U(req->vdr_version, ==, 1);
4885 	VERIFY3U(req->vdr_len, >=, sizeof (struct vdi_time_info_v1));
4886 
4887 	struct vm *vm = arg;
4888 	struct vdi_time_info_v1 *out = req->vdr_data;
4889 
4890 	/*
4891 	 * Since write operations on VMM_TIME data are strict about vcpuid
4892 	 * (see: vmm_data_write_vmm_time()), read operations should be as well.
4893 	 */
4894 	if (req->vdr_vcpuid != -1) {
4895 		return (EINVAL);
4896 	}
4897 
4898 	/* Take a snapshot of this point in time */
4899 	uint64_t tsc;
4900 	hrtime_t hrtime;
4901 	timespec_t hrestime;
4902 	vmm_time_snapshot(&tsc, &hrtime, &hrestime);
4903 
4904 	/* Write the output values */
4905 	out->vt_guest_freq = vm->guest_freq;
4906 
4907 	/*
4908 	 * Use only the VM-wide TSC offset for calculating the guest TSC,
4909 	 * ignoring per-vCPU offsets. This value is provided as a "base" guest
4910 	 * TSC at the time of the read; per-vCPU offsets are factored in as
4911 	 * needed elsewhere, either when running the vCPU or if the guest reads
4912 	 * the TSC via rdmsr.
4913 	 */
4914 	out->vt_guest_tsc = calc_guest_tsc(tsc, vm->freq_multiplier,
4915 	    vm->tsc_offset);
4916 	out->vt_boot_hrtime = vm->boot_hrtime;
4917 	out->vt_hrtime = hrtime;
4918 	out->vt_hres_sec = hrestime.tv_sec;
4919 	out->vt_hres_ns = hrestime.tv_nsec;
4920 
4921 	return (0);
4922 }
4923 
4924 /*
4925  * Modify VMM Time data related values
4926  *
4927  * This interface serves to allow guests' TSC and device timers to continue
4928  * functioning across live migrations. On a successful write, the VM-wide TSC
4929  * offset and boot_hrtime of the guest are updated.
4930  *
4931  * The interface requires an hrtime of the system at which the caller wrote
4932  * this data; this allows us to adjust the TSC and boot_hrtime slightly to
4933  * account for time passing between the userspace call and application
4934  * of the data here.
4935  *
4936  * There are several possibilities for invalid input, including:
4937  * - a requested guest frequency of 0, or a frequency otherwise unsupported by
4938  *   the underlying platform
4939  * - hrtime or boot_hrtime values that appear to be from the future
4940  * - the requested frequency does not match the host, and this system does not
4941  *   have hardware TSC scaling support
4942  */
4943 static int
vmm_data_write_vmm_time(void * arg,const vmm_data_req_t * req)4944 vmm_data_write_vmm_time(void *arg, const vmm_data_req_t *req)
4945 {
4946 	VERIFY3U(req->vdr_class, ==, VDC_VMM_TIME);
4947 	VERIFY3U(req->vdr_version, ==, 1);
4948 	VERIFY3U(req->vdr_len, >=, sizeof (struct vdi_time_info_v1));
4949 
4950 	struct vm *vm = arg;
4951 	const struct vdi_time_info_v1 *src = req->vdr_data;
4952 
4953 	/*
4954 	 * While vcpuid values != -1 are tolerated by the vmm_data machinery for
4955 	 * VM-wide endpoints, the time-related data is more strict: It relies on
4956 	 * write-locking the VM (implied by the vcpuid -1) to prevent vCPUs or
4957 	 * other bits from observing inconsistent values while the state is
4958 	 * being written.
4959 	 */
4960 	if (req->vdr_vcpuid != -1) {
4961 		return (EINVAL);
4962 	}
4963 
4964 	/*
4965 	 * Platform-specific checks will verify the requested frequency against
4966 	 * the supported range further, but a frequency of 0 is never valid.
4967 	 */
4968 	if (src->vt_guest_freq == 0) {
4969 		return (EINVAL);
4970 	}
4971 
4972 	/*
4973 	 * Check whether the request frequency is supported and get the
4974 	 * frequency multiplier.
4975 	 */
4976 	uint64_t mult = VM_TSCM_NOSCALE;
4977 	freqratio_res_t res = ops->vmfreqratio(src->vt_guest_freq,
4978 	    vmm_host_freq, &mult);
4979 	switch (res) {
4980 	case FR_SCALING_NOT_SUPPORTED:
4981 		/*
4982 		 * This system doesn't support TSC scaling, and the guest/host
4983 		 * frequencies differ
4984 		 */
4985 		return (EPERM);
4986 	case FR_OUT_OF_RANGE:
4987 		/* Requested frequency ratio is too small/large */
4988 		return (EINVAL);
4989 	case FR_SCALING_NOT_NEEDED:
4990 		/* Host and guest frequencies are the same */
4991 		VERIFY3U(mult, ==, VM_TSCM_NOSCALE);
4992 		break;
4993 	case FR_VALID:
4994 		VERIFY3U(mult, !=, VM_TSCM_NOSCALE);
4995 		break;
4996 	}
4997 
4998 	/*
4999 	 * Find (and validate) the hrtime delta between the input request and
5000 	 * when we received it so that we can bump the TSC to account for time
5001 	 * passing.
5002 	 *
5003 	 * We ignore the hrestime as input, as this is a field that
5004 	 * exists for reads.
5005 	 */
5006 	uint64_t tsc;
5007 	hrtime_t hrtime;
5008 	timespec_t hrestime;
5009 	vmm_time_snapshot(&tsc, &hrtime, &hrestime);
5010 	if ((src->vt_hrtime > hrtime) || (src->vt_boot_hrtime > hrtime)) {
5011 		/*
5012 		 * The caller has passed in an hrtime / boot_hrtime from the
5013 		 * future.
5014 		 */
5015 		return (EINVAL);
5016 	}
5017 	hrtime_t hrt_delta = hrtime - src->vt_hrtime;
5018 
5019 	/* Calculate guest TSC adjustment */
5020 	const uint64_t host_ticks = unscalehrtime(hrt_delta);
5021 	const uint64_t guest_ticks = vmm_scale_tsc(host_ticks,
5022 	    vm->freq_multiplier);
5023 	const uint64_t base_guest_tsc = src->vt_guest_tsc + guest_ticks;
5024 
5025 	/* Update guest time data */
5026 	vm->freq_multiplier = mult;
5027 	vm->guest_freq = src->vt_guest_freq;
5028 	vm->boot_hrtime = src->vt_boot_hrtime;
5029 	vm->tsc_offset = calc_tsc_offset(tsc, base_guest_tsc,
5030 	    vm->freq_multiplier);
5031 
5032 	return (0);
5033 }
5034 
5035 static const vmm_data_version_entry_t vmm_time_v1 = {
5036 	.vdve_class = VDC_VMM_TIME,
5037 	.vdve_version = 1,
5038 	.vdve_len_expect = sizeof (struct vdi_time_info_v1),
5039 	.vdve_readf = vmm_data_read_vmm_time,
5040 	.vdve_writef = vmm_data_write_vmm_time,
5041 };
5042 VMM_DATA_VERSION(vmm_time_v1);
5043 
5044 
5045 static int
vmm_data_read_versions(void * arg,const vmm_data_req_t * req)5046 vmm_data_read_versions(void *arg, const vmm_data_req_t *req)
5047 {
5048 	VERIFY3U(req->vdr_class, ==, VDC_VERSION);
5049 	VERIFY3U(req->vdr_version, ==, 1);
5050 
5051 	const uint32_t total_size = SET_COUNT(vmm_data_version_entries) *
5052 	    sizeof (struct vdi_version_entry_v1);
5053 
5054 	/* Make sure there is room for all of the entries */
5055 	*req->vdr_result_len = total_size;
5056 	if (req->vdr_len < *req->vdr_result_len) {
5057 		return (ENOSPC);
5058 	}
5059 
5060 	struct vdi_version_entry_v1 *entryp = req->vdr_data;
5061 	const vmm_data_version_entry_t **vdpp;
5062 	SET_FOREACH(vdpp, vmm_data_version_entries) {
5063 		const vmm_data_version_entry_t *vdp = *vdpp;
5064 
5065 		entryp->vve_class = vdp->vdve_class;
5066 		entryp->vve_version = vdp->vdve_version;
5067 		entryp->vve_len_expect = vdp->vdve_len_expect;
5068 		entryp->vve_len_per_item = vdp->vdve_len_per_item;
5069 		entryp++;
5070 	}
5071 	return (0);
5072 }
5073 
5074 static int
vmm_data_write_versions(void * arg,const vmm_data_req_t * req)5075 vmm_data_write_versions(void *arg, const vmm_data_req_t *req)
5076 {
5077 	/* Writing to the version information makes no sense */
5078 	return (EPERM);
5079 }
5080 
5081 static const vmm_data_version_entry_t versions_v1 = {
5082 	.vdve_class = VDC_VERSION,
5083 	.vdve_version = 1,
5084 	.vdve_len_per_item = sizeof (struct vdi_version_entry_v1),
5085 	.vdve_readf = vmm_data_read_versions,
5086 	.vdve_writef = vmm_data_write_versions,
5087 };
5088 VMM_DATA_VERSION(versions_v1);
5089 
5090 int
vmm_data_read(struct vm * vm,const vmm_data_req_t * req)5091 vmm_data_read(struct vm *vm, const vmm_data_req_t *req)
5092 {
5093 	int err = 0;
5094 
5095 	const vmm_data_version_entry_t *entry = NULL;
5096 	err = vmm_data_find(req, &entry);
5097 	if (err != 0) {
5098 		return (err);
5099 	}
5100 	ASSERT(entry != NULL);
5101 
5102 	if (entry->vdve_readf != NULL) {
5103 		void *datap = vmm_data_from_class(req, vm);
5104 
5105 		err = entry->vdve_readf(datap, req);
5106 	} else if (entry->vdve_vcpu_readf != NULL) {
5107 		err = entry->vdve_vcpu_readf(vm, req->vdr_vcpuid, req);
5108 	} else {
5109 		err = EINVAL;
5110 	}
5111 
5112 	/*
5113 	 * Successful reads of fixed-length data should populate the length of
5114 	 * that result.
5115 	 */
5116 	if (err == 0 && entry->vdve_len_expect != 0) {
5117 		*req->vdr_result_len = entry->vdve_len_expect;
5118 	}
5119 
5120 	return (err);
5121 }
5122 
5123 int
vmm_data_write(struct vm * vm,const vmm_data_req_t * req)5124 vmm_data_write(struct vm *vm, const vmm_data_req_t *req)
5125 {
5126 	int err = 0;
5127 
5128 	const vmm_data_version_entry_t *entry = NULL;
5129 	err = vmm_data_find(req, &entry);
5130 	if (err != 0) {
5131 		return (err);
5132 	}
5133 	ASSERT(entry != NULL);
5134 
5135 	if (entry->vdve_writef != NULL) {
5136 		void *datap = vmm_data_from_class(req, vm);
5137 
5138 		err = entry->vdve_writef(datap, req);
5139 	} else if (entry->vdve_vcpu_writef != NULL) {
5140 		err = entry->vdve_vcpu_writef(vm, req->vdr_vcpuid, req);
5141 	} else {
5142 		err = EINVAL;
5143 	}
5144 
5145 	/*
5146 	 * Successful writes of fixed-length data should populate the length of
5147 	 * that result.
5148 	 */
5149 	if (err == 0 && entry->vdve_len_expect != 0) {
5150 		*req->vdr_result_len = entry->vdve_len_expect;
5151 	}
5152 
5153 	return (err);
5154 }
5155