svm.c revision 284894
11541Srgrimes/*-
21541Srgrimes * Copyright (c) 2013, Anish Gupta (akgupt3@gmail.com)
31541Srgrimes * All rights reserved.
41541Srgrimes *
551138Salfred * Redistribution and use in source and binary forms, with or without
61541Srgrimes * modification, are permitted provided that the following conditions
71541Srgrimes * are met:
8106149Sdwmalone * 1. Redistributions of source code must retain the above copyright
91541Srgrimes *    notice unmodified, this list of conditions, and the following
1064002Speter *    disclaimer.
111541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
121541Srgrimes *    notice, this list of conditions and the following disclaimer in the
131541Srgrimes *    documentation and/or other materials provided with the distribution.
141541Srgrimes *
151541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
161541Srgrimes * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17171210Speter * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
181541Srgrimes * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
191541Srgrimes * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
201541Srgrimes * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
211541Srgrimes * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
221541Srgrimes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
231541Srgrimes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
241541Srgrimes * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
251541Srgrimes */
261541Srgrimes
27194392Sjhb#include <sys/cdefs.h>
28171210Speter__FBSDID("$FreeBSD: stable/10/sys/amd64/vmm/amd/svm.c 284894 2015-06-27 22:48:22Z neel $");
291541Srgrimes
301541Srgrimes#include <sys/param.h>
311541Srgrimes#include <sys/systm.h>
321541Srgrimes#include <sys/smp.h>
331541Srgrimes#include <sys/kernel.h>
341541Srgrimes#include <sys/malloc.h>
351541Srgrimes#include <sys/pcpu.h>
361541Srgrimes#include <sys/proc.h>
371541Srgrimes#include <sys/sysctl.h>
381541Srgrimes
391541Srgrimes#include <vm/vm.h>
401541Srgrimes#include <vm/pmap.h>
411541Srgrimes
421541Srgrimes#include <machine/cpufunc.h>
431541Srgrimes#include <machine/psl.h>
441541Srgrimes#include <machine/pmap.h>
451541Srgrimes#include <machine/md_var.h>
461541Srgrimes#include <machine/specialreg.h>
47171210Speter#include <machine/smp.h>
481541Srgrimes#include <machine/vmm.h>
49171210Speter#include <machine/vmm_dev.h>
501541Srgrimes#include <machine/vmm_instruction_emul.h>
511541Srgrimes
521541Srgrimes#include "vmm_lapic.h"
531541Srgrimes#include "vmm_stat.h"
541541Srgrimes#include "vmm_ktr.h"
55171210Speter#include "vmm_ioport.h"
561541Srgrimes#include "vatpic.h"
57171210Speter#include "vlapic.h"
581541Srgrimes#include "vlapic_priv.h"
591541Srgrimes
601541Srgrimes#include "x86.h"
61171210Speter#include "vmcb.h"
621541Srgrimes#include "svm.h"
631541Srgrimes#include "svm_softc.h"
641541Srgrimes#include "svm_msr.h"
651541Srgrimes#include "npt.h"
661541Srgrimes
671541SrgrimesSYSCTL_DECL(_hw_vmm);
681541SrgrimesSYSCTL_NODE(_hw_vmm, OID_AUTO, svm, CTLFLAG_RW, NULL, NULL);
691541Srgrimes
701541Srgrimes/*
71171210Speter * SVM CPUID function 0x8000_000A, edx bit decoding.
72171210Speter */
73171210Speter#define AMD_CPUID_SVM_NP		BIT(0)  /* Nested paging or RVI */
741541Srgrimes#define AMD_CPUID_SVM_LBR		BIT(1)  /* Last branch virtualization */
751541Srgrimes#define AMD_CPUID_SVM_SVML		BIT(2)  /* SVM lock */
761541Srgrimes#define AMD_CPUID_SVM_NRIP_SAVE		BIT(3)  /* Next RIP is saved */
771541Srgrimes#define AMD_CPUID_SVM_TSC_RATE		BIT(4)  /* TSC rate control. */
781541Srgrimes#define AMD_CPUID_SVM_VMCB_CLEAN	BIT(5)  /* VMCB state caching */
791541Srgrimes#define AMD_CPUID_SVM_FLUSH_BY_ASID	BIT(6)  /* Flush by ASID */
80171210Speter#define AMD_CPUID_SVM_DECODE_ASSIST	BIT(7)  /* Decode assist */
811541Srgrimes#define AMD_CPUID_SVM_PAUSE_INC		BIT(10) /* Pause intercept filter. */
821541Srgrimes#define AMD_CPUID_SVM_PAUSE_FTH		BIT(12) /* Pause filter threshold */
831541Srgrimes#define	AMD_CPUID_SVM_AVIC		BIT(13)	/* AVIC present */
841541Srgrimes
851541Srgrimes#define	VMCB_CACHE_DEFAULT	(VMCB_CACHE_ASID 	|	\
861541Srgrimes				VMCB_CACHE_IOPM		|	\
871541Srgrimes				VMCB_CACHE_I		|	\
881541Srgrimes				VMCB_CACHE_TPR		|	\
891541Srgrimes				VMCB_CACHE_CR2		|	\
901541Srgrimes				VMCB_CACHE_CR		|	\
911541Srgrimes				VMCB_CACHE_DT		|	\
921541Srgrimes				VMCB_CACHE_SEG		|	\
93171210Speter				VMCB_CACHE_NP)
941541Srgrimes
951541Srgrimesstatic uint32_t vmcb_clean = VMCB_CACHE_DEFAULT;
96171210SpeterSYSCTL_INT(_hw_vmm_svm, OID_AUTO, vmcb_clean, CTLFLAG_RDTUN, &vmcb_clean,
97171210Speter    0, NULL);
981541Srgrimes
991541Srgrimesstatic MALLOC_DEFINE(M_SVM, "svm", "svm");
1001541Srgrimesstatic MALLOC_DEFINE(M_SVM_VLAPIC, "svm-vlapic", "svm-vlapic");
1011541Srgrimes
1021541Srgrimes/* Per-CPU context area. */
1031541Srgrimesextern struct pcpu __pcpu[];
1041541Srgrimes
1051541Srgrimesstatic uint32_t svm_feature;	/* AMD SVM features. */
1061541SrgrimesSYSCTL_UINT(_hw_vmm_svm, OID_AUTO, features, CTLFLAG_RD, &svm_feature, 0,
1071541Srgrimes    "SVM features advertised by CPUID.8000000AH:EDX");
108171210Speter
1091541Srgrimesstatic int disable_npf_assist;
110171210SpeterSYSCTL_INT(_hw_vmm_svm, OID_AUTO, disable_npf_assist, CTLFLAG_RWTUN,
111171210Speter    &disable_npf_assist, 0, NULL);
112171210Speter
1131541Srgrimes/* Maximum ASIDs supported by the processor */
1141541Srgrimesstatic uint32_t nasid;
1151541SrgrimesSYSCTL_UINT(_hw_vmm_svm, OID_AUTO, num_asids, CTLFLAG_RD, &nasid, 0,
1161541Srgrimes    "Number of ASIDs supported by this processor");
117171210Speter
118171210Speter/* Current ASID generation for each host cpu */
119171210Speterstatic struct asid asid[MAXCPU];
120171210Speter
121171210Speter/*
122171210Speter * SVM host state saved area of size 4KB for each core.
123171210Speter */
1241541Srgrimesstatic uint8_t hsave[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
1251541Srgrimes
1261541Srgrimesstatic VMM_STAT_AMD(VCPU_EXITINTINFO, "VM exits during event delivery");
1271541Srgrimesstatic VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "Events pending at VM entry");
12814220Speterstatic VMM_STAT_AMD(VMEXIT_VINTR, "VM exits due to interrupt window");
1291541Srgrimes
1301541Srgrimesstatic int svm_setreg(void *arg, int vcpu, int ident, uint64_t val);
1311541Srgrimes
1321541Srgrimesstatic __inline int
1331541Srgrimesflush_by_asid(void)
134171210Speter{
1358019Sache
1368019Sache	return (svm_feature & AMD_CPUID_SVM_FLUSH_BY_ASID);
1371541Srgrimes}
138171210Speter
139171210Speterstatic __inline int
1401541Srgrimesdecode_assist(void)
1411541Srgrimes{
1421541Srgrimes
1431541Srgrimes	return (svm_feature & AMD_CPUID_SVM_DECODE_ASSIST);
1441541Srgrimes}
1451541Srgrimes
1461541Srgrimesstatic void
1471541Srgrimessvm_disable(void *arg __unused)
1481541Srgrimes{
1491541Srgrimes	uint64_t efer;
150171210Speter
151171210Speter	efer = rdmsr(MSR_EFER);
152171210Speter	efer &= ~EFER_SVM;
153171210Speter	wrmsr(MSR_EFER, efer);
154171210Speter}
155171210Speter
1561541Srgrimes/*
1571541Srgrimes * Disable SVM on all CPUs.
158171210Speter */
159171210Speterstatic int
16014220Spetersvm_cleanup(void)
16114220Speter{
16214220Speter
163177634Sdfr	smp_rendezvous(NULL, svm_disable, NULL, NULL);
1641541Srgrimes	return (0);
165171210Speter}
166194392Sjhb
167194392Sjhb/*
1681541Srgrimes * Verify that all the features required by bhyve are available.
169127891Sdfr */
1701541Srgrimesstatic int
171194392Sjhbcheck_svm_features(void)
172194392Sjhb{
173194392Sjhb	u_int regs[4];
1741549Srgrimes
1752442Sdg	/* CPUID Fn8000_000A is for SVM */
1761541Srgrimes	do_cpuid(0x8000000A, regs);
1771541Srgrimes	svm_feature = regs[3];
1782729Sdfr
1792729Sdfr	nasid = regs[1];
1801541Srgrimes	KASSERT(nasid > 1, ("Insufficient ASIDs for guests: %#x", nasid));
1811541Srgrimes
182171210Speter	/* bhyve requires the Nested Paging feature */
183171210Speter	if (!(svm_feature & AMD_CPUID_SVM_NP)) {
184178888Sjulian		printf("SVM: Nested Paging feature not available.\n");
1852297Swollman		return (ENXIO);
18614220Speter	}
18714220Speter
18814220Speter	/* bhyve requires the NRIP Save feature */
1891541Srgrimes	if (!(svm_feature & AMD_CPUID_SVM_NRIP_SAVE)) {
1901541Srgrimes		printf("SVM: NRIP Save feature not available.\n");
1911541Srgrimes		return (ENXIO);
1921541Srgrimes	}
19332889Sphk
19432889Sphk	return (0);
19532889Sphk}
19632889Sphk
1971541Srgrimesstatic void
1981541Srgrimessvm_enable(void *arg __unused)
1991541Srgrimes{
2001541Srgrimes	uint64_t efer;
2011541Srgrimes
2021541Srgrimes	efer = rdmsr(MSR_EFER);
2031541Srgrimes	efer |= EFER_SVM;
2041541Srgrimes	wrmsr(MSR_EFER, efer);
2051541Srgrimes
206171210Speter	wrmsr(MSR_VM_HSAVE_PA, vtophys(hsave[curcpu]));
2071541Srgrimes}
208171210Speter
209171210Speter/*
210171210Speter * Return 1 if SVM is enabled on this processor and 0 otherwise.
2111541Srgrimes */
2121541Srgrimesstatic int
2131541Srgrimessvm_available(void)
21435938Sdyson{
21535938Sdyson	uint64_t msr;
21628400Speter
21725582Speter	/* Section 15.4 Enabling SVM from APM2. */
21829349Speter	if ((amd_feature2 & AMDID2_SVM) == 0) {
2192124Sdg		printf("SVM: not available.\n");
2202124Sdg		return (0);
2212124Sdg	}
2222124Sdg
2232124Sdg	msr = rdmsr(MSR_VM_CR);
2242124Sdg	if ((msr & VM_CR_SVMDIS) != 0) {
2252124Sdg		printf("SVM: disabled by BIOS.\n");
2262124Sdg		return (0);
2272124Sdg	}
2282124Sdg
229194919Sjhb	return (1);
23012865Speter}
23112865Speter
23259829Speterstatic int
233194919Sjhbsvm_init(int ipinum)
23412865Speter{
23512865Speter	int error, cpu;
23612865Speter
23712865Speter	if (!svm_available())
238194919Sjhb		return (ENXIO);
23912865Speter
24012865Speter	error = check_svm_features();
24125582Speter	if (error)
24225582Speter		return (error);
24325582Speter
244156138Sdavidxu	vmcb_clean &= VMCB_CACHE_DEFAULT;
245156138Sdavidxu
246156138Sdavidxu	for (cpu = 0; cpu < MAXCPU; cpu++) {
247156138Sdavidxu		/*
248156138Sdavidxu		 * Initialize the host ASIDs to their "highest" valid values.
24925582Speter		 *
250227776Slstewart		 * The next ASID allocation will rollover both 'gen' and 'num'
251227776Slstewart		 * and start off the sequence at {1,1}.
252227776Slstewart		 */
25314220Speter		asid[cpu].gen = ~0UL;
25414220Speter		asid[cpu].num = nasid - 1;
25514220Speter	}
256239347Sdavidxu
257137875Smarks	svm_msr_init();
25814220Speter	svm_npt_init(ipinum);
25914220Speter
26014220Speter	/* Enable SVM on all CPUs */
26129349Speter	smp_rendezvous(NULL, svm_enable, NULL, NULL);
26224452Speter
26324440Speter	return (0);
264151868Sdavidxu}
265151868Sdavidxu
266151868Sdavidxustatic void
267152846Sdavidxusvm_restore(void)
268152846Sdavidxu{
269152846Sdavidxu
270152846Sdavidxu	svm_enable(NULL);
271152846Sdavidxu}
272152846Sdavidxu
27325537Sdfr/* Pentium compatible MSRs */
27425537Sdfr#define MSR_PENTIUM_START 	0
27525537Sdfr#define MSR_PENTIUM_END 	0x1FFF
27625537Sdfr/* AMD 6th generation and Intel compatible MSRs */
27725537Sdfr#define MSR_AMD6TH_START 	0xC0000000UL
27825537Sdfr#define MSR_AMD6TH_END 		0xC0001FFFUL
27925537Sdfr/* AMD 7th and 8th generation compatible MSRs */
28025537Sdfr#define MSR_AMD7TH_START 	0xC0010000UL
28135938Sdyson#define MSR_AMD7TH_END 		0xC0011FFFUL
28225537Sdfr
28335938Sdyson/*
28435938Sdyson * Get the index and bit position for a MSR in permission bitmap.
28535938Sdyson * Two bits are used for each MSR: lower bit for read and higher bit for write.
28635938Sdyson */
28735938Sdysonstatic int
28835938Sdysonsvm_msr_index(uint64_t msr, int *index, int *bit)
28935938Sdyson{
29025537Sdfr	uint32_t base, off;
29125537Sdfr
29225537Sdfr	*index = -1;
29325537Sdfr	*bit = (msr % 4) * 2;
29425537Sdfr	base = 0;
29525537Sdfr
29625537Sdfr	if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
29725537Sdfr		*index = msr / 4;
298147814Sjhb		return (0);
299147814Sjhb	}
30025537Sdfr
30125537Sdfr	base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
30225537Sdfr	if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
30325537Sdfr		off = (msr - MSR_AMD6TH_START);
30425537Sdfr		*index = (off + base) / 4;
30525537Sdfr		return (0);
306194392Sjhb	}
30751138Salfred
30851138Salfred	base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
30925537Sdfr	if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
31025537Sdfr		off = (msr - MSR_AMD7TH_START);
31125537Sdfr		*index = (off + base) / 4;
31225537Sdfr		return (0);
31325537Sdfr	}
31425537Sdfr
31525537Sdfr	return (EINVAL);
31625537Sdfr}
31725537Sdfr
31825537Sdfr/*
31928400Speter * Allow vcpu to read or write the 'msr' without trapping into the hypervisor.
32056115Speter */
32156115Speterstatic void
32236034Spetersvm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
32326671Sdyson{
32426671Sdyson	int index, bit, error;
32526671Sdyson
32626671Sdyson	error = svm_msr_index(msr, &index, &bit);
327151868Sdavidxu	KASSERT(error == 0, ("%s: invalid msr %#lx", __func__, msr));
328151868Sdavidxu	KASSERT(index >= 0 && index < SVM_MSR_BITMAP_SIZE,
329151868Sdavidxu	    ("%s: invalid index %d for msr %#lx", __func__, index, msr));
33026671Sdyson	KASSERT(bit >= 0 && bit <= 6, ("%s: invalid bit position %d "
33169514Sjake	    "msr %#lx", __func__, bit, msr));
33269514Sjake
33326671Sdyson	if (read)
33426671Sdyson		perm_bitmap[index] &= ~(1UL << bit);
33529391Sphk
33634925Sdufault	if (write)
33734925Sdufault		perm_bitmap[index] &= ~(2UL << bit);
33834925Sdufault}
33934925Sdufault
34034925Sdufaultstatic void
34134925Sdufaultsvm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
34234925Sdufault{
34334925Sdufault
34435938Sdyson	svm_msr_perm(perm_bitmap, msr, true, true);
345194392Sjhb}
34641089Speter
34746155Sphkstatic void
348211999Skibsvm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
34951791Smarcel{
35051791Smarcel
351194392Sjhb	svm_msr_perm(perm_bitmap, msr, true, false);
35251791Smarcel}
353194392Sjhb
354112895Sjeffstatic __inline int
355112895Sjeffsvm_get_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask)
35656271Srwatson{
35756271Srwatson	struct vmcb_ctrl *ctrl;
35856271Srwatson
35956271Srwatson	KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
36056271Srwatson
36156271Srwatson	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
36256271Srwatson	return (ctrl->intercept[idx] & bitmask ? 1 : 0);
36356271Srwatson}
36454803Srwatson
36554803Srwatsonstatic __inline void
36654803Srwatsonsvm_set_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask,
36754803Srwatson    int enabled)
36855943Sjasone{
36956115Speter	struct vmcb_ctrl *ctrl;
37056115Speter	uint32_t oldval;
37159288Sjlemon
37259288Sjlemon	KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
37398198Srwatson
37498198Srwatson	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
37598198Srwatson	oldval = ctrl->intercept[idx];
37698198Srwatson
37798198Srwatson	if (enabled)
37898198Srwatson		ctrl->intercept[idx] |= bitmask;
379183362Sjhb	else
38075039Srwatson		ctrl->intercept[idx] &= ~bitmask;
38175039Srwatson
38275039Srwatson	if (ctrl->intercept[idx] != oldval) {
38375427Srwatson		svm_set_dirty(sc, vcpu, VMCB_CACHE_I);
384194392Sjhb		VCPU_CTR3(sc->vm, vcpu, "intercept[%d] modified "
38583796Srwatson		    "from %#x to %#x", idx, oldval, ctrl->intercept[idx]);
386211999Skib	}
38785891Sphk}
388177091Sjeff
389177091Sjeffstatic __inline void
390177091Sjeffsvm_disable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
391177091Sjeff{
392177091Sjeff
393100897Srwatson	svm_set_intercept(sc, vcpu, off, bitmask, 0);
394100897Srwatson}
395100897Srwatson
396100897Srwatsonstatic __inline void
397100897Srwatsonsvm_enable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
398100897Srwatson{
39994936Smux
40096084Smux	svm_set_intercept(sc, vcpu, off, bitmask, 1);
40197372Smarcel}
40299856Salfred
403101426Srwatsonstatic void
404122540Smckusickvmcb_init(struct svm_softc *sc, int vcpu, uint64_t iopm_base_pa,
405122540Smckusick    uint64_t msrpm_base_pa, uint64_t np_pml4)
406122540Smckusick{
407122540Smckusick	struct vmcb_ctrl *ctrl;
408103575Salfred	struct vmcb_state *state;
409103575Salfred	uint32_t mask;
410103575Salfred	int n;
411103575Salfred
412103575Salfred	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
413103575Salfred	state = svm_get_vmcb_state(sc, vcpu);
414103575Salfred
415103575Salfred	ctrl->iopm_base_pa = iopm_base_pa;
416103575Salfred	ctrl->msrpm_base_pa = msrpm_base_pa;
417103575Salfred
418105692Srwatson	/* Enable nested paging */
419105692Srwatson	ctrl->np_enable = 1;
420105692Srwatson	ctrl->n_cr3 = np_pml4;
421104731Srwatson
422104731Srwatson	/*
423104731Srwatson	 * Intercept accesses to the control registers that are not shadowed
424106467Srwatson	 * in the VMCB - i.e. all except cr0, cr2, cr3, cr4 and cr8.
425105950Speter	 */
426105950Speter	for (n = 0; n < 16; n++) {
427105692Srwatson		mask = (BIT(n) << 16) | BIT(n);
428105692Srwatson		if (n == 0 || n == 2 || n == 3 || n == 4 || n == 8)
429105692Srwatson			svm_disable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
430106978Sdeischen		else
431106978Sdeischen			svm_enable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
432106978Sdeischen	}
433107914Sdillon
434108406Srwatson
435108406Srwatson	/*
436108406Srwatson	 * Intercept everything when tracing guest exceptions otherwise
437108406Srwatson	 * just intercept machine check exception.
438112895Sjeff	 */
439112902Sjeff	if (vcpu_trace_exceptions(sc->vm, vcpu)) {
440112902Sjeff		for (n = 0; n < 32; n++) {
441112902Sjeff			/*
442112902Sjeff			 * Skip unimplemented vectors in the exception bitmap.
443112909Sjeff			 */
444112909Sjeff			if (n == 2 || n == 9) {
445113276Smike				continue;
446115800Srwatson			}
447115800Srwatson			svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(n));
448115800Srwatson		}
449177091Sjeff	} else {
450125369Sdeischen		svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(IDT_MC));
451127484Smtm	}
452127484Smtm
453132117Sphk	/* Intercept various events (for e.g. I/O, MSR and CPUID accesses) */
454136831Srwatson	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IO);
455136831Srwatson	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_MSR);
456136831Srwatson	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_CPUID);
457136831Srwatson	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INTR);
458136831Srwatson	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INIT);
459136831Srwatson	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_NMI);
460136831Srwatson	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SMI);
461136831Srwatson	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SHUTDOWN);
462136831Srwatson	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
463139013Sdavidxu	    VMCB_INTCPT_FERR_FREEZE);
464145435Sdavidxu
465151317Sdavidxu	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MONITOR);
466156138Sdavidxu	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_MWAIT);
467156138Sdavidxu
468156138Sdavidxu	/*
469156138Sdavidxu	 * From section "Canonicalization and Consistency Checks" in APMv2
470156138Sdavidxu	 * the VMRUN intercept bit must be set to pass the consistency check.
471156138Sdavidxu	 */
472153681Sphk	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMRUN);
473155328Sdavidxu
474157039Sdavidxu	/*
475162498Sdavidxu	 * The ASID will be set to a non-zero value just before VMRUN.
476162498Sdavidxu	 */
477162498Sdavidxu	ctrl->asid = 0;
478161679Sdavidxu
479161679Sdavidxu	/*
480163953Srrs	 * Section 15.21.1, Interrupt Masking in EFLAGS
481163953Srrs	 * Section 15.21.2, Virtualizing APIC.TPR
482163953Srrs	 *
483163953Srrs	 * This must be set for %rflag and %cr8 isolation of guest and host.
484171210Speter	 */
485171210Speter	ctrl->v_intr_masking = 1;
486171210Speter
487171210Speter	/* Enable Last Branch Record aka LBR for debugging */
488171210Speter	ctrl->lbr_virt_en = 1;
489171210Speter	state->dbgctl = BIT(0);
490171861Sdavidxu
491175165Sjhb	/* EFER_SVM must always be set when the guest is executing */
492175165Sjhb	state->efer = EFER_SVM;
493176731Sjeff
494176731Sjeff	/* Set up the PAT to power-on state */
495176731Sjeff	state->g_pat = PAT_VALUE(0, PAT_WRITE_BACK)	|
496176731Sjeff	    PAT_VALUE(1, PAT_WRITE_THROUGH)	|
497176731Sjeff	    PAT_VALUE(2, PAT_UNCACHED)		|
498177790Skib	    PAT_VALUE(3, PAT_UNCACHEABLE)	|
499177790Skib	    PAT_VALUE(4, PAT_WRITE_BACK)	|
500177790Skib	    PAT_VALUE(5, PAT_WRITE_THROUGH)	|
501177790Skib	    PAT_VALUE(6, PAT_UNCACHED)		|
502177790Skib	    PAT_VALUE(7, PAT_UNCACHEABLE);
503177790Skib}
504177790Skib
505177790Skib/*
506177790Skib * Initialize a virtual machine.
507177790Skib */
508177790Skibstatic void *
509177790Skibsvm_vminit(struct vm *vm, pmap_t pmap)
510177790Skib{
511177790Skib	struct svm_softc *svm_sc;
512177790Skib	struct svm_vcpu *vcpu;
513181905Sed	vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
514184589Sdfr	int i;
515191675Sjamie
516191675Sjamie	svm_sc = malloc(sizeof (struct svm_softc), M_SVM, M_WAITOK | M_ZERO);
517191675Sjamie	svm_sc->vm = vm;
518194263Sjhb	svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
519194919Sjhb
520194919Sjhb	/*
521194919Sjhb	 * Intercept read and write accesses to all MSRs.
522195459Strasz	 */
523255220Spjd	memset(svm_sc->msr_bitmap, 0xFF, sizeof(svm_sc->msr_bitmap));
524255220Spjd
525219132Srwatson	/*
526219132Srwatson	 * Access to the following MSRs is redirected to the VMCB when the
527224988Sjonathan	 * guest is executing. Therefore it is safe to allow the guest to
528224988Sjonathan	 * read/write these MSRs directly without hypervisor involvement.
529224988Sjonathan	 */
530224988Sjonathan	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
531198510Skib	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
532219305Strasz	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
533219305Strasz
534220164Strasz	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
535220164Strasz	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
536220164Strasz	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
537220164Strasz	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
538220164Strasz	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
539220792Smdf	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
540227071Sjhb	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
541242959Skib	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
542247604Spjd
543247604Spjd	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
544247604Spjd
545247604Spjd	/*
546247604Spjd	 * Intercept writes to make sure that the EFER_SVM bit is not cleared.
547247668Spjd	 */
548247668Spjd	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
549248600Spjd
550250155Sjilles	/* Intercept access to all I/O ports. */
551250160Sjilles	memset(svm_sc->iopm_bitmap, 0xFF, sizeof(svm_sc->iopm_bitmap));
552251527Sglebius
553255709Sjhb	iopm_pa = vtophys(svm_sc->iopm_bitmap);
554275987Sdchagin	msrpm_pa = vtophys(svm_sc->msr_bitmap);
555293475Sdchagin	pml4_pa = svm_sc->nptp;
556293475Sdchagin	for (i = 0; i < VM_MAXCPU; i++) {
5571541Srgrimes		vcpu = svm_get_vcpu(svm_sc, i);
558		vcpu->nextrip = ~0;
559		vcpu->lastcpu = NOCPU;
560		vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
561		vmcb_init(svm_sc, i, iopm_pa, msrpm_pa, pml4_pa);
562		svm_msr_guest_init(svm_sc, i);
563	}
564	return (svm_sc);
565}
566
567static int
568svm_cpl(struct vmcb_state *state)
569{
570
571	/*
572	 * From APMv2:
573	 *   "Retrieve the CPL from the CPL field in the VMCB, not
574	 *    from any segment DPL"
575	 */
576	return (state->cpl);
577}
578
579static enum vm_cpu_mode
580svm_vcpu_mode(struct vmcb *vmcb)
581{
582	struct vmcb_segment seg;
583	struct vmcb_state *state;
584	int error;
585
586	state = &vmcb->state;
587
588	if (state->efer & EFER_LMA) {
589		error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
590		KASSERT(error == 0, ("%s: vmcb_seg(cs) error %d", __func__,
591		    error));
592
593		/*
594		 * Section 4.8.1 for APM2, check if Code Segment has
595		 * Long attribute set in descriptor.
596		 */
597		if (seg.attrib & VMCB_CS_ATTRIB_L)
598			return (CPU_MODE_64BIT);
599		else
600			return (CPU_MODE_COMPATIBILITY);
601	} else  if (state->cr0 & CR0_PE) {
602		return (CPU_MODE_PROTECTED);
603	} else {
604		return (CPU_MODE_REAL);
605	}
606}
607
608static enum vm_paging_mode
609svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
610{
611
612	if ((cr0 & CR0_PG) == 0)
613		return (PAGING_MODE_FLAT);
614	if ((cr4 & CR4_PAE) == 0)
615		return (PAGING_MODE_32);
616	if (efer & EFER_LME)
617		return (PAGING_MODE_64);
618	else
619		return (PAGING_MODE_PAE);
620}
621
622/*
623 * ins/outs utility routines
624 */
625static uint64_t
626svm_inout_str_index(struct svm_regctx *regs, int in)
627{
628	uint64_t val;
629
630	val = in ? regs->sctx_rdi : regs->sctx_rsi;
631
632	return (val);
633}
634
635static uint64_t
636svm_inout_str_count(struct svm_regctx *regs, int rep)
637{
638	uint64_t val;
639
640	val = rep ? regs->sctx_rcx : 1;
641
642	return (val);
643}
644
645static void
646svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
647    int in, struct vm_inout_str *vis)
648{
649	int error, s;
650
651	if (in) {
652		vis->seg_name = VM_REG_GUEST_ES;
653	} else {
654		/* The segment field has standard encoding */
655		s = (info1 >> 10) & 0x7;
656		vis->seg_name = vm_segment_name(s);
657	}
658
659	error = vmcb_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
660	KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
661}
662
663static int
664svm_inout_str_addrsize(uint64_t info1)
665{
666        uint32_t size;
667
668        size = (info1 >> 7) & 0x7;
669        switch (size) {
670        case 1:
671                return (2);     /* 16 bit */
672        case 2:
673                return (4);     /* 32 bit */
674        case 4:
675                return (8);     /* 64 bit */
676        default:
677                panic("%s: invalid size encoding %d", __func__, size);
678        }
679}
680
681static void
682svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
683{
684	struct vmcb_state *state;
685
686	state = &vmcb->state;
687	paging->cr3 = state->cr3;
688	paging->cpl = svm_cpl(state);
689	paging->cpu_mode = svm_vcpu_mode(vmcb);
690	paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
691	    state->efer);
692}
693
694#define	UNHANDLED 0
695
696/*
697 * Handle guest I/O intercept.
698 */
699static int
700svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
701{
702	struct vmcb_ctrl *ctrl;
703	struct vmcb_state *state;
704	struct svm_regctx *regs;
705	struct vm_inout_str *vis;
706	uint64_t info1;
707	int inout_string;
708
709	state = svm_get_vmcb_state(svm_sc, vcpu);
710	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
711	regs  = svm_get_guest_regctx(svm_sc, vcpu);
712
713	info1 = ctrl->exitinfo1;
714	inout_string = info1 & BIT(2) ? 1 : 0;
715
716	/*
717	 * The effective segment number in EXITINFO1[12:10] is populated
718	 * only if the processor has the DecodeAssist capability.
719	 *
720	 * XXX this is not specified explicitly in APMv2 but can be verified
721	 * empirically.
722	 */
723	if (inout_string && !decode_assist())
724		return (UNHANDLED);
725
726	vmexit->exitcode 	= VM_EXITCODE_INOUT;
727	vmexit->u.inout.in 	= (info1 & BIT(0)) ? 1 : 0;
728	vmexit->u.inout.string 	= inout_string;
729	vmexit->u.inout.rep 	= (info1 & BIT(3)) ? 1 : 0;
730	vmexit->u.inout.bytes 	= (info1 >> 4) & 0x7;
731	vmexit->u.inout.port 	= (uint16_t)(info1 >> 16);
732	vmexit->u.inout.eax 	= (uint32_t)(state->rax);
733
734	if (inout_string) {
735		vmexit->exitcode = VM_EXITCODE_INOUT_STR;
736		vis = &vmexit->u.inout_str;
737		svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
738		vis->rflags = state->rflags;
739		vis->cr0 = state->cr0;
740		vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
741		vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
742		vis->addrsize = svm_inout_str_addrsize(info1);
743		svm_inout_str_seginfo(svm_sc, vcpu, info1,
744		    vmexit->u.inout.in, vis);
745	}
746
747	return (UNHANDLED);
748}
749
750static int
751npf_fault_type(uint64_t exitinfo1)
752{
753
754	if (exitinfo1 & VMCB_NPF_INFO1_W)
755		return (VM_PROT_WRITE);
756	else if (exitinfo1 & VMCB_NPF_INFO1_ID)
757		return (VM_PROT_EXECUTE);
758	else
759		return (VM_PROT_READ);
760}
761
762static bool
763svm_npf_emul_fault(uint64_t exitinfo1)
764{
765
766	if (exitinfo1 & VMCB_NPF_INFO1_ID) {
767		return (false);
768	}
769
770	if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
771		return (false);
772	}
773
774	if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
775		return (false);
776	}
777
778	return (true);
779}
780
781static void
782svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
783{
784	struct vm_guest_paging *paging;
785	struct vmcb_segment seg;
786	struct vmcb_ctrl *ctrl;
787	char *inst_bytes;
788	int error, inst_len;
789
790	ctrl = &vmcb->ctrl;
791	paging = &vmexit->u.inst_emul.paging;
792
793	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
794	vmexit->u.inst_emul.gpa = gpa;
795	vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
796	svm_paging_info(vmcb, paging);
797
798	error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
799	KASSERT(error == 0, ("%s: vmcb_seg(CS) error %d", __func__, error));
800
801	switch(paging->cpu_mode) {
802	case CPU_MODE_PROTECTED:
803	case CPU_MODE_COMPATIBILITY:
804		/*
805		 * Section 4.8.1 of APM2, Default Operand Size or D bit.
806		 */
807		vmexit->u.inst_emul.cs_d = (seg.attrib & VMCB_CS_ATTRIB_D) ?
808		    1 : 0;
809		break;
810	default:
811		vmexit->u.inst_emul.cs_d = 0;
812		break;
813	}
814
815	/*
816	 * Copy the instruction bytes into 'vie' if available.
817	 */
818	if (decode_assist() && !disable_npf_assist) {
819		inst_len = ctrl->inst_len;
820		inst_bytes = ctrl->inst_bytes;
821	} else {
822		inst_len = 0;
823		inst_bytes = NULL;
824	}
825	vie_init(&vmexit->u.inst_emul.vie, inst_bytes, inst_len);
826}
827
828#ifdef KTR
829static const char *
830intrtype_to_str(int intr_type)
831{
832	switch (intr_type) {
833	case VMCB_EVENTINJ_TYPE_INTR:
834		return ("hwintr");
835	case VMCB_EVENTINJ_TYPE_NMI:
836		return ("nmi");
837	case VMCB_EVENTINJ_TYPE_INTn:
838		return ("swintr");
839	case VMCB_EVENTINJ_TYPE_EXCEPTION:
840		return ("exception");
841	default:
842		panic("%s: unknown intr_type %d", __func__, intr_type);
843	}
844}
845#endif
846
847/*
848 * Inject an event to vcpu as described in section 15.20, "Event injection".
849 */
850static void
851svm_eventinject(struct svm_softc *sc, int vcpu, int intr_type, int vector,
852		 uint32_t error, bool ec_valid)
853{
854	struct vmcb_ctrl *ctrl;
855
856	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
857
858	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0,
859	    ("%s: event already pending %#lx", __func__, ctrl->eventinj));
860
861	KASSERT(vector >=0 && vector <= 255, ("%s: invalid vector %d",
862	    __func__, vector));
863
864	switch (intr_type) {
865	case VMCB_EVENTINJ_TYPE_INTR:
866	case VMCB_EVENTINJ_TYPE_NMI:
867	case VMCB_EVENTINJ_TYPE_INTn:
868		break;
869	case VMCB_EVENTINJ_TYPE_EXCEPTION:
870		if (vector >= 0 && vector <= 31 && vector != 2)
871			break;
872		/* FALLTHROUGH */
873	default:
874		panic("%s: invalid intr_type/vector: %d/%d", __func__,
875		    intr_type, vector);
876	}
877	ctrl->eventinj = vector | (intr_type << 8) | VMCB_EVENTINJ_VALID;
878	if (ec_valid) {
879		ctrl->eventinj |= VMCB_EVENTINJ_EC_VALID;
880		ctrl->eventinj |= (uint64_t)error << 32;
881		VCPU_CTR3(sc->vm, vcpu, "Injecting %s at vector %d errcode %#x",
882		    intrtype_to_str(intr_type), vector, error);
883	} else {
884		VCPU_CTR2(sc->vm, vcpu, "Injecting %s at vector %d",
885		    intrtype_to_str(intr_type), vector);
886	}
887}
888
889static void
890svm_update_virqinfo(struct svm_softc *sc, int vcpu)
891{
892	struct vm *vm;
893	struct vlapic *vlapic;
894	struct vmcb_ctrl *ctrl;
895	int pending;
896
897	vm = sc->vm;
898	vlapic = vm_lapic(vm, vcpu);
899	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
900
901	/* Update %cr8 in the emulated vlapic */
902	vlapic_set_cr8(vlapic, ctrl->v_tpr);
903
904	/*
905	 * If V_IRQ indicates that the interrupt injection attempted on then
906	 * last VMRUN was successful then update the vlapic accordingly.
907	 */
908	if (ctrl->v_intr_vector != 0) {
909		pending = ctrl->v_irq;
910		KASSERT(ctrl->v_intr_vector >= 16, ("%s: invalid "
911		    "v_intr_vector %d", __func__, ctrl->v_intr_vector));
912		KASSERT(!ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
913		VCPU_CTR2(vm, vcpu, "v_intr_vector %d %s", ctrl->v_intr_vector,
914		    pending ? "pending" : "accepted");
915		if (!pending)
916			vlapic_intr_accepted(vlapic, ctrl->v_intr_vector);
917	}
918}
919
920static void
921svm_save_intinfo(struct svm_softc *svm_sc, int vcpu)
922{
923	struct vmcb_ctrl *ctrl;
924	uint64_t intinfo;
925
926	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
927	intinfo = ctrl->exitintinfo;
928	if (!VMCB_EXITINTINFO_VALID(intinfo))
929		return;
930
931	/*
932	 * From APMv2, Section "Intercepts during IDT interrupt delivery"
933	 *
934	 * If a #VMEXIT happened during event delivery then record the event
935	 * that was being delivered.
936	 */
937	VCPU_CTR2(svm_sc->vm, vcpu, "SVM:Pending INTINFO(0x%lx), vector=%d.\n",
938		intinfo, VMCB_EXITINTINFO_VECTOR(intinfo));
939	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
940	vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
941}
942
943static __inline int
944vintr_intercept_enabled(struct svm_softc *sc, int vcpu)
945{
946
947	return (svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
948	    VMCB_INTCPT_VINTR));
949}
950
951static __inline void
952enable_intr_window_exiting(struct svm_softc *sc, int vcpu)
953{
954	struct vmcb_ctrl *ctrl;
955
956	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
957
958	if (ctrl->v_irq && ctrl->v_intr_vector == 0) {
959		KASSERT(ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
960		KASSERT(vintr_intercept_enabled(sc, vcpu),
961		    ("%s: vintr intercept should be enabled", __func__));
962		return;
963	}
964
965	VCPU_CTR0(sc->vm, vcpu, "Enable intr window exiting");
966	ctrl->v_irq = 1;
967	ctrl->v_ign_tpr = 1;
968	ctrl->v_intr_vector = 0;
969	svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
970	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
971}
972
973static __inline void
974disable_intr_window_exiting(struct svm_softc *sc, int vcpu)
975{
976	struct vmcb_ctrl *ctrl;
977
978	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
979
980	if (!ctrl->v_irq && ctrl->v_intr_vector == 0) {
981		KASSERT(!vintr_intercept_enabled(sc, vcpu),
982		    ("%s: vintr intercept should be disabled", __func__));
983		return;
984	}
985
986#ifdef KTR
987	if (ctrl->v_intr_vector == 0)
988		VCPU_CTR0(sc->vm, vcpu, "Disable intr window exiting");
989	else
990		VCPU_CTR0(sc->vm, vcpu, "Clearing V_IRQ interrupt injection");
991#endif
992	ctrl->v_irq = 0;
993	ctrl->v_intr_vector = 0;
994	svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
995	svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
996}
997
998static int
999svm_modify_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t val)
1000{
1001	struct vmcb_ctrl *ctrl;
1002	int oldval, newval;
1003
1004	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1005	oldval = ctrl->intr_shadow;
1006	newval = val ? 1 : 0;
1007	if (newval != oldval) {
1008		ctrl->intr_shadow = newval;
1009		VCPU_CTR1(sc->vm, vcpu, "Setting intr_shadow to %d", newval);
1010	}
1011	return (0);
1012}
1013
1014static int
1015svm_get_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t *val)
1016{
1017	struct vmcb_ctrl *ctrl;
1018
1019	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1020	*val = ctrl->intr_shadow;
1021	return (0);
1022}
1023
1024/*
1025 * Once an NMI is injected it blocks delivery of further NMIs until the handler
1026 * executes an IRET. The IRET intercept is enabled when an NMI is injected to
1027 * to track when the vcpu is done handling the NMI.
1028 */
1029static int
1030nmi_blocked(struct svm_softc *sc, int vcpu)
1031{
1032	int blocked;
1033
1034	blocked = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1035	    VMCB_INTCPT_IRET);
1036	return (blocked);
1037}
1038
1039static void
1040enable_nmi_blocking(struct svm_softc *sc, int vcpu)
1041{
1042
1043	KASSERT(!nmi_blocked(sc, vcpu), ("vNMI already blocked"));
1044	VCPU_CTR0(sc->vm, vcpu, "vNMI blocking enabled");
1045	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1046}
1047
1048static void
1049clear_nmi_blocking(struct svm_softc *sc, int vcpu)
1050{
1051	int error;
1052
1053	KASSERT(nmi_blocked(sc, vcpu), ("vNMI already unblocked"));
1054	VCPU_CTR0(sc->vm, vcpu, "vNMI blocking cleared");
1055	/*
1056	 * When the IRET intercept is cleared the vcpu will attempt to execute
1057	 * the "iret" when it runs next. However, it is possible to inject
1058	 * another NMI into the vcpu before the "iret" has actually executed.
1059	 *
1060	 * For e.g. if the "iret" encounters a #NPF when accessing the stack
1061	 * it will trap back into the hypervisor. If an NMI is pending for
1062	 * the vcpu it will be injected into the guest.
1063	 *
1064	 * XXX this needs to be fixed
1065	 */
1066	svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1067
1068	/*
1069	 * Set 'intr_shadow' to prevent an NMI from being injected on the
1070	 * immediate VMRUN.
1071	 */
1072	error = svm_modify_intr_shadow(sc, vcpu, 1);
1073	KASSERT(!error, ("%s: error %d setting intr_shadow", __func__, error));
1074}
1075
1076static int
1077emulate_wrmsr(struct svm_softc *sc, int vcpu, u_int num, uint64_t val,
1078    bool *retu)
1079{
1080	int error;
1081
1082	if (lapic_msr(num))
1083		error = lapic_wrmsr(sc->vm, vcpu, num, val, retu);
1084	else if (num == MSR_EFER)
1085		error = svm_setreg(sc, vcpu, VM_REG_GUEST_EFER, val);
1086	else
1087		error = svm_wrmsr(sc, vcpu, num, val, retu);
1088
1089	return (error);
1090}
1091
1092static int
1093emulate_rdmsr(struct svm_softc *sc, int vcpu, u_int num, bool *retu)
1094{
1095	struct vmcb_state *state;
1096	struct svm_regctx *ctx;
1097	uint64_t result;
1098	int error;
1099
1100	if (lapic_msr(num))
1101		error = lapic_rdmsr(sc->vm, vcpu, num, &result, retu);
1102	else
1103		error = svm_rdmsr(sc, vcpu, num, &result, retu);
1104
1105	if (error == 0) {
1106		state = svm_get_vmcb_state(sc, vcpu);
1107		ctx = svm_get_guest_regctx(sc, vcpu);
1108		state->rax = result & 0xffffffff;
1109		ctx->sctx_rdx = result >> 32;
1110	}
1111
1112	return (error);
1113}
1114
1115#ifdef KTR
1116static const char *
1117exit_reason_to_str(uint64_t reason)
1118{
1119	static char reasonbuf[32];
1120
1121	switch (reason) {
1122	case VMCB_EXIT_INVALID:
1123		return ("invalvmcb");
1124	case VMCB_EXIT_SHUTDOWN:
1125		return ("shutdown");
1126	case VMCB_EXIT_NPF:
1127		return ("nptfault");
1128	case VMCB_EXIT_PAUSE:
1129		return ("pause");
1130	case VMCB_EXIT_HLT:
1131		return ("hlt");
1132	case VMCB_EXIT_CPUID:
1133		return ("cpuid");
1134	case VMCB_EXIT_IO:
1135		return ("inout");
1136	case VMCB_EXIT_MC:
1137		return ("mchk");
1138	case VMCB_EXIT_INTR:
1139		return ("extintr");
1140	case VMCB_EXIT_NMI:
1141		return ("nmi");
1142	case VMCB_EXIT_VINTR:
1143		return ("vintr");
1144	case VMCB_EXIT_MSR:
1145		return ("msr");
1146	case VMCB_EXIT_IRET:
1147		return ("iret");
1148	case VMCB_EXIT_MONITOR:
1149		return ("monitor");
1150	case VMCB_EXIT_MWAIT:
1151		return ("mwait");
1152	default:
1153		snprintf(reasonbuf, sizeof(reasonbuf), "%#lx", reason);
1154		return (reasonbuf);
1155	}
1156}
1157#endif	/* KTR */
1158
1159/*
1160 * From section "State Saved on Exit" in APMv2: nRIP is saved for all #VMEXITs
1161 * that are due to instruction intercepts as well as MSR and IOIO intercepts
1162 * and exceptions caused by INT3, INTO and BOUND instructions.
1163 *
1164 * Return 1 if the nRIP is valid and 0 otherwise.
1165 */
1166static int
1167nrip_valid(uint64_t exitcode)
1168{
1169	switch (exitcode) {
1170	case 0x00 ... 0x0F:	/* read of CR0 through CR15 */
1171	case 0x10 ... 0x1F:	/* write of CR0 through CR15 */
1172	case 0x20 ... 0x2F:	/* read of DR0 through DR15 */
1173	case 0x30 ... 0x3F:	/* write of DR0 through DR15 */
1174	case 0x43:		/* INT3 */
1175	case 0x44:		/* INTO */
1176	case 0x45:		/* BOUND */
1177	case 0x65 ... 0x7C:	/* VMEXIT_CR0_SEL_WRITE ... VMEXIT_MSR */
1178	case 0x80 ... 0x8D:	/* VMEXIT_VMRUN ... VMEXIT_XSETBV */
1179		return (1);
1180	default:
1181		return (0);
1182	}
1183}
1184
1185/*
1186 * Collateral for a generic SVM VM-exit.
1187 */
1188static void
1189vm_exit_svm(struct vm_exit *vme, uint64_t code, uint64_t info1, uint64_t info2)
1190{
1191
1192	vme->exitcode = VM_EXITCODE_SVM;
1193	vme->u.svm.exitcode = code;
1194	vme->u.svm.exitinfo1 = info1;
1195	vme->u.svm.exitinfo2 = info2;
1196}
1197
1198static int
1199svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
1200{
1201	struct vmcb *vmcb;
1202	struct vmcb_state *state;
1203	struct vmcb_ctrl *ctrl;
1204	struct svm_regctx *ctx;
1205	uint64_t code, info1, info2, val;
1206	uint32_t eax, ecx, edx;
1207	int error, errcode_valid, handled, idtvec, reflect;
1208	bool retu;
1209
1210	ctx = svm_get_guest_regctx(svm_sc, vcpu);
1211	vmcb = svm_get_vmcb(svm_sc, vcpu);
1212	state = &vmcb->state;
1213	ctrl = &vmcb->ctrl;
1214
1215	handled = 0;
1216	code = ctrl->exitcode;
1217	info1 = ctrl->exitinfo1;
1218	info2 = ctrl->exitinfo2;
1219
1220	vmexit->exitcode = VM_EXITCODE_BOGUS;
1221	vmexit->rip = state->rip;
1222	vmexit->inst_length = nrip_valid(code) ? ctrl->nrip - state->rip : 0;
1223
1224	vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_COUNT, 1);
1225
1226	/*
1227	 * #VMEXIT(INVALID) needs to be handled early because the VMCB is
1228	 * in an inconsistent state and can trigger assertions that would
1229	 * never happen otherwise.
1230	 */
1231	if (code == VMCB_EXIT_INVALID) {
1232		vm_exit_svm(vmexit, code, info1, info2);
1233		return (0);
1234	}
1235
1236	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
1237	    "injection valid bit is set %#lx", __func__, ctrl->eventinj));
1238
1239	KASSERT(vmexit->inst_length >= 0 && vmexit->inst_length <= 15,
1240	    ("invalid inst_length %d: code (%#lx), info1 (%#lx), info2 (%#lx)",
1241	    vmexit->inst_length, code, info1, info2));
1242
1243	svm_update_virqinfo(svm_sc, vcpu);
1244	svm_save_intinfo(svm_sc, vcpu);
1245
1246	switch (code) {
1247	case VMCB_EXIT_IRET:
1248		/*
1249		 * Restart execution at "iret" but with the intercept cleared.
1250		 */
1251		vmexit->inst_length = 0;
1252		clear_nmi_blocking(svm_sc, vcpu);
1253		handled = 1;
1254		break;
1255	case VMCB_EXIT_VINTR:	/* interrupt window exiting */
1256		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_VINTR, 1);
1257		handled = 1;
1258		break;
1259	case VMCB_EXIT_INTR:	/* external interrupt */
1260		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
1261		handled = 1;
1262		break;
1263	case VMCB_EXIT_NMI:	/* external NMI */
1264		handled = 1;
1265		break;
1266	case 0x40 ... 0x5F:
1267		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXCEPTION, 1);
1268		reflect = 1;
1269		idtvec = code - 0x40;
1270		switch (idtvec) {
1271		case IDT_MC:
1272			/*
1273			 * Call the machine check handler by hand. Also don't
1274			 * reflect the machine check back into the guest.
1275			 */
1276			reflect = 0;
1277			VCPU_CTR0(svm_sc->vm, vcpu, "Vectoring to MCE handler");
1278			__asm __volatile("int $18");
1279			break;
1280		case IDT_PF:
1281			error = svm_setreg(svm_sc, vcpu, VM_REG_GUEST_CR2,
1282			    info2);
1283			KASSERT(error == 0, ("%s: error %d updating cr2",
1284			    __func__, error));
1285			/* fallthru */
1286		case IDT_NP:
1287		case IDT_SS:
1288		case IDT_GP:
1289		case IDT_AC:
1290		case IDT_TS:
1291			errcode_valid = 1;
1292			break;
1293
1294		case IDT_DF:
1295			errcode_valid = 1;
1296			info1 = 0;
1297			break;
1298
1299		case IDT_BP:
1300		case IDT_OF:
1301		case IDT_BR:
1302			/*
1303			 * The 'nrip' field is populated for INT3, INTO and
1304			 * BOUND exceptions and this also implies that
1305			 * 'inst_length' is non-zero.
1306			 *
1307			 * Reset 'inst_length' to zero so the guest %rip at
1308			 * event injection is identical to what it was when
1309			 * the exception originally happened.
1310			 */
1311			VCPU_CTR2(svm_sc->vm, vcpu, "Reset inst_length from %d "
1312			    "to zero before injecting exception %d",
1313			    vmexit->inst_length, idtvec);
1314			vmexit->inst_length = 0;
1315			/* fallthru */
1316		default:
1317			errcode_valid = 0;
1318			info1 = 0;
1319			break;
1320		}
1321		KASSERT(vmexit->inst_length == 0, ("invalid inst_length (%d) "
1322		    "when reflecting exception %d into guest",
1323		    vmexit->inst_length, idtvec));
1324
1325		if (reflect) {
1326			/* Reflect the exception back into the guest */
1327			VCPU_CTR2(svm_sc->vm, vcpu, "Reflecting exception "
1328			    "%d/%#x into the guest", idtvec, (int)info1);
1329			error = vm_inject_exception(svm_sc->vm, vcpu, idtvec,
1330			    errcode_valid, info1, 0);
1331			KASSERT(error == 0, ("%s: vm_inject_exception error %d",
1332			    __func__, error));
1333		}
1334		handled = 1;
1335		break;
1336	case VMCB_EXIT_MSR:	/* MSR access. */
1337		eax = state->rax;
1338		ecx = ctx->sctx_rcx;
1339		edx = ctx->sctx_rdx;
1340		retu = false;
1341
1342		if (info1) {
1343			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_WRMSR, 1);
1344			val = (uint64_t)edx << 32 | eax;
1345			VCPU_CTR2(svm_sc->vm, vcpu, "wrmsr %#x val %#lx",
1346			    ecx, val);
1347			if (emulate_wrmsr(svm_sc, vcpu, ecx, val, &retu)) {
1348				vmexit->exitcode = VM_EXITCODE_WRMSR;
1349				vmexit->u.msr.code = ecx;
1350				vmexit->u.msr.wval = val;
1351			} else if (!retu) {
1352				handled = 1;
1353			} else {
1354				KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1355				    ("emulate_wrmsr retu with bogus exitcode"));
1356			}
1357		} else {
1358			VCPU_CTR1(svm_sc->vm, vcpu, "rdmsr %#x", ecx);
1359			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_RDMSR, 1);
1360			if (emulate_rdmsr(svm_sc, vcpu, ecx, &retu)) {
1361				vmexit->exitcode = VM_EXITCODE_RDMSR;
1362				vmexit->u.msr.code = ecx;
1363			} else if (!retu) {
1364				handled = 1;
1365			} else {
1366				KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1367				    ("emulate_rdmsr retu with bogus exitcode"));
1368			}
1369		}
1370		break;
1371	case VMCB_EXIT_IO:
1372		handled = svm_handle_io(svm_sc, vcpu, vmexit);
1373		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
1374		break;
1375	case VMCB_EXIT_CPUID:
1376		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
1377		handled = x86_emulate_cpuid(svm_sc->vm, vcpu,
1378		    (uint32_t *)&state->rax,
1379		    (uint32_t *)&ctx->sctx_rbx,
1380		    (uint32_t *)&ctx->sctx_rcx,
1381		    (uint32_t *)&ctx->sctx_rdx);
1382		break;
1383	case VMCB_EXIT_HLT:
1384		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
1385		vmexit->exitcode = VM_EXITCODE_HLT;
1386		vmexit->u.hlt.rflags = state->rflags;
1387		break;
1388	case VMCB_EXIT_PAUSE:
1389		vmexit->exitcode = VM_EXITCODE_PAUSE;
1390		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
1391		break;
1392	case VMCB_EXIT_NPF:
1393		/* EXITINFO2 contains the faulting guest physical address */
1394		if (info1 & VMCB_NPF_INFO1_RSV) {
1395			VCPU_CTR2(svm_sc->vm, vcpu, "nested page fault with "
1396			    "reserved bits set: info1(%#lx) info2(%#lx)",
1397			    info1, info2);
1398		} else if (vm_mem_allocated(svm_sc->vm, info2)) {
1399			vmexit->exitcode = VM_EXITCODE_PAGING;
1400			vmexit->u.paging.gpa = info2;
1401			vmexit->u.paging.fault_type = npf_fault_type(info1);
1402			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1403			VCPU_CTR3(svm_sc->vm, vcpu, "nested page fault "
1404			    "on gpa %#lx/%#lx at rip %#lx",
1405			    info2, info1, state->rip);
1406		} else if (svm_npf_emul_fault(info1)) {
1407			svm_handle_inst_emul(vmcb, info2, vmexit);
1408			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INST_EMUL, 1);
1409			VCPU_CTR3(svm_sc->vm, vcpu, "inst_emul fault "
1410			    "for gpa %#lx/%#lx at rip %#lx",
1411			    info2, info1, state->rip);
1412		}
1413		break;
1414	case VMCB_EXIT_MONITOR:
1415		vmexit->exitcode = VM_EXITCODE_MONITOR;
1416		break;
1417	case VMCB_EXIT_MWAIT:
1418		vmexit->exitcode = VM_EXITCODE_MWAIT;
1419		break;
1420	default:
1421		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
1422		break;
1423	}
1424
1425	VCPU_CTR4(svm_sc->vm, vcpu, "%s %s vmexit at %#lx/%d",
1426	    handled ? "handled" : "unhandled", exit_reason_to_str(code),
1427	    vmexit->rip, vmexit->inst_length);
1428
1429	if (handled) {
1430		vmexit->rip += vmexit->inst_length;
1431		vmexit->inst_length = 0;
1432		state->rip = vmexit->rip;
1433	} else {
1434		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
1435			/*
1436			 * If this VM exit was not claimed by anybody then
1437			 * treat it as a generic SVM exit.
1438			 */
1439			vm_exit_svm(vmexit, code, info1, info2);
1440		} else {
1441			/*
1442			 * The exitcode and collateral have been populated.
1443			 * The VM exit will be processed further in userland.
1444			 */
1445		}
1446	}
1447	return (handled);
1448}
1449
1450static void
1451svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
1452{
1453	uint64_t intinfo;
1454
1455	if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
1456		return;
1457
1458	KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1459	    "valid: %#lx", __func__, intinfo));
1460
1461	svm_eventinject(svm_sc, vcpu, VMCB_EXITINTINFO_TYPE(intinfo),
1462		VMCB_EXITINTINFO_VECTOR(intinfo),
1463		VMCB_EXITINTINFO_EC(intinfo),
1464		VMCB_EXITINTINFO_EC_VALID(intinfo));
1465	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1466	VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1467}
1468
1469/*
1470 * Inject event to virtual cpu.
1471 */
1472static void
1473svm_inj_interrupts(struct svm_softc *sc, int vcpu, struct vlapic *vlapic)
1474{
1475	struct vmcb_ctrl *ctrl;
1476	struct vmcb_state *state;
1477	struct svm_vcpu *vcpustate;
1478	uint8_t v_tpr;
1479	int vector, need_intr_window, pending_apic_vector;
1480
1481	state = svm_get_vmcb_state(sc, vcpu);
1482	ctrl  = svm_get_vmcb_ctrl(sc, vcpu);
1483	vcpustate = svm_get_vcpu(sc, vcpu);
1484
1485	need_intr_window = 0;
1486	pending_apic_vector = 0;
1487
1488	if (vcpustate->nextrip != state->rip) {
1489		ctrl->intr_shadow = 0;
1490		VCPU_CTR2(sc->vm, vcpu, "Guest interrupt blocking "
1491		    "cleared due to rip change: %#lx/%#lx",
1492		    vcpustate->nextrip, state->rip);
1493	}
1494
1495	/*
1496	 * Inject pending events or exceptions for this vcpu.
1497	 *
1498	 * An event might be pending because the previous #VMEXIT happened
1499	 * during event delivery (i.e. ctrl->exitintinfo).
1500	 *
1501	 * An event might also be pending because an exception was injected
1502	 * by the hypervisor (e.g. #PF during instruction emulation).
1503	 */
1504	svm_inj_intinfo(sc, vcpu);
1505
1506	/* NMI event has priority over interrupts. */
1507	if (vm_nmi_pending(sc->vm, vcpu)) {
1508		if (nmi_blocked(sc, vcpu)) {
1509			/*
1510			 * Can't inject another NMI if the guest has not
1511			 * yet executed an "iret" after the last NMI.
1512			 */
1513			VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due "
1514			    "to NMI-blocking");
1515		} else if (ctrl->intr_shadow) {
1516			/*
1517			 * Can't inject an NMI if the vcpu is in an intr_shadow.
1518			 */
1519			VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due to "
1520			    "interrupt shadow");
1521			need_intr_window = 1;
1522			goto done;
1523		} else if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1524			/*
1525			 * If there is already an exception/interrupt pending
1526			 * then defer the NMI until after that.
1527			 */
1528			VCPU_CTR1(sc->vm, vcpu, "Cannot inject NMI due to "
1529			    "eventinj %#lx", ctrl->eventinj);
1530
1531			/*
1532			 * Use self-IPI to trigger a VM-exit as soon as
1533			 * possible after the event injection is completed.
1534			 *
1535			 * This works only if the external interrupt exiting
1536			 * is at a lower priority than the event injection.
1537			 *
1538			 * Although not explicitly specified in APMv2 the
1539			 * relative priorities were verified empirically.
1540			 */
1541			ipi_cpu(curcpu, IPI_AST);	/* XXX vmm_ipinum? */
1542		} else {
1543			vm_nmi_clear(sc->vm, vcpu);
1544
1545			/* Inject NMI, vector number is not used */
1546			svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_NMI,
1547			    IDT_NMI, 0, false);
1548
1549			/* virtual NMI blocking is now in effect */
1550			enable_nmi_blocking(sc, vcpu);
1551
1552			VCPU_CTR0(sc->vm, vcpu, "Injecting vNMI");
1553		}
1554	}
1555
1556	if (!vm_extint_pending(sc->vm, vcpu)) {
1557		/*
1558		 * APIC interrupts are delivered using the V_IRQ offload.
1559		 *
1560		 * The primary benefit is that the hypervisor doesn't need to
1561		 * deal with the various conditions that inhibit interrupts.
1562		 * It also means that TPR changes via CR8 will be handled
1563		 * without any hypervisor involvement.
1564		 *
1565		 * Note that the APIC vector must remain pending in the vIRR
1566		 * until it is confirmed that it was delivered to the guest.
1567		 * This can be confirmed based on the value of V_IRQ at the
1568		 * next #VMEXIT (1 = pending, 0 = delivered).
1569		 *
1570		 * Also note that it is possible that another higher priority
1571		 * vector can become pending before this vector is delivered
1572		 * to the guest. This is alright because vcpu_notify_event()
1573		 * will send an IPI and force the vcpu to trap back into the
1574		 * hypervisor. The higher priority vector will be injected on
1575		 * the next VMRUN.
1576		 */
1577		if (vlapic_pending_intr(vlapic, &vector)) {
1578			KASSERT(vector >= 16 && vector <= 255,
1579			    ("invalid vector %d from local APIC", vector));
1580			pending_apic_vector = vector;
1581		}
1582		goto done;
1583	}
1584
1585	/* Ask the legacy pic for a vector to inject */
1586	vatpic_pending_intr(sc->vm, &vector);
1587	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d from INTR",
1588	    vector));
1589
1590	/*
1591	 * If the guest has disabled interrupts or is in an interrupt shadow
1592	 * then we cannot inject the pending interrupt.
1593	 */
1594	if ((state->rflags & PSL_I) == 0) {
1595		VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1596		    "rflags %#lx", vector, state->rflags);
1597		need_intr_window = 1;
1598		goto done;
1599	}
1600
1601	if (ctrl->intr_shadow) {
1602		VCPU_CTR1(sc->vm, vcpu, "Cannot inject vector %d due to "
1603		    "interrupt shadow", vector);
1604		need_intr_window = 1;
1605		goto done;
1606	}
1607
1608	if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1609		VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1610		    "eventinj %#lx", vector, ctrl->eventinj);
1611		need_intr_window = 1;
1612		goto done;
1613	}
1614
1615	/*
1616	 * Legacy PIC interrupts are delivered via the event injection
1617	 * mechanism.
1618	 */
1619	svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1620
1621	vm_extint_clear(sc->vm, vcpu);
1622	vatpic_intr_accepted(sc->vm, vector);
1623
1624	/*
1625	 * Force a VM-exit as soon as the vcpu is ready to accept another
1626	 * interrupt. This is done because the PIC might have another vector
1627	 * that it wants to inject. Also, if the APIC has a pending interrupt
1628	 * that was preempted by the ExtInt then it allows us to inject the
1629	 * APIC vector as soon as possible.
1630	 */
1631	need_intr_window = 1;
1632done:
1633	/*
1634	 * The guest can modify the TPR by writing to %CR8. In guest mode
1635	 * the processor reflects this write to V_TPR without hypervisor
1636	 * intervention.
1637	 *
1638	 * The guest can also modify the TPR by writing to it via the memory
1639	 * mapped APIC page. In this case, the write will be emulated by the
1640	 * hypervisor. For this reason V_TPR must be updated before every
1641	 * VMRUN.
1642	 */
1643	v_tpr = vlapic_get_cr8(vlapic);
1644	KASSERT(v_tpr <= 15, ("invalid v_tpr %#x", v_tpr));
1645	if (ctrl->v_tpr != v_tpr) {
1646		VCPU_CTR2(sc->vm, vcpu, "VMCB V_TPR changed from %#x to %#x",
1647		    ctrl->v_tpr, v_tpr);
1648		ctrl->v_tpr = v_tpr;
1649		svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1650	}
1651
1652	if (pending_apic_vector) {
1653		/*
1654		 * If an APIC vector is being injected then interrupt window
1655		 * exiting is not possible on this VMRUN.
1656		 */
1657		KASSERT(!need_intr_window, ("intr_window exiting impossible"));
1658		VCPU_CTR1(sc->vm, vcpu, "Injecting vector %d using V_IRQ",
1659		    pending_apic_vector);
1660
1661		ctrl->v_irq = 1;
1662		ctrl->v_ign_tpr = 0;
1663		ctrl->v_intr_vector = pending_apic_vector;
1664		ctrl->v_intr_prio = pending_apic_vector >> 4;
1665		svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1666	} else if (need_intr_window) {
1667		/*
1668		 * We use V_IRQ in conjunction with the VINTR intercept to
1669		 * trap into the hypervisor as soon as a virtual interrupt
1670		 * can be delivered.
1671		 *
1672		 * Since injected events are not subject to intercept checks
1673		 * we need to ensure that the V_IRQ is not actually going to
1674		 * be delivered on VM entry. The KASSERT below enforces this.
1675		 */
1676		KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) != 0 ||
1677		    (state->rflags & PSL_I) == 0 || ctrl->intr_shadow,
1678		    ("Bogus intr_window_exiting: eventinj (%#lx), "
1679		    "intr_shadow (%u), rflags (%#lx)",
1680		    ctrl->eventinj, ctrl->intr_shadow, state->rflags));
1681		enable_intr_window_exiting(sc, vcpu);
1682	} else {
1683		disable_intr_window_exiting(sc, vcpu);
1684	}
1685}
1686
1687static __inline void
1688restore_host_tss(void)
1689{
1690	struct system_segment_descriptor *tss_sd;
1691
1692	/*
1693	 * The TSS descriptor was in use prior to launching the guest so it
1694	 * has been marked busy.
1695	 *
1696	 * 'ltr' requires the descriptor to be marked available so change the
1697	 * type to "64-bit available TSS".
1698	 */
1699	tss_sd = PCPU_GET(tss);
1700	tss_sd->sd_type = SDT_SYSTSS;
1701	ltr(GSEL(GPROC0_SEL, SEL_KPL));
1702}
1703
1704static void
1705check_asid(struct svm_softc *sc, int vcpuid, pmap_t pmap, u_int thiscpu)
1706{
1707	struct svm_vcpu *vcpustate;
1708	struct vmcb_ctrl *ctrl;
1709	long eptgen;
1710	bool alloc_asid;
1711
1712	KASSERT(CPU_ISSET(thiscpu, &pmap->pm_active), ("%s: nested pmap not "
1713	    "active on cpu %u", __func__, thiscpu));
1714
1715	vcpustate = svm_get_vcpu(sc, vcpuid);
1716	ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1717
1718	/*
1719	 * The TLB entries associated with the vcpu's ASID are not valid
1720	 * if either of the following conditions is true:
1721	 *
1722	 * 1. The vcpu's ASID generation is different than the host cpu's
1723	 *    ASID generation. This happens when the vcpu migrates to a new
1724	 *    host cpu. It can also happen when the number of vcpus executing
1725	 *    on a host cpu is greater than the number of ASIDs available.
1726	 *
1727	 * 2. The pmap generation number is different than the value cached in
1728	 *    the 'vcpustate'. This happens when the host invalidates pages
1729	 *    belonging to the guest.
1730	 *
1731	 *	asidgen		eptgen	      Action
1732	 *	mismatch	mismatch
1733	 *	   0		   0		(a)
1734	 *	   0		   1		(b1) or (b2)
1735	 *	   1		   0		(c)
1736	 *	   1		   1		(d)
1737	 *
1738	 * (a) There is no mismatch in eptgen or ASID generation and therefore
1739	 *     no further action is needed.
1740	 *
1741	 * (b1) If the cpu supports FlushByAsid then the vcpu's ASID is
1742	 *      retained and the TLB entries associated with this ASID
1743	 *      are flushed by VMRUN.
1744	 *
1745	 * (b2) If the cpu does not support FlushByAsid then a new ASID is
1746	 *      allocated.
1747	 *
1748	 * (c) A new ASID is allocated.
1749	 *
1750	 * (d) A new ASID is allocated.
1751	 */
1752
1753	alloc_asid = false;
1754	eptgen = pmap->pm_eptgen;
1755	ctrl->tlb_ctrl = VMCB_TLB_FLUSH_NOTHING;
1756
1757	if (vcpustate->asid.gen != asid[thiscpu].gen) {
1758		alloc_asid = true;	/* (c) and (d) */
1759	} else if (vcpustate->eptgen != eptgen) {
1760		if (flush_by_asid())
1761			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;	/* (b1) */
1762		else
1763			alloc_asid = true;			/* (b2) */
1764	} else {
1765		/*
1766		 * This is the common case (a).
1767		 */
1768		KASSERT(!alloc_asid, ("ASID allocation not necessary"));
1769		KASSERT(ctrl->tlb_ctrl == VMCB_TLB_FLUSH_NOTHING,
1770		    ("Invalid VMCB tlb_ctrl: %#x", ctrl->tlb_ctrl));
1771	}
1772
1773	if (alloc_asid) {
1774		if (++asid[thiscpu].num >= nasid) {
1775			asid[thiscpu].num = 1;
1776			if (++asid[thiscpu].gen == 0)
1777				asid[thiscpu].gen = 1;
1778			/*
1779			 * If this cpu does not support "flush-by-asid"
1780			 * then flush the entire TLB on a generation
1781			 * bump. Subsequent ASID allocation in this
1782			 * generation can be done without a TLB flush.
1783			 */
1784			if (!flush_by_asid())
1785				ctrl->tlb_ctrl = VMCB_TLB_FLUSH_ALL;
1786		}
1787		vcpustate->asid.gen = asid[thiscpu].gen;
1788		vcpustate->asid.num = asid[thiscpu].num;
1789
1790		ctrl->asid = vcpustate->asid.num;
1791		svm_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1792		/*
1793		 * If this cpu supports "flush-by-asid" then the TLB
1794		 * was not flushed after the generation bump. The TLB
1795		 * is flushed selectively after every new ASID allocation.
1796		 */
1797		if (flush_by_asid())
1798			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1799	}
1800	vcpustate->eptgen = eptgen;
1801
1802	KASSERT(ctrl->asid != 0, ("Guest ASID must be non-zero"));
1803	KASSERT(ctrl->asid == vcpustate->asid.num,
1804	    ("ASID mismatch: %u/%u", ctrl->asid, vcpustate->asid.num));
1805}
1806
1807static __inline void
1808disable_gintr(void)
1809{
1810
1811	__asm __volatile("clgi");
1812}
1813
1814static __inline void
1815enable_gintr(void)
1816{
1817
1818        __asm __volatile("stgi");
1819}
1820
1821/*
1822 * Start vcpu with specified RIP.
1823 */
1824static int
1825svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1826	void *rend_cookie, void *suspended_cookie)
1827{
1828	struct svm_regctx *gctx;
1829	struct svm_softc *svm_sc;
1830	struct svm_vcpu *vcpustate;
1831	struct vmcb_state *state;
1832	struct vmcb_ctrl *ctrl;
1833	struct vm_exit *vmexit;
1834	struct vlapic *vlapic;
1835	struct vm *vm;
1836	uint64_t vmcb_pa;
1837	u_int thiscpu;
1838	int handled;
1839
1840	svm_sc = arg;
1841	vm = svm_sc->vm;
1842
1843	vcpustate = svm_get_vcpu(svm_sc, vcpu);
1844	state = svm_get_vmcb_state(svm_sc, vcpu);
1845	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1846	vmexit = vm_exitinfo(vm, vcpu);
1847	vlapic = vm_lapic(vm, vcpu);
1848
1849	/*
1850	 * Stash 'curcpu' on the stack as 'thiscpu'.
1851	 *
1852	 * The per-cpu data area is not accessible until MSR_GSBASE is restored
1853	 * after the #VMEXIT. Since VMRUN is executed inside a critical section
1854	 * 'curcpu' and 'thiscpu' are guaranteed to identical.
1855	 */
1856	thiscpu = curcpu;
1857
1858	gctx = svm_get_guest_regctx(svm_sc, vcpu);
1859	vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1860
1861	if (vcpustate->lastcpu != thiscpu) {
1862		/*
1863		 * Force new ASID allocation by invalidating the generation.
1864		 */
1865		vcpustate->asid.gen = 0;
1866
1867		/*
1868		 * Invalidate the VMCB state cache by marking all fields dirty.
1869		 */
1870		svm_set_dirty(svm_sc, vcpu, 0xffffffff);
1871
1872		/*
1873		 * XXX
1874		 * Setting 'vcpustate->lastcpu' here is bit premature because
1875		 * we may return from this function without actually executing
1876		 * the VMRUN  instruction. This could happen if a rendezvous
1877		 * or an AST is pending on the first time through the loop.
1878		 *
1879		 * This works for now but any new side-effects of vcpu
1880		 * migration should take this case into account.
1881		 */
1882		vcpustate->lastcpu = thiscpu;
1883		vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1884	}
1885
1886	svm_msr_guest_enter(svm_sc, vcpu);
1887
1888	/* Update Guest RIP */
1889	state->rip = rip;
1890
1891	do {
1892		/*
1893		 * Disable global interrupts to guarantee atomicity during
1894		 * loading of guest state. This includes not only the state
1895		 * loaded by the "vmrun" instruction but also software state
1896		 * maintained by the hypervisor: suspended and rendezvous
1897		 * state, NPT generation number, vlapic interrupts etc.
1898		 */
1899		disable_gintr();
1900
1901		if (vcpu_suspended(suspended_cookie)) {
1902			enable_gintr();
1903			vm_exit_suspended(vm, vcpu, state->rip);
1904			break;
1905		}
1906
1907		if (vcpu_rendezvous_pending(rend_cookie)) {
1908			enable_gintr();
1909			vm_exit_rendezvous(vm, vcpu, state->rip);
1910			break;
1911		}
1912
1913		/* We are asked to give the cpu by scheduler. */
1914		if (curthread->td_flags & (TDF_ASTPENDING | TDF_NEEDRESCHED)) {
1915			enable_gintr();
1916			vm_exit_astpending(vm, vcpu, state->rip);
1917			break;
1918		}
1919
1920		svm_inj_interrupts(svm_sc, vcpu, vlapic);
1921
1922		/* Activate the nested pmap on 'thiscpu' */
1923		CPU_SET_ATOMIC_ACQ(thiscpu, &pmap->pm_active);
1924
1925		/*
1926		 * Check the pmap generation and the ASID generation to
1927		 * ensure that the vcpu does not use stale TLB mappings.
1928		 */
1929		check_asid(svm_sc, vcpu, pmap, thiscpu);
1930
1931		ctrl->vmcb_clean = vmcb_clean & ~vcpustate->dirty;
1932		vcpustate->dirty = 0;
1933		VCPU_CTR1(vm, vcpu, "vmcb clean %#x", ctrl->vmcb_clean);
1934
1935		/* Launch Virtual Machine. */
1936		VCPU_CTR1(vm, vcpu, "Resume execution at %#lx", state->rip);
1937		svm_launch(vmcb_pa, gctx);
1938
1939		CPU_CLR_ATOMIC(thiscpu, &pmap->pm_active);
1940
1941		/*
1942		 * Restore MSR_GSBASE to point to the pcpu data area.
1943		 *
1944		 * Note that accesses done via PCPU_GET/PCPU_SET will work
1945		 * only after MSR_GSBASE is restored.
1946		 *
1947		 * Also note that we don't bother restoring MSR_KGSBASE
1948		 * since it is not used in the kernel and will be restored
1949		 * when the VMRUN ioctl returns to userspace.
1950		 */
1951		wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[thiscpu]);
1952		KASSERT(curcpu == thiscpu, ("thiscpu/curcpu (%u/%u) mismatch",
1953		    thiscpu, curcpu));
1954
1955		/*
1956		 * The host GDTR and IDTR is saved by VMRUN and restored
1957		 * automatically on #VMEXIT. However, the host TSS needs
1958		 * to be restored explicitly.
1959		 */
1960		restore_host_tss();
1961
1962		/* #VMEXIT disables interrupts so re-enable them here. */
1963		enable_gintr();
1964
1965		/* Update 'nextrip' */
1966		vcpustate->nextrip = state->rip;
1967
1968		/* Handle #VMEXIT and if required return to user space. */
1969		handled = svm_vmexit(svm_sc, vcpu, vmexit);
1970	} while (handled);
1971
1972	svm_msr_guest_exit(svm_sc, vcpu);
1973
1974	return (0);
1975}
1976
1977static void
1978svm_vmcleanup(void *arg)
1979{
1980	struct svm_softc *sc = arg;
1981
1982	free(sc, M_SVM);
1983}
1984
1985static register_t *
1986swctx_regptr(struct svm_regctx *regctx, int reg)
1987{
1988
1989	switch (reg) {
1990	case VM_REG_GUEST_RBX:
1991		return (&regctx->sctx_rbx);
1992	case VM_REG_GUEST_RCX:
1993		return (&regctx->sctx_rcx);
1994	case VM_REG_GUEST_RDX:
1995		return (&regctx->sctx_rdx);
1996	case VM_REG_GUEST_RDI:
1997		return (&regctx->sctx_rdi);
1998	case VM_REG_GUEST_RSI:
1999		return (&regctx->sctx_rsi);
2000	case VM_REG_GUEST_RBP:
2001		return (&regctx->sctx_rbp);
2002	case VM_REG_GUEST_R8:
2003		return (&regctx->sctx_r8);
2004	case VM_REG_GUEST_R9:
2005		return (&regctx->sctx_r9);
2006	case VM_REG_GUEST_R10:
2007		return (&regctx->sctx_r10);
2008	case VM_REG_GUEST_R11:
2009		return (&regctx->sctx_r11);
2010	case VM_REG_GUEST_R12:
2011		return (&regctx->sctx_r12);
2012	case VM_REG_GUEST_R13:
2013		return (&regctx->sctx_r13);
2014	case VM_REG_GUEST_R14:
2015		return (&regctx->sctx_r14);
2016	case VM_REG_GUEST_R15:
2017		return (&regctx->sctx_r15);
2018	default:
2019		return (NULL);
2020	}
2021}
2022
2023static int
2024svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
2025{
2026	struct svm_softc *svm_sc;
2027	register_t *reg;
2028
2029	svm_sc = arg;
2030
2031	if (ident == VM_REG_GUEST_INTR_SHADOW) {
2032		return (svm_get_intr_shadow(svm_sc, vcpu, val));
2033	}
2034
2035	if (vmcb_read(svm_sc, vcpu, ident, val) == 0) {
2036		return (0);
2037	}
2038
2039	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2040
2041	if (reg != NULL) {
2042		*val = *reg;
2043		return (0);
2044	}
2045
2046	VCPU_CTR1(svm_sc->vm, vcpu, "svm_getreg: unknown register %#x", ident);
2047	return (EINVAL);
2048}
2049
2050static int
2051svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
2052{
2053	struct svm_softc *svm_sc;
2054	register_t *reg;
2055
2056	svm_sc = arg;
2057
2058	if (ident == VM_REG_GUEST_INTR_SHADOW) {
2059		return (svm_modify_intr_shadow(svm_sc, vcpu, val));
2060	}
2061
2062	if (vmcb_write(svm_sc, vcpu, ident, val) == 0) {
2063		return (0);
2064	}
2065
2066	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2067
2068	if (reg != NULL) {
2069		*reg = val;
2070		return (0);
2071	}
2072
2073	/*
2074	 * XXX deal with CR3 and invalidate TLB entries tagged with the
2075	 * vcpu's ASID. This needs to be treated differently depending on
2076	 * whether 'running' is true/false.
2077	 */
2078
2079	VCPU_CTR1(svm_sc->vm, vcpu, "svm_setreg: unknown register %#x", ident);
2080	return (EINVAL);
2081}
2082
2083static int
2084svm_setcap(void *arg, int vcpu, int type, int val)
2085{
2086	struct svm_softc *sc;
2087	int error;
2088
2089	sc = arg;
2090	error = 0;
2091	switch (type) {
2092	case VM_CAP_HALT_EXIT:
2093		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2094		    VMCB_INTCPT_HLT, val);
2095		break;
2096	case VM_CAP_PAUSE_EXIT:
2097		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2098		    VMCB_INTCPT_PAUSE, val);
2099		break;
2100	case VM_CAP_UNRESTRICTED_GUEST:
2101		/* Unrestricted guest execution cannot be disabled in SVM */
2102		if (val == 0)
2103			error = EINVAL;
2104		break;
2105	default:
2106		error = ENOENT;
2107		break;
2108	}
2109	return (error);
2110}
2111
2112static int
2113svm_getcap(void *arg, int vcpu, int type, int *retval)
2114{
2115	struct svm_softc *sc;
2116	int error;
2117
2118	sc = arg;
2119	error = 0;
2120
2121	switch (type) {
2122	case VM_CAP_HALT_EXIT:
2123		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2124		    VMCB_INTCPT_HLT);
2125		break;
2126	case VM_CAP_PAUSE_EXIT:
2127		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2128		    VMCB_INTCPT_PAUSE);
2129		break;
2130	case VM_CAP_UNRESTRICTED_GUEST:
2131		*retval = 1;	/* unrestricted guest is always enabled */
2132		break;
2133	default:
2134		error = ENOENT;
2135		break;
2136	}
2137	return (error);
2138}
2139
2140static struct vlapic *
2141svm_vlapic_init(void *arg, int vcpuid)
2142{
2143	struct svm_softc *svm_sc;
2144	struct vlapic *vlapic;
2145
2146	svm_sc = arg;
2147	vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
2148	vlapic->vm = svm_sc->vm;
2149	vlapic->vcpuid = vcpuid;
2150	vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
2151
2152	vlapic_init(vlapic);
2153
2154	return (vlapic);
2155}
2156
2157static void
2158svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
2159{
2160
2161        vlapic_cleanup(vlapic);
2162        free(vlapic, M_SVM_VLAPIC);
2163}
2164
2165struct vmm_ops vmm_ops_amd = {
2166	svm_init,
2167	svm_cleanup,
2168	svm_restore,
2169	svm_vminit,
2170	svm_vmrun,
2171	svm_vmcleanup,
2172	svm_getreg,
2173	svm_setreg,
2174	vmcb_getdesc,
2175	vmcb_setdesc,
2176	svm_getcap,
2177	svm_setcap,
2178	svm_npt_alloc,
2179	svm_npt_free,
2180	svm_vlapic_init,
2181	svm_vlapic_cleanup
2182};
2183