svm.c revision 271557
12311Sjkh/*-
22311Sjkh * Copyright (c) 2013, Anish Gupta (akgupt3@gmail.com)
32311Sjkh * All rights reserved.
42311Sjkh *
52311Sjkh * Redistribution and use in source and binary forms, with or without
62311Sjkh * modification, are permitted provided that the following conditions
72311Sjkh * are met:
82311Sjkh * 1. Redistributions of source code must retain the above copyright
92311Sjkh *    notice unmodified, this list of conditions, and the following
102311Sjkh *    disclaimer.
112311Sjkh * 2. Redistributions in binary form must reproduce the above copyright
122311Sjkh *    notice, this list of conditions and the following disclaimer in the
132311Sjkh *    documentation and/or other materials provided with the distribution.
142311Sjkh *
152311Sjkh * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
162311Sjkh * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
172311Sjkh * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
182311Sjkh * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
1929452Scharnier * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
2050479Speter * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
212311Sjkh * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
222311Sjkh * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
232311Sjkh * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
242311Sjkh * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
252311Sjkh */
262311Sjkh
272311Sjkh#include <sys/cdefs.h>
282311Sjkh__FBSDID("$FreeBSD: projects/bhyve_svm/sys/amd64/vmm/amd/svm.c 271557 2014-09-13 22:45:04Z neel $");
292311Sjkh
302311Sjkh#include <sys/param.h>
312311Sjkh#include <sys/systm.h>
322311Sjkh#include <sys/smp.h>
332311Sjkh#include <sys/kernel.h>
342311Sjkh#include <sys/malloc.h>
352311Sjkh#include <sys/pcpu.h>
3629452Scharnier#include <sys/proc.h>
372311Sjkh#include <sys/sysctl.h>
382311Sjkh
392311Sjkh#include <vm/vm.h>
402311Sjkh#include <vm/pmap.h>
412311Sjkh
422311Sjkh#include <machine/cpufunc.h>
432311Sjkh#include <machine/psl.h>
442311Sjkh#include <machine/pmap.h>
452311Sjkh#include <machine/md_var.h>
462311Sjkh#include <machine/vmparam.h>
472311Sjkh#include <machine/specialreg.h>
482311Sjkh#include <machine/segments.h>
492311Sjkh#include <machine/smp.h>
502311Sjkh#include <machine/vmm.h>
512311Sjkh#include <machine/vmm_dev.h>
522311Sjkh#include <machine/vmm_instruction_emul.h>
532311Sjkh
542311Sjkh#include <x86/apicreg.h>
552311Sjkh
562311Sjkh#include "vmm_lapic.h"
572311Sjkh#include "vmm_msr.h"
582311Sjkh#include "vmm_stat.h"
592311Sjkh#include "vmm_ktr.h"
602311Sjkh#include "vmm_ioport.h"
612311Sjkh#include "vatpic.h"
622311Sjkh#include "vlapic.h"
632311Sjkh#include "vlapic_priv.h"
642311Sjkh
652311Sjkh#include "x86.h"
662311Sjkh#include "vmcb.h"
672311Sjkh#include "svm.h"
682311Sjkh#include "svm_softc.h"
692311Sjkh#include "npt.h"
702311Sjkh
712311SjkhSYSCTL_DECL(_hw_vmm);
722311SjkhSYSCTL_NODE(_hw_vmm, OID_AUTO, svm, CTLFLAG_RW, NULL, NULL);
732311Sjkh
742311Sjkh/*
752311Sjkh * SVM CPUID function 0x8000_000A, edx bit decoding.
762311Sjkh */
772311Sjkh#define AMD_CPUID_SVM_NP		BIT(0)  /* Nested paging or RVI */
782311Sjkh#define AMD_CPUID_SVM_LBR		BIT(1)  /* Last branch virtualization */
792311Sjkh#define AMD_CPUID_SVM_SVML		BIT(2)  /* SVM lock */
802311Sjkh#define AMD_CPUID_SVM_NRIP_SAVE		BIT(3)  /* Next RIP is saved */
812311Sjkh#define AMD_CPUID_SVM_TSC_RATE		BIT(4)  /* TSC rate control. */
822311Sjkh#define AMD_CPUID_SVM_VMCB_CLEAN	BIT(5)  /* VMCB state caching */
832311Sjkh#define AMD_CPUID_SVM_FLUSH_BY_ASID	BIT(6)  /* Flush by ASID */
842311Sjkh#define AMD_CPUID_SVM_DECODE_ASSIST	BIT(7)  /* Decode assist */
852311Sjkh#define AMD_CPUID_SVM_PAUSE_INC		BIT(10) /* Pause intercept filter. */
862311Sjkh#define AMD_CPUID_SVM_PAUSE_FTH		BIT(12) /* Pause filter threshold */
872311Sjkh
882311Sjkh#define	VMCB_CACHE_DEFAULT	(VMCB_CACHE_ASID 	|	\
892311Sjkh				VMCB_CACHE_IOPM		|	\
902311Sjkh				VMCB_CACHE_I		|	\
912311Sjkh				VMCB_CACHE_TPR		|	\
922311Sjkh				VMCB_CACHE_NP)
932311Sjkh
942311SjkhMALLOC_DEFINE(M_SVM, "svm", "svm");
952311SjkhMALLOC_DEFINE(M_SVM_VLAPIC, "svm-vlapic", "svm-vlapic");
962311Sjkh
972311Sjkh/* Per-CPU context area. */
982311Sjkhextern struct pcpu __pcpu[];
992311Sjkh
1002311Sjkhstatic int svm_getdesc(void *arg, int vcpu, int type, struct seg_desc *desc);
1012311Sjkh
1022311Sjkhstatic uint32_t svm_feature;	/* AMD SVM features. */
1032311SjkhSYSCTL_UINT(_hw_vmm_svm, OID_AUTO, features, CTLFLAG_RD, &svm_feature, 0,
1042311Sjkh    "SVM features advertised by CPUID.8000000AH:EDX");
1052311Sjkh
1062311Sjkhstatic int disable_npf_assist;
1072311SjkhSYSCTL_INT(_hw_vmm_svm, OID_AUTO, disable_npf_assist, CTLFLAG_RWTUN,
1082311Sjkh    &disable_npf_assist, 0, NULL);
1092311Sjkh
1102311Sjkh/* Maximum ASIDs supported by the processor */
1112311Sjkhstatic uint32_t nasid;
1122311SjkhSYSCTL_UINT(_hw_vmm_svm, OID_AUTO, num_asids, CTLFLAG_RD, &nasid, 0,
1132311Sjkh    "Number of ASIDs supported by this processor");
1142311Sjkh
1152311Sjkh/* Current ASID generation for each host cpu */
1162311Sjkhstatic struct asid asid[MAXCPU];
1172311Sjkh
1182311Sjkh/*
1192311Sjkh * SVM host state saved area of size 4KB for each core.
1202311Sjkh */
1212311Sjkhstatic uint8_t hsave[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
1222311Sjkh
1232311Sjkh/*
1242311Sjkh * S/w saved host context.
1252311Sjkh */
1262311Sjkhstatic struct svm_regctx host_ctx[MAXCPU];
1272311Sjkh
1282311Sjkhstatic VMM_STAT_AMD(VCPU_EXITINTINFO, "VM exits during event delivery");
1292311Sjkhstatic VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "Events pending at VM entry");
1302311Sjkhstatic VMM_STAT_AMD(VMEXIT_VINTR, "VM exits due to interrupt window");
1312311Sjkh
1322311Sjkh/*
1332311Sjkh * Common function to enable or disabled SVM for a CPU.
1342311Sjkh */
1352311Sjkhstatic int
1362311Sjkhcpu_svm_enable_disable(boolean_t enable)
1372311Sjkh{
1382311Sjkh	uint64_t efer_msr;
1392311Sjkh
1402311Sjkh	efer_msr = rdmsr(MSR_EFER);
1412311Sjkh
1422311Sjkh	if (enable)
1432311Sjkh		efer_msr |= EFER_SVM;
1442311Sjkh	else
1452311Sjkh		efer_msr &= ~EFER_SVM;
1462311Sjkh
1472311Sjkh	wrmsr(MSR_EFER, efer_msr);
1482311Sjkh
1492311Sjkh	return(0);
1502311Sjkh}
1512311Sjkh
1522311Sjkh/*
1532311Sjkh * Disable SVM on a CPU.
1542311Sjkh */
1552311Sjkhstatic void
1562311Sjkhsvm_disable(void *arg __unused)
1572311Sjkh{
1582311Sjkh
1592311Sjkh	(void)cpu_svm_enable_disable(FALSE);
1602311Sjkh}
1612311Sjkh
1622311Sjkh/*
1632311Sjkh * Disable SVM for all CPUs.
1642311Sjkh */
1652311Sjkhstatic int
1662311Sjkhsvm_cleanup(void)
1672311Sjkh{
1682311Sjkh
1692311Sjkh	smp_rendezvous(NULL, svm_disable, NULL, NULL);
1702311Sjkh	return (0);
1712311Sjkh}
1722311Sjkh
1732311Sjkh/*
1742311Sjkh * Check for required BHyVe SVM features in a CPU.
1752311Sjkh */
1762311Sjkhstatic int
1772311Sjkhsvm_cpuid_features(void)
1782311Sjkh{
17929452Scharnier	u_int regs[4];
18029452Scharnier
1812311Sjkh	/* CPUID Fn8000_000A is for SVM */
18229452Scharnier	do_cpuid(0x8000000A, regs);
18329452Scharnier	svm_feature = regs[3];
1842311Sjkh
1852311Sjkh	printf("SVM rev: 0x%x NASID:0x%x\n", regs[0] & 0xFF, regs[1]);
1862311Sjkh	nasid = regs[1];
1872311Sjkh	KASSERT(nasid > 1, ("Insufficient ASIDs for guests: %#x", nasid));
1882311Sjkh
1892311Sjkh	printf("SVM Features:0x%b\n", svm_feature,
1902311Sjkh		"\020"
1912311Sjkh		"\001NP"		/* Nested paging */
1922311Sjkh		"\002LbrVirt"		/* LBR virtualization */
1932311Sjkh		"\003SVML"		/* SVM lock */
1942311Sjkh		"\004NRIPS"		/* NRIP save */
1952311Sjkh		"\005TscRateMsr"	/* MSR based TSC rate control */
19629452Scharnier		"\006VmcbClean"		/* VMCB clean bits */
1972311Sjkh		"\007FlushByAsid"	/* Flush by ASID */
19829452Scharnier		"\010DecodeAssist"	/* Decode assist */
1992311Sjkh		"\011<b20>"
2002311Sjkh		"\012<b20>"
20129452Scharnier		"\013PauseFilter"
2022311Sjkh		"\014<b20>"
2032311Sjkh		"\015PauseFilterThreshold"
20429452Scharnier		"\016AVIC"
20529452Scharnier		);
20629452Scharnier
20729452Scharnier	/* SVM Lock */
2082311Sjkh	if (!(svm_feature & AMD_CPUID_SVM_SVML)) {
2092311Sjkh		printf("SVM is disabled by BIOS, please enable in BIOS.\n");
2102311Sjkh		return (ENXIO);
2112311Sjkh	}
21229452Scharnier
2132311Sjkh	/*
21429452Scharnier	 * bhyve need RVI to work.
2152311Sjkh	 */
2162311Sjkh	if (!(svm_feature & AMD_CPUID_SVM_NP)) {
21729452Scharnier		printf("Missing Nested paging or RVI SVM support in processor.\n");
2182311Sjkh		return (EIO);
2192311Sjkh	}
22029452Scharnier
22129452Scharnier	if (svm_feature & AMD_CPUID_SVM_NRIP_SAVE)
2222311Sjkh		return (0);
2232311Sjkh
2242311Sjkh	return (EIO);
2252311Sjkh}
2262311Sjkh
2272311Sjkhstatic __inline int
2282311Sjkhflush_by_asid(void)
2292311Sjkh{
2302311Sjkh
2312311Sjkh	return (svm_feature & AMD_CPUID_SVM_FLUSH_BY_ASID);
2322311Sjkh}
2332311Sjkh
2342311Sjkhstatic __inline int
2352311Sjkhdecode_assist(void)
2362311Sjkh{
2372311Sjkh
2382311Sjkh	return (svm_feature & AMD_CPUID_SVM_DECODE_ASSIST);
2392311Sjkh}
2402311Sjkh
2412311Sjkh/*
2422311Sjkh * Enable SVM for a CPU.
2432311Sjkh */
2442311Sjkhstatic void
2452311Sjkhsvm_enable(void *arg __unused)
2462311Sjkh{
2472311Sjkh	uint64_t hsave_pa;
2482311Sjkh
2492311Sjkh	(void)cpu_svm_enable_disable(TRUE);
2502311Sjkh
2512311Sjkh	hsave_pa = vtophys(hsave[curcpu]);
2522311Sjkh	wrmsr(MSR_VM_HSAVE_PA, hsave_pa);
2532311Sjkh
2542311Sjkh	if (rdmsr(MSR_VM_HSAVE_PA) != hsave_pa) {
2552311Sjkh		panic("VM_HSAVE_PA is wrong on CPU%d\n", curcpu);
2562311Sjkh	}
2572311Sjkh}
2582311Sjkh
2592311Sjkh/*
2602311Sjkh * Check if a processor support SVM.
2612311Sjkh */
2622311Sjkhstatic int
2632311Sjkhis_svm_enabled(void)
2642311Sjkh{
2652311Sjkh	uint64_t msr;
2662311Sjkh
2672311Sjkh	 /* Section 15.4 Enabling SVM from APM2. */
2682311Sjkh	if ((amd_feature2 & AMDID2_SVM) == 0) {
2692311Sjkh		printf("SVM is not supported on this processor.\n");
2702311Sjkh		return (ENXIO);
2712311Sjkh	}
2722311Sjkh
2732311Sjkh	msr = rdmsr(MSR_VM_CR);
2742311Sjkh	/* Make sure SVM is not disabled by BIOS. */
2752311Sjkh	if ((msr & VM_CR_SVMDIS) == 0) {
2762311Sjkh		return svm_cpuid_features();
2772311Sjkh	}
2782311Sjkh
2792311Sjkh	printf("SVM disabled by Key, consult TPM/BIOS manual.\n");
2802311Sjkh	return (ENXIO);
2812311Sjkh}
2822311Sjkh
2832311Sjkh/*
2842311Sjkh * Enable SVM on CPU and initialize nested page table h/w.
2852311Sjkh */
2862311Sjkhstatic int
2872311Sjkhsvm_init(int ipinum)
2882311Sjkh{
2892311Sjkh	int err, cpu;
2902311Sjkh
2912311Sjkh	err = is_svm_enabled();
2922311Sjkh	if (err)
2932311Sjkh		return (err);
2942311Sjkh
2952311Sjkh	for (cpu = 0; cpu < MAXCPU; cpu++) {
2962311Sjkh		/*
2972311Sjkh		 * Initialize the host ASIDs to their "highest" valid values.
2982311Sjkh		 *
2992311Sjkh		 * The next ASID allocation will rollover both 'gen' and 'num'
3002311Sjkh		 * and start off the sequence at {1,1}.
3012311Sjkh		 */
3022311Sjkh		asid[cpu].gen = ~0UL;
3032311Sjkh		asid[cpu].num = nasid - 1;
3042311Sjkh	}
3052311Sjkh
3062311Sjkh	svm_npt_init(ipinum);
3072311Sjkh
3082311Sjkh	/* Start SVM on all CPUs */
3092311Sjkh	smp_rendezvous(NULL, svm_enable, NULL, NULL);
3102311Sjkh
3112311Sjkh	return (0);
3122311Sjkh}
3132311Sjkh
3142311Sjkhstatic void
3152311Sjkhsvm_restore(void)
3162311Sjkh{
3172311Sjkh	svm_enable(NULL);
3182311Sjkh}
3192311Sjkh
3202311Sjkh/*
3212311Sjkh * Get index and bit position for a MSR in MSR permission
3222311Sjkh * bitmap. Two bits are used for each MSR, lower bit is
3232311Sjkh * for read and higher bit is for write.
3242311Sjkh */
3252311Sjkhstatic int
3262311Sjkhsvm_msr_index(uint64_t msr, int *index, int *bit)
327184809Smatteo{
3282311Sjkh	uint32_t base, off;
3292311Sjkh
3302311Sjkh/* Pentium compatible MSRs */
3312311Sjkh#define MSR_PENTIUM_START 	0
3322311Sjkh#define MSR_PENTIUM_END 	0x1FFF
3332311Sjkh/* AMD 6th generation and Intel compatible MSRs */
33494389Sdwmalone#define MSR_AMD6TH_START 	0xC0000000UL
33594389Sdwmalone#define MSR_AMD6TH_END 		0xC0001FFFUL
3362311Sjkh/* AMD 7th and 8th generation compatible MSRs */
3372311Sjkh#define MSR_AMD7TH_START 	0xC0010000UL
3382311Sjkh#define MSR_AMD7TH_END 		0xC0011FFFUL
3392311Sjkh
3402311Sjkh	*index = -1;
3412311Sjkh	*bit = (msr % 4) * 2;
3422311Sjkh	base = 0;
3432311Sjkh
3442311Sjkh	if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
3452311Sjkh		*index = msr / 4;
3462311Sjkh		return (0);
3472311Sjkh	}
3482311Sjkh
3492311Sjkh	base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
3502311Sjkh	if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
3512311Sjkh		off = (msr - MSR_AMD6TH_START);
352101293Stjr		*index = (off + base) / 4;
353101293Stjr		return (0);
3542311Sjkh	}
355101293Stjr
356101293Stjr	base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
357141571Sstefanf	if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
3582311Sjkh		off = (msr - MSR_AMD7TH_START);
359101293Stjr		*index = (off + base) / 4;
360101293Stjr		return (0);
361101293Stjr	}
362101293Stjr
363101293Stjr	return (EIO);
3642311Sjkh}
365101293Stjr
3662311Sjkh/*
3672311Sjkh * Give virtual cpu the complete access to MSR(read & write).
3682311Sjkh */
369101293Stjrstatic int
370101293Stjrsvm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
371101293Stjr{
372101293Stjr	int index, bit, err;
3732311Sjkh
374101293Stjr	err = svm_msr_index(msr, &index, &bit);
3752311Sjkh	if (err) {
376101293Stjr		ERR("MSR 0x%lx is not writeable by guest.\n", msr);
3772311Sjkh		return (err);
378101293Stjr	}
379101293Stjr
380101293Stjr	if (index < 0 || index > (SVM_MSR_BITMAP_SIZE)) {
381101293Stjr		ERR("MSR 0x%lx index out of range(%d).\n", msr, index);
382101293Stjr		return (EINVAL);
383101293Stjr	}
3842311Sjkh	if (bit < 0 || bit > 8) {
3852311Sjkh		ERR("MSR 0x%lx bit out of range(%d).\n", msr, bit);
3862311Sjkh		return (EINVAL);
3872311Sjkh	}
3882311Sjkh
3892311Sjkh	/* Disable intercept for read and write. */
3902311Sjkh	if (read)
3912311Sjkh		perm_bitmap[index] &= ~(1UL << bit);
3922311Sjkh	if (write)
3932311Sjkh		perm_bitmap[index] &= ~(2UL << bit);
3942311Sjkh	CTR2(KTR_VMM, "Guest has control:0x%x on SVM:MSR(0x%lx).\n",
3952311Sjkh		(perm_bitmap[index] >> bit) & 0x3, msr);
3962311Sjkh
3972311Sjkh	return (0);
3982311Sjkh}
3992311Sjkh
4002311Sjkhstatic int
4012311Sjkhsvm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
4022311Sjkh{
4032311Sjkh	return svm_msr_perm(perm_bitmap, msr, true, true);
4042311Sjkh}
4052311Sjkh
4062311Sjkhstatic int
4072311Sjkhsvm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
4082311Sjkh{
4092311Sjkh	return svm_msr_perm(perm_bitmap, msr, true, false);
4102311Sjkh}
4112311Sjkh
4122311Sjkhstatic __inline void
41360825Sghelmervcpu_set_dirty(struct svm_softc *sc, int vcpu, uint32_t dirtybits)
41460825Sghelmer{
41560825Sghelmer	struct svm_vcpu *vcpustate;
4162311Sjkh
41760825Sghelmer	vcpustate = svm_get_vcpu(sc, vcpu);
41860825Sghelmer
41960825Sghelmer	vcpustate->dirty |= dirtybits;
42060825Sghelmer}
42160825Sghelmer
42260825Sghelmerstatic __inline int
4232311Sjkhsvm_get_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask)
4242311Sjkh{
42560825Sghelmer	struct vmcb_ctrl *ctrl;
42660825Sghelmer
42760825Sghelmer	KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
42860825Sghelmer
42960825Sghelmer	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
43060825Sghelmer	return (ctrl->intercept[idx] & bitmask ? 1 : 0);
43160825Sghelmer}
43260825Sghelmer
4332311Sjkhstatic __inline void
43460825Sghelmersvm_set_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask,
43560825Sghelmer    int enabled)
43660825Sghelmer{
43760825Sghelmer	struct vmcb_ctrl *ctrl;
43860825Sghelmer	uint32_t oldval;
43960825Sghelmer
44060825Sghelmer	KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
44160825Sghelmer
44260825Sghelmer	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
44360825Sghelmer	oldval = ctrl->intercept[idx];
44460825Sghelmer
4452311Sjkh	if (enabled)
4462311Sjkh		ctrl->intercept[idx] |= bitmask;
4472311Sjkh	else
4482311Sjkh		ctrl->intercept[idx] &= ~bitmask;
4492311Sjkh
4502311Sjkh	if (ctrl->intercept[idx] != oldval) {
4512311Sjkh		vcpu_set_dirty(sc, vcpu, VMCB_CACHE_I);
4522311Sjkh		VCPU_CTR3(sc->vm, vcpu, "intercept[%d] modified "
4532311Sjkh		    "from %#x to %#x", idx, oldval, ctrl->intercept[idx]);
4542311Sjkh	}
4552311Sjkh}
4562311Sjkh
4572311Sjkhstatic __inline void
4582311Sjkhsvm_disable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
4592311Sjkh{
4602311Sjkh	svm_set_intercept(sc, vcpu, off, bitmask, 0);
4612311Sjkh}
4622311Sjkh
4632311Sjkhstatic __inline void
4642311Sjkhsvm_enable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
4652311Sjkh{
4662311Sjkh	svm_set_intercept(sc, vcpu, off, bitmask, 1);
4672311Sjkh}
4682311Sjkh
4692311Sjkhstatic void
4702311Sjkhvmcb_init(struct svm_softc *sc, int vcpu, uint64_t iopm_base_pa,
4712311Sjkh    uint64_t msrpm_base_pa, uint64_t np_pml4)
4722311Sjkh{
4732311Sjkh	struct vmcb_ctrl *ctrl;
4742311Sjkh	struct vmcb_state *state;
4752311Sjkh	uint32_t mask;
4762311Sjkh	int n;
4772311Sjkh
4782311Sjkh	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
4792311Sjkh	state = svm_get_vmcb_state(sc, vcpu);
4802311Sjkh
4812311Sjkh	ctrl->iopm_base_pa = iopm_base_pa;
4822311Sjkh	ctrl->msrpm_base_pa = msrpm_base_pa;
4832311Sjkh
4842311Sjkh	/* Enable nested paging */
4852311Sjkh	ctrl->np_enable = 1;
4862311Sjkh	ctrl->n_cr3 = np_pml4;
4872311Sjkh
4882311Sjkh	/*
4892311Sjkh	 * Intercept accesses to the control registers that are not shadowed
4902311Sjkh	 * in the VMCB - i.e. all except cr0, cr2, cr3, cr4 and cr8.
4912311Sjkh	 */
4922311Sjkh	for (n = 0; n < 16; n++) {
4932311Sjkh		mask = (BIT(n) << 16) | BIT(n);
4942311Sjkh		if (n == 0 || n == 2 || n == 3 || n == 4 || n == 8)
4952311Sjkh			svm_disable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
4962311Sjkh		else
4972311Sjkh			svm_enable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
4982311Sjkh	}
4992311Sjkh
5002311Sjkh	/* Intercept Machine Check exceptions. */
5012311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(IDT_MC));
5022311Sjkh
5032311Sjkh	/* Intercept various events (for e.g. I/O, MSR and CPUID accesses) */
5042311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IO);
5052311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_MSR);
5062311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_HLT);
5072311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_CPUID);
5082311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INTR);
5092311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INIT);
5102311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_NMI);
5112311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SMI);
5122311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SHUTDOWN);
5132311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
5142311Sjkh	    VMCB_INTCPT_FERR_FREEZE);
5152311Sjkh
5162311Sjkh	/*
5172311Sjkh	 * From section "Canonicalization and Consistency Checks" in APMv2
5182311Sjkh	 * the VMRUN intercept bit must be set to pass the consistency check.
5192311Sjkh	 */
5202311Sjkh	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMRUN);
521185043Smatteo
522184809Smatteo	/*
5232311Sjkh	 * The ASID will be set to a non-zero value just before VMRUN.
5242311Sjkh	 */
5252311Sjkh	ctrl->asid = 0;
5262311Sjkh
5272311Sjkh	/*
5282311Sjkh	 * Section 15.21.1, Interrupt Masking in EFLAGS
5292311Sjkh	 * Section 15.21.2, Virtualizing APIC.TPR
5302311Sjkh	 *
5312311Sjkh	 * This must be set for %rflag and %cr8 isolation of guest and host.
5322311Sjkh	 */
5332311Sjkh	ctrl->v_intr_masking = 1;
5342311Sjkh
5352311Sjkh	/* Enable Last Branch Record aka LBR for debugging */
5362311Sjkh	ctrl->lbr_virt_en = 1;
5372311Sjkh	state->dbgctl = BIT(0);
5382311Sjkh
5392311Sjkh	/* EFER_SVM must always be set when the guest is executing */
5402311Sjkh	state->efer = EFER_SVM;
5412311Sjkh
5422311Sjkh	/* Set up the PAT to power-on state */
5432311Sjkh	state->g_pat = PAT_VALUE(0, PAT_WRITE_BACK)	|
5442311Sjkh	    PAT_VALUE(1, PAT_WRITE_THROUGH)	|
5452311Sjkh	    PAT_VALUE(2, PAT_UNCACHED)		|
5462311Sjkh	    PAT_VALUE(3, PAT_UNCACHEABLE)	|
5472311Sjkh	    PAT_VALUE(4, PAT_WRITE_BACK)	|
5482311Sjkh	    PAT_VALUE(5, PAT_WRITE_THROUGH)	|
5492311Sjkh	    PAT_VALUE(6, PAT_UNCACHED)		|
5502311Sjkh	    PAT_VALUE(7, PAT_UNCACHEABLE);
5512311Sjkh}
5522311Sjkh
5532311Sjkh/*
5542311Sjkh * Initialise a virtual machine.
55560825Sghelmer */
55660825Sghelmerstatic void *
5572311Sjkhsvm_vminit(struct vm *vm, pmap_t pmap)
5582311Sjkh{
5592311Sjkh	struct svm_softc *svm_sc;
5602311Sjkh	struct svm_vcpu *vcpu;
5612311Sjkh	vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
5622311Sjkh	int i;
5632311Sjkh
5642311Sjkh	svm_sc = (struct svm_softc *)malloc(sizeof (struct svm_softc),
5652311Sjkh			M_SVM, M_WAITOK | M_ZERO);
5662311Sjkh
5672311Sjkh	svm_sc->vm = vm;
5682311Sjkh	svm_sc->svm_feature = svm_feature;
5692311Sjkh	svm_sc->vcpu_cnt = VM_MAXCPU;
5702311Sjkh	svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
5712311Sjkh
57242711Sdanny	/*
5738857Srgrimes	 * Intercept MSR access to all MSRs except GSBASE, FSBASE,... etc.
57442711Sdanny	 */
57542711Sdanny	 memset(svm_sc->msr_bitmap, 0xFF, sizeof(svm_sc->msr_bitmap));
57642711Sdanny
57742711Sdanny	/*
5782311Sjkh	 * Following MSR can be completely controlled by virtual machines
5792311Sjkh	 * since access to following are translated to access to VMCB.
5802311Sjkh	 */
5812311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
5822311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
5832311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
5842311Sjkh
5852311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
5862311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
5872311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
5882311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
5892311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
5902311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
5918164Sache	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
5922311Sjkh
5932311Sjkh	/* For Nested Paging/RVI only. */
5942311Sjkh	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
5952311Sjkh
5962311Sjkh	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
5972311Sjkh	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
5982311Sjkh
599	 /* Intercept access to all I/O ports. */
600	memset(svm_sc->iopm_bitmap, 0xFF, sizeof(svm_sc->iopm_bitmap));
601
602	/* Cache physical address for multiple vcpus. */
603	iopm_pa = vtophys(svm_sc->iopm_bitmap);
604	msrpm_pa = vtophys(svm_sc->msr_bitmap);
605	pml4_pa = svm_sc->nptp;
606
607	for (i = 0; i < svm_sc->vcpu_cnt; i++) {
608		vcpu = svm_get_vcpu(svm_sc, i);
609		vcpu->lastcpu = NOCPU;
610		vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
611		vmcb_init(svm_sc, i, iopm_pa, msrpm_pa, pml4_pa);
612	}
613	return (svm_sc);
614}
615
616static int
617svm_cpl(struct vmcb_state *state)
618{
619
620	/*
621	 * From APMv2:
622	 *   "Retrieve the CPL from the CPL field in the VMCB, not
623	 *    from any segment DPL"
624	 */
625	return (state->cpl);
626}
627
628static enum vm_cpu_mode
629svm_vcpu_mode(struct vmcb *vmcb)
630{
631	struct vmcb_segment *seg;
632	struct vmcb_state *state;
633
634	state = &vmcb->state;
635
636	if (state->efer & EFER_LMA) {
637		seg = vmcb_seg(vmcb, VM_REG_GUEST_CS);
638		/*
639		 * Section 4.8.1 for APM2, check if Code Segment has
640		 * Long attribute set in descriptor.
641		 */
642		if (seg->attrib & VMCB_CS_ATTRIB_L)
643			return (CPU_MODE_64BIT);
644		else
645			return (CPU_MODE_COMPATIBILITY);
646	} else  if (state->cr0 & CR0_PE) {
647		return (CPU_MODE_PROTECTED);
648	} else {
649		return (CPU_MODE_REAL);
650	}
651}
652
653static enum vm_paging_mode
654svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
655{
656
657	if ((cr0 & CR0_PG) == 0)
658		return (PAGING_MODE_FLAT);
659	if ((cr4 & CR4_PAE) == 0)
660		return (PAGING_MODE_32);
661	if (efer & EFER_LME)
662		return (PAGING_MODE_64);
663	else
664		return (PAGING_MODE_PAE);
665}
666
667/*
668 * ins/outs utility routines
669 */
670static uint64_t
671svm_inout_str_index(struct svm_regctx *regs, int in)
672{
673	uint64_t val;
674
675	val = in ? regs->e.g.sctx_rdi : regs->e.g.sctx_rsi;
676
677	return (val);
678}
679
680static uint64_t
681svm_inout_str_count(struct svm_regctx *regs, int rep)
682{
683	uint64_t val;
684
685	val = rep ? regs->sctx_rcx : 1;
686
687	return (val);
688}
689
690static void
691svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
692    int in, struct vm_inout_str *vis)
693{
694	int error, s;
695
696	if (in) {
697		vis->seg_name = VM_REG_GUEST_ES;
698	} else {
699		/* The segment field has standard encoding */
700		s = (info1 >> 10) & 0x7;
701		vis->seg_name = vm_segment_name(s);
702	}
703
704	error = svm_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
705	KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
706}
707
708static int
709svm_inout_str_addrsize(uint64_t info1)
710{
711        uint32_t size;
712
713        size = (info1 >> 7) & 0x7;
714        switch (size) {
715        case 1:
716                return (2);     /* 16 bit */
717        case 2:
718                return (4);     /* 32 bit */
719        case 4:
720                return (8);     /* 64 bit */
721        default:
722                panic("%s: invalid size encoding %d", __func__, size);
723        }
724}
725
726static void
727svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
728{
729	struct vmcb_state *state;
730
731	state = &vmcb->state;
732	paging->cr3 = state->cr3;
733	paging->cpl = svm_cpl(state);
734	paging->cpu_mode = svm_vcpu_mode(vmcb);
735	paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
736	    state->efer);
737}
738
739
740/*
741 * Handle guest I/O intercept.
742 */
743static bool
744svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
745{
746	struct vmcb_ctrl *ctrl;
747	struct vmcb_state *state;
748	struct svm_regctx *regs;
749	struct vm_inout_str *vis;
750	uint64_t info1;
751
752	state = svm_get_vmcb_state(svm_sc, vcpu);
753	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
754	regs  = svm_get_guest_regctx(svm_sc, vcpu);
755	info1 = ctrl->exitinfo1;
756
757	vmexit->exitcode 	= VM_EXITCODE_INOUT;
758	vmexit->u.inout.in 	= (info1 & BIT(0)) ? 1 : 0;
759	vmexit->u.inout.string 	= (info1 & BIT(2)) ? 1 : 0;
760	vmexit->u.inout.rep 	= (info1 & BIT(3)) ? 1 : 0;
761	vmexit->u.inout.bytes 	= (info1 >> 4) & 0x7;
762	vmexit->u.inout.port 	= (uint16_t)(info1 >> 16);
763	vmexit->u.inout.eax 	= (uint32_t)(state->rax);
764
765	if (vmexit->u.inout.string) {
766		vmexit->exitcode = VM_EXITCODE_INOUT_STR;
767		vis = &vmexit->u.inout_str;
768		svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
769		vis->rflags = state->rflags;
770		vis->cr0 = state->cr0;
771		vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
772		vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
773		vis->addrsize = svm_inout_str_addrsize(info1);
774		svm_inout_str_seginfo(svm_sc, vcpu, info1,
775		    vmexit->u.inout.in, vis);
776	}
777
778	return (false);
779}
780
781static int
782svm_npf_paging(uint64_t exitinfo1)
783{
784
785	if (exitinfo1 & VMCB_NPF_INFO1_W)
786		return (VM_PROT_WRITE);
787
788	return (VM_PROT_READ);
789}
790
791static bool
792svm_npf_emul_fault(uint64_t exitinfo1)
793{
794
795	if (exitinfo1 & VMCB_NPF_INFO1_ID) {
796		return (false);
797	}
798
799	if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
800		return (false);
801	}
802
803	if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
804		return (false);
805	}
806
807	return (true);
808}
809
810static void
811svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
812{
813	struct vm_guest_paging *paging;
814	struct vmcb_segment *seg;
815	struct vmcb_ctrl *ctrl;
816	char *inst_bytes;
817	int inst_len;
818
819	ctrl = &vmcb->ctrl;
820	paging = &vmexit->u.inst_emul.paging;
821
822	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
823	vmexit->u.inst_emul.gpa = gpa;
824	vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
825	svm_paging_info(vmcb, paging);
826
827	/*
828	 * The inst_length will be determined by decoding the instruction.
829	 */
830	vmexit->inst_length = 0;
831
832	seg = vmcb_seg(vmcb, VM_REG_GUEST_CS);
833	switch(paging->cpu_mode) {
834	case CPU_MODE_PROTECTED:
835	case CPU_MODE_COMPATIBILITY:
836		/*
837		 * Section 4.8.1 of APM2, Default Operand Size or D bit.
838		 */
839		vmexit->u.inst_emul.cs_d = (seg->attrib & VMCB_CS_ATTRIB_D) ?
840		    1 : 0;
841		break;
842	default:
843		vmexit->u.inst_emul.cs_d = 0;
844		break;
845	}
846
847	/*
848	 * Copy the instruction bytes into 'vie' if available.
849	 */
850	if (decode_assist() && !disable_npf_assist) {
851		inst_len = ctrl->inst_len;
852		inst_bytes = ctrl->inst_bytes;
853	} else {
854		inst_len = 0;
855		inst_bytes = NULL;
856	}
857	vie_init(&vmexit->u.inst_emul.vie, inst_bytes, inst_len);
858}
859
860/*
861 * Intercept access to MSR_EFER to prevent the guest from clearing the
862 * SVM enable bit.
863 */
864static void
865svm_write_efer(struct svm_softc *sc, int vcpu, uint32_t edx, uint32_t eax)
866{
867	struct vmcb_state *state;
868	uint64_t oldval;
869
870	state = svm_get_vmcb_state(sc, vcpu);
871
872	oldval = state->efer;
873	state->efer = (uint64_t)edx << 32 | eax | EFER_SVM;
874	if (state->efer != oldval) {
875		VCPU_CTR2(sc->vm, vcpu, "Guest EFER changed from %#lx to %#lx",
876		    oldval, state->efer);
877		vcpu_set_dirty(sc, vcpu, VMCB_CACHE_CR);
878	}
879}
880
881#ifdef KTR
882static const char *
883intrtype_to_str(int intr_type)
884{
885	switch (intr_type) {
886	case VMCB_EVENTINJ_TYPE_INTR:
887		return ("hwintr");
888	case VMCB_EVENTINJ_TYPE_NMI:
889		return ("nmi");
890	case VMCB_EVENTINJ_TYPE_INTn:
891		return ("swintr");
892	case VMCB_EVENTINJ_TYPE_EXCEPTION:
893		return ("exception");
894	default:
895		panic("%s: unknown intr_type %d", __func__, intr_type);
896	}
897}
898#endif
899
900/*
901 * Inject an event to vcpu as described in section 15.20, "Event injection".
902 */
903static void
904svm_eventinject(struct svm_softc *sc, int vcpu, int intr_type, int vector,
905		 uint32_t error, bool ec_valid)
906{
907	struct vmcb_ctrl *ctrl;
908
909	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
910
911	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0,
912	    ("%s: event already pending %#lx", __func__, ctrl->eventinj));
913
914	KASSERT(vector >=0 && vector <= 255, ("%s: invalid vector %d",
915	    __func__, vector));
916
917	switch (intr_type) {
918	case VMCB_EVENTINJ_TYPE_INTR:
919	case VMCB_EVENTINJ_TYPE_NMI:
920	case VMCB_EVENTINJ_TYPE_INTn:
921		break;
922	case VMCB_EVENTINJ_TYPE_EXCEPTION:
923		if (vector >= 0 && vector <= 31 && vector != 2)
924			break;
925		/* FALLTHROUGH */
926	default:
927		panic("%s: invalid intr_type/vector: %d/%d", __func__,
928		    intr_type, vector);
929	}
930	ctrl->eventinj = vector | (intr_type << 8) | VMCB_EVENTINJ_VALID;
931	if (ec_valid) {
932		ctrl->eventinj |= VMCB_EVENTINJ_EC_VALID;
933		ctrl->eventinj |= (uint64_t)error << 32;
934		VCPU_CTR3(sc->vm, vcpu, "Injecting %s at vector %d errcode %#x",
935		    intrtype_to_str(intr_type), vector, error);
936	} else {
937		VCPU_CTR2(sc->vm, vcpu, "Injecting %s at vector %d",
938		    intrtype_to_str(intr_type), vector);
939	}
940}
941
942static void
943svm_save_intinfo(struct svm_softc *svm_sc, int vcpu)
944{
945	struct vmcb_ctrl *ctrl;
946	uint64_t intinfo;
947
948	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
949	intinfo = ctrl->exitintinfo;
950	if (!VMCB_EXITINTINFO_VALID(intinfo))
951		return;
952
953	/*
954	 * From APMv2, Section "Intercepts during IDT interrupt delivery"
955	 *
956	 * If a #VMEXIT happened during event delivery then record the event
957	 * that was being delivered.
958	 */
959	VCPU_CTR2(svm_sc->vm, vcpu, "SVM:Pending INTINFO(0x%lx), vector=%d.\n",
960		intinfo, VMCB_EXITINTINFO_VECTOR(intinfo));
961	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
962	vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
963}
964
965static __inline void
966enable_intr_window_exiting(struct svm_softc *sc, int vcpu)
967{
968	struct vmcb_ctrl *ctrl;
969
970	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
971
972	if (ctrl->v_irq == 0) {
973		VCPU_CTR0(sc->vm, vcpu, "Enable intr window exiting");
974		ctrl->v_irq = 1;
975		ctrl->v_ign_tpr = 1;
976		vcpu_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
977		svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
978		    VMCB_INTCPT_VINTR);
979	}
980}
981
982static __inline void
983disable_intr_window_exiting(struct svm_softc *sc, int vcpu)
984{
985	struct vmcb_ctrl *ctrl;
986
987	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
988
989	if (ctrl->v_irq) {
990		VCPU_CTR0(sc->vm, vcpu, "Disable intr window exiting");
991		ctrl->v_irq = 0;
992		vcpu_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
993		svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
994		    VMCB_INTCPT_VINTR);
995	}
996}
997
998static int
999nmi_blocked(struct svm_softc *sc, int vcpu)
1000{
1001	/* XXX need to track NMI blocking */
1002	return (0);
1003}
1004
1005static void
1006enable_nmi_blocking(struct svm_softc *sc, int vcpu)
1007{
1008	/* XXX enable iret intercept */
1009}
1010
1011#ifdef notyet
1012static void
1013clear_nmi_blocking(struct svm_softc *sc, int vcpu)
1014{
1015	/* XXX disable iret intercept */
1016}
1017#endif
1018
1019#ifdef KTR
1020static const char *
1021exit_reason_to_str(uint64_t reason)
1022{
1023	static char reasonbuf[32];
1024
1025	switch (reason) {
1026	case VMCB_EXIT_INVALID:
1027		return ("invalvmcb");
1028	case VMCB_EXIT_SHUTDOWN:
1029		return ("shutdown");
1030	case VMCB_EXIT_NPF:
1031		return ("nptfault");
1032	case VMCB_EXIT_PAUSE:
1033		return ("pause");
1034	case VMCB_EXIT_HLT:
1035		return ("hlt");
1036	case VMCB_EXIT_CPUID:
1037		return ("cpuid");
1038	case VMCB_EXIT_IO:
1039		return ("inout");
1040	case VMCB_EXIT_MC:
1041		return ("mchk");
1042	case VMCB_EXIT_INTR:
1043		return ("extintr");
1044	case VMCB_EXIT_VINTR:
1045		return ("vintr");
1046	case VMCB_EXIT_MSR:
1047		return ("msr");
1048	default:
1049		snprintf(reasonbuf, sizeof(reasonbuf), "%#lx", reason);
1050		return (reasonbuf);
1051	}
1052}
1053#endif	/* KTR */
1054
1055/*
1056 * Determine the cause of virtual cpu exit and handle VMEXIT.
1057 * Return: false - Break vcpu execution loop and handle vmexit
1058 *		   in kernel or user space.
1059 *	   true  - Continue vcpu run.
1060 */
1061static bool
1062svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
1063{
1064	struct vmcb_state *state;
1065	struct vmcb_ctrl *ctrl;
1066	struct svm_regctx *ctx;
1067	uint64_t code, info1, info2, val;
1068	uint32_t eax, ecx, edx;
1069	bool update_rip, loop, retu;
1070
1071	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1072
1073	state = svm_get_vmcb_state(svm_sc, vcpu);
1074	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
1075	ctx   = svm_get_guest_regctx(svm_sc, vcpu);
1076	code  = ctrl->exitcode;
1077	info1 = ctrl->exitinfo1;
1078	info2 = ctrl->exitinfo2;
1079
1080	update_rip = true;
1081	loop = true;
1082	vmexit->exitcode = VM_EXITCODE_VMX;
1083	vmexit->u.vmx.status = 0;
1084
1085	vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_COUNT, 1);
1086
1087	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
1088	    "injection valid bit is set %#lx", __func__, ctrl->eventinj));
1089
1090	svm_save_intinfo(svm_sc, vcpu);
1091
1092	switch (code) {
1093	case VMCB_EXIT_VINTR:
1094		update_rip = false;
1095		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_VINTR, 1);
1096		break;
1097	case VMCB_EXIT_MC:	/* Machine Check. */
1098		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_MTRAP, 1);
1099		vmexit->exitcode = VM_EXITCODE_MTRAP;
1100		loop = false;
1101		break;
1102	case VMCB_EXIT_MSR:	/* MSR access. */
1103		eax = state->rax;
1104		ecx = ctx->sctx_rcx;
1105		edx = ctx->e.g.sctx_rdx;
1106
1107		if (ecx == MSR_EFER) {
1108			KASSERT(info1 != 0, ("rdmsr(MSR_EFER) is not "
1109			    "emulated: info1(%#lx) info2(%#lx)",
1110			    info1, info2));
1111			svm_write_efer(svm_sc, vcpu, edx, eax);
1112			break;
1113		}
1114
1115		retu = false;
1116		if (info1) {
1117			/* VM exited because of write MSR */
1118			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_WRMSR, 1);
1119			vmexit->exitcode = VM_EXITCODE_WRMSR;
1120			vmexit->u.msr.code = ecx;
1121			val = (uint64_t)edx << 32 | eax;
1122			if (emulate_wrmsr(svm_sc->vm, vcpu, ecx, val, &retu)) {
1123				vmexit->u.msr.wval = val;
1124				loop = false;
1125			} else
1126				loop = retu ? false : true;
1127			VCPU_CTR3(svm_sc->vm, vcpu,
1128			    "VMEXIT WRMSR(%s handling) 0x%lx @0x%x",
1129			    loop ? "kernel" : "user", val, ecx);
1130		} else {
1131			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_RDMSR, 1);
1132			vmexit->exitcode = VM_EXITCODE_RDMSR;
1133			vmexit->u.msr.code = ecx;
1134			if (emulate_rdmsr(svm_sc->vm, vcpu, ecx, &retu))
1135				loop = false;
1136			else
1137				loop = retu ? false : true;
1138			VCPU_CTR3(svm_sc->vm, vcpu, "SVM:VMEXIT RDMSR"
1139			    " MSB=0x%08x, LSB=%08x @0x%x",
1140			    ctx->e.g.sctx_rdx, state->rax, ecx);
1141		}
1142
1143#define MSR_AMDK8_IPM           0xc0010055
1144		/*
1145		 * We can't hide AMD C1E idle capability since its
1146		 * based on CPU generation, for now ignore access to
1147		 * this MSR by vcpus
1148		 * XXX: special handling of AMD C1E - Ignore.
1149		 */
1150		 if (ecx == MSR_AMDK8_IPM)
1151			loop = true;
1152		break;
1153	case VMCB_EXIT_INTR:
1154		/*
1155		 * Exit on External Interrupt.
1156		 * Give host interrupt handler to run and if its guest
1157		 * interrupt, local APIC will inject event in guest.
1158		 */
1159		update_rip = false;
1160		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
1161		break;
1162	case VMCB_EXIT_IO:
1163		loop = svm_handle_io(svm_sc, vcpu, vmexit);
1164		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
1165		break;
1166	case VMCB_EXIT_CPUID:
1167		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
1168		loop = x86_emulate_cpuid(svm_sc->vm, vcpu,
1169		    (uint32_t *)&state->rax,
1170		    (uint32_t *)&ctx->sctx_rbx,
1171		    (uint32_t *)&ctx->sctx_rcx,
1172		    (uint32_t *)&ctx->e.g.sctx_rdx);
1173		break;
1174	case VMCB_EXIT_HLT:
1175		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
1176		vmexit->exitcode = VM_EXITCODE_HLT;
1177		vmexit->u.hlt.rflags = state->rflags;
1178		loop = false;
1179		break;
1180	case VMCB_EXIT_PAUSE:
1181		vmexit->exitcode = VM_EXITCODE_PAUSE;
1182		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
1183		loop = false;
1184		break;
1185	case VMCB_EXIT_NPF:
1186		loop = false;
1187		update_rip = false;
1188		if (info1 & VMCB_NPF_INFO1_RSV) {
1189			VCPU_CTR2(svm_sc->vm, vcpu, "nested page fault with "
1190			    "reserved bits set: info1(%#lx) info2(%#lx)",
1191			    info1, info2);
1192			break;
1193		}
1194
1195		/* EXITINFO2 has the physical fault address (GPA). */
1196		if(vm_mem_allocated(svm_sc->vm, info2)) {
1197			vmexit->exitcode = VM_EXITCODE_PAGING;
1198			vmexit->u.paging.gpa = info2;
1199			vmexit->u.paging.fault_type = svm_npf_paging(info1);
1200			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1201			VCPU_CTR3(svm_sc->vm, vcpu, "nested page fault "
1202			    "on gpa %#lx/%#lx at rip %#lx",
1203			    info2, info1, state->rip);
1204		} else if (svm_npf_emul_fault(info1)) {
1205			svm_handle_inst_emul(svm_get_vmcb(svm_sc, vcpu),
1206				info2, vmexit);
1207			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INST_EMUL, 1);
1208			VCPU_CTR3(svm_sc->vm, vcpu, "inst_emul fault "
1209			    "for gpa %#lx/%#lx at rip %#lx",
1210			    info2, info1, state->rip);
1211		}
1212		break;
1213	case VMCB_EXIT_SHUTDOWN:
1214		loop = false;
1215		break;
1216	case VMCB_EXIT_INVALID:
1217		loop = false;
1218		break;
1219	default:
1220		/* Return to user space. */
1221		loop = false;
1222		update_rip = false;
1223		VCPU_CTR3(svm_sc->vm, vcpu, "VMEXIT=0x%lx"
1224			" EXITINFO1: 0x%lx EXITINFO2:0x%lx\n",
1225			ctrl->exitcode, info1, info2);
1226		VCPU_CTR3(svm_sc->vm, vcpu, "SVM:RIP: 0x%lx nRIP:0x%lx"
1227			" Inst decoder len:%d\n", state->rip,
1228			ctrl->nrip, ctrl->inst_len);
1229		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
1230		break;
1231	}
1232
1233	VCPU_CTR4(svm_sc->vm, vcpu, "%s %s vmexit at %#lx nrip %#lx",
1234	    loop ? "handled" : "unhandled", exit_reason_to_str(code),
1235	    state->rip, update_rip ? ctrl->nrip : state->rip);
1236
1237	vmexit->rip = state->rip;
1238	if (update_rip) {
1239		if (ctrl->nrip == 0) {
1240 			VCPU_CTR1(svm_sc->vm, vcpu, "SVM_ERR:nRIP is not set "
1241				 "for RIP0x%lx.\n", state->rip);
1242			vmexit->exitcode = VM_EXITCODE_VMX;
1243		} else
1244			vmexit->rip = ctrl->nrip;
1245	}
1246
1247	/* If vcpu execution is continued, update RIP. */
1248	if (loop) {
1249		state->rip = vmexit->rip;
1250	}
1251
1252	return (loop);
1253}
1254
1255static void
1256svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
1257{
1258	uint64_t intinfo;
1259
1260	if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
1261		return;
1262
1263	KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1264	    "valid: %#lx", __func__, intinfo));
1265
1266	svm_eventinject(svm_sc, vcpu, VMCB_EXITINTINFO_TYPE(intinfo),
1267		VMCB_EXITINTINFO_VECTOR(intinfo),
1268		VMCB_EXITINTINFO_EC(intinfo),
1269		VMCB_EXITINTINFO_EC_VALID(intinfo));
1270	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1271	VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1272}
1273
1274/*
1275 * Inject event to virtual cpu.
1276 */
1277static void
1278svm_inj_interrupts(struct svm_softc *sc, int vcpu, struct vlapic *vlapic)
1279{
1280	struct vmcb_ctrl *ctrl;
1281	struct vmcb_state *state;
1282	int extint_pending;
1283	int vector, need_intr_window;
1284
1285	state = svm_get_vmcb_state(sc, vcpu);
1286	ctrl  = svm_get_vmcb_ctrl(sc, vcpu);
1287
1288	need_intr_window = 0;
1289
1290	/*
1291	 * Inject pending events or exceptions for this vcpu.
1292	 *
1293	 * An event might be pending because the previous #VMEXIT happened
1294	 * during event delivery (i.e. ctrl->exitintinfo).
1295	 *
1296	 * An event might also be pending because an exception was injected
1297	 * by the hypervisor (e.g. #PF during instruction emulation).
1298	 */
1299	svm_inj_intinfo(sc, vcpu);
1300
1301	/* NMI event has priority over interrupts. */
1302	if (vm_nmi_pending(sc->vm, vcpu)) {
1303		if (nmi_blocked(sc, vcpu)) {
1304			/*
1305			 * Can't inject another NMI if the guest has not
1306			 * yet executed an "iret" after the last NMI.
1307			 */
1308			VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due "
1309			    "to NMI-blocking");
1310		} else if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1311			/*
1312			 * If there is already an exception/interrupt pending
1313			 * then defer the NMI until after that.
1314			 */
1315			VCPU_CTR1(sc->vm, vcpu, "Cannot inject NMI due to "
1316			    "eventinj %#lx", ctrl->eventinj);
1317
1318			/*
1319			 * Use self-IPI to trigger a VM-exit as soon as
1320			 * possible after the event injection is completed.
1321			 *
1322			 * This works only if the external interrupt exiting
1323			 * is at a lower priority than the event injection.
1324			 *
1325			 * Although not explicitly specified in APMv2 the
1326			 * relative priorities were verified empirically.
1327			 */
1328			ipi_cpu(curcpu, IPI_AST);	/* XXX vmm_ipinum? */
1329		} else {
1330			vm_nmi_clear(sc->vm, vcpu);
1331
1332			/* Inject NMI, vector number is not used */
1333			svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_NMI,
1334			    IDT_NMI, 0, false);
1335
1336			/* virtual NMI blocking is now in effect */
1337			enable_nmi_blocking(sc, vcpu);
1338
1339			VCPU_CTR0(sc->vm, vcpu, "Injecting vNMI");
1340		}
1341	}
1342
1343	extint_pending = vm_extint_pending(sc->vm, vcpu);
1344
1345	if (!extint_pending) {
1346		/* Ask the local apic for a vector to inject */
1347		if (!vlapic_pending_intr(vlapic, &vector)) {
1348			goto done;	/* nothing to inject */
1349		}
1350		KASSERT(vector >= 16 && vector <= 255,
1351		    ("invalid vector %d from local APIC", vector));
1352	} else {
1353                /* Ask the legacy pic for a vector to inject */
1354                vatpic_pending_intr(sc->vm, &vector);
1355		KASSERT(vector >= 0 && vector <= 255,
1356		    ("invalid vector %d from local APIC", vector));
1357	}
1358
1359	/*
1360	 * If the guest has disabled interrupts or is in an interrupt shadow
1361	 * then we cannot inject the pending interrupt.
1362	 */
1363	if ((state->rflags & PSL_I) == 0) {
1364		VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1365		    "rflags %#lx", vector, state->rflags);
1366		need_intr_window = 1;
1367		goto done;
1368	}
1369
1370	if (ctrl->intr_shadow) {
1371		VCPU_CTR1(sc->vm, vcpu, "Cannot inject vector %d due to "
1372		    "interrupt shadow", vector);
1373		need_intr_window = 1;
1374		goto done;
1375	}
1376
1377	if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1378		VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1379		    "eventinj %#lx", vector, ctrl->eventinj);
1380		need_intr_window = 1;
1381		goto done;
1382	}
1383
1384	svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1385
1386        if (!extint_pending) {
1387                /* Update the Local APIC ISR */
1388                vlapic_intr_accepted(vlapic, vector);
1389        } else {
1390                vm_extint_clear(sc->vm, vcpu);
1391                vatpic_intr_accepted(sc->vm, vector);
1392		/*
1393		 * Force a VM-exit as soon as the vcpu is ready to accept
1394		 * another interrupt. This is done because the PIC might
1395		 * have another vector that it wants to inject. Also, if
1396		 * the vlapic has a pending interrupt that was preempted
1397		 * by the ExtInt then it allows us to inject the APIC
1398		 * vector as soon as possible.
1399		 */
1400		need_intr_window = 1;
1401        }
1402done:
1403	if (need_intr_window) {
1404		/*
1405		 * We use V_IRQ in conjunction with the VINTR intercept to
1406		 * trap into the hypervisor as soon as a virtual interrupt
1407		 * can be delivered.
1408		 *
1409		 * Since injected events are not subject to intercept checks
1410		 * we need to ensure that the V_IRQ is not actually going to
1411		 * be delivered on VM entry. The KASSERT below enforces this.
1412		 */
1413		KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) != 0 ||
1414		    (state->rflags & PSL_I) == 0 || ctrl->intr_shadow,
1415		    ("Bogus intr_window_exiting: eventinj (%#lx), "
1416		    "intr_shadow (%u), rflags (%#lx)",
1417		    ctrl->eventinj, ctrl->intr_shadow, state->rflags));
1418		enable_intr_window_exiting(sc, vcpu);
1419	} else {
1420		disable_intr_window_exiting(sc, vcpu);
1421	}
1422}
1423
1424static __inline void
1425restore_host_tss(void)
1426{
1427	struct system_segment_descriptor *tss_sd;
1428
1429	/*
1430	 * The TSS descriptor was in use prior to launching the guest so it
1431	 * has been marked busy.
1432	 *
1433	 * 'ltr' requires the descriptor to be marked available so change the
1434	 * type to "64-bit available TSS".
1435	 */
1436	tss_sd = PCPU_GET(tss);
1437	tss_sd->sd_type = SDT_SYSTSS;
1438	ltr(GSEL(GPROC0_SEL, SEL_KPL));
1439}
1440
1441static void
1442check_asid(struct svm_softc *sc, int vcpuid, pmap_t pmap, u_int thiscpu)
1443{
1444	struct svm_vcpu *vcpustate;
1445	struct vmcb_ctrl *ctrl;
1446	long eptgen;
1447	bool alloc_asid;
1448
1449	KASSERT(CPU_ISSET(thiscpu, &pmap->pm_active), ("%s: nested pmap not "
1450	    "active on cpu %u", __func__, thiscpu));
1451
1452	vcpustate = svm_get_vcpu(sc, vcpuid);
1453	ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1454
1455	/*
1456	 * The TLB entries associated with the vcpu's ASID are not valid
1457	 * if either of the following conditions is true:
1458	 *
1459	 * 1. The vcpu's ASID generation is different than the host cpu's
1460	 *    ASID generation. This happens when the vcpu migrates to a new
1461	 *    host cpu. It can also happen when the number of vcpus executing
1462	 *    on a host cpu is greater than the number of ASIDs available.
1463	 *
1464	 * 2. The pmap generation number is different than the value cached in
1465	 *    the 'vcpustate'. This happens when the host invalidates pages
1466	 *    belonging to the guest.
1467	 *
1468	 *	asidgen		eptgen	      Action
1469	 *	mismatch	mismatch
1470	 *	   0		   0		(a)
1471	 *	   0		   1		(b1) or (b2)
1472	 *	   1		   0		(c)
1473	 *	   1		   1		(d)
1474	 *
1475	 * (a) There is no mismatch in eptgen or ASID generation and therefore
1476	 *     no further action is needed.
1477	 *
1478	 * (b1) If the cpu supports FlushByAsid then the vcpu's ASID is
1479	 *      retained and the TLB entries associated with this ASID
1480	 *      are flushed by VMRUN.
1481	 *
1482	 * (b2) If the cpu does not support FlushByAsid then a new ASID is
1483	 *      allocated.
1484	 *
1485	 * (c) A new ASID is allocated.
1486	 *
1487	 * (d) A new ASID is allocated.
1488	 */
1489
1490	alloc_asid = false;
1491	eptgen = pmap->pm_eptgen;
1492	ctrl->tlb_ctrl = VMCB_TLB_FLUSH_NOTHING;
1493
1494	if (vcpustate->asid.gen != asid[thiscpu].gen) {
1495		alloc_asid = true;	/* (c) and (d) */
1496	} else if (vcpustate->eptgen != eptgen) {
1497		if (flush_by_asid())
1498			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;	/* (b1) */
1499		else
1500			alloc_asid = true;			/* (b2) */
1501	} else {
1502		/*
1503		 * This is the common case (a).
1504		 */
1505		KASSERT(!alloc_asid, ("ASID allocation not necessary"));
1506		KASSERT(ctrl->tlb_ctrl == VMCB_TLB_FLUSH_NOTHING,
1507		    ("Invalid VMCB tlb_ctrl: %#x", ctrl->tlb_ctrl));
1508	}
1509
1510	if (alloc_asid) {
1511		if (++asid[thiscpu].num >= nasid) {
1512			asid[thiscpu].num = 1;
1513			if (++asid[thiscpu].gen == 0)
1514				asid[thiscpu].gen = 1;
1515			/*
1516			 * If this cpu does not support "flush-by-asid"
1517			 * then flush the entire TLB on a generation
1518			 * bump. Subsequent ASID allocation in this
1519			 * generation can be done without a TLB flush.
1520			 */
1521			if (!flush_by_asid())
1522				ctrl->tlb_ctrl = VMCB_TLB_FLUSH_ALL;
1523		}
1524		vcpustate->asid.gen = asid[thiscpu].gen;
1525		vcpustate->asid.num = asid[thiscpu].num;
1526
1527		ctrl->asid = vcpustate->asid.num;
1528		vcpu_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1529		/*
1530		 * If this cpu supports "flush-by-asid" then the TLB
1531		 * was not flushed after the generation bump. The TLB
1532		 * is flushed selectively after every new ASID allocation.
1533		 */
1534		if (flush_by_asid())
1535			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1536	}
1537	vcpustate->eptgen = eptgen;
1538
1539	KASSERT(ctrl->asid != 0, ("Guest ASID must be non-zero"));
1540	KASSERT(ctrl->asid == vcpustate->asid.num,
1541	    ("ASID mismatch: %u/%u", ctrl->asid, vcpustate->asid.num));
1542}
1543
1544/*
1545 * Start vcpu with specified RIP.
1546 */
1547static int
1548svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1549	void *rend_cookie, void *suspended_cookie)
1550{
1551	struct svm_regctx *hctx, *gctx;
1552	struct svm_softc *svm_sc;
1553	struct svm_vcpu *vcpustate;
1554	struct vmcb_state *state;
1555	struct vmcb_ctrl *ctrl;
1556	struct vm_exit *vmexit;
1557	struct vlapic *vlapic;
1558	struct vm *vm;
1559	uint64_t vmcb_pa;
1560	u_int thiscpu;
1561	bool loop;	/* Continue vcpu execution loop. */
1562
1563	loop = true;
1564	svm_sc = arg;
1565	vm = svm_sc->vm;
1566
1567	vcpustate = svm_get_vcpu(svm_sc, vcpu);
1568	state = svm_get_vmcb_state(svm_sc, vcpu);
1569	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1570	vmexit = vm_exitinfo(vm, vcpu);
1571	vlapic = vm_lapic(vm, vcpu);
1572
1573	/*
1574	 * Stash 'curcpu' on the stack as 'thiscpu'.
1575	 *
1576	 * The per-cpu data area is not accessible until MSR_GSBASE is restored
1577	 * after the #VMEXIT. Since VMRUN is executed inside a critical section
1578	 * 'curcpu' and 'thiscpu' are guaranteed to identical.
1579	 */
1580	thiscpu = curcpu;
1581
1582	gctx = svm_get_guest_regctx(svm_sc, vcpu);
1583	hctx = &host_ctx[thiscpu];
1584	vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1585
1586	if (vcpustate->lastcpu != thiscpu) {
1587		/*
1588		 * Force new ASID allocation by invalidating the generation.
1589		 */
1590		vcpustate->asid.gen = 0;
1591
1592		/*
1593		 * Invalidate the VMCB state cache by marking all fields dirty.
1594		 */
1595		vcpu_set_dirty(svm_sc, vcpu, 0xffffffff);
1596
1597		/*
1598		 * XXX
1599		 * Setting 'vcpustate->lastcpu' here is bit premature because
1600		 * we may return from this function without actually executing
1601		 * the VMRUN  instruction. This could happen if a rendezvous
1602		 * or an AST is pending on the first time through the loop.
1603		 *
1604		 * This works for now but any new side-effects of vcpu
1605		 * migration should take this case into account.
1606		 */
1607		vcpustate->lastcpu = thiscpu;
1608		vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1609	}
1610
1611	/* Update Guest RIP */
1612	state->rip = rip;
1613
1614	do {
1615		vmexit->inst_length = 0;
1616
1617		/*
1618		 * Disable global interrupts to guarantee atomicity during
1619		 * loading of guest state. This includes not only the state
1620		 * loaded by the "vmrun" instruction but also software state
1621		 * maintained by the hypervisor: suspended and rendezvous
1622		 * state, NPT generation number, vlapic interrupts etc.
1623		 */
1624		disable_gintr();
1625
1626		if (vcpu_suspended(suspended_cookie)) {
1627			enable_gintr();
1628			vm_exit_suspended(vm, vcpu, state->rip);
1629			break;
1630		}
1631
1632		if (vcpu_rendezvous_pending(rend_cookie)) {
1633			enable_gintr();
1634			vm_exit_rendezvous(vm, vcpu, state->rip);
1635			break;
1636		}
1637
1638		/* We are asked to give the cpu by scheduler. */
1639		if (curthread->td_flags & (TDF_ASTPENDING | TDF_NEEDRESCHED)) {
1640			enable_gintr();
1641			vm_exit_astpending(vm, vcpu, state->rip);
1642			break;
1643		}
1644
1645		svm_inj_interrupts(svm_sc, vcpu, vlapic);
1646
1647		/* Activate the nested pmap on 'thiscpu' */
1648		CPU_SET_ATOMIC_ACQ(thiscpu, &pmap->pm_active);
1649
1650		/*
1651		 * Check the pmap generation and the ASID generation to
1652		 * ensure that the vcpu does not use stale TLB mappings.
1653		 */
1654		check_asid(svm_sc, vcpu, pmap, thiscpu);
1655
1656		ctrl->vmcb_clean = VMCB_CACHE_DEFAULT & ~vcpustate->dirty;
1657		vcpustate->dirty = 0;
1658		VCPU_CTR1(vm, vcpu, "vmcb clean %#x", ctrl->vmcb_clean);
1659
1660		/* Launch Virtual Machine. */
1661		VCPU_CTR1(vm, vcpu, "Resume execution at %#lx", state->rip);
1662		svm_launch(vmcb_pa, gctx, hctx);
1663
1664		CPU_CLR_ATOMIC(thiscpu, &pmap->pm_active);
1665
1666		/*
1667		 * Restore MSR_GSBASE to point to the pcpu data area.
1668		 *
1669		 * Note that accesses done via PCPU_GET/PCPU_SET will work
1670		 * only after MSR_GSBASE is restored.
1671		 *
1672		 * Also note that we don't bother restoring MSR_KGSBASE
1673		 * since it is not used in the kernel and will be restored
1674		 * when the VMRUN ioctl returns to userspace.
1675		 */
1676		wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[thiscpu]);
1677		KASSERT(curcpu == thiscpu, ("thiscpu/curcpu (%u/%u) mismatch",
1678		    thiscpu, curcpu));
1679
1680		/*
1681		 * The host GDTR and IDTR is saved by VMRUN and restored
1682		 * automatically on #VMEXIT. However, the host TSS needs
1683		 * to be restored explicitly.
1684		 */
1685		restore_host_tss();
1686
1687		/* #VMEXIT disables interrupts so re-enable them here. */
1688		enable_gintr();
1689
1690		/* Handle #VMEXIT and if required return to user space. */
1691		loop = svm_vmexit(svm_sc, vcpu, vmexit);
1692	} while (loop);
1693
1694	return (0);
1695}
1696
1697/*
1698 * Cleanup for virtual machine.
1699 */
1700static void
1701svm_vmcleanup(void *arg)
1702{
1703	struct svm_softc *svm_sc;
1704
1705	svm_sc = arg;
1706
1707	VCPU_CTR0(svm_sc->vm, 0, "SVM:cleanup\n");
1708
1709	free(svm_sc, M_SVM);
1710}
1711
1712/*
1713 * Return pointer to hypervisor saved register state.
1714 */
1715static register_t *
1716swctx_regptr(struct svm_regctx *regctx, int reg)
1717{
1718
1719	switch (reg) {
1720		case VM_REG_GUEST_RBX:
1721			return (&regctx->sctx_rbx);
1722		case VM_REG_GUEST_RCX:
1723			return (&regctx->sctx_rcx);
1724		case VM_REG_GUEST_RDX:
1725			return (&regctx->e.g.sctx_rdx);
1726		case VM_REG_GUEST_RDI:
1727			return (&regctx->e.g.sctx_rdi);
1728		case VM_REG_GUEST_RSI:
1729			return (&regctx->e.g.sctx_rsi);
1730		case VM_REG_GUEST_RBP:
1731			return (&regctx->sctx_rbp);
1732		case VM_REG_GUEST_R8:
1733			return (&regctx->sctx_r8);
1734		case VM_REG_GUEST_R9:
1735			return (&regctx->sctx_r9);
1736		case VM_REG_GUEST_R10:
1737			return (&regctx->sctx_r10);
1738		case VM_REG_GUEST_R11:
1739			return (&regctx->sctx_r11);
1740		case VM_REG_GUEST_R12:
1741			return (&regctx->sctx_r12);
1742		case VM_REG_GUEST_R13:
1743			return (&regctx->sctx_r13);
1744		case VM_REG_GUEST_R14:
1745			return (&regctx->sctx_r14);
1746		case VM_REG_GUEST_R15:
1747			return (&regctx->sctx_r15);
1748		default:
1749			ERR("Unknown register requested, reg=%d.\n", reg);
1750			break;
1751	}
1752
1753	return (NULL);
1754}
1755
1756/*
1757 * Interface to read guest registers.
1758 * This can be SVM h/w saved or hypervisor saved register.
1759 */
1760static int
1761svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
1762{
1763	struct svm_softc *svm_sc;
1764	struct vmcb *vmcb;
1765	register_t *reg;
1766
1767	svm_sc = arg;
1768	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1769
1770	vmcb = svm_get_vmcb(svm_sc, vcpu);
1771
1772	if (vmcb_read(vmcb, ident, val) == 0) {
1773		return (0);
1774	}
1775
1776	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
1777
1778	if (reg != NULL) {
1779		*val = *reg;
1780		return (0);
1781	}
1782
1783 	ERR("SVM_ERR:reg type %x is not saved in VMCB.\n", ident);
1784	return (EINVAL);
1785}
1786
1787/*
1788 * Interface to write to guest registers.
1789 * This can be SVM h/w saved or hypervisor saved register.
1790 */
1791static int
1792svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
1793{
1794	struct svm_softc *svm_sc;
1795	struct vmcb *vmcb;
1796	register_t *reg;
1797
1798	svm_sc = arg;
1799	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1800
1801	vmcb = svm_get_vmcb(svm_sc, vcpu);
1802	if (vmcb_write(vmcb, ident, val) == 0) {
1803		return (0);
1804	}
1805
1806	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
1807
1808	if (reg != NULL) {
1809		*reg = val;
1810		return (0);
1811	}
1812
1813	/*
1814	 * XXX deal with CR3 and invalidate TLB entries tagged with the
1815	 * vcpu's ASID. This needs to be treated differently depending on
1816	 * whether 'running' is true/false.
1817	 */
1818
1819 	ERR("SVM_ERR:reg type %x is not saved in VMCB.\n", ident);
1820	return (EINVAL);
1821}
1822
1823
1824/*
1825 * Inteface to set various descriptors.
1826 */
1827static int
1828svm_setdesc(void *arg, int vcpu, int type, struct seg_desc *desc)
1829{
1830	struct svm_softc *svm_sc;
1831	struct vmcb *vmcb;
1832	struct vmcb_segment *seg;
1833	uint16_t attrib;
1834
1835	svm_sc = arg;
1836	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1837
1838	vmcb = svm_get_vmcb(svm_sc, vcpu);
1839
1840	VCPU_CTR1(svm_sc->vm, vcpu, "SVM:set_desc: Type%d\n", type);
1841
1842	seg = vmcb_seg(vmcb, type);
1843	if (seg == NULL) {
1844		ERR("SVM_ERR:Unsupported segment type%d\n", type);
1845		return (EINVAL);
1846	}
1847
1848	/* Map seg_desc access to VMCB attribute format.*/
1849	attrib = ((desc->access & 0xF000) >> 4) | (desc->access & 0xFF);
1850	VCPU_CTR3(svm_sc->vm, vcpu, "SVM:[sel %d attribute 0x%x limit:0x%x]\n",
1851		type, desc->access, desc->limit);
1852	seg->attrib = attrib;
1853	seg->base = desc->base;
1854	seg->limit = desc->limit;
1855
1856	return (0);
1857}
1858
1859/*
1860 * Interface to get guest descriptor.
1861 */
1862static int
1863svm_getdesc(void *arg, int vcpu, int type, struct seg_desc *desc)
1864{
1865	struct svm_softc *svm_sc;
1866	struct vmcb_segment	*seg;
1867
1868	svm_sc = arg;
1869	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1870
1871	VCPU_CTR1(svm_sc->vm, vcpu, "SVM:get_desc: Type%d\n", type);
1872
1873	seg = vmcb_seg(svm_get_vmcb(svm_sc, vcpu), type);
1874	if (!seg) {
1875		ERR("SVM_ERR:Unsupported segment type%d\n", type);
1876		return (EINVAL);
1877	}
1878
1879	/* Map seg_desc access to VMCB attribute format.*/
1880	desc->access = ((seg->attrib & 0xF00) << 4) | (seg->attrib & 0xFF);
1881	desc->base = seg->base;
1882	desc->limit = seg->limit;
1883
1884	/*
1885	 * VT-x uses bit 16 (Unusable) to indicate a segment that has been
1886	 * loaded with a NULL segment selector. The 'desc->access' field is
1887	 * interpreted in the VT-x format by the processor-independent code.
1888	 *
1889	 * SVM uses the 'P' bit to convey the same information so convert it
1890	 * into the VT-x format. For more details refer to section
1891	 * "Segment State in the VMCB" in APMv2.
1892	 */
1893	if (type == VM_REG_GUEST_CS && type == VM_REG_GUEST_TR)
1894		desc->access |= 0x80;		/* CS and TS always present */
1895
1896	if (!(desc->access & 0x80))
1897		desc->access |= 0x10000;	/* Unusable segment */
1898
1899	return (0);
1900}
1901
1902static int
1903svm_setcap(void *arg, int vcpu, int type, int val)
1904{
1905	struct svm_softc *sc;
1906	int error;
1907
1908	sc = arg;
1909	error = 0;
1910	switch (type) {
1911	case VM_CAP_HALT_EXIT:
1912		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1913		    VMCB_INTCPT_HLT, val);
1914		break;
1915	case VM_CAP_PAUSE_EXIT:
1916		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1917		    VMCB_INTCPT_PAUSE, val);
1918		break;
1919	case VM_CAP_UNRESTRICTED_GUEST:
1920		/* Unrestricted guest execution cannot be disabled in SVM */
1921		if (val == 0)
1922			error = EINVAL;
1923		break;
1924	default:
1925		error = ENOENT;
1926		break;
1927	}
1928	return (error);
1929}
1930
1931static int
1932svm_getcap(void *arg, int vcpu, int type, int *retval)
1933{
1934	struct svm_softc *sc;
1935	int error;
1936
1937	sc = arg;
1938	error = 0;
1939
1940	switch (type) {
1941	case VM_CAP_HALT_EXIT:
1942		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1943		    VMCB_INTCPT_HLT);
1944		break;
1945	case VM_CAP_PAUSE_EXIT:
1946		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1947		    VMCB_INTCPT_PAUSE);
1948		break;
1949	case VM_CAP_UNRESTRICTED_GUEST:
1950		*retval = 1;	/* unrestricted guest is always enabled */
1951		break;
1952	default:
1953		error = ENOENT;
1954		break;
1955	}
1956	return (error);
1957}
1958
1959static struct vlapic *
1960svm_vlapic_init(void *arg, int vcpuid)
1961{
1962	struct svm_softc *svm_sc;
1963	struct vlapic *vlapic;
1964
1965	svm_sc = arg;
1966	vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
1967	vlapic->vm = svm_sc->vm;
1968	vlapic->vcpuid = vcpuid;
1969	vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
1970
1971	vlapic_init(vlapic);
1972
1973	return (vlapic);
1974}
1975
1976static void
1977svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
1978{
1979
1980        vlapic_cleanup(vlapic);
1981        free(vlapic, M_SVM_VLAPIC);
1982}
1983
1984struct vmm_ops vmm_ops_amd = {
1985	svm_init,
1986	svm_cleanup,
1987	svm_restore,
1988	svm_vminit,
1989	svm_vmrun,
1990	svm_vmcleanup,
1991	svm_getreg,
1992	svm_setreg,
1993	svm_getdesc,
1994	svm_setdesc,
1995	svm_getcap,
1996	svm_setcap,
1997	svm_npt_alloc,
1998	svm_npt_free,
1999	svm_vlapic_init,
2000	svm_vlapic_cleanup
2001};
2002