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