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