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