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