svm.c revision 271342
1/*-
2 * Copyright (c) 2013, Anish Gupta (akgupt3@gmail.com)
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice unmodified, this list of conditions, and the following
10 *    disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: projects/bhyve_svm/sys/amd64/vmm/amd/svm.c 271342 2014-09-10 01:10:53Z neel $");
29
30#include <sys/param.h>
31#include <sys/systm.h>
32#include <sys/smp.h>
33#include <sys/kernel.h>
34#include <sys/malloc.h>
35#include <sys/pcpu.h>
36#include <sys/proc.h>
37
38#include <vm/vm.h>
39#include <vm/pmap.h>
40
41#include <machine/cpufunc.h>
42#include <machine/psl.h>
43#include <machine/pmap.h>
44#include <machine/md_var.h>
45#include <machine/vmparam.h>
46#include <machine/specialreg.h>
47#include <machine/segments.h>
48#include <machine/vmm.h>
49#include <machine/vmm_dev.h>
50#include <machine/vmm_instruction_emul.h>
51
52#include <x86/apicreg.h>
53
54#include "vmm_lapic.h"
55#include "vmm_msr.h"
56#include "vmm_stat.h"
57#include "vmm_ktr.h"
58#include "vmm_ioport.h"
59#include "vatpic.h"
60#include "vlapic.h"
61#include "vlapic_priv.h"
62
63#include "x86.h"
64#include "vmcb.h"
65#include "svm.h"
66#include "svm_softc.h"
67#include "npt.h"
68
69/*
70 * SVM CPUID function 0x8000_000A, edx bit decoding.
71 */
72#define AMD_CPUID_SVM_NP		BIT(0)  /* Nested paging or RVI */
73#define AMD_CPUID_SVM_LBR		BIT(1)  /* Last branch virtualization */
74#define AMD_CPUID_SVM_SVML		BIT(2)  /* SVM lock */
75#define AMD_CPUID_SVM_NRIP_SAVE		BIT(3)  /* Next RIP is saved */
76#define AMD_CPUID_SVM_TSC_RATE		BIT(4)  /* TSC rate control. */
77#define AMD_CPUID_SVM_VMCB_CLEAN	BIT(5)  /* VMCB state caching */
78#define AMD_CPUID_SVM_FLUSH_BY_ASID	BIT(6)  /* Flush by ASID */
79#define AMD_CPUID_SVM_DECODE_ASSIST	BIT(7)  /* Decode assist */
80#define AMD_CPUID_SVM_PAUSE_INC		BIT(10) /* Pause intercept filter. */
81#define AMD_CPUID_SVM_PAUSE_FTH		BIT(12) /* Pause filter threshold */
82
83#define	VMCB_CACHE_DEFAULT	\
84	(VMCB_CACHE_ASID | VMCB_CACHE_IOPM | VMCB_CACHE_NP)
85
86MALLOC_DEFINE(M_SVM, "svm", "svm");
87MALLOC_DEFINE(M_SVM_VLAPIC, "svm-vlapic", "svm-vlapic");
88
89/* Per-CPU context area. */
90extern struct pcpu __pcpu[];
91
92static int svm_getdesc(void *arg, int vcpu, int type, struct seg_desc *desc);
93
94static uint32_t svm_feature;	/* AMD SVM features. */
95
96/* Maximum ASIDs supported by the processor */
97static uint32_t nasid;
98
99/* Current ASID generation for each host cpu */
100static struct asid asid[MAXCPU];
101
102/*
103 * SVM host state saved area of size 4KB for each core.
104 */
105static uint8_t hsave[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
106
107/*
108 * S/w saved host context.
109 */
110static struct svm_regctx host_ctx[MAXCPU];
111
112static VMM_STAT_AMD(VCPU_EXITINTINFO, "Valid VMCB EXITINTINFO");
113static VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "VMM pending exception injected");
114
115/*
116 * Common function to enable or disabled SVM for a CPU.
117 */
118static int
119cpu_svm_enable_disable(boolean_t enable)
120{
121	uint64_t efer_msr;
122
123	efer_msr = rdmsr(MSR_EFER);
124
125	if (enable)
126		efer_msr |= EFER_SVM;
127	else
128		efer_msr &= ~EFER_SVM;
129
130	wrmsr(MSR_EFER, efer_msr);
131
132	return(0);
133}
134
135/*
136 * Disable SVM on a CPU.
137 */
138static void
139svm_disable(void *arg __unused)
140{
141
142	(void)cpu_svm_enable_disable(FALSE);
143}
144
145/*
146 * Disable SVM for all CPUs.
147 */
148static int
149svm_cleanup(void)
150{
151
152	smp_rendezvous(NULL, svm_disable, NULL, NULL);
153	return (0);
154}
155
156/*
157 * Check for required BHyVe SVM features in a CPU.
158 */
159static int
160svm_cpuid_features(void)
161{
162	u_int regs[4];
163
164	/* CPUID Fn8000_000A is for SVM */
165	do_cpuid(0x8000000A, regs);
166	svm_feature = regs[3];
167
168	printf("SVM rev: 0x%x NASID:0x%x\n", regs[0] & 0xFF, regs[1]);
169	nasid = regs[1];
170	KASSERT(nasid > 1, ("Insufficient ASIDs for guests: %#x", nasid));
171
172	printf("SVM Features:0x%b\n", svm_feature,
173		"\020"
174		"\001NP"		/* Nested paging */
175		"\002LbrVirt"		/* LBR virtualization */
176		"\003SVML"		/* SVM lock */
177		"\004NRIPS"		/* NRIP save */
178		"\005TscRateMsr"	/* MSR based TSC rate control */
179		"\006VmcbClean"		/* VMCB clean bits */
180		"\007FlushByAsid"	/* Flush by ASID */
181		"\010DecodeAssist"	/* Decode assist */
182		"\011<b20>"
183		"\012<b20>"
184		"\013PauseFilter"
185		"\014<b20>"
186		"\015PauseFilterThreshold"
187		"\016AVIC"
188		);
189
190	/* SVM Lock */
191	if (!(svm_feature & AMD_CPUID_SVM_SVML)) {
192		printf("SVM is disabled by BIOS, please enable in BIOS.\n");
193		return (ENXIO);
194	}
195
196	/*
197	 * bhyve need RVI to work.
198	 */
199	if (!(svm_feature & AMD_CPUID_SVM_NP)) {
200		printf("Missing Nested paging or RVI SVM support in processor.\n");
201		return (EIO);
202	}
203
204	if (svm_feature & AMD_CPUID_SVM_NRIP_SAVE)
205		return (0);
206
207	return (EIO);
208}
209
210static __inline int
211flush_by_asid(void)
212{
213	return (svm_feature & AMD_CPUID_SVM_FLUSH_BY_ASID);
214}
215
216/*
217 * Enable SVM for a CPU.
218 */
219static void
220svm_enable(void *arg __unused)
221{
222	uint64_t hsave_pa;
223
224	(void)cpu_svm_enable_disable(TRUE);
225
226	hsave_pa = vtophys(hsave[curcpu]);
227	wrmsr(MSR_VM_HSAVE_PA, hsave_pa);
228
229	if (rdmsr(MSR_VM_HSAVE_PA) != hsave_pa) {
230		panic("VM_HSAVE_PA is wrong on CPU%d\n", curcpu);
231	}
232}
233
234/*
235 * Check if a processor support SVM.
236 */
237static int
238is_svm_enabled(void)
239{
240	uint64_t msr;
241
242	 /* Section 15.4 Enabling SVM from APM2. */
243	if ((amd_feature2 & AMDID2_SVM) == 0) {
244		printf("SVM is not supported on this processor.\n");
245		return (ENXIO);
246	}
247
248	msr = rdmsr(MSR_VM_CR);
249	/* Make sure SVM is not disabled by BIOS. */
250	if ((msr & VM_CR_SVMDIS) == 0) {
251		return svm_cpuid_features();
252	}
253
254	printf("SVM disabled by Key, consult TPM/BIOS manual.\n");
255	return (ENXIO);
256}
257
258/*
259 * Enable SVM on CPU and initialize nested page table h/w.
260 */
261static int
262svm_init(int ipinum)
263{
264	int err, cpu;
265
266	err = is_svm_enabled();
267	if (err)
268		return (err);
269
270	for (cpu = 0; cpu < MAXCPU; cpu++) {
271		/*
272		 * Initialize the host ASIDs to their "highest" valid values.
273		 *
274		 * The next ASID allocation will rollover both 'gen' and 'num'
275		 * and start off the sequence at {1,1}.
276		 */
277		asid[cpu].gen = ~0UL;
278		asid[cpu].num = nasid - 1;
279	}
280
281	svm_npt_init(ipinum);
282
283	/* Start SVM on all CPUs */
284	smp_rendezvous(NULL, svm_enable, NULL, NULL);
285
286	return (0);
287}
288
289static void
290svm_restore(void)
291{
292	svm_enable(NULL);
293}
294
295/*
296 * Get index and bit position for a MSR in MSR permission
297 * bitmap. Two bits are used for each MSR, lower bit is
298 * for read and higher bit is for write.
299 */
300static int
301svm_msr_index(uint64_t msr, int *index, int *bit)
302{
303	uint32_t base, off;
304
305/* Pentium compatible MSRs */
306#define MSR_PENTIUM_START 	0
307#define MSR_PENTIUM_END 	0x1FFF
308/* AMD 6th generation and Intel compatible MSRs */
309#define MSR_AMD6TH_START 	0xC0000000UL
310#define MSR_AMD6TH_END 		0xC0001FFFUL
311/* AMD 7th and 8th generation compatible MSRs */
312#define MSR_AMD7TH_START 	0xC0010000UL
313#define MSR_AMD7TH_END 		0xC0011FFFUL
314
315	*index = -1;
316	*bit = (msr % 4) * 2;
317	base = 0;
318
319	if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
320		*index = msr / 4;
321		return (0);
322	}
323
324	base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
325	if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
326		off = (msr - MSR_AMD6TH_START);
327		*index = (off + base) / 4;
328		return (0);
329	}
330
331	base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
332	if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
333		off = (msr - MSR_AMD7TH_START);
334		*index = (off + base) / 4;
335		return (0);
336	}
337
338	return (EIO);
339}
340
341/*
342 * Give virtual cpu the complete access to MSR(read & write).
343 */
344static int
345svm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
346{
347	int index, bit, err;
348
349	err = svm_msr_index(msr, &index, &bit);
350	if (err) {
351		ERR("MSR 0x%lx is not writeable by guest.\n", msr);
352		return (err);
353	}
354
355	if (index < 0 || index > (SVM_MSR_BITMAP_SIZE)) {
356		ERR("MSR 0x%lx index out of range(%d).\n", msr, index);
357		return (EINVAL);
358	}
359	if (bit < 0 || bit > 8) {
360		ERR("MSR 0x%lx bit out of range(%d).\n", msr, bit);
361		return (EINVAL);
362	}
363
364	/* Disable intercept for read and write. */
365	if (read)
366		perm_bitmap[index] &= ~(1UL << bit);
367	if (write)
368		perm_bitmap[index] &= ~(2UL << bit);
369	CTR2(KTR_VMM, "Guest has control:0x%x on SVM:MSR(0x%lx).\n",
370		(perm_bitmap[index] >> bit) & 0x3, msr);
371
372	return (0);
373}
374
375static int
376svm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
377{
378	return svm_msr_perm(perm_bitmap, msr, true, true);
379}
380
381static int
382svm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
383{
384	return svm_msr_perm(perm_bitmap, msr, true, false);
385}
386
387static __inline void
388vcpu_set_dirty(struct svm_softc *sc, int vcpu, uint32_t dirtybits)
389{
390	struct svm_vcpu *vcpustate;
391
392	vcpustate = svm_get_vcpu(sc, vcpu);
393
394	vcpustate->dirty |= dirtybits;
395}
396
397/*
398 * Initialise a virtual machine.
399 */
400static void *
401svm_vminit(struct vm *vm, pmap_t pmap)
402{
403	struct svm_softc *svm_sc;
404	struct svm_vcpu *vcpu;
405	vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
406	int i;
407
408	svm_sc = (struct svm_softc *)malloc(sizeof (struct svm_softc),
409			M_SVM, M_WAITOK | M_ZERO);
410
411	svm_sc->vm = vm;
412	svm_sc->svm_feature = svm_feature;
413	svm_sc->vcpu_cnt = VM_MAXCPU;
414	svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
415
416	/*
417	 * Intercept MSR access to all MSRs except GSBASE, FSBASE,... etc.
418	 */
419	 memset(svm_sc->msr_bitmap, 0xFF, sizeof(svm_sc->msr_bitmap));
420
421	/*
422	 * Following MSR can be completely controlled by virtual machines
423	 * since access to following are translated to access to VMCB.
424	 */
425	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
426	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
427	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
428
429	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
430	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
431	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
432	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
433	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
434	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
435	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
436
437	/* For Nested Paging/RVI only. */
438	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
439
440	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
441	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
442
443	 /* Intercept access to all I/O ports. */
444	memset(svm_sc->iopm_bitmap, 0xFF, sizeof(svm_sc->iopm_bitmap));
445
446	/* Cache physical address for multiple vcpus. */
447	iopm_pa = vtophys(svm_sc->iopm_bitmap);
448	msrpm_pa = vtophys(svm_sc->msr_bitmap);
449	pml4_pa = svm_sc->nptp;
450
451	for (i = 0; i < svm_sc->vcpu_cnt; i++) {
452		vcpu = svm_get_vcpu(svm_sc, i);
453		vcpu->lastcpu = NOCPU;
454		vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
455		svm_init_vmcb(&vcpu->vmcb, iopm_pa, msrpm_pa, pml4_pa);
456	}
457	return (svm_sc);
458}
459
460static int
461svm_cpl(struct vmcb_state *state)
462{
463
464	/*
465	 * From APMv2:
466	 *   "Retrieve the CPL from the CPL field in the VMCB, not
467	 *    from any segment DPL"
468	 */
469	return (state->cpl);
470}
471
472static enum vm_cpu_mode
473svm_vcpu_mode(struct vmcb *vmcb)
474{
475	struct vmcb_segment *seg;
476	struct vmcb_state *state;
477
478	state = &vmcb->state;
479
480	if (state->efer & EFER_LMA) {
481		seg = vmcb_seg(vmcb, VM_REG_GUEST_CS);
482		/*
483		 * Section 4.8.1 for APM2, check if Code Segment has
484		 * Long attribute set in descriptor.
485		 */
486		if (seg->attrib & VMCB_CS_ATTRIB_L)
487			return (CPU_MODE_64BIT);
488		else
489			return (CPU_MODE_COMPATIBILITY);
490	} else  if (state->cr0 & CR0_PE) {
491		return (CPU_MODE_PROTECTED);
492	} else {
493		return (CPU_MODE_REAL);
494	}
495}
496
497static enum vm_paging_mode
498svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
499{
500
501	if ((cr0 & CR0_PG) == 0)
502		return (PAGING_MODE_FLAT);
503	if ((cr4 & CR4_PAE) == 0)
504		return (PAGING_MODE_32);
505	if (efer & EFER_LME)
506		return (PAGING_MODE_64);
507	else
508		return (PAGING_MODE_PAE);
509}
510
511/*
512 * ins/outs utility routines
513 */
514static uint64_t
515svm_inout_str_index(struct svm_regctx *regs, int in)
516{
517	uint64_t val;
518
519	val = in ? regs->e.g.sctx_rdi : regs->e.g.sctx_rsi;
520
521	return (val);
522}
523
524static uint64_t
525svm_inout_str_count(struct svm_regctx *regs, int rep)
526{
527	uint64_t val;
528
529	val = rep ? regs->sctx_rcx : 1;
530
531	return (val);
532}
533
534static void
535svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
536    int in, struct vm_inout_str *vis)
537{
538	int error, s;
539
540	if (in) {
541		vis->seg_name = VM_REG_GUEST_ES;
542	} else {
543		/* The segment field has standard encoding */
544		s = (info1 >> 10) & 0x7;
545		vis->seg_name = vm_segment_name(s);
546	}
547
548	error = svm_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
549	KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
550}
551
552static int
553svm_inout_str_addrsize(uint64_t info1)
554{
555        uint32_t size;
556
557        size = (info1 >> 7) & 0x7;
558        switch (size) {
559        case 1:
560                return (2);     /* 16 bit */
561        case 2:
562                return (4);     /* 32 bit */
563        case 4:
564                return (8);     /* 64 bit */
565        default:
566                panic("%s: invalid size encoding %d", __func__, size);
567        }
568}
569
570static void
571svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
572{
573	struct vmcb_state *state;
574
575	state = &vmcb->state;
576	paging->cr3 = state->cr3;
577	paging->cpl = svm_cpl(state);
578	paging->cpu_mode = svm_vcpu_mode(vmcb);
579	paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
580	    state->efer);
581}
582
583
584/*
585 * Handle guest I/O intercept.
586 */
587static bool
588svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
589{
590	struct vmcb_ctrl *ctrl;
591	struct vmcb_state *state;
592	struct svm_regctx *regs;
593	struct vm_inout_str *vis;
594	uint64_t info1;
595
596	state = svm_get_vmcb_state(svm_sc, vcpu);
597	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
598	regs  = svm_get_guest_regctx(svm_sc, vcpu);
599	info1 = ctrl->exitinfo1;
600
601	vmexit->exitcode 	= VM_EXITCODE_INOUT;
602	vmexit->u.inout.in 	= (info1 & BIT(0)) ? 1 : 0;
603	vmexit->u.inout.string 	= (info1 & BIT(2)) ? 1 : 0;
604	vmexit->u.inout.rep 	= (info1 & BIT(3)) ? 1 : 0;
605	vmexit->u.inout.bytes 	= (info1 >> 4) & 0x7;
606	vmexit->u.inout.port 	= (uint16_t)(info1 >> 16);
607	vmexit->u.inout.eax 	= (uint32_t)(state->rax);
608
609	if (vmexit->u.inout.string) {
610		vmexit->exitcode = VM_EXITCODE_INOUT_STR;
611		vis = &vmexit->u.inout_str;
612		svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
613		vis->rflags = state->rflags;
614		vis->cr0 = state->cr0;
615		vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
616		vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
617		vis->addrsize = svm_inout_str_addrsize(info1);
618		svm_inout_str_seginfo(svm_sc, vcpu, info1,
619		    vmexit->u.inout.in, vis);
620	}
621
622	return (false);
623}
624
625static int
626svm_npf_paging(uint64_t exitinfo1)
627{
628
629	if (exitinfo1 & VMCB_NPF_INFO1_W)
630		return (VM_PROT_WRITE);
631
632	return (VM_PROT_READ);
633}
634
635static bool
636svm_npf_emul_fault(uint64_t exitinfo1)
637{
638
639	if (exitinfo1 & VMCB_NPF_INFO1_ID) {
640		return (false);
641	}
642
643	if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
644		return (false);
645	}
646
647	if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
648		return (false);
649	}
650
651	return (true);
652}
653
654static void
655svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
656{
657	struct vm_guest_paging *paging;
658	struct vmcb_segment *seg;
659
660	paging = &vmexit->u.inst_emul.paging;
661	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
662	vmexit->u.inst_emul.gpa = gpa;
663	vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
664	svm_paging_info(vmcb, paging);
665
666	/*
667	 * If DecodeAssist SVM feature doesn't exist, we don't have NPF
668	 * instuction length. RIP will be calculated based on the length
669	 * determined by instruction emulation.
670	 */
671	vmexit->inst_length = VIE_INST_SIZE;
672
673	seg = vmcb_seg(vmcb, VM_REG_GUEST_CS);
674	switch(paging->cpu_mode) {
675	case CPU_MODE_PROTECTED:
676	case CPU_MODE_COMPATIBILITY:
677		/*
678		 * Section 4.8.1 of APM2, Default Operand Size or D bit.
679		 */
680		vmexit->u.inst_emul.cs_d = (seg->attrib & VMCB_CS_ATTRIB_D) ?
681		    1 : 0;
682		break;
683	default:
684		vmexit->u.inst_emul.cs_d = 0;
685		break;
686	}
687}
688
689/*
690 * Intercept access to MSR_EFER to prevent the guest from clearing the
691 * SVM enable bit.
692 */
693static void
694svm_write_efer(struct svm_softc *sc, int vcpu, uint32_t edx, uint32_t eax)
695{
696	struct vmcb_state *state;
697	uint64_t oldval;
698
699	state = svm_get_vmcb_state(sc, vcpu);
700
701	oldval = state->efer;
702	state->efer = (uint64_t)edx << 32 | eax | EFER_SVM;
703	if (state->efer != oldval) {
704		VCPU_CTR2(sc->vm, vcpu, "Guest EFER changed from %#lx to %#lx",
705		    oldval, state->efer);
706		vcpu_set_dirty(sc, vcpu, VMCB_CACHE_CR);
707	}
708}
709
710static void
711svm_save_intinfo(struct svm_softc *svm_sc, int vcpu)
712{
713	struct vmcb_ctrl *ctrl;
714	uint64_t intinfo;
715
716	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
717	intinfo = ctrl->exitintinfo;
718	if (!VMCB_EXITINTINFO_VALID(intinfo))
719		return;
720
721	/*
722	 * From APMv2, Section "Intercepts during IDT interrupt delivery"
723	 *
724	 * If a #VMEXIT happened during event delivery then record the event
725	 * that was being delivered.
726	 */
727	VCPU_CTR2(svm_sc->vm, vcpu, "SVM:Pending INTINFO(0x%lx), vector=%d.\n",
728		intinfo, VMCB_EXITINTINFO_VECTOR(intinfo));
729	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
730	vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
731}
732
733/*
734 * Determine the cause of virtual cpu exit and handle VMEXIT.
735 * Return: false - Break vcpu execution loop and handle vmexit
736 *		   in kernel or user space.
737 *	   true  - Continue vcpu run.
738 */
739static bool
740svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
741{
742	struct vmcb_state *state;
743	struct vmcb_ctrl *ctrl;
744	struct svm_regctx *ctx;
745	uint64_t code, info1, info2, val;
746	uint32_t eax, ecx, edx;
747	bool update_rip, loop, retu;
748
749	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
750
751	state = svm_get_vmcb_state(svm_sc, vcpu);
752	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
753	ctx   = svm_get_guest_regctx(svm_sc, vcpu);
754	code  = ctrl->exitcode;
755	info1 = ctrl->exitinfo1;
756	info2 = ctrl->exitinfo2;
757
758	update_rip = true;
759	loop = true;
760	vmexit->exitcode = VM_EXITCODE_VMX;
761	vmexit->u.vmx.status = 0;
762
763	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
764	    "injection valid bit is set %#lx", __func__, ctrl->eventinj));
765
766	svm_save_intinfo(svm_sc, vcpu);
767
768	switch (code) {
769		case	VMCB_EXIT_MC: /* Machine Check. */
770			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_MTRAP, 1);
771			vmexit->exitcode = VM_EXITCODE_MTRAP;
772			loop = false;
773			break;
774
775		case	VMCB_EXIT_MSR:	/* MSR access. */
776			eax = state->rax;
777			ecx = ctx->sctx_rcx;
778			edx = ctx->e.g.sctx_rdx;
779
780			if (ecx == MSR_EFER) {
781				KASSERT(info1 != 0, ("rdmsr(MSR_EFER) is not "
782				    "emulated: info1(%#lx) info2(%#lx)",
783				    info1, info2));
784				svm_write_efer(svm_sc, vcpu, edx, eax);
785				break;
786			}
787
788			retu = false;
789			if (info1) {
790				/* VM exited because of write MSR */
791				vmm_stat_incr(svm_sc->vm, vcpu,
792					VMEXIT_WRMSR, 1);
793				vmexit->exitcode = VM_EXITCODE_WRMSR;
794				vmexit->u.msr.code = ecx;
795				val = (uint64_t)edx << 32 | eax;
796				if (emulate_wrmsr(svm_sc->vm, vcpu, ecx, val,
797					&retu)) {
798					vmexit->u.msr.wval = val;
799					loop = false;
800				} else
801					loop = retu ? false : true;
802
803				VCPU_CTR3(svm_sc->vm, vcpu,
804					"VMEXIT WRMSR(%s handling) 0x%lx @0x%x",
805					loop ? "kernel" : "user", val, ecx);
806			} else {
807				vmm_stat_incr(svm_sc->vm, vcpu,
808					VMEXIT_RDMSR, 1);
809				vmexit->exitcode = VM_EXITCODE_RDMSR;
810				vmexit->u.msr.code = ecx;
811				if (emulate_rdmsr(svm_sc->vm, vcpu, ecx,
812					&retu)) {
813					loop = false;
814				} else
815					loop = retu ? false : true;
816				VCPU_CTR3(svm_sc->vm, vcpu, "SVM:VMEXIT RDMSR"
817					" MSB=0x%08x, LSB=%08x @0x%x",
818					ctx->e.g.sctx_rdx, state->rax, ecx);
819			}
820
821#define MSR_AMDK8_IPM           0xc0010055
822			/*
823			 * We can't hide AMD C1E idle capability since its
824			 * based on CPU generation, for now ignore access to
825			 * this MSR by vcpus
826			 * XXX: special handling of AMD C1E - Ignore.
827			 */
828			 if (ecx == MSR_AMDK8_IPM)
829				loop = true;
830			break;
831
832		case VMCB_EXIT_INTR:
833			/*
834			 * Exit on External Interrupt.
835			 * Give host interrupt handler to run and if its guest
836			 * interrupt, local APIC will inject event in guest.
837			 */
838			update_rip = false;
839			VCPU_CTR1(svm_sc->vm, vcpu, "SVM:VMEXIT ExtInt"
840				" RIP:0x%lx.\n", state->rip);
841			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
842			break;
843
844		case VMCB_EXIT_IO:
845			loop = svm_handle_io(svm_sc, vcpu, vmexit);
846			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
847			break;
848
849		case VMCB_EXIT_CPUID:
850			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
851			(void)x86_emulate_cpuid(svm_sc->vm, vcpu,
852					(uint32_t *)&state->rax,
853					(uint32_t *)&ctx->sctx_rbx,
854					(uint32_t *)&ctx->sctx_rcx,
855					(uint32_t *)&ctx->e.g.sctx_rdx);
856			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:VMEXIT CPUID\n");
857			break;
858
859		case VMCB_EXIT_HLT:
860			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
861 			if (ctrl->v_irq) {
862				 /* Interrupt is pending, can't halt guest. */
863				vmm_stat_incr(svm_sc->vm, vcpu,
864					VMEXIT_HLT_IGNORED, 1);
865				VCPU_CTR0(svm_sc->vm, vcpu,
866					"VMEXIT halt ignored.");
867			} else {
868				VCPU_CTR0(svm_sc->vm, vcpu,
869					"VMEXIT halted CPU.");
870				vmexit->exitcode = VM_EXITCODE_HLT;
871				vmexit->u.hlt.rflags = state->rflags;
872				loop = false;
873
874			}
875			break;
876
877		case VMCB_EXIT_PAUSE:
878			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:VMEXIT pause");
879			vmexit->exitcode = VM_EXITCODE_PAUSE;
880			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
881
882			break;
883
884		case VMCB_EXIT_NPF:
885			loop = false;
886			update_rip = false;
887
888        		if (info1 & VMCB_NPF_INFO1_RSV) {
889 				VCPU_CTR2(svm_sc->vm, vcpu, "SVM_ERR:NPT"
890					" reserved bit is set,"
891					"INFO1:0x%lx INFO2:0x%lx .\n",
892					info1, info2);
893        			break;
894			}
895
896			 /* EXITINFO2 has the physical fault address (GPA). */
897			if(vm_mem_allocated(svm_sc->vm, info2)) {
898 				VCPU_CTR3(svm_sc->vm, vcpu, "SVM:NPF-paging,"
899					"RIP:0x%lx INFO1:0x%lx INFO2:0x%lx .\n",
900				 	state->rip, info1, info2);
901				vmexit->exitcode = VM_EXITCODE_PAGING;
902				vmexit->u.paging.gpa = info2;
903				vmexit->u.paging.fault_type =
904					svm_npf_paging(info1);
905				vmm_stat_incr(svm_sc->vm, vcpu,
906					VMEXIT_NESTED_FAULT, 1);
907			} else if (svm_npf_emul_fault(info1)) {
908 				VCPU_CTR3(svm_sc->vm, vcpu, "SVM:NPF inst_emul,"
909					"RIP:0x%lx INFO1:0x%lx INFO2:0x%lx .\n",
910					state->rip, info1, info2);
911				svm_handle_inst_emul(svm_get_vmcb(svm_sc, vcpu),
912					info2, vmexit);
913				vmm_stat_incr(svm_sc->vm, vcpu,
914					VMEXIT_INST_EMUL, 1);
915			}
916
917			break;
918
919		case VMCB_EXIT_SHUTDOWN:
920			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:VMEXIT shutdown.");
921			loop = false;
922			break;
923
924		case VMCB_EXIT_INVALID:
925			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:VMEXIT INVALID.");
926			loop = false;
927			break;
928
929		default:
930			 /* Return to user space. */
931			loop = false;
932			update_rip = false;
933			VCPU_CTR3(svm_sc->vm, vcpu, "VMEXIT=0x%lx"
934				" EXITINFO1: 0x%lx EXITINFO2:0x%lx\n",
935		 		ctrl->exitcode, info1, info2);
936			VCPU_CTR3(svm_sc->vm, vcpu, "SVM:RIP: 0x%lx nRIP:0x%lx"
937				" Inst decoder len:%d\n", state->rip,
938				ctrl->nrip, ctrl->inst_decode_size);
939			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
940			break;
941	}
942
943	vmexit->rip = state->rip;
944	if (update_rip) {
945		if (ctrl->nrip == 0) {
946 			VCPU_CTR1(svm_sc->vm, vcpu, "SVM_ERR:nRIP is not set "
947				 "for RIP0x%lx.\n", state->rip);
948			vmexit->exitcode = VM_EXITCODE_VMX;
949		} else
950			vmexit->rip = ctrl->nrip;
951	}
952
953	/* If vcpu execution is continued, update RIP. */
954	if (loop) {
955		state->rip = vmexit->rip;
956	}
957
958	if (state->rip == 0) {
959		VCPU_CTR0(svm_sc->vm, vcpu, "SVM_ERR:RIP is NULL\n");
960		vmexit->exitcode = VM_EXITCODE_VMX;
961	}
962
963	return (loop);
964}
965
966/*
967 * Inject NMI to virtual cpu.
968 */
969static int
970svm_inject_nmi(struct svm_softc *svm_sc, int vcpu)
971{
972	struct vmcb_ctrl *ctrl;
973
974	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
975
976	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
977	 /* Can't inject another NMI if last one is pending.*/
978	if (!vm_nmi_pending(svm_sc->vm, vcpu))
979		return (0);
980
981	/* Inject NMI, vector number is not used.*/
982	vmcb_eventinject(ctrl, VMCB_EVENTINJ_TYPE_NMI, IDT_NMI, 0, false);
983
984	/* Acknowledge the request is accepted.*/
985	vm_nmi_clear(svm_sc->vm, vcpu);
986
987	VCPU_CTR0(svm_sc->vm, vcpu, "SVM:Injected NMI.\n");
988
989	return (1);
990}
991
992static void
993svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
994{
995	struct vmcb_ctrl *ctrl;
996	uint64_t intinfo;
997
998	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
999
1000	if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
1001		return;
1002
1003	KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1004	    "valid: %#lx", __func__, intinfo));
1005
1006	vmcb_eventinject(ctrl, VMCB_EXITINTINFO_TYPE(intinfo),
1007		VMCB_EXITINTINFO_VECTOR(intinfo),
1008		VMCB_EXITINTINFO_EC(intinfo),
1009		VMCB_EXITINTINFO_EC_VALID(intinfo));
1010	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1011	VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1012}
1013
1014/*
1015 * Inject event to virtual cpu.
1016 */
1017static void
1018svm_inj_interrupts(struct svm_softc *svm_sc, int vcpu, struct vlapic *vlapic)
1019{
1020	struct vmcb_ctrl *ctrl;
1021	struct vmcb_state *state;
1022	int extint_pending;
1023	int vector;
1024
1025	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1026
1027	state = svm_get_vmcb_state(svm_sc, vcpu);
1028	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
1029
1030	svm_inj_intinfo(svm_sc, vcpu);
1031
1032	/* Can't inject multiple events at once. */
1033	if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1034		VCPU_CTR1(svm_sc->vm, vcpu,
1035			"SVM:Last event(0x%lx) is pending.\n", ctrl->eventinj);
1036		return ;
1037	}
1038
1039	/* Wait for guest to come out of interrupt shadow. */
1040	if (ctrl->intr_shadow) {
1041		VCPU_CTR0(svm_sc->vm, vcpu, "SVM:Guest in interrupt shadow.\n");
1042		return;
1043	}
1044
1045	/* NMI event has priority over interrupts.*/
1046	if (svm_inject_nmi(svm_sc, vcpu)) {
1047		return;
1048	}
1049
1050	extint_pending = vm_extint_pending(svm_sc->vm, vcpu);
1051
1052	if (!extint_pending) {
1053		/* Ask the local apic for a vector to inject */
1054		if (!vlapic_pending_intr(vlapic, &vector))
1055			return;
1056	} else {
1057                /* Ask the legacy pic for a vector to inject */
1058                vatpic_pending_intr(svm_sc->vm, &vector);
1059	}
1060
1061	if (vector < 32 || vector > 255) {
1062		VCPU_CTR1(svm_sc->vm, vcpu, "SVM_ERR:Event injection"
1063			"invalid vector=%d.\n", vector);
1064		ERR("SVM_ERR:Event injection invalid vector=%d.\n", vector);
1065		return;
1066	}
1067
1068	if ((state->rflags & PSL_I) == 0) {
1069		VCPU_CTR0(svm_sc->vm, vcpu, "SVM:Interrupt is disabled\n");
1070		return;
1071	}
1072
1073	vmcb_eventinject(ctrl, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1074
1075        if (!extint_pending) {
1076                /* Update the Local APIC ISR */
1077                vlapic_intr_accepted(vlapic, vector);
1078        } else {
1079                vm_extint_clear(svm_sc->vm, vcpu);
1080                vatpic_intr_accepted(svm_sc->vm, vector);
1081
1082                /*
1083		 * XXX need to recheck exting_pending ala VT-x
1084		 */
1085        }
1086
1087	VCPU_CTR1(svm_sc->vm, vcpu, "SVM:event injected,vector=%d.\n", vector);
1088}
1089
1090static __inline void
1091restore_host_tss(void)
1092{
1093	struct system_segment_descriptor *tss_sd;
1094
1095	/*
1096	 * The TSS descriptor was in use prior to launching the guest so it
1097	 * has been marked busy.
1098	 *
1099	 * 'ltr' requires the descriptor to be marked available so change the
1100	 * type to "64-bit available TSS".
1101	 */
1102	tss_sd = PCPU_GET(tss);
1103	tss_sd->sd_type = SDT_SYSTSS;
1104	ltr(GSEL(GPROC0_SEL, SEL_KPL));
1105}
1106
1107static void
1108check_asid(struct svm_softc *sc, int vcpuid, pmap_t pmap, u_int thiscpu)
1109{
1110	struct svm_vcpu *vcpustate;
1111	struct vmcb_ctrl *ctrl;
1112	long eptgen;
1113	bool alloc_asid;
1114
1115	KASSERT(CPU_ISSET(thiscpu, &pmap->pm_active), ("%s: nested pmap not "
1116	    "active on cpu %u", __func__, thiscpu));
1117
1118	vcpustate = svm_get_vcpu(sc, vcpuid);
1119	ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1120
1121	/*
1122	 * The TLB entries associated with the vcpu's ASID are not valid
1123	 * if either of the following conditions is true:
1124	 *
1125	 * 1. The vcpu's ASID generation is different than the host cpu's
1126	 *    ASID generation. This happens when the vcpu migrates to a new
1127	 *    host cpu. It can also happen when the number of vcpus executing
1128	 *    on a host cpu is greater than the number of ASIDs available.
1129	 *
1130	 * 2. The pmap generation number is different than the value cached in
1131	 *    the 'vcpustate'. This happens when the host invalidates pages
1132	 *    belonging to the guest.
1133	 *
1134	 *	asidgen		eptgen	      Action
1135	 *	mismatch	mismatch
1136	 *	   0		   0		(a)
1137	 *	   0		   1		(b1) or (b2)
1138	 *	   1		   0		(c)
1139	 *	   1		   1		(d)
1140	 *
1141	 * (a) There is no mismatch in eptgen or ASID generation and therefore
1142	 *     no further action is needed.
1143	 *
1144	 * (b1) If the cpu supports FlushByAsid then the vcpu's ASID is
1145	 *      retained and the TLB entries associated with this ASID
1146	 *      are flushed by VMRUN.
1147	 *
1148	 * (b2) If the cpu does not support FlushByAsid then a new ASID is
1149	 *      allocated.
1150	 *
1151	 * (c) A new ASID is allocated.
1152	 *
1153	 * (d) A new ASID is allocated.
1154	 */
1155
1156	alloc_asid = false;
1157	eptgen = pmap->pm_eptgen;
1158	ctrl->tlb_ctrl = VMCB_TLB_FLUSH_NOTHING;
1159
1160	if (vcpustate->asid.gen != asid[thiscpu].gen) {
1161		alloc_asid = true;	/* (c) and (d) */
1162	} else if (vcpustate->eptgen != eptgen) {
1163		if (flush_by_asid())
1164			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;	/* (b1) */
1165		else
1166			alloc_asid = true;			/* (b2) */
1167	} else {
1168		/*
1169		 * This is the common case (a).
1170		 */
1171		KASSERT(!alloc_asid, ("ASID allocation not necessary"));
1172		KASSERT(ctrl->tlb_ctrl == VMCB_TLB_FLUSH_NOTHING,
1173		    ("Invalid VMCB tlb_ctrl: %#x", ctrl->tlb_ctrl));
1174	}
1175
1176	if (alloc_asid) {
1177		if (++asid[thiscpu].num >= nasid) {
1178			asid[thiscpu].num = 1;
1179			if (++asid[thiscpu].gen == 0)
1180				asid[thiscpu].gen = 1;
1181			/*
1182			 * If this cpu does not support "flush-by-asid"
1183			 * then flush the entire TLB on a generation
1184			 * bump. Subsequent ASID allocation in this
1185			 * generation can be done without a TLB flush.
1186			 */
1187			if (!flush_by_asid())
1188				ctrl->tlb_ctrl = VMCB_TLB_FLUSH_ALL;
1189		}
1190		vcpustate->asid.gen = asid[thiscpu].gen;
1191		vcpustate->asid.num = asid[thiscpu].num;
1192
1193		ctrl->asid = vcpustate->asid.num;
1194		vcpu_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1195		/*
1196		 * If this cpu supports "flush-by-asid" then the TLB
1197		 * was not flushed after the generation bump. The TLB
1198		 * is flushed selectively after every new ASID allocation.
1199		 */
1200		if (flush_by_asid())
1201			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1202	}
1203	vcpustate->eptgen = eptgen;
1204
1205	KASSERT(ctrl->asid != 0, ("Guest ASID must be non-zero"));
1206	KASSERT(ctrl->asid == vcpustate->asid.num,
1207	    ("ASID mismatch: %u/%u", ctrl->asid, vcpustate->asid.num));
1208}
1209
1210/*
1211 * Start vcpu with specified RIP.
1212 */
1213static int
1214svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1215	void *rend_cookie, void *suspended_cookie)
1216{
1217	struct svm_regctx *hctx, *gctx;
1218	struct svm_softc *svm_sc;
1219	struct svm_vcpu *vcpustate;
1220	struct vmcb_state *state;
1221	struct vmcb_ctrl *ctrl;
1222	struct vm_exit *vmexit;
1223	struct vlapic *vlapic;
1224	struct vm *vm;
1225	uint64_t vmcb_pa;
1226	u_int thiscpu;
1227	bool loop;	/* Continue vcpu execution loop. */
1228
1229	loop = true;
1230	svm_sc = arg;
1231	vm = svm_sc->vm;
1232
1233	vcpustate = svm_get_vcpu(svm_sc, vcpu);
1234	state = svm_get_vmcb_state(svm_sc, vcpu);
1235	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1236	vmexit = vm_exitinfo(vm, vcpu);
1237	vlapic = vm_lapic(vm, vcpu);
1238
1239	/*
1240	 * Stash 'curcpu' on the stack as 'thiscpu'.
1241	 *
1242	 * The per-cpu data area is not accessible until MSR_GSBASE is restored
1243	 * after the #VMEXIT. Since VMRUN is executed inside a critical section
1244	 * 'curcpu' and 'thiscpu' are guaranteed to identical.
1245	 */
1246	thiscpu = curcpu;
1247
1248	gctx = svm_get_guest_regctx(svm_sc, vcpu);
1249	hctx = &host_ctx[thiscpu];
1250	vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1251
1252	if (vcpustate->lastcpu != thiscpu) {
1253		/*
1254		 * Force new ASID allocation by invalidating the generation.
1255		 */
1256		vcpustate->asid.gen = 0;
1257
1258		/*
1259		 * Invalidate the VMCB state cache by marking all fields dirty.
1260		 */
1261		vcpu_set_dirty(svm_sc, vcpu, 0xffffffff);
1262
1263		/*
1264		 * XXX
1265		 * Setting 'vcpustate->lastcpu' here is bit premature because
1266		 * we may return from this function without actually executing
1267		 * the VMRUN  instruction. This could happen if a rendezvous
1268		 * or an AST is pending on the first time through the loop.
1269		 *
1270		 * This works for now but any new side-effects of vcpu
1271		 * migration should take this case into account.
1272		 */
1273		vcpustate->lastcpu = thiscpu;
1274		vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1275	}
1276
1277	VCPU_CTR3(vm, vcpu, "SVM:Enter vmrun RIP:0x%lx"
1278		" inst len=%d/%d\n",
1279		rip, vmexit->inst_length,
1280		vmexit->u.inst_emul.vie.num_valid);
1281	/* Update Guest RIP */
1282	state->rip = rip;
1283
1284	do {
1285		vmexit->inst_length = 0;
1286
1287		/*
1288		 * Disable global interrupts to guarantee atomicity during
1289		 * loading of guest state. This includes not only the state
1290		 * loaded by the "vmrun" instruction but also software state
1291		 * maintained by the hypervisor: suspended and rendezvous
1292		 * state, NPT generation number, vlapic interrupts etc.
1293		 */
1294		disable_gintr();
1295
1296		if (vcpu_suspended(suspended_cookie)) {
1297			enable_gintr();
1298			vm_exit_suspended(vm, vcpu, state->rip);
1299			break;
1300		}
1301
1302		if (vcpu_rendezvous_pending(rend_cookie)) {
1303			enable_gintr();
1304			vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1305			vmm_stat_incr(vm, vcpu, VMEXIT_RENDEZVOUS, 1);
1306			VCPU_CTR1(vm, vcpu,
1307				"SVM: VCPU rendezvous, RIP:0x%lx\n",
1308				state->rip);
1309			vmexit->rip = state->rip;
1310			break;
1311		}
1312
1313		/* We are asked to give the cpu by scheduler. */
1314		if (curthread->td_flags & (TDF_ASTPENDING | TDF_NEEDRESCHED)) {
1315			enable_gintr();
1316			vmexit->exitcode = VM_EXITCODE_BOGUS;
1317			vmm_stat_incr(vm, vcpu, VMEXIT_ASTPENDING, 1);
1318			VCPU_CTR1(vm, vcpu,
1319				"SVM: ASTPENDING, RIP:0x%lx\n", state->rip);
1320			vmexit->rip = state->rip;
1321			break;
1322		}
1323
1324		svm_inj_interrupts(svm_sc, vcpu, vlapic);
1325
1326		/* Activate the nested pmap on 'thiscpu' */
1327		CPU_SET_ATOMIC_ACQ(thiscpu, &pmap->pm_active);
1328
1329		/*
1330		 * Check the pmap generation and the ASID generation to
1331		 * ensure that the vcpu does not use stale TLB mappings.
1332		 */
1333		check_asid(svm_sc, vcpu, pmap, thiscpu);
1334
1335		ctrl->vmcb_clean = VMCB_CACHE_DEFAULT & ~vcpustate->dirty;
1336		vcpustate->dirty = 0;
1337
1338		/* Launch Virtual Machine. */
1339		svm_launch(vmcb_pa, gctx, hctx);
1340
1341		CPU_CLR_ATOMIC(thiscpu, &pmap->pm_active);
1342
1343		/*
1344		 * Restore MSR_GSBASE to point to the pcpu data area.
1345		 *
1346		 * Note that accesses done via PCPU_GET/PCPU_SET will work
1347		 * only after MSR_GSBASE is restored.
1348		 *
1349		 * Also note that we don't bother restoring MSR_KGSBASE
1350		 * since it is not used in the kernel and will be restored
1351		 * when the VMRUN ioctl returns to userspace.
1352		 */
1353		wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[thiscpu]);
1354		KASSERT(curcpu == thiscpu, ("thiscpu/curcpu (%u/%u) mismatch",
1355		    thiscpu, curcpu));
1356
1357		/*
1358		 * The host GDTR and IDTR is saved by VMRUN and restored
1359		 * automatically on #VMEXIT. However, the host TSS needs
1360		 * to be restored explicitly.
1361		 */
1362		restore_host_tss();
1363
1364		/* #VMEXIT disables interrupts so re-enable them here. */
1365		enable_gintr();
1366
1367		/* Handle #VMEXIT and if required return to user space. */
1368		loop = svm_vmexit(svm_sc, vcpu, vmexit);
1369		vcpustate->loop++;
1370		vmm_stat_incr(vm, vcpu, VMEXIT_COUNT, 1);
1371	} while (loop);
1372
1373	return (0);
1374}
1375
1376/*
1377 * Cleanup for virtual machine.
1378 */
1379static void
1380svm_vmcleanup(void *arg)
1381{
1382	struct svm_softc *svm_sc;
1383
1384	svm_sc = arg;
1385
1386	VCPU_CTR0(svm_sc->vm, 0, "SVM:cleanup\n");
1387
1388	free(svm_sc, M_SVM);
1389}
1390
1391/*
1392 * Return pointer to hypervisor saved register state.
1393 */
1394static register_t *
1395swctx_regptr(struct svm_regctx *regctx, int reg)
1396{
1397
1398	switch (reg) {
1399		case VM_REG_GUEST_RBX:
1400			return (&regctx->sctx_rbx);
1401		case VM_REG_GUEST_RCX:
1402			return (&regctx->sctx_rcx);
1403		case VM_REG_GUEST_RDX:
1404			return (&regctx->e.g.sctx_rdx);
1405		case VM_REG_GUEST_RDI:
1406			return (&regctx->e.g.sctx_rdi);
1407		case VM_REG_GUEST_RSI:
1408			return (&regctx->e.g.sctx_rsi);
1409		case VM_REG_GUEST_RBP:
1410			return (&regctx->sctx_rbp);
1411		case VM_REG_GUEST_R8:
1412			return (&regctx->sctx_r8);
1413		case VM_REG_GUEST_R9:
1414			return (&regctx->sctx_r9);
1415		case VM_REG_GUEST_R10:
1416			return (&regctx->sctx_r10);
1417		case VM_REG_GUEST_R11:
1418			return (&regctx->sctx_r11);
1419		case VM_REG_GUEST_R12:
1420			return (&regctx->sctx_r12);
1421		case VM_REG_GUEST_R13:
1422			return (&regctx->sctx_r13);
1423		case VM_REG_GUEST_R14:
1424			return (&regctx->sctx_r14);
1425		case VM_REG_GUEST_R15:
1426			return (&regctx->sctx_r15);
1427		default:
1428			ERR("Unknown register requested, reg=%d.\n", reg);
1429			break;
1430	}
1431
1432	return (NULL);
1433}
1434
1435/*
1436 * Interface to read guest registers.
1437 * This can be SVM h/w saved or hypervisor saved register.
1438 */
1439static int
1440svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
1441{
1442	struct svm_softc *svm_sc;
1443	struct vmcb *vmcb;
1444	register_t *reg;
1445
1446	svm_sc = arg;
1447	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1448
1449	vmcb = svm_get_vmcb(svm_sc, vcpu);
1450
1451	if (vmcb_read(vmcb, ident, val) == 0) {
1452		return (0);
1453	}
1454
1455	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
1456
1457	if (reg != NULL) {
1458		*val = *reg;
1459		return (0);
1460	}
1461
1462 	ERR("SVM_ERR:reg type %x is not saved in VMCB.\n", ident);
1463	return (EINVAL);
1464}
1465
1466/*
1467 * Interface to write to guest registers.
1468 * This can be SVM h/w saved or hypervisor saved register.
1469 */
1470static int
1471svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
1472{
1473	struct svm_softc *svm_sc;
1474	struct vmcb *vmcb;
1475	register_t *reg;
1476
1477	svm_sc = arg;
1478	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1479
1480	vmcb = svm_get_vmcb(svm_sc, vcpu);
1481	if (vmcb_write(vmcb, ident, val) == 0) {
1482		return (0);
1483	}
1484
1485	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
1486
1487	if (reg != NULL) {
1488		*reg = val;
1489		return (0);
1490	}
1491
1492	/*
1493	 * XXX deal with CR3 and invalidate TLB entries tagged with the
1494	 * vcpu's ASID. This needs to be treated differently depending on
1495	 * whether 'running' is true/false.
1496	 */
1497
1498 	ERR("SVM_ERR:reg type %x is not saved in VMCB.\n", ident);
1499	return (EINVAL);
1500}
1501
1502
1503/*
1504 * Inteface to set various descriptors.
1505 */
1506static int
1507svm_setdesc(void *arg, int vcpu, int type, struct seg_desc *desc)
1508{
1509	struct svm_softc *svm_sc;
1510	struct vmcb *vmcb;
1511	struct vmcb_segment *seg;
1512	uint16_t attrib;
1513
1514	svm_sc = arg;
1515	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1516
1517	vmcb = svm_get_vmcb(svm_sc, vcpu);
1518
1519	VCPU_CTR1(svm_sc->vm, vcpu, "SVM:set_desc: Type%d\n", type);
1520
1521	seg = vmcb_seg(vmcb, type);
1522	if (seg == NULL) {
1523		ERR("SVM_ERR:Unsupported segment type%d\n", type);
1524		return (EINVAL);
1525	}
1526
1527	/* Map seg_desc access to VMCB attribute format.*/
1528	attrib = ((desc->access & 0xF000) >> 4) | (desc->access & 0xFF);
1529	VCPU_CTR3(svm_sc->vm, vcpu, "SVM:[sel %d attribute 0x%x limit:0x%x]\n",
1530		type, desc->access, desc->limit);
1531	seg->attrib = attrib;
1532	seg->base = desc->base;
1533	seg->limit = desc->limit;
1534
1535	return (0);
1536}
1537
1538/*
1539 * Interface to get guest descriptor.
1540 */
1541static int
1542svm_getdesc(void *arg, int vcpu, int type, struct seg_desc *desc)
1543{
1544	struct svm_softc *svm_sc;
1545	struct vmcb_segment	*seg;
1546
1547	svm_sc = arg;
1548	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1549
1550	VCPU_CTR1(svm_sc->vm, vcpu, "SVM:get_desc: Type%d\n", type);
1551
1552	seg = vmcb_seg(svm_get_vmcb(svm_sc, vcpu), type);
1553	if (!seg) {
1554		ERR("SVM_ERR:Unsupported segment type%d\n", type);
1555		return (EINVAL);
1556	}
1557
1558	/* Map seg_desc access to VMCB attribute format.*/
1559	desc->access = ((seg->attrib & 0xF00) << 4) | (seg->attrib & 0xFF);
1560	desc->base = seg->base;
1561	desc->limit = seg->limit;
1562
1563	/*
1564	 * VT-x uses bit 16 (Unusable) to indicate a segment that has been
1565	 * loaded with a NULL segment selector. The 'desc->access' field is
1566	 * interpreted in the VT-x format by the processor-independent code.
1567	 *
1568	 * SVM uses the 'P' bit to convey the same information so convert it
1569	 * into the VT-x format. For more details refer to section
1570	 * "Segment State in the VMCB" in APMv2.
1571	 */
1572	if (type == VM_REG_GUEST_CS && type == VM_REG_GUEST_TR)
1573		desc->access |= 0x80;		/* CS and TS always present */
1574
1575	if (!(desc->access & 0x80))
1576		desc->access |= 0x10000;	/* Unusable segment */
1577
1578	return (0);
1579}
1580
1581static int
1582svm_setcap(void *arg, int vcpu, int type, int val)
1583{
1584	struct svm_softc *svm_sc;
1585	struct vmcb_ctrl *ctrl;
1586	int ret = ENOENT;
1587
1588	svm_sc = arg;
1589	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1590
1591	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1592
1593	switch (type) {
1594		case VM_CAP_HALT_EXIT:
1595			if (val)
1596				ctrl->ctrl1 |= VMCB_INTCPT_HLT;
1597			else
1598				ctrl->ctrl1 &= ~VMCB_INTCPT_HLT;
1599			ret = 0;
1600			VCPU_CTR1(svm_sc->vm, vcpu, "SVM:Set_gap:Halt exit %s.\n",
1601				val ? "enabled": "disabled");
1602			break;
1603
1604		case VM_CAP_PAUSE_EXIT:
1605			if (val)
1606				ctrl->ctrl1 |= VMCB_INTCPT_PAUSE;
1607			else
1608				ctrl->ctrl1 &= ~VMCB_INTCPT_PAUSE;
1609			ret = 0;
1610			VCPU_CTR1(svm_sc->vm, vcpu, "SVM:Set_gap:Pause exit %s.\n",
1611				val ? "enabled": "disabled");
1612			break;
1613
1614		case VM_CAP_MTRAP_EXIT:
1615			if (val)
1616				ctrl->exception |= BIT(IDT_MC);
1617			else
1618				ctrl->exception &= ~BIT(IDT_MC);
1619			ret = 0;
1620			VCPU_CTR1(svm_sc->vm, vcpu, "SVM:Set_gap:MC exit %s.\n",
1621				val ? "enabled": "disabled");
1622			break;
1623
1624		case VM_CAP_UNRESTRICTED_GUEST:
1625			/* SVM doesn't need special capability for SMP.*/
1626			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:Set_gap:Unrestricted "
1627			"always enabled.\n");
1628			ret = 0;
1629			break;
1630
1631		default:
1632			break;
1633		}
1634
1635	return (ret);
1636}
1637
1638static int
1639svm_getcap(void *arg, int vcpu, int type, int *retval)
1640{
1641	struct svm_softc *svm_sc;
1642	struct vmcb_ctrl *ctrl;
1643
1644	svm_sc = arg;
1645	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1646
1647	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1648
1649	switch (type) {
1650		case VM_CAP_HALT_EXIT:
1651		*retval = (ctrl->ctrl1 & VMCB_INTCPT_HLT) ? 1 : 0;
1652		VCPU_CTR1(svm_sc->vm, vcpu, "SVM:get_cap:Halt exit %s.\n",
1653			*retval ? "enabled": "disabled");
1654		break;
1655
1656		case VM_CAP_PAUSE_EXIT:
1657		*retval = (ctrl->ctrl1 & VMCB_INTCPT_PAUSE) ? 1 : 0;
1658		VCPU_CTR1(svm_sc->vm, vcpu, "SVM:get_cap:Pause exit %s.\n",
1659			*retval ? "enabled": "disabled");
1660		break;
1661
1662		case VM_CAP_MTRAP_EXIT:
1663		*retval = (ctrl->exception & BIT(IDT_MC)) ? 1 : 0;
1664		VCPU_CTR1(svm_sc->vm, vcpu, "SVM:get_cap:MC exit %s.\n",
1665			*retval ? "enabled": "disabled");
1666		break;
1667
1668	case VM_CAP_UNRESTRICTED_GUEST:
1669		VCPU_CTR0(svm_sc->vm, vcpu, "SVM:get_cap:Unrestricted.\n");
1670		*retval = 1;
1671		break;
1672		default:
1673		break;
1674	}
1675
1676	return (0);
1677}
1678
1679static struct vlapic *
1680svm_vlapic_init(void *arg, int vcpuid)
1681{
1682	struct svm_softc *svm_sc;
1683	struct vlapic *vlapic;
1684
1685	svm_sc = arg;
1686	vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
1687	vlapic->vm = svm_sc->vm;
1688	vlapic->vcpuid = vcpuid;
1689	vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
1690
1691	vlapic_init(vlapic);
1692
1693	return (vlapic);
1694}
1695
1696static void
1697svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
1698{
1699
1700        vlapic_cleanup(vlapic);
1701        free(vlapic, M_SVM_VLAPIC);
1702}
1703
1704struct vmm_ops vmm_ops_amd = {
1705	svm_init,
1706	svm_cleanup,
1707	svm_restore,
1708	svm_vminit,
1709	svm_vmrun,
1710	svm_vmcleanup,
1711	svm_getreg,
1712	svm_setreg,
1713	svm_getdesc,
1714	svm_setdesc,
1715	svm_getcap,
1716	svm_setcap,
1717	svm_npt_alloc,
1718	svm_npt_free,
1719	svm_vlapic_init,
1720	svm_vlapic_cleanup
1721};
1722