svm.c revision 276098
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: head/sys/amd64/vmm/amd/svm.c 276098 2014-12-23 02:14:49Z 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#include <sys/sysctl.h>
38
39#include <vm/vm.h>
40#include <vm/pmap.h>
41
42#include <machine/cpufunc.h>
43#include <machine/psl.h>
44#include <machine/pmap.h>
45#include <machine/md_var.h>
46#include <machine/specialreg.h>
47#include <machine/smp.h>
48#include <machine/vmm.h>
49#include <machine/vmm_dev.h>
50#include <machine/vmm_instruction_emul.h>
51
52#include "vmm_lapic.h"
53#include "vmm_stat.h"
54#include "vmm_ktr.h"
55#include "vmm_ioport.h"
56#include "vatpic.h"
57#include "vlapic.h"
58#include "vlapic_priv.h"
59
60#include "x86.h"
61#include "vmcb.h"
62#include "svm.h"
63#include "svm_softc.h"
64#include "svm_msr.h"
65#include "npt.h"
66
67SYSCTL_DECL(_hw_vmm);
68SYSCTL_NODE(_hw_vmm, OID_AUTO, svm, CTLFLAG_RW, NULL, NULL);
69
70/*
71 * SVM CPUID function 0x8000_000A, edx bit decoding.
72 */
73#define AMD_CPUID_SVM_NP		BIT(0)  /* Nested paging or RVI */
74#define AMD_CPUID_SVM_LBR		BIT(1)  /* Last branch virtualization */
75#define AMD_CPUID_SVM_SVML		BIT(2)  /* SVM lock */
76#define AMD_CPUID_SVM_NRIP_SAVE		BIT(3)  /* Next RIP is saved */
77#define AMD_CPUID_SVM_TSC_RATE		BIT(4)  /* TSC rate control. */
78#define AMD_CPUID_SVM_VMCB_CLEAN	BIT(5)  /* VMCB state caching */
79#define AMD_CPUID_SVM_FLUSH_BY_ASID	BIT(6)  /* Flush by ASID */
80#define AMD_CPUID_SVM_DECODE_ASSIST	BIT(7)  /* Decode assist */
81#define AMD_CPUID_SVM_PAUSE_INC		BIT(10) /* Pause intercept filter. */
82#define AMD_CPUID_SVM_PAUSE_FTH		BIT(12) /* Pause filter threshold */
83
84#define	VMCB_CACHE_DEFAULT	(VMCB_CACHE_ASID 	|	\
85				VMCB_CACHE_IOPM		|	\
86				VMCB_CACHE_I		|	\
87				VMCB_CACHE_TPR		|	\
88				VMCB_CACHE_CR2		|	\
89				VMCB_CACHE_CR		|	\
90				VMCB_CACHE_DT		|	\
91				VMCB_CACHE_SEG		|	\
92				VMCB_CACHE_NP)
93
94static uint32_t vmcb_clean = VMCB_CACHE_DEFAULT;
95SYSCTL_INT(_hw_vmm_svm, OID_AUTO, vmcb_clean, CTLFLAG_RDTUN, &vmcb_clean,
96    0, NULL);
97
98static MALLOC_DEFINE(M_SVM, "svm", "svm");
99static MALLOC_DEFINE(M_SVM_VLAPIC, "svm-vlapic", "svm-vlapic");
100
101/* Per-CPU context area. */
102extern struct pcpu __pcpu[];
103
104static uint32_t svm_feature;	/* AMD SVM features. */
105SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, features, CTLFLAG_RD, &svm_feature, 0,
106    "SVM features advertised by CPUID.8000000AH:EDX");
107
108static int disable_npf_assist;
109SYSCTL_INT(_hw_vmm_svm, OID_AUTO, disable_npf_assist, CTLFLAG_RWTUN,
110    &disable_npf_assist, 0, NULL);
111
112/* Maximum ASIDs supported by the processor */
113static uint32_t nasid;
114SYSCTL_UINT(_hw_vmm_svm, OID_AUTO, num_asids, CTLFLAG_RD, &nasid, 0,
115    "Number of ASIDs supported by this processor");
116
117/* Current ASID generation for each host cpu */
118static struct asid asid[MAXCPU];
119
120/*
121 * SVM host state saved area of size 4KB for each core.
122 */
123static uint8_t hsave[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
124
125static VMM_STAT_AMD(VCPU_EXITINTINFO, "VM exits during event delivery");
126static VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "Events pending at VM entry");
127static VMM_STAT_AMD(VMEXIT_VINTR, "VM exits due to interrupt window");
128
129static int svm_setreg(void *arg, int vcpu, int ident, uint64_t val);
130
131static __inline int
132flush_by_asid(void)
133{
134
135	return (svm_feature & AMD_CPUID_SVM_FLUSH_BY_ASID);
136}
137
138static __inline int
139decode_assist(void)
140{
141
142	return (svm_feature & AMD_CPUID_SVM_DECODE_ASSIST);
143}
144
145static void
146svm_disable(void *arg __unused)
147{
148	uint64_t efer;
149
150	efer = rdmsr(MSR_EFER);
151	efer &= ~EFER_SVM;
152	wrmsr(MSR_EFER, efer);
153}
154
155/*
156 * Disable SVM on all CPUs.
157 */
158static int
159svm_cleanup(void)
160{
161
162	smp_rendezvous(NULL, svm_disable, NULL, NULL);
163	return (0);
164}
165
166/*
167 * Verify that all the features required by bhyve are available.
168 */
169static int
170check_svm_features(void)
171{
172	u_int regs[4];
173
174	/* CPUID Fn8000_000A is for SVM */
175	do_cpuid(0x8000000A, regs);
176	svm_feature = regs[3];
177
178	nasid = regs[1];
179	KASSERT(nasid > 1, ("Insufficient ASIDs for guests: %#x", nasid));
180
181	/* bhyve requires the Nested Paging feature */
182	if (!(svm_feature & AMD_CPUID_SVM_NP)) {
183		printf("SVM: Nested Paging feature not available.\n");
184		return (ENXIO);
185	}
186
187	/* bhyve requires the NRIP Save feature */
188	if (!(svm_feature & AMD_CPUID_SVM_NRIP_SAVE)) {
189		printf("SVM: NRIP Save feature not available.\n");
190		return (ENXIO);
191	}
192
193	return (0);
194}
195
196static void
197svm_enable(void *arg __unused)
198{
199	uint64_t efer;
200
201	efer = rdmsr(MSR_EFER);
202	efer |= EFER_SVM;
203	wrmsr(MSR_EFER, efer);
204
205	wrmsr(MSR_VM_HSAVE_PA, vtophys(hsave[curcpu]));
206}
207
208/*
209 * Return 1 if SVM is enabled on this processor and 0 otherwise.
210 */
211static int
212svm_available(void)
213{
214	uint64_t msr;
215
216	/* Section 15.4 Enabling SVM from APM2. */
217	if ((amd_feature2 & AMDID2_SVM) == 0) {
218		printf("SVM: not available.\n");
219		return (0);
220	}
221
222	msr = rdmsr(MSR_VM_CR);
223	if ((msr & VM_CR_SVMDIS) != 0) {
224		printf("SVM: disabled by BIOS.\n");
225		return (0);
226	}
227
228	return (1);
229}
230
231static int
232svm_init(int ipinum)
233{
234	int error, cpu;
235
236	if (!svm_available())
237		return (ENXIO);
238
239	error = check_svm_features();
240	if (error)
241		return (error);
242
243	vmcb_clean &= VMCB_CACHE_DEFAULT;
244
245	for (cpu = 0; cpu < MAXCPU; cpu++) {
246		/*
247		 * Initialize the host ASIDs to their "highest" valid values.
248		 *
249		 * The next ASID allocation will rollover both 'gen' and 'num'
250		 * and start off the sequence at {1,1}.
251		 */
252		asid[cpu].gen = ~0UL;
253		asid[cpu].num = nasid - 1;
254	}
255
256	svm_msr_init();
257	svm_npt_init(ipinum);
258
259	/* Enable SVM on all CPUs */
260	smp_rendezvous(NULL, svm_enable, NULL, NULL);
261
262	return (0);
263}
264
265static void
266svm_restore(void)
267{
268
269	svm_enable(NULL);
270}
271
272/* Pentium compatible MSRs */
273#define MSR_PENTIUM_START 	0
274#define MSR_PENTIUM_END 	0x1FFF
275/* AMD 6th generation and Intel compatible MSRs */
276#define MSR_AMD6TH_START 	0xC0000000UL
277#define MSR_AMD6TH_END 		0xC0001FFFUL
278/* AMD 7th and 8th generation compatible MSRs */
279#define MSR_AMD7TH_START 	0xC0010000UL
280#define MSR_AMD7TH_END 		0xC0011FFFUL
281
282/*
283 * Get the index and bit position for a MSR in permission bitmap.
284 * Two bits are used for each MSR: lower bit for read and higher bit for write.
285 */
286static int
287svm_msr_index(uint64_t msr, int *index, int *bit)
288{
289	uint32_t base, off;
290
291	*index = -1;
292	*bit = (msr % 4) * 2;
293	base = 0;
294
295	if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
296		*index = msr / 4;
297		return (0);
298	}
299
300	base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
301	if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
302		off = (msr - MSR_AMD6TH_START);
303		*index = (off + base) / 4;
304		return (0);
305	}
306
307	base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
308	if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
309		off = (msr - MSR_AMD7TH_START);
310		*index = (off + base) / 4;
311		return (0);
312	}
313
314	return (EINVAL);
315}
316
317/*
318 * Allow vcpu to read or write the 'msr' without trapping into the hypervisor.
319 */
320static void
321svm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
322{
323	int index, bit, error;
324
325	error = svm_msr_index(msr, &index, &bit);
326	KASSERT(error == 0, ("%s: invalid msr %#lx", __func__, msr));
327	KASSERT(index >= 0 && index < SVM_MSR_BITMAP_SIZE,
328	    ("%s: invalid index %d for msr %#lx", __func__, index, msr));
329	KASSERT(bit >= 0 && bit <= 6, ("%s: invalid bit position %d "
330	    "msr %#lx", __func__, bit, msr));
331
332	if (read)
333		perm_bitmap[index] &= ~(1UL << bit);
334
335	if (write)
336		perm_bitmap[index] &= ~(2UL << bit);
337}
338
339static void
340svm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
341{
342
343	svm_msr_perm(perm_bitmap, msr, true, true);
344}
345
346static void
347svm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
348{
349
350	svm_msr_perm(perm_bitmap, msr, true, false);
351}
352
353static __inline int
354svm_get_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask)
355{
356	struct vmcb_ctrl *ctrl;
357
358	KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
359
360	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
361	return (ctrl->intercept[idx] & bitmask ? 1 : 0);
362}
363
364static __inline void
365svm_set_intercept(struct svm_softc *sc, int vcpu, int idx, uint32_t bitmask,
366    int enabled)
367{
368	struct vmcb_ctrl *ctrl;
369	uint32_t oldval;
370
371	KASSERT(idx >=0 && idx < 5, ("invalid intercept index %d", idx));
372
373	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
374	oldval = ctrl->intercept[idx];
375
376	if (enabled)
377		ctrl->intercept[idx] |= bitmask;
378	else
379		ctrl->intercept[idx] &= ~bitmask;
380
381	if (ctrl->intercept[idx] != oldval) {
382		svm_set_dirty(sc, vcpu, VMCB_CACHE_I);
383		VCPU_CTR3(sc->vm, vcpu, "intercept[%d] modified "
384		    "from %#x to %#x", idx, oldval, ctrl->intercept[idx]);
385	}
386}
387
388static __inline void
389svm_disable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
390{
391
392	svm_set_intercept(sc, vcpu, off, bitmask, 0);
393}
394
395static __inline void
396svm_enable_intercept(struct svm_softc *sc, int vcpu, int off, uint32_t bitmask)
397{
398
399	svm_set_intercept(sc, vcpu, off, bitmask, 1);
400}
401
402static void
403vmcb_init(struct svm_softc *sc, int vcpu, uint64_t iopm_base_pa,
404    uint64_t msrpm_base_pa, uint64_t np_pml4)
405{
406	struct vmcb_ctrl *ctrl;
407	struct vmcb_state *state;
408	uint32_t mask;
409	int n;
410
411	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
412	state = svm_get_vmcb_state(sc, vcpu);
413
414	ctrl->iopm_base_pa = iopm_base_pa;
415	ctrl->msrpm_base_pa = msrpm_base_pa;
416
417	/* Enable nested paging */
418	ctrl->np_enable = 1;
419	ctrl->n_cr3 = np_pml4;
420
421	/*
422	 * Intercept accesses to the control registers that are not shadowed
423	 * in the VMCB - i.e. all except cr0, cr2, cr3, cr4 and cr8.
424	 */
425	for (n = 0; n < 16; n++) {
426		mask = (BIT(n) << 16) | BIT(n);
427		if (n == 0 || n == 2 || n == 3 || n == 4 || n == 8)
428			svm_disable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
429		else
430			svm_enable_intercept(sc, vcpu, VMCB_CR_INTCPT, mask);
431	}
432
433
434	/*
435	 * Intercept everything when tracing guest exceptions otherwise
436	 * just intercept machine check exception.
437	 */
438	if (vcpu_trace_exceptions(sc->vm, vcpu)) {
439		for (n = 0; n < 32; n++) {
440			/*
441			 * Skip unimplemented vectors in the exception bitmap.
442			 */
443			if (n == 2 || n == 9) {
444				continue;
445			}
446			svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(n));
447		}
448	} else {
449		svm_enable_intercept(sc, vcpu, VMCB_EXC_INTCPT, BIT(IDT_MC));
450	}
451
452	/* Intercept various events (for e.g. I/O, MSR and CPUID accesses) */
453	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IO);
454	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_MSR);
455	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_CPUID);
456	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INTR);
457	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_INIT);
458	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_NMI);
459	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SMI);
460	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_SHUTDOWN);
461	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
462	    VMCB_INTCPT_FERR_FREEZE);
463
464	/*
465	 * From section "Canonicalization and Consistency Checks" in APMv2
466	 * the VMRUN intercept bit must be set to pass the consistency check.
467	 */
468	svm_enable_intercept(sc, vcpu, VMCB_CTRL2_INTCPT, VMCB_INTCPT_VMRUN);
469
470	/*
471	 * The ASID will be set to a non-zero value just before VMRUN.
472	 */
473	ctrl->asid = 0;
474
475	/*
476	 * Section 15.21.1, Interrupt Masking in EFLAGS
477	 * Section 15.21.2, Virtualizing APIC.TPR
478	 *
479	 * This must be set for %rflag and %cr8 isolation of guest and host.
480	 */
481	ctrl->v_intr_masking = 1;
482
483	/* Enable Last Branch Record aka LBR for debugging */
484	ctrl->lbr_virt_en = 1;
485	state->dbgctl = BIT(0);
486
487	/* EFER_SVM must always be set when the guest is executing */
488	state->efer = EFER_SVM;
489
490	/* Set up the PAT to power-on state */
491	state->g_pat = PAT_VALUE(0, PAT_WRITE_BACK)	|
492	    PAT_VALUE(1, PAT_WRITE_THROUGH)	|
493	    PAT_VALUE(2, PAT_UNCACHED)		|
494	    PAT_VALUE(3, PAT_UNCACHEABLE)	|
495	    PAT_VALUE(4, PAT_WRITE_BACK)	|
496	    PAT_VALUE(5, PAT_WRITE_THROUGH)	|
497	    PAT_VALUE(6, PAT_UNCACHED)		|
498	    PAT_VALUE(7, PAT_UNCACHEABLE);
499}
500
501/*
502 * Initialize a virtual machine.
503 */
504static void *
505svm_vminit(struct vm *vm, pmap_t pmap)
506{
507	struct svm_softc *svm_sc;
508	struct svm_vcpu *vcpu;
509	vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
510	int i;
511
512	svm_sc = malloc(sizeof (struct svm_softc), M_SVM, M_WAITOK | M_ZERO);
513	svm_sc->vm = vm;
514	svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
515
516	/*
517	 * Intercept read and write accesses to all MSRs.
518	 */
519	memset(svm_sc->msr_bitmap, 0xFF, sizeof(svm_sc->msr_bitmap));
520
521	/*
522	 * Access to the following MSRs is redirected to the VMCB when the
523	 * guest is executing. Therefore it is safe to allow the guest to
524	 * read/write these MSRs directly without hypervisor involvement.
525	 */
526	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
527	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
528	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
529
530	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
531	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
532	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
533	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
534	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
535	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
536	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
537	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
538
539	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
540
541	/*
542	 * Intercept writes to make sure that the EFER_SVM bit is not cleared.
543	 */
544	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_EFER);
545
546	/* Intercept access to all I/O ports. */
547	memset(svm_sc->iopm_bitmap, 0xFF, sizeof(svm_sc->iopm_bitmap));
548
549	iopm_pa = vtophys(svm_sc->iopm_bitmap);
550	msrpm_pa = vtophys(svm_sc->msr_bitmap);
551	pml4_pa = svm_sc->nptp;
552	for (i = 0; i < VM_MAXCPU; i++) {
553		vcpu = svm_get_vcpu(svm_sc, i);
554		vcpu->lastcpu = NOCPU;
555		vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
556		vmcb_init(svm_sc, i, iopm_pa, msrpm_pa, pml4_pa);
557		svm_msr_guest_init(svm_sc, i);
558	}
559	return (svm_sc);
560}
561
562static int
563svm_cpl(struct vmcb_state *state)
564{
565
566	/*
567	 * From APMv2:
568	 *   "Retrieve the CPL from the CPL field in the VMCB, not
569	 *    from any segment DPL"
570	 */
571	return (state->cpl);
572}
573
574static enum vm_cpu_mode
575svm_vcpu_mode(struct vmcb *vmcb)
576{
577	struct vmcb_segment seg;
578	struct vmcb_state *state;
579	int error;
580
581	state = &vmcb->state;
582
583	if (state->efer & EFER_LMA) {
584		error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
585		KASSERT(error == 0, ("%s: vmcb_seg(cs) error %d", __func__,
586		    error));
587
588		/*
589		 * Section 4.8.1 for APM2, check if Code Segment has
590		 * Long attribute set in descriptor.
591		 */
592		if (seg.attrib & VMCB_CS_ATTRIB_L)
593			return (CPU_MODE_64BIT);
594		else
595			return (CPU_MODE_COMPATIBILITY);
596	} else  if (state->cr0 & CR0_PE) {
597		return (CPU_MODE_PROTECTED);
598	} else {
599		return (CPU_MODE_REAL);
600	}
601}
602
603static enum vm_paging_mode
604svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
605{
606
607	if ((cr0 & CR0_PG) == 0)
608		return (PAGING_MODE_FLAT);
609	if ((cr4 & CR4_PAE) == 0)
610		return (PAGING_MODE_32);
611	if (efer & EFER_LME)
612		return (PAGING_MODE_64);
613	else
614		return (PAGING_MODE_PAE);
615}
616
617/*
618 * ins/outs utility routines
619 */
620static uint64_t
621svm_inout_str_index(struct svm_regctx *regs, int in)
622{
623	uint64_t val;
624
625	val = in ? regs->sctx_rdi : regs->sctx_rsi;
626
627	return (val);
628}
629
630static uint64_t
631svm_inout_str_count(struct svm_regctx *regs, int rep)
632{
633	uint64_t val;
634
635	val = rep ? regs->sctx_rcx : 1;
636
637	return (val);
638}
639
640static void
641svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
642    int in, struct vm_inout_str *vis)
643{
644	int error, s;
645
646	if (in) {
647		vis->seg_name = VM_REG_GUEST_ES;
648	} else {
649		/* The segment field has standard encoding */
650		s = (info1 >> 10) & 0x7;
651		vis->seg_name = vm_segment_name(s);
652	}
653
654	error = vmcb_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
655	KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
656}
657
658static int
659svm_inout_str_addrsize(uint64_t info1)
660{
661        uint32_t size;
662
663        size = (info1 >> 7) & 0x7;
664        switch (size) {
665        case 1:
666                return (2);     /* 16 bit */
667        case 2:
668                return (4);     /* 32 bit */
669        case 4:
670                return (8);     /* 64 bit */
671        default:
672                panic("%s: invalid size encoding %d", __func__, size);
673        }
674}
675
676static void
677svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
678{
679	struct vmcb_state *state;
680
681	state = &vmcb->state;
682	paging->cr3 = state->cr3;
683	paging->cpl = svm_cpl(state);
684	paging->cpu_mode = svm_vcpu_mode(vmcb);
685	paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
686	    state->efer);
687}
688
689#define	UNHANDLED 0
690
691/*
692 * Handle guest I/O intercept.
693 */
694static int
695svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
696{
697	struct vmcb_ctrl *ctrl;
698	struct vmcb_state *state;
699	struct svm_regctx *regs;
700	struct vm_inout_str *vis;
701	uint64_t info1;
702	int inout_string;
703
704	state = svm_get_vmcb_state(svm_sc, vcpu);
705	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
706	regs  = svm_get_guest_regctx(svm_sc, vcpu);
707
708	info1 = ctrl->exitinfo1;
709	inout_string = info1 & BIT(2) ? 1 : 0;
710
711	/*
712	 * The effective segment number in EXITINFO1[12:10] is populated
713	 * only if the processor has the DecodeAssist capability.
714	 *
715	 * XXX this is not specified explicitly in APMv2 but can be verified
716	 * empirically.
717	 */
718	if (inout_string && !decode_assist())
719		return (UNHANDLED);
720
721	vmexit->exitcode 	= VM_EXITCODE_INOUT;
722	vmexit->u.inout.in 	= (info1 & BIT(0)) ? 1 : 0;
723	vmexit->u.inout.string 	= inout_string;
724	vmexit->u.inout.rep 	= (info1 & BIT(3)) ? 1 : 0;
725	vmexit->u.inout.bytes 	= (info1 >> 4) & 0x7;
726	vmexit->u.inout.port 	= (uint16_t)(info1 >> 16);
727	vmexit->u.inout.eax 	= (uint32_t)(state->rax);
728
729	if (inout_string) {
730		vmexit->exitcode = VM_EXITCODE_INOUT_STR;
731		vis = &vmexit->u.inout_str;
732		svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
733		vis->rflags = state->rflags;
734		vis->cr0 = state->cr0;
735		vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
736		vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
737		vis->addrsize = svm_inout_str_addrsize(info1);
738		svm_inout_str_seginfo(svm_sc, vcpu, info1,
739		    vmexit->u.inout.in, vis);
740	}
741
742	return (UNHANDLED);
743}
744
745static int
746npf_fault_type(uint64_t exitinfo1)
747{
748
749	if (exitinfo1 & VMCB_NPF_INFO1_W)
750		return (VM_PROT_WRITE);
751	else if (exitinfo1 & VMCB_NPF_INFO1_ID)
752		return (VM_PROT_EXECUTE);
753	else
754		return (VM_PROT_READ);
755}
756
757static bool
758svm_npf_emul_fault(uint64_t exitinfo1)
759{
760
761	if (exitinfo1 & VMCB_NPF_INFO1_ID) {
762		return (false);
763	}
764
765	if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
766		return (false);
767	}
768
769	if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
770		return (false);
771	}
772
773	return (true);
774}
775
776static void
777svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
778{
779	struct vm_guest_paging *paging;
780	struct vmcb_segment seg;
781	struct vmcb_ctrl *ctrl;
782	char *inst_bytes;
783	int error, inst_len;
784
785	ctrl = &vmcb->ctrl;
786	paging = &vmexit->u.inst_emul.paging;
787
788	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
789	vmexit->u.inst_emul.gpa = gpa;
790	vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
791	svm_paging_info(vmcb, paging);
792
793	error = vmcb_seg(vmcb, VM_REG_GUEST_CS, &seg);
794	KASSERT(error == 0, ("%s: vmcb_seg(CS) error %d", __func__, error));
795
796	switch(paging->cpu_mode) {
797	case CPU_MODE_PROTECTED:
798	case CPU_MODE_COMPATIBILITY:
799		/*
800		 * Section 4.8.1 of APM2, Default Operand Size or D bit.
801		 */
802		vmexit->u.inst_emul.cs_d = (seg.attrib & VMCB_CS_ATTRIB_D) ?
803		    1 : 0;
804		break;
805	default:
806		vmexit->u.inst_emul.cs_d = 0;
807		break;
808	}
809
810	/*
811	 * Copy the instruction bytes into 'vie' if available.
812	 */
813	if (decode_assist() && !disable_npf_assist) {
814		inst_len = ctrl->inst_len;
815		inst_bytes = ctrl->inst_bytes;
816	} else {
817		inst_len = 0;
818		inst_bytes = NULL;
819	}
820	vie_init(&vmexit->u.inst_emul.vie, inst_bytes, inst_len);
821}
822
823#ifdef KTR
824static const char *
825intrtype_to_str(int intr_type)
826{
827	switch (intr_type) {
828	case VMCB_EVENTINJ_TYPE_INTR:
829		return ("hwintr");
830	case VMCB_EVENTINJ_TYPE_NMI:
831		return ("nmi");
832	case VMCB_EVENTINJ_TYPE_INTn:
833		return ("swintr");
834	case VMCB_EVENTINJ_TYPE_EXCEPTION:
835		return ("exception");
836	default:
837		panic("%s: unknown intr_type %d", __func__, intr_type);
838	}
839}
840#endif
841
842/*
843 * Inject an event to vcpu as described in section 15.20, "Event injection".
844 */
845static void
846svm_eventinject(struct svm_softc *sc, int vcpu, int intr_type, int vector,
847		 uint32_t error, bool ec_valid)
848{
849	struct vmcb_ctrl *ctrl;
850
851	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
852
853	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0,
854	    ("%s: event already pending %#lx", __func__, ctrl->eventinj));
855
856	KASSERT(vector >=0 && vector <= 255, ("%s: invalid vector %d",
857	    __func__, vector));
858
859	switch (intr_type) {
860	case VMCB_EVENTINJ_TYPE_INTR:
861	case VMCB_EVENTINJ_TYPE_NMI:
862	case VMCB_EVENTINJ_TYPE_INTn:
863		break;
864	case VMCB_EVENTINJ_TYPE_EXCEPTION:
865		if (vector >= 0 && vector <= 31 && vector != 2)
866			break;
867		/* FALLTHROUGH */
868	default:
869		panic("%s: invalid intr_type/vector: %d/%d", __func__,
870		    intr_type, vector);
871	}
872	ctrl->eventinj = vector | (intr_type << 8) | VMCB_EVENTINJ_VALID;
873	if (ec_valid) {
874		ctrl->eventinj |= VMCB_EVENTINJ_EC_VALID;
875		ctrl->eventinj |= (uint64_t)error << 32;
876		VCPU_CTR3(sc->vm, vcpu, "Injecting %s at vector %d errcode %#x",
877		    intrtype_to_str(intr_type), vector, error);
878	} else {
879		VCPU_CTR2(sc->vm, vcpu, "Injecting %s at vector %d",
880		    intrtype_to_str(intr_type), vector);
881	}
882}
883
884static void
885svm_update_virqinfo(struct svm_softc *sc, int vcpu)
886{
887	struct vm *vm;
888	struct vlapic *vlapic;
889	struct vmcb_ctrl *ctrl;
890	int pending;
891
892	vm = sc->vm;
893	vlapic = vm_lapic(vm, vcpu);
894	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
895
896	/* Update %cr8 in the emulated vlapic */
897	vlapic_set_cr8(vlapic, ctrl->v_tpr);
898
899	/*
900	 * If V_IRQ indicates that the interrupt injection attempted on then
901	 * last VMRUN was successful then update the vlapic accordingly.
902	 */
903	if (ctrl->v_intr_vector != 0) {
904		pending = ctrl->v_irq;
905		KASSERT(ctrl->v_intr_vector >= 16, ("%s: invalid "
906		    "v_intr_vector %d", __func__, ctrl->v_intr_vector));
907		KASSERT(!ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
908		VCPU_CTR2(vm, vcpu, "v_intr_vector %d %s", ctrl->v_intr_vector,
909		    pending ? "pending" : "accepted");
910		if (!pending)
911			vlapic_intr_accepted(vlapic, ctrl->v_intr_vector);
912	}
913}
914
915static void
916svm_save_intinfo(struct svm_softc *svm_sc, int vcpu)
917{
918	struct vmcb_ctrl *ctrl;
919	uint64_t intinfo;
920
921	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
922	intinfo = ctrl->exitintinfo;
923	if (!VMCB_EXITINTINFO_VALID(intinfo))
924		return;
925
926	/*
927	 * From APMv2, Section "Intercepts during IDT interrupt delivery"
928	 *
929	 * If a #VMEXIT happened during event delivery then record the event
930	 * that was being delivered.
931	 */
932	VCPU_CTR2(svm_sc->vm, vcpu, "SVM:Pending INTINFO(0x%lx), vector=%d.\n",
933		intinfo, VMCB_EXITINTINFO_VECTOR(intinfo));
934	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_EXITINTINFO, 1);
935	vm_exit_intinfo(svm_sc->vm, vcpu, intinfo);
936}
937
938static __inline int
939vintr_intercept_enabled(struct svm_softc *sc, int vcpu)
940{
941
942	return (svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
943	    VMCB_INTCPT_VINTR));
944}
945
946static __inline void
947enable_intr_window_exiting(struct svm_softc *sc, int vcpu)
948{
949	struct vmcb_ctrl *ctrl;
950
951	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
952
953	if (ctrl->v_irq && ctrl->v_intr_vector == 0) {
954		KASSERT(ctrl->v_ign_tpr, ("%s: invalid v_ign_tpr", __func__));
955		KASSERT(vintr_intercept_enabled(sc, vcpu),
956		    ("%s: vintr intercept should be enabled", __func__));
957		return;
958	}
959
960	VCPU_CTR0(sc->vm, vcpu, "Enable intr window exiting");
961	ctrl->v_irq = 1;
962	ctrl->v_ign_tpr = 1;
963	ctrl->v_intr_vector = 0;
964	svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
965	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
966}
967
968static __inline void
969disable_intr_window_exiting(struct svm_softc *sc, int vcpu)
970{
971	struct vmcb_ctrl *ctrl;
972
973	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
974
975	if (!ctrl->v_irq && ctrl->v_intr_vector == 0) {
976		KASSERT(!vintr_intercept_enabled(sc, vcpu),
977		    ("%s: vintr intercept should be disabled", __func__));
978		return;
979	}
980
981#ifdef KTR
982	if (ctrl->v_intr_vector == 0)
983		VCPU_CTR0(sc->vm, vcpu, "Disable intr window exiting");
984	else
985		VCPU_CTR0(sc->vm, vcpu, "Clearing V_IRQ interrupt injection");
986#endif
987	ctrl->v_irq = 0;
988	ctrl->v_intr_vector = 0;
989	svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
990	svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_VINTR);
991}
992
993static int
994svm_modify_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t val)
995{
996	struct vmcb_ctrl *ctrl;
997	int oldval, newval;
998
999	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1000	oldval = ctrl->intr_shadow;
1001	newval = val ? 1 : 0;
1002	if (newval != oldval) {
1003		ctrl->intr_shadow = newval;
1004		VCPU_CTR1(sc->vm, vcpu, "Setting intr_shadow to %d", newval);
1005	}
1006	return (0);
1007}
1008
1009static int
1010svm_get_intr_shadow(struct svm_softc *sc, int vcpu, uint64_t *val)
1011{
1012	struct vmcb_ctrl *ctrl;
1013
1014	ctrl = svm_get_vmcb_ctrl(sc, vcpu);
1015	*val = ctrl->intr_shadow;
1016	return (0);
1017}
1018
1019/*
1020 * Once an NMI is injected it blocks delivery of further NMIs until the handler
1021 * executes an IRET. The IRET intercept is enabled when an NMI is injected to
1022 * to track when the vcpu is done handling the NMI.
1023 */
1024static int
1025nmi_blocked(struct svm_softc *sc, int vcpu)
1026{
1027	int blocked;
1028
1029	blocked = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
1030	    VMCB_INTCPT_IRET);
1031	return (blocked);
1032}
1033
1034static void
1035enable_nmi_blocking(struct svm_softc *sc, int vcpu)
1036{
1037
1038	KASSERT(!nmi_blocked(sc, vcpu), ("vNMI already blocked"));
1039	VCPU_CTR0(sc->vm, vcpu, "vNMI blocking enabled");
1040	svm_enable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1041}
1042
1043static void
1044clear_nmi_blocking(struct svm_softc *sc, int vcpu)
1045{
1046	int error;
1047
1048	KASSERT(nmi_blocked(sc, vcpu), ("vNMI already unblocked"));
1049	VCPU_CTR0(sc->vm, vcpu, "vNMI blocking cleared");
1050	/*
1051	 * When the IRET intercept is cleared the vcpu will attempt to execute
1052	 * the "iret" when it runs next. However, it is possible to inject
1053	 * another NMI into the vcpu before the "iret" has actually executed.
1054	 *
1055	 * For e.g. if the "iret" encounters a #NPF when accessing the stack
1056	 * it will trap back into the hypervisor. If an NMI is pending for
1057	 * the vcpu it will be injected into the guest.
1058	 *
1059	 * XXX this needs to be fixed
1060	 */
1061	svm_disable_intercept(sc, vcpu, VMCB_CTRL1_INTCPT, VMCB_INTCPT_IRET);
1062
1063	/*
1064	 * Set 'intr_shadow' to prevent an NMI from being injected on the
1065	 * immediate VMRUN.
1066	 */
1067	error = svm_modify_intr_shadow(sc, vcpu, 1);
1068	KASSERT(!error, ("%s: error %d setting intr_shadow", __func__, error));
1069}
1070
1071static int
1072emulate_wrmsr(struct svm_softc *sc, int vcpu, u_int num, uint64_t val,
1073    bool *retu)
1074{
1075	int error;
1076
1077	if (lapic_msr(num))
1078		error = lapic_wrmsr(sc->vm, vcpu, num, val, retu);
1079	else if (num == MSR_EFER)
1080		error = svm_setreg(sc, vcpu, VM_REG_GUEST_EFER, val);
1081	else
1082		error = svm_wrmsr(sc, vcpu, num, val, retu);
1083
1084	return (error);
1085}
1086
1087static int
1088emulate_rdmsr(struct svm_softc *sc, int vcpu, u_int num, bool *retu)
1089{
1090	struct vmcb_state *state;
1091	struct svm_regctx *ctx;
1092	uint64_t result;
1093	int error;
1094
1095	if (lapic_msr(num))
1096		error = lapic_rdmsr(sc->vm, vcpu, num, &result, retu);
1097	else
1098		error = svm_rdmsr(sc, vcpu, num, &result, retu);
1099
1100	if (error == 0) {
1101		state = svm_get_vmcb_state(sc, vcpu);
1102		ctx = svm_get_guest_regctx(sc, vcpu);
1103		state->rax = result & 0xffffffff;
1104		ctx->sctx_rdx = result >> 32;
1105	}
1106
1107	return (error);
1108}
1109
1110#ifdef KTR
1111static const char *
1112exit_reason_to_str(uint64_t reason)
1113{
1114	static char reasonbuf[32];
1115
1116	switch (reason) {
1117	case VMCB_EXIT_INVALID:
1118		return ("invalvmcb");
1119	case VMCB_EXIT_SHUTDOWN:
1120		return ("shutdown");
1121	case VMCB_EXIT_NPF:
1122		return ("nptfault");
1123	case VMCB_EXIT_PAUSE:
1124		return ("pause");
1125	case VMCB_EXIT_HLT:
1126		return ("hlt");
1127	case VMCB_EXIT_CPUID:
1128		return ("cpuid");
1129	case VMCB_EXIT_IO:
1130		return ("inout");
1131	case VMCB_EXIT_MC:
1132		return ("mchk");
1133	case VMCB_EXIT_INTR:
1134		return ("extintr");
1135	case VMCB_EXIT_NMI:
1136		return ("nmi");
1137	case VMCB_EXIT_VINTR:
1138		return ("vintr");
1139	case VMCB_EXIT_MSR:
1140		return ("msr");
1141	case VMCB_EXIT_IRET:
1142		return ("iret");
1143	default:
1144		snprintf(reasonbuf, sizeof(reasonbuf), "%#lx", reason);
1145		return (reasonbuf);
1146	}
1147}
1148#endif	/* KTR */
1149
1150/*
1151 * From section "State Saved on Exit" in APMv2: nRIP is saved for all #VMEXITs
1152 * that are due to instruction intercepts as well as MSR and IOIO intercepts
1153 * and exceptions caused by INT3, INTO and BOUND instructions.
1154 *
1155 * Return 1 if the nRIP is valid and 0 otherwise.
1156 */
1157static int
1158nrip_valid(uint64_t exitcode)
1159{
1160	switch (exitcode) {
1161	case 0x00 ... 0x0F:	/* read of CR0 through CR15 */
1162	case 0x10 ... 0x1F:	/* write of CR0 through CR15 */
1163	case 0x20 ... 0x2F:	/* read of DR0 through DR15 */
1164	case 0x30 ... 0x3F:	/* write of DR0 through DR15 */
1165	case 0x43:		/* INT3 */
1166	case 0x44:		/* INTO */
1167	case 0x45:		/* BOUND */
1168	case 0x65 ... 0x7C:	/* VMEXIT_CR0_SEL_WRITE ... VMEXIT_MSR */
1169	case 0x80 ... 0x8D:	/* VMEXIT_VMRUN ... VMEXIT_XSETBV */
1170		return (1);
1171	default:
1172		return (0);
1173	}
1174}
1175
1176/*
1177 * Collateral for a generic SVM VM-exit.
1178 */
1179static void
1180vm_exit_svm(struct vm_exit *vme, uint64_t code, uint64_t info1, uint64_t info2)
1181{
1182
1183	vme->exitcode = VM_EXITCODE_SVM;
1184	vme->u.svm.exitcode = code;
1185	vme->u.svm.exitinfo1 = info1;
1186	vme->u.svm.exitinfo2 = info2;
1187}
1188
1189static int
1190svm_vmexit(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
1191{
1192	struct vmcb *vmcb;
1193	struct vmcb_state *state;
1194	struct vmcb_ctrl *ctrl;
1195	struct svm_regctx *ctx;
1196	struct vm_exception exception;
1197	uint64_t code, info1, info2, val;
1198	uint32_t eax, ecx, edx;
1199	int error, errcode_valid, handled, idtvec, reflect;
1200	bool retu;
1201
1202	ctx = svm_get_guest_regctx(svm_sc, vcpu);
1203	vmcb = svm_get_vmcb(svm_sc, vcpu);
1204	state = &vmcb->state;
1205	ctrl = &vmcb->ctrl;
1206
1207	handled = 0;
1208	code = ctrl->exitcode;
1209	info1 = ctrl->exitinfo1;
1210	info2 = ctrl->exitinfo2;
1211
1212	vmexit->exitcode = VM_EXITCODE_BOGUS;
1213	vmexit->rip = state->rip;
1214	vmexit->inst_length = nrip_valid(code) ? ctrl->nrip - state->rip : 0;
1215
1216	vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_COUNT, 1);
1217
1218	/*
1219	 * #VMEXIT(INVALID) needs to be handled early because the VMCB is
1220	 * in an inconsistent state and can trigger assertions that would
1221	 * never happen otherwise.
1222	 */
1223	if (code == VMCB_EXIT_INVALID) {
1224		vm_exit_svm(vmexit, code, info1, info2);
1225		return (0);
1226	}
1227
1228	KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) == 0, ("%s: event "
1229	    "injection valid bit is set %#lx", __func__, ctrl->eventinj));
1230
1231	KASSERT(vmexit->inst_length >= 0 && vmexit->inst_length <= 15,
1232	    ("invalid inst_length %d: code (%#lx), info1 (%#lx), info2 (%#lx)",
1233	    vmexit->inst_length, code, info1, info2));
1234
1235	svm_update_virqinfo(svm_sc, vcpu);
1236	svm_save_intinfo(svm_sc, vcpu);
1237
1238	switch (code) {
1239	case VMCB_EXIT_IRET:
1240		/*
1241		 * Restart execution at "iret" but with the intercept cleared.
1242		 */
1243		vmexit->inst_length = 0;
1244		clear_nmi_blocking(svm_sc, vcpu);
1245		handled = 1;
1246		break;
1247	case VMCB_EXIT_VINTR:	/* interrupt window exiting */
1248		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_VINTR, 1);
1249		handled = 1;
1250		break;
1251	case VMCB_EXIT_INTR:	/* external interrupt */
1252		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
1253		handled = 1;
1254		break;
1255	case VMCB_EXIT_NMI:	/* external NMI */
1256		handled = 1;
1257		break;
1258	case 0x40 ... 0x5F:
1259		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXCEPTION, 1);
1260		reflect = 1;
1261		idtvec = code - 0x40;
1262		switch (idtvec) {
1263		case IDT_MC:
1264			/*
1265			 * Call the machine check handler by hand. Also don't
1266			 * reflect the machine check back into the guest.
1267			 */
1268			reflect = 0;
1269			VCPU_CTR0(svm_sc->vm, vcpu, "Vectoring to MCE handler");
1270			__asm __volatile("int $18");
1271			break;
1272		case IDT_PF:
1273			error = svm_setreg(svm_sc, vcpu, VM_REG_GUEST_CR2,
1274			    info2);
1275			KASSERT(error == 0, ("%s: error %d updating cr2",
1276			    __func__, error));
1277			/* fallthru */
1278		case IDT_NP:
1279		case IDT_SS:
1280		case IDT_GP:
1281		case IDT_AC:
1282		case IDT_TS:
1283			errcode_valid = 1;
1284			break;
1285
1286		case IDT_DF:
1287			errcode_valid = 1;
1288			info1 = 0;
1289			break;
1290
1291		case IDT_BP:
1292		case IDT_OF:
1293		case IDT_BR:
1294			/*
1295			 * The 'nrip' field is populated for INT3, INTO and
1296			 * BOUND exceptions and this also implies that
1297			 * 'inst_length' is non-zero.
1298			 *
1299			 * Reset 'inst_length' to zero so the guest %rip at
1300			 * event injection is identical to what it was when
1301			 * the exception originally happened.
1302			 */
1303			VCPU_CTR2(svm_sc->vm, vcpu, "Reset inst_length from %d "
1304			    "to zero before injecting exception %d",
1305			    vmexit->inst_length, idtvec);
1306			vmexit->inst_length = 0;
1307			/* fallthru */
1308		default:
1309			errcode_valid = 0;
1310			break;
1311		}
1312		KASSERT(vmexit->inst_length == 0, ("invalid inst_length (%d) "
1313		    "when reflecting exception %d into guest",
1314		    vmexit->inst_length, idtvec));
1315
1316		if (reflect) {
1317			/* Reflect the exception back into the guest */
1318			exception.vector = idtvec;
1319			exception.error_code_valid = errcode_valid;
1320			exception.error_code = errcode_valid ? info1 : 0;
1321			VCPU_CTR2(svm_sc->vm, vcpu, "Reflecting exception "
1322			    "%d/%#x into the guest", exception.vector,
1323			    exception.error_code);
1324			error = vm_inject_exception(svm_sc->vm, vcpu,
1325			    &exception);
1326			KASSERT(error == 0, ("%s: vm_inject_exception error %d",
1327			    __func__, error));
1328		}
1329		handled = 1;
1330		break;
1331	case VMCB_EXIT_MSR:	/* MSR access. */
1332		eax = state->rax;
1333		ecx = ctx->sctx_rcx;
1334		edx = ctx->sctx_rdx;
1335		retu = false;
1336
1337		if (info1) {
1338			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_WRMSR, 1);
1339			val = (uint64_t)edx << 32 | eax;
1340			VCPU_CTR2(svm_sc->vm, vcpu, "wrmsr %#x val %#lx",
1341			    ecx, val);
1342			if (emulate_wrmsr(svm_sc, vcpu, ecx, val, &retu)) {
1343				vmexit->exitcode = VM_EXITCODE_WRMSR;
1344				vmexit->u.msr.code = ecx;
1345				vmexit->u.msr.wval = val;
1346			} else if (!retu) {
1347				handled = 1;
1348			} else {
1349				KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1350				    ("emulate_wrmsr retu with bogus exitcode"));
1351			}
1352		} else {
1353			VCPU_CTR1(svm_sc->vm, vcpu, "rdmsr %#x", ecx);
1354			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_RDMSR, 1);
1355			if (emulate_rdmsr(svm_sc, vcpu, ecx, &retu)) {
1356				vmexit->exitcode = VM_EXITCODE_RDMSR;
1357				vmexit->u.msr.code = ecx;
1358			} else if (!retu) {
1359				handled = 1;
1360			} else {
1361				KASSERT(vmexit->exitcode != VM_EXITCODE_BOGUS,
1362				    ("emulate_rdmsr retu with bogus exitcode"));
1363			}
1364		}
1365		break;
1366	case VMCB_EXIT_IO:
1367		handled = svm_handle_io(svm_sc, vcpu, vmexit);
1368		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
1369		break;
1370	case VMCB_EXIT_CPUID:
1371		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
1372		handled = x86_emulate_cpuid(svm_sc->vm, vcpu,
1373		    (uint32_t *)&state->rax,
1374		    (uint32_t *)&ctx->sctx_rbx,
1375		    (uint32_t *)&ctx->sctx_rcx,
1376		    (uint32_t *)&ctx->sctx_rdx);
1377		break;
1378	case VMCB_EXIT_HLT:
1379		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
1380		vmexit->exitcode = VM_EXITCODE_HLT;
1381		vmexit->u.hlt.rflags = state->rflags;
1382		break;
1383	case VMCB_EXIT_PAUSE:
1384		vmexit->exitcode = VM_EXITCODE_PAUSE;
1385		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
1386		break;
1387	case VMCB_EXIT_NPF:
1388		/* EXITINFO2 contains the faulting guest physical address */
1389		if (info1 & VMCB_NPF_INFO1_RSV) {
1390			VCPU_CTR2(svm_sc->vm, vcpu, "nested page fault with "
1391			    "reserved bits set: info1(%#lx) info2(%#lx)",
1392			    info1, info2);
1393		} else if (vm_mem_allocated(svm_sc->vm, info2)) {
1394			vmexit->exitcode = VM_EXITCODE_PAGING;
1395			vmexit->u.paging.gpa = info2;
1396			vmexit->u.paging.fault_type = npf_fault_type(info1);
1397			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_NESTED_FAULT, 1);
1398			VCPU_CTR3(svm_sc->vm, vcpu, "nested page fault "
1399			    "on gpa %#lx/%#lx at rip %#lx",
1400			    info2, info1, state->rip);
1401		} else if (svm_npf_emul_fault(info1)) {
1402			svm_handle_inst_emul(vmcb, info2, vmexit);
1403			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INST_EMUL, 1);
1404			VCPU_CTR3(svm_sc->vm, vcpu, "inst_emul fault "
1405			    "for gpa %#lx/%#lx at rip %#lx",
1406			    info2, info1, state->rip);
1407		}
1408		break;
1409	default:
1410		vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
1411		break;
1412	}
1413
1414	VCPU_CTR4(svm_sc->vm, vcpu, "%s %s vmexit at %#lx/%d",
1415	    handled ? "handled" : "unhandled", exit_reason_to_str(code),
1416	    vmexit->rip, vmexit->inst_length);
1417
1418	if (handled) {
1419		vmexit->rip += vmexit->inst_length;
1420		vmexit->inst_length = 0;
1421		state->rip = vmexit->rip;
1422	} else {
1423		if (vmexit->exitcode == VM_EXITCODE_BOGUS) {
1424			/*
1425			 * If this VM exit was not claimed by anybody then
1426			 * treat it as a generic SVM exit.
1427			 */
1428			vm_exit_svm(vmexit, code, info1, info2);
1429		} else {
1430			/*
1431			 * The exitcode and collateral have been populated.
1432			 * The VM exit will be processed further in userland.
1433			 */
1434		}
1435	}
1436	return (handled);
1437}
1438
1439static void
1440svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
1441{
1442	uint64_t intinfo;
1443
1444	if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
1445		return;
1446
1447	KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1448	    "valid: %#lx", __func__, intinfo));
1449
1450	svm_eventinject(svm_sc, vcpu, VMCB_EXITINTINFO_TYPE(intinfo),
1451		VMCB_EXITINTINFO_VECTOR(intinfo),
1452		VMCB_EXITINTINFO_EC(intinfo),
1453		VMCB_EXITINTINFO_EC_VALID(intinfo));
1454	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1455	VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1456}
1457
1458/*
1459 * Inject event to virtual cpu.
1460 */
1461static void
1462svm_inj_interrupts(struct svm_softc *sc, int vcpu, struct vlapic *vlapic)
1463{
1464	struct vmcb_ctrl *ctrl;
1465	struct vmcb_state *state;
1466	uint8_t v_tpr;
1467	int vector, need_intr_window, pending_apic_vector;
1468
1469	state = svm_get_vmcb_state(sc, vcpu);
1470	ctrl  = svm_get_vmcb_ctrl(sc, vcpu);
1471
1472	need_intr_window = 0;
1473	pending_apic_vector = 0;
1474
1475	/*
1476	 * Inject pending events or exceptions for this vcpu.
1477	 *
1478	 * An event might be pending because the previous #VMEXIT happened
1479	 * during event delivery (i.e. ctrl->exitintinfo).
1480	 *
1481	 * An event might also be pending because an exception was injected
1482	 * by the hypervisor (e.g. #PF during instruction emulation).
1483	 */
1484	svm_inj_intinfo(sc, vcpu);
1485
1486	/* NMI event has priority over interrupts. */
1487	if (vm_nmi_pending(sc->vm, vcpu)) {
1488		if (nmi_blocked(sc, vcpu)) {
1489			/*
1490			 * Can't inject another NMI if the guest has not
1491			 * yet executed an "iret" after the last NMI.
1492			 */
1493			VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due "
1494			    "to NMI-blocking");
1495		} else if (ctrl->intr_shadow) {
1496			/*
1497			 * Can't inject an NMI if the vcpu is in an intr_shadow.
1498			 */
1499			VCPU_CTR0(sc->vm, vcpu, "Cannot inject NMI due to "
1500			    "interrupt shadow");
1501			need_intr_window = 1;
1502			goto done;
1503		} else if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1504			/*
1505			 * If there is already an exception/interrupt pending
1506			 * then defer the NMI until after that.
1507			 */
1508			VCPU_CTR1(sc->vm, vcpu, "Cannot inject NMI due to "
1509			    "eventinj %#lx", ctrl->eventinj);
1510
1511			/*
1512			 * Use self-IPI to trigger a VM-exit as soon as
1513			 * possible after the event injection is completed.
1514			 *
1515			 * This works only if the external interrupt exiting
1516			 * is at a lower priority than the event injection.
1517			 *
1518			 * Although not explicitly specified in APMv2 the
1519			 * relative priorities were verified empirically.
1520			 */
1521			ipi_cpu(curcpu, IPI_AST);	/* XXX vmm_ipinum? */
1522		} else {
1523			vm_nmi_clear(sc->vm, vcpu);
1524
1525			/* Inject NMI, vector number is not used */
1526			svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_NMI,
1527			    IDT_NMI, 0, false);
1528
1529			/* virtual NMI blocking is now in effect */
1530			enable_nmi_blocking(sc, vcpu);
1531
1532			VCPU_CTR0(sc->vm, vcpu, "Injecting vNMI");
1533		}
1534	}
1535
1536	if (!vm_extint_pending(sc->vm, vcpu)) {
1537		/*
1538		 * APIC interrupts are delivered using the V_IRQ offload.
1539		 *
1540		 * The primary benefit is that the hypervisor doesn't need to
1541		 * deal with the various conditions that inhibit interrupts.
1542		 * It also means that TPR changes via CR8 will be handled
1543		 * without any hypervisor involvement.
1544		 *
1545		 * Note that the APIC vector must remain pending in the vIRR
1546		 * until it is confirmed that it was delivered to the guest.
1547		 * This can be confirmed based on the value of V_IRQ at the
1548		 * next #VMEXIT (1 = pending, 0 = delivered).
1549		 *
1550		 * Also note that it is possible that another higher priority
1551		 * vector can become pending before this vector is delivered
1552		 * to the guest. This is alright because vcpu_notify_event()
1553		 * will send an IPI and force the vcpu to trap back into the
1554		 * hypervisor. The higher priority vector will be injected on
1555		 * the next VMRUN.
1556		 */
1557		if (vlapic_pending_intr(vlapic, &vector)) {
1558			KASSERT(vector >= 16 && vector <= 255,
1559			    ("invalid vector %d from local APIC", vector));
1560			pending_apic_vector = vector;
1561		}
1562		goto done;
1563	}
1564
1565	/* Ask the legacy pic for a vector to inject */
1566	vatpic_pending_intr(sc->vm, &vector);
1567	KASSERT(vector >= 0 && vector <= 255, ("invalid vector %d from INTR",
1568	    vector));
1569
1570	/*
1571	 * If the guest has disabled interrupts or is in an interrupt shadow
1572	 * then we cannot inject the pending interrupt.
1573	 */
1574	if ((state->rflags & PSL_I) == 0) {
1575		VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1576		    "rflags %#lx", vector, state->rflags);
1577		need_intr_window = 1;
1578		goto done;
1579	}
1580
1581	if (ctrl->intr_shadow) {
1582		VCPU_CTR1(sc->vm, vcpu, "Cannot inject vector %d due to "
1583		    "interrupt shadow", vector);
1584		need_intr_window = 1;
1585		goto done;
1586	}
1587
1588	if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1589		VCPU_CTR2(sc->vm, vcpu, "Cannot inject vector %d due to "
1590		    "eventinj %#lx", vector, ctrl->eventinj);
1591		need_intr_window = 1;
1592		goto done;
1593	}
1594
1595	/*
1596	 * Legacy PIC interrupts are delivered via the event injection
1597	 * mechanism.
1598	 */
1599	svm_eventinject(sc, vcpu, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1600
1601	vm_extint_clear(sc->vm, vcpu);
1602	vatpic_intr_accepted(sc->vm, vector);
1603
1604	/*
1605	 * Force a VM-exit as soon as the vcpu is ready to accept another
1606	 * interrupt. This is done because the PIC might have another vector
1607	 * that it wants to inject. Also, if the APIC has a pending interrupt
1608	 * that was preempted by the ExtInt then it allows us to inject the
1609	 * APIC vector as soon as possible.
1610	 */
1611	need_intr_window = 1;
1612done:
1613	/*
1614	 * The guest can modify the TPR by writing to %CR8. In guest mode
1615	 * the processor reflects this write to V_TPR without hypervisor
1616	 * intervention.
1617	 *
1618	 * The guest can also modify the TPR by writing to it via the memory
1619	 * mapped APIC page. In this case, the write will be emulated by the
1620	 * hypervisor. For this reason V_TPR must be updated before every
1621	 * VMRUN.
1622	 */
1623	v_tpr = vlapic_get_cr8(vlapic);
1624	KASSERT(v_tpr >= 0 && v_tpr <= 15, ("invalid v_tpr %#x", v_tpr));
1625	if (ctrl->v_tpr != v_tpr) {
1626		VCPU_CTR2(sc->vm, vcpu, "VMCB V_TPR changed from %#x to %#x",
1627		    ctrl->v_tpr, v_tpr);
1628		ctrl->v_tpr = v_tpr;
1629		svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1630	}
1631
1632	if (pending_apic_vector) {
1633		/*
1634		 * If an APIC vector is being injected then interrupt window
1635		 * exiting is not possible on this VMRUN.
1636		 */
1637		KASSERT(!need_intr_window, ("intr_window exiting impossible"));
1638		VCPU_CTR1(sc->vm, vcpu, "Injecting vector %d using V_IRQ",
1639		    pending_apic_vector);
1640
1641		ctrl->v_irq = 1;
1642		ctrl->v_ign_tpr = 0;
1643		ctrl->v_intr_vector = pending_apic_vector;
1644		ctrl->v_intr_prio = pending_apic_vector >> 4;
1645		svm_set_dirty(sc, vcpu, VMCB_CACHE_TPR);
1646	} else if (need_intr_window) {
1647		/*
1648		 * We use V_IRQ in conjunction with the VINTR intercept to
1649		 * trap into the hypervisor as soon as a virtual interrupt
1650		 * can be delivered.
1651		 *
1652		 * Since injected events are not subject to intercept checks
1653		 * we need to ensure that the V_IRQ is not actually going to
1654		 * be delivered on VM entry. The KASSERT below enforces this.
1655		 */
1656		KASSERT((ctrl->eventinj & VMCB_EVENTINJ_VALID) != 0 ||
1657		    (state->rflags & PSL_I) == 0 || ctrl->intr_shadow,
1658		    ("Bogus intr_window_exiting: eventinj (%#lx), "
1659		    "intr_shadow (%u), rflags (%#lx)",
1660		    ctrl->eventinj, ctrl->intr_shadow, state->rflags));
1661		enable_intr_window_exiting(sc, vcpu);
1662	} else {
1663		disable_intr_window_exiting(sc, vcpu);
1664	}
1665}
1666
1667static __inline void
1668restore_host_tss(void)
1669{
1670	struct system_segment_descriptor *tss_sd;
1671
1672	/*
1673	 * The TSS descriptor was in use prior to launching the guest so it
1674	 * has been marked busy.
1675	 *
1676	 * 'ltr' requires the descriptor to be marked available so change the
1677	 * type to "64-bit available TSS".
1678	 */
1679	tss_sd = PCPU_GET(tss);
1680	tss_sd->sd_type = SDT_SYSTSS;
1681	ltr(GSEL(GPROC0_SEL, SEL_KPL));
1682}
1683
1684static void
1685check_asid(struct svm_softc *sc, int vcpuid, pmap_t pmap, u_int thiscpu)
1686{
1687	struct svm_vcpu *vcpustate;
1688	struct vmcb_ctrl *ctrl;
1689	long eptgen;
1690	bool alloc_asid;
1691
1692	KASSERT(CPU_ISSET(thiscpu, &pmap->pm_active), ("%s: nested pmap not "
1693	    "active on cpu %u", __func__, thiscpu));
1694
1695	vcpustate = svm_get_vcpu(sc, vcpuid);
1696	ctrl = svm_get_vmcb_ctrl(sc, vcpuid);
1697
1698	/*
1699	 * The TLB entries associated with the vcpu's ASID are not valid
1700	 * if either of the following conditions is true:
1701	 *
1702	 * 1. The vcpu's ASID generation is different than the host cpu's
1703	 *    ASID generation. This happens when the vcpu migrates to a new
1704	 *    host cpu. It can also happen when the number of vcpus executing
1705	 *    on a host cpu is greater than the number of ASIDs available.
1706	 *
1707	 * 2. The pmap generation number is different than the value cached in
1708	 *    the 'vcpustate'. This happens when the host invalidates pages
1709	 *    belonging to the guest.
1710	 *
1711	 *	asidgen		eptgen	      Action
1712	 *	mismatch	mismatch
1713	 *	   0		   0		(a)
1714	 *	   0		   1		(b1) or (b2)
1715	 *	   1		   0		(c)
1716	 *	   1		   1		(d)
1717	 *
1718	 * (a) There is no mismatch in eptgen or ASID generation and therefore
1719	 *     no further action is needed.
1720	 *
1721	 * (b1) If the cpu supports FlushByAsid then the vcpu's ASID is
1722	 *      retained and the TLB entries associated with this ASID
1723	 *      are flushed by VMRUN.
1724	 *
1725	 * (b2) If the cpu does not support FlushByAsid then a new ASID is
1726	 *      allocated.
1727	 *
1728	 * (c) A new ASID is allocated.
1729	 *
1730	 * (d) A new ASID is allocated.
1731	 */
1732
1733	alloc_asid = false;
1734	eptgen = pmap->pm_eptgen;
1735	ctrl->tlb_ctrl = VMCB_TLB_FLUSH_NOTHING;
1736
1737	if (vcpustate->asid.gen != asid[thiscpu].gen) {
1738		alloc_asid = true;	/* (c) and (d) */
1739	} else if (vcpustate->eptgen != eptgen) {
1740		if (flush_by_asid())
1741			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;	/* (b1) */
1742		else
1743			alloc_asid = true;			/* (b2) */
1744	} else {
1745		/*
1746		 * This is the common case (a).
1747		 */
1748		KASSERT(!alloc_asid, ("ASID allocation not necessary"));
1749		KASSERT(ctrl->tlb_ctrl == VMCB_TLB_FLUSH_NOTHING,
1750		    ("Invalid VMCB tlb_ctrl: %#x", ctrl->tlb_ctrl));
1751	}
1752
1753	if (alloc_asid) {
1754		if (++asid[thiscpu].num >= nasid) {
1755			asid[thiscpu].num = 1;
1756			if (++asid[thiscpu].gen == 0)
1757				asid[thiscpu].gen = 1;
1758			/*
1759			 * If this cpu does not support "flush-by-asid"
1760			 * then flush the entire TLB on a generation
1761			 * bump. Subsequent ASID allocation in this
1762			 * generation can be done without a TLB flush.
1763			 */
1764			if (!flush_by_asid())
1765				ctrl->tlb_ctrl = VMCB_TLB_FLUSH_ALL;
1766		}
1767		vcpustate->asid.gen = asid[thiscpu].gen;
1768		vcpustate->asid.num = asid[thiscpu].num;
1769
1770		ctrl->asid = vcpustate->asid.num;
1771		svm_set_dirty(sc, vcpuid, VMCB_CACHE_ASID);
1772		/*
1773		 * If this cpu supports "flush-by-asid" then the TLB
1774		 * was not flushed after the generation bump. The TLB
1775		 * is flushed selectively after every new ASID allocation.
1776		 */
1777		if (flush_by_asid())
1778			ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1779	}
1780	vcpustate->eptgen = eptgen;
1781
1782	KASSERT(ctrl->asid != 0, ("Guest ASID must be non-zero"));
1783	KASSERT(ctrl->asid == vcpustate->asid.num,
1784	    ("ASID mismatch: %u/%u", ctrl->asid, vcpustate->asid.num));
1785}
1786
1787static __inline void
1788disable_gintr(void)
1789{
1790
1791        __asm __volatile("clgi" : : :);
1792}
1793
1794static __inline void
1795enable_gintr(void)
1796{
1797
1798        __asm __volatile("stgi" : : :);
1799}
1800
1801/*
1802 * Start vcpu with specified RIP.
1803 */
1804static int
1805svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1806	void *rend_cookie, void *suspended_cookie)
1807{
1808	struct svm_regctx *gctx;
1809	struct svm_softc *svm_sc;
1810	struct svm_vcpu *vcpustate;
1811	struct vmcb_state *state;
1812	struct vmcb_ctrl *ctrl;
1813	struct vm_exit *vmexit;
1814	struct vlapic *vlapic;
1815	struct vm *vm;
1816	uint64_t vmcb_pa;
1817	u_int thiscpu;
1818	int handled;
1819
1820	svm_sc = arg;
1821	vm = svm_sc->vm;
1822
1823	vcpustate = svm_get_vcpu(svm_sc, vcpu);
1824	state = svm_get_vmcb_state(svm_sc, vcpu);
1825	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1826	vmexit = vm_exitinfo(vm, vcpu);
1827	vlapic = vm_lapic(vm, vcpu);
1828
1829	/*
1830	 * Stash 'curcpu' on the stack as 'thiscpu'.
1831	 *
1832	 * The per-cpu data area is not accessible until MSR_GSBASE is restored
1833	 * after the #VMEXIT. Since VMRUN is executed inside a critical section
1834	 * 'curcpu' and 'thiscpu' are guaranteed to identical.
1835	 */
1836	thiscpu = curcpu;
1837
1838	gctx = svm_get_guest_regctx(svm_sc, vcpu);
1839	vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1840
1841	if (vcpustate->lastcpu != thiscpu) {
1842		/*
1843		 * Force new ASID allocation by invalidating the generation.
1844		 */
1845		vcpustate->asid.gen = 0;
1846
1847		/*
1848		 * Invalidate the VMCB state cache by marking all fields dirty.
1849		 */
1850		svm_set_dirty(svm_sc, vcpu, 0xffffffff);
1851
1852		/*
1853		 * XXX
1854		 * Setting 'vcpustate->lastcpu' here is bit premature because
1855		 * we may return from this function without actually executing
1856		 * the VMRUN  instruction. This could happen if a rendezvous
1857		 * or an AST is pending on the first time through the loop.
1858		 *
1859		 * This works for now but any new side-effects of vcpu
1860		 * migration should take this case into account.
1861		 */
1862		vcpustate->lastcpu = thiscpu;
1863		vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1864	}
1865
1866	svm_msr_guest_enter(svm_sc, vcpu);
1867
1868	/* Update Guest RIP */
1869	state->rip = rip;
1870
1871	do {
1872		/*
1873		 * Disable global interrupts to guarantee atomicity during
1874		 * loading of guest state. This includes not only the state
1875		 * loaded by the "vmrun" instruction but also software state
1876		 * maintained by the hypervisor: suspended and rendezvous
1877		 * state, NPT generation number, vlapic interrupts etc.
1878		 */
1879		disable_gintr();
1880
1881		if (vcpu_suspended(suspended_cookie)) {
1882			enable_gintr();
1883			vm_exit_suspended(vm, vcpu, state->rip);
1884			break;
1885		}
1886
1887		if (vcpu_rendezvous_pending(rend_cookie)) {
1888			enable_gintr();
1889			vm_exit_rendezvous(vm, vcpu, state->rip);
1890			break;
1891		}
1892
1893		/* We are asked to give the cpu by scheduler. */
1894		if (curthread->td_flags & (TDF_ASTPENDING | TDF_NEEDRESCHED)) {
1895			enable_gintr();
1896			vm_exit_astpending(vm, vcpu, state->rip);
1897			break;
1898		}
1899
1900		svm_inj_interrupts(svm_sc, vcpu, vlapic);
1901
1902		/* Activate the nested pmap on 'thiscpu' */
1903		CPU_SET_ATOMIC_ACQ(thiscpu, &pmap->pm_active);
1904
1905		/*
1906		 * Check the pmap generation and the ASID generation to
1907		 * ensure that the vcpu does not use stale TLB mappings.
1908		 */
1909		check_asid(svm_sc, vcpu, pmap, thiscpu);
1910
1911		ctrl->vmcb_clean = vmcb_clean & ~vcpustate->dirty;
1912		vcpustate->dirty = 0;
1913		VCPU_CTR1(vm, vcpu, "vmcb clean %#x", ctrl->vmcb_clean);
1914
1915		/* Launch Virtual Machine. */
1916		VCPU_CTR1(vm, vcpu, "Resume execution at %#lx", state->rip);
1917		svm_launch(vmcb_pa, gctx);
1918
1919		CPU_CLR_ATOMIC(thiscpu, &pmap->pm_active);
1920
1921		/*
1922		 * Restore MSR_GSBASE to point to the pcpu data area.
1923		 *
1924		 * Note that accesses done via PCPU_GET/PCPU_SET will work
1925		 * only after MSR_GSBASE is restored.
1926		 *
1927		 * Also note that we don't bother restoring MSR_KGSBASE
1928		 * since it is not used in the kernel and will be restored
1929		 * when the VMRUN ioctl returns to userspace.
1930		 */
1931		wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[thiscpu]);
1932		KASSERT(curcpu == thiscpu, ("thiscpu/curcpu (%u/%u) mismatch",
1933		    thiscpu, curcpu));
1934
1935		/*
1936		 * The host GDTR and IDTR is saved by VMRUN and restored
1937		 * automatically on #VMEXIT. However, the host TSS needs
1938		 * to be restored explicitly.
1939		 */
1940		restore_host_tss();
1941
1942		/* #VMEXIT disables interrupts so re-enable them here. */
1943		enable_gintr();
1944
1945		/* Handle #VMEXIT and if required return to user space. */
1946		handled = svm_vmexit(svm_sc, vcpu, vmexit);
1947	} while (handled);
1948
1949	svm_msr_guest_exit(svm_sc, vcpu);
1950
1951	return (0);
1952}
1953
1954static void
1955svm_vmcleanup(void *arg)
1956{
1957	struct svm_softc *sc = arg;
1958
1959	free(sc, M_SVM);
1960}
1961
1962static register_t *
1963swctx_regptr(struct svm_regctx *regctx, int reg)
1964{
1965
1966	switch (reg) {
1967	case VM_REG_GUEST_RBX:
1968		return (&regctx->sctx_rbx);
1969	case VM_REG_GUEST_RCX:
1970		return (&regctx->sctx_rcx);
1971	case VM_REG_GUEST_RDX:
1972		return (&regctx->sctx_rdx);
1973	case VM_REG_GUEST_RDI:
1974		return (&regctx->sctx_rdi);
1975	case VM_REG_GUEST_RSI:
1976		return (&regctx->sctx_rsi);
1977	case VM_REG_GUEST_RBP:
1978		return (&regctx->sctx_rbp);
1979	case VM_REG_GUEST_R8:
1980		return (&regctx->sctx_r8);
1981	case VM_REG_GUEST_R9:
1982		return (&regctx->sctx_r9);
1983	case VM_REG_GUEST_R10:
1984		return (&regctx->sctx_r10);
1985	case VM_REG_GUEST_R11:
1986		return (&regctx->sctx_r11);
1987	case VM_REG_GUEST_R12:
1988		return (&regctx->sctx_r12);
1989	case VM_REG_GUEST_R13:
1990		return (&regctx->sctx_r13);
1991	case VM_REG_GUEST_R14:
1992		return (&regctx->sctx_r14);
1993	case VM_REG_GUEST_R15:
1994		return (&regctx->sctx_r15);
1995	default:
1996		return (NULL);
1997	}
1998}
1999
2000static int
2001svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
2002{
2003	struct svm_softc *svm_sc;
2004	register_t *reg;
2005
2006	svm_sc = arg;
2007
2008	if (ident == VM_REG_GUEST_INTR_SHADOW) {
2009		return (svm_get_intr_shadow(svm_sc, vcpu, val));
2010	}
2011
2012	if (vmcb_read(svm_sc, vcpu, ident, val) == 0) {
2013		return (0);
2014	}
2015
2016	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2017
2018	if (reg != NULL) {
2019		*val = *reg;
2020		return (0);
2021	}
2022
2023	VCPU_CTR1(svm_sc->vm, vcpu, "svm_getreg: unknown register %#x", ident);
2024	return (EINVAL);
2025}
2026
2027static int
2028svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
2029{
2030	struct svm_softc *svm_sc;
2031	register_t *reg;
2032
2033	svm_sc = arg;
2034
2035	if (ident == VM_REG_GUEST_INTR_SHADOW) {
2036		return (svm_modify_intr_shadow(svm_sc, vcpu, val));
2037	}
2038
2039	if (vmcb_write(svm_sc, vcpu, ident, val) == 0) {
2040		return (0);
2041	}
2042
2043	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
2044
2045	if (reg != NULL) {
2046		*reg = val;
2047		return (0);
2048	}
2049
2050	/*
2051	 * XXX deal with CR3 and invalidate TLB entries tagged with the
2052	 * vcpu's ASID. This needs to be treated differently depending on
2053	 * whether 'running' is true/false.
2054	 */
2055
2056	VCPU_CTR1(svm_sc->vm, vcpu, "svm_setreg: unknown register %#x", ident);
2057	return (EINVAL);
2058}
2059
2060static int
2061svm_setcap(void *arg, int vcpu, int type, int val)
2062{
2063	struct svm_softc *sc;
2064	int error;
2065
2066	sc = arg;
2067	error = 0;
2068	switch (type) {
2069	case VM_CAP_HALT_EXIT:
2070		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2071		    VMCB_INTCPT_HLT, val);
2072		break;
2073	case VM_CAP_PAUSE_EXIT:
2074		svm_set_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2075		    VMCB_INTCPT_PAUSE, val);
2076		break;
2077	case VM_CAP_UNRESTRICTED_GUEST:
2078		/* Unrestricted guest execution cannot be disabled in SVM */
2079		if (val == 0)
2080			error = EINVAL;
2081		break;
2082	default:
2083		error = ENOENT;
2084		break;
2085	}
2086	return (error);
2087}
2088
2089static int
2090svm_getcap(void *arg, int vcpu, int type, int *retval)
2091{
2092	struct svm_softc *sc;
2093	int error;
2094
2095	sc = arg;
2096	error = 0;
2097
2098	switch (type) {
2099	case VM_CAP_HALT_EXIT:
2100		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2101		    VMCB_INTCPT_HLT);
2102		break;
2103	case VM_CAP_PAUSE_EXIT:
2104		*retval = svm_get_intercept(sc, vcpu, VMCB_CTRL1_INTCPT,
2105		    VMCB_INTCPT_PAUSE);
2106		break;
2107	case VM_CAP_UNRESTRICTED_GUEST:
2108		*retval = 1;	/* unrestricted guest is always enabled */
2109		break;
2110	default:
2111		error = ENOENT;
2112		break;
2113	}
2114	return (error);
2115}
2116
2117static struct vlapic *
2118svm_vlapic_init(void *arg, int vcpuid)
2119{
2120	struct svm_softc *svm_sc;
2121	struct vlapic *vlapic;
2122
2123	svm_sc = arg;
2124	vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
2125	vlapic->vm = svm_sc->vm;
2126	vlapic->vcpuid = vcpuid;
2127	vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
2128
2129	vlapic_init(vlapic);
2130
2131	return (vlapic);
2132}
2133
2134static void
2135svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
2136{
2137
2138        vlapic_cleanup(vlapic);
2139        free(vlapic, M_SVM_VLAPIC);
2140}
2141
2142struct vmm_ops vmm_ops_amd = {
2143	svm_init,
2144	svm_cleanup,
2145	svm_restore,
2146	svm_vminit,
2147	svm_vmrun,
2148	svm_vmcleanup,
2149	svm_getreg,
2150	svm_setreg,
2151	vmcb_getdesc,
2152	vmcb_setdesc,
2153	svm_getcap,
2154	svm_setcap,
2155	svm_npt_alloc,
2156	svm_npt_free,
2157	svm_vlapic_init,
2158	svm_vlapic_cleanup
2159};
2160