svm.c revision 271152
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 271152 2014-09-05 03:33:16Z 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_ASID_FLUSH	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
83MALLOC_DEFINE(M_SVM, "svm", "svm");
84MALLOC_DEFINE(M_SVM_VLAPIC, "svm-vlapic", "svm-vlapic");
85
86/* Per-CPU context area. */
87extern struct pcpu __pcpu[];
88
89static bool svm_vmexit(struct svm_softc *svm_sc, int vcpu,
90			struct vm_exit *vmexit);
91static int svm_msr_rw_ok(uint8_t *btmap, uint64_t msr);
92static int svm_msr_rd_ok(uint8_t *btmap, uint64_t msr);
93static int svm_msr_index(uint64_t msr, int *index, int *bit);
94static int svm_getdesc(void *arg, int vcpu, int type, struct seg_desc *desc);
95
96static uint32_t svm_feature; /* AMD SVM features. */
97
98/*
99 * Starting guest ASID, 0 is reserved for host.
100 * Each guest will have its own unique ASID.
101 */
102static uint32_t guest_asid = 1;
103
104/*
105 * Max ASID processor can support.
106 * This limit the maximum number of virtual machines that can be created.
107 */
108static int max_asid;
109
110/*
111 * SVM host state saved area of size 4KB for each core.
112 */
113static uint8_t hsave[MAXCPU][PAGE_SIZE] __aligned(PAGE_SIZE);
114
115/*
116 * S/w saved host context.
117 */
118static struct svm_regctx host_ctx[MAXCPU];
119
120static VMM_STAT_AMD(VCPU_EXITINTINFO, "Valid VMCB EXITINTINFO");
121static VMM_STAT_AMD(VCPU_INTINFO_INJECTED, "VMM pending exception injected");
122
123/*
124 * Common function to enable or disabled SVM for a CPU.
125 */
126static int
127cpu_svm_enable_disable(boolean_t enable)
128{
129	uint64_t efer_msr;
130
131	efer_msr = rdmsr(MSR_EFER);
132
133	if (enable)
134		efer_msr |= EFER_SVM;
135	else
136		efer_msr &= ~EFER_SVM;
137
138	wrmsr(MSR_EFER, efer_msr);
139
140	return(0);
141}
142
143/*
144 * Disable SVM on a CPU.
145 */
146static void
147svm_disable(void *arg __unused)
148{
149
150	(void)cpu_svm_enable_disable(FALSE);
151}
152
153/*
154 * Disable SVM for all CPUs.
155 */
156static int
157svm_cleanup(void)
158{
159
160	smp_rendezvous(NULL, svm_disable, NULL, NULL);
161	return (0);
162}
163
164/*
165 * Check for required BHyVe SVM features in a CPU.
166 */
167static int
168svm_cpuid_features(void)
169{
170	u_int regs[4];
171
172	/* CPUID Fn8000_000A is for SVM */
173	do_cpuid(0x8000000A, regs);
174	svm_feature = regs[3];
175
176	printf("SVM rev: 0x%x NASID:0x%x\n", regs[0] & 0xFF, regs[1]);
177	max_asid = regs[1];
178
179	printf("SVM Features:0x%b\n", svm_feature,
180		"\020"
181		"\001NP"		/* Nested paging */
182		"\002LbrVirt"		/* LBR virtualization */
183		"\003SVML"		/* SVM lock */
184		"\004NRIPS"		/* NRIP save */
185		"\005TscRateMsr"	/* MSR based TSC rate control */
186		"\006VmcbClean"		/* VMCB clean bits */
187		"\007FlushByAsid"	/* Flush by ASID */
188		"\010DecodeAssist"	/* Decode assist */
189		"\011<b20>"
190		"\012<b20>"
191		"\013PauseFilter"
192		"\014<b20>"
193		"\015PauseFilterThreshold"
194		"\016AVIC"
195		);
196
197	/* SVM Lock */
198	if (!(svm_feature & AMD_CPUID_SVM_SVML)) {
199		printf("SVM is disabled by BIOS, please enable in BIOS.\n");
200		return (ENXIO);
201	}
202
203	/*
204	 * bhyve need RVI to work.
205	 */
206	if (!(svm_feature & AMD_CPUID_SVM_NP)) {
207		printf("Missing Nested paging or RVI SVM support in processor.\n");
208		return (EIO);
209	}
210
211	if (svm_feature & AMD_CPUID_SVM_NRIP_SAVE)
212		return (0);
213
214	return (EIO);
215}
216
217/*
218 * Enable SVM for a CPU.
219 */
220static void
221svm_enable(void *arg __unused)
222{
223	uint64_t hsave_pa;
224
225	(void)cpu_svm_enable_disable(TRUE);
226
227	hsave_pa = vtophys(hsave[curcpu]);
228	wrmsr(MSR_VM_HSAVE_PA, hsave_pa);
229
230	if (rdmsr(MSR_VM_HSAVE_PA) != hsave_pa) {
231		panic("VM_HSAVE_PA is wrong on CPU%d\n", curcpu);
232	}
233}
234
235/*
236 * Check if a processor support SVM.
237 */
238static int
239is_svm_enabled(void)
240{
241	uint64_t msr;
242
243	 /* Section 15.4 Enabling SVM from APM2. */
244	if ((amd_feature2 & AMDID2_SVM) == 0) {
245		printf("SVM is not supported on this processor.\n");
246		return (ENXIO);
247	}
248
249	msr = rdmsr(MSR_VM_CR);
250	/* Make sure SVM is not disabled by BIOS. */
251	if ((msr & VM_CR_SVMDIS) == 0) {
252		return svm_cpuid_features();
253	}
254
255	printf("SVM disabled by Key, consult TPM/BIOS manual.\n");
256	return (ENXIO);
257}
258
259/*
260 * Enable SVM on CPU and initialize nested page table h/w.
261 */
262static int
263svm_init(int ipinum)
264{
265	int err;
266
267	err = is_svm_enabled();
268	if (err)
269		return (err);
270
271
272	svm_npt_init(ipinum);
273
274	/* Start SVM on all CPUs */
275	smp_rendezvous(NULL, svm_enable, NULL, NULL);
276
277	return (0);
278}
279
280static void
281svm_restore(void)
282{
283	svm_enable(NULL);
284}
285/*
286 * Get index and bit position for a MSR in MSR permission
287 * bitmap. Two bits are used for each MSR, lower bit is
288 * for read and higher bit is for write.
289 */
290static int
291svm_msr_index(uint64_t msr, int *index, int *bit)
292{
293	uint32_t base, off;
294
295/* Pentium compatible MSRs */
296#define MSR_PENTIUM_START 	0
297#define MSR_PENTIUM_END 	0x1FFF
298/* AMD 6th generation and Intel compatible MSRs */
299#define MSR_AMD6TH_START 	0xC0000000UL
300#define MSR_AMD6TH_END 		0xC0001FFFUL
301/* AMD 7th and 8th generation compatible MSRs */
302#define MSR_AMD7TH_START 	0xC0010000UL
303#define MSR_AMD7TH_END 		0xC0011FFFUL
304
305	*index = -1;
306	*bit = (msr % 4) * 2;
307	base = 0;
308
309	if (msr >= MSR_PENTIUM_START && msr <= MSR_PENTIUM_END) {
310		*index = msr / 4;
311		return (0);
312	}
313
314	base += (MSR_PENTIUM_END - MSR_PENTIUM_START + 1);
315	if (msr >= MSR_AMD6TH_START && msr <= MSR_AMD6TH_END) {
316		off = (msr - MSR_AMD6TH_START);
317		*index = (off + base) / 4;
318		return (0);
319	}
320
321	base += (MSR_AMD6TH_END - MSR_AMD6TH_START + 1);
322	if (msr >= MSR_AMD7TH_START && msr <= MSR_AMD7TH_END) {
323		off = (msr - MSR_AMD7TH_START);
324		*index = (off + base) / 4;
325		return (0);
326	}
327
328	return (EIO);
329}
330
331/*
332 * Give virtual cpu the complete access to MSR(read & write).
333 */
334static int
335svm_msr_perm(uint8_t *perm_bitmap, uint64_t msr, bool read, bool write)
336{
337	int index, bit, err;
338
339	err = svm_msr_index(msr, &index, &bit);
340	if (err) {
341		ERR("MSR 0x%lx is not writeable by guest.\n", msr);
342		return (err);
343	}
344
345	if (index < 0 || index > (SVM_MSR_BITMAP_SIZE)) {
346		ERR("MSR 0x%lx index out of range(%d).\n", msr, index);
347		return (EINVAL);
348	}
349	if (bit < 0 || bit > 8) {
350		ERR("MSR 0x%lx bit out of range(%d).\n", msr, bit);
351		return (EINVAL);
352	}
353
354	/* Disable intercept for read and write. */
355	if (read)
356		perm_bitmap[index] &= ~(1UL << bit);
357	if (write)
358		perm_bitmap[index] &= ~(2UL << bit);
359	CTR2(KTR_VMM, "Guest has control:0x%x on SVM:MSR(0x%lx).\n",
360		(perm_bitmap[index] >> bit) & 0x3, msr);
361
362	return (0);
363}
364
365static int
366svm_msr_rw_ok(uint8_t *perm_bitmap, uint64_t msr)
367{
368	return svm_msr_perm(perm_bitmap, msr, true, true);
369}
370
371static int
372svm_msr_rd_ok(uint8_t *perm_bitmap, uint64_t msr)
373{
374	return svm_msr_perm(perm_bitmap, msr, true, false);
375}
376
377/*
378 * Initialise a virtual machine.
379 */
380static void *
381svm_vminit(struct vm *vm, pmap_t pmap)
382{
383	struct svm_softc *svm_sc;
384	struct svm_vcpu *vcpu;
385	vm_paddr_t msrpm_pa, iopm_pa, pml4_pa;
386	int i, error;
387
388	if (guest_asid >= max_asid) {
389		ERR("Host support max ASID:%d, can't create more guests.\n",
390			max_asid);
391		return (NULL);
392	}
393
394	svm_sc = (struct svm_softc *)malloc(sizeof (struct svm_softc),
395			M_SVM, M_WAITOK | M_ZERO);
396
397	svm_sc->vm = vm;
398	svm_sc->svm_feature = svm_feature;
399	svm_sc->vcpu_cnt = VM_MAXCPU;
400	svm_sc->nptp = (vm_offset_t)vtophys(pmap->pm_pml4);
401	/*
402	 * Each guest has its own unique ASID.
403	 * ASID(Address Space Identifier) is used by TLB entry.
404	 */
405	svm_sc->asid = guest_asid++;
406
407	/*
408	 * Intercept MSR access to all MSRs except GSBASE, FSBASE,... etc.
409	 */
410	 memset(svm_sc->msr_bitmap, 0xFF, sizeof(svm_sc->msr_bitmap));
411
412	/*
413	 * Following MSR can be completely controlled by virtual machines
414	 * since access to following are translated to access to VMCB.
415	 */
416	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_GSBASE);
417	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_FSBASE);
418	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_KGSBASE);
419
420	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_STAR);
421	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_LSTAR);
422	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_CSTAR);
423	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SF_MASK);
424	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_CS_MSR);
425	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_ESP_MSR);
426	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_SYSENTER_EIP_MSR);
427
428	/* For Nested Paging/RVI only. */
429	svm_msr_rw_ok(svm_sc->msr_bitmap, MSR_PAT);
430
431	svm_msr_rd_ok(svm_sc->msr_bitmap, MSR_TSC);
432
433	 /* Intercept access to all I/O ports. */
434	memset(svm_sc->iopm_bitmap, 0xFF, sizeof(svm_sc->iopm_bitmap));
435
436	/* Cache physical address for multiple vcpus. */
437	iopm_pa = vtophys(svm_sc->iopm_bitmap);
438	msrpm_pa = vtophys(svm_sc->msr_bitmap);
439	pml4_pa = svm_sc->nptp;
440
441	for (i = 0; i < svm_sc->vcpu_cnt; i++) {
442		vcpu = svm_get_vcpu(svm_sc, i);
443		vcpu->lastcpu = NOCPU;
444		vcpu->vmcb_pa = vtophys(&vcpu->vmcb);
445		error = svm_init_vmcb(&vcpu->vmcb, iopm_pa, msrpm_pa, pml4_pa,
446		    svm_sc->asid);
447		if (error)
448			goto cleanup;
449	}
450
451	return (svm_sc);
452
453cleanup:
454	free(svm_sc, M_SVM);
455	return (NULL);
456}
457
458static int
459svm_cpl(struct vmcb_state *state)
460{
461
462	/*
463	 * From APMv2:
464	 *   "Retrieve the CPL from the CPL field in the VMCB, not
465	 *    from any segment DPL"
466	 */
467	return (state->cpl);
468}
469
470static enum vm_cpu_mode
471svm_vcpu_mode(struct vmcb *vmcb)
472{
473	struct vmcb_segment *seg;
474	struct vmcb_state *state;
475
476	state = &vmcb->state;
477
478	if (state->efer & EFER_LMA) {
479		seg = vmcb_seg(vmcb, VM_REG_GUEST_CS);
480		/*
481		 * Section 4.8.1 for APM2, check if Code Segment has
482		 * Long attribute set in descriptor.
483		 */
484		if (seg->attrib & VMCB_CS_ATTRIB_L)
485			return (CPU_MODE_64BIT);
486		else
487			return (CPU_MODE_COMPATIBILITY);
488	} else  if (state->cr0 & CR0_PE) {
489		return (CPU_MODE_PROTECTED);
490	} else {
491		return (CPU_MODE_REAL);
492	}
493}
494
495static enum vm_paging_mode
496svm_paging_mode(uint64_t cr0, uint64_t cr4, uint64_t efer)
497{
498
499	if ((cr0 & CR0_PG) == 0)
500		return (PAGING_MODE_FLAT);
501	if ((cr4 & CR4_PAE) == 0)
502		return (PAGING_MODE_32);
503	if (efer & EFER_LME)
504		return (PAGING_MODE_64);
505	else
506		return (PAGING_MODE_PAE);
507}
508
509/*
510 * ins/outs utility routines
511 */
512static uint64_t
513svm_inout_str_index(struct svm_regctx *regs, int in)
514{
515	uint64_t val;
516
517	val = in ? regs->e.g.sctx_rdi : regs->e.g.sctx_rsi;
518
519	return (val);
520}
521
522static uint64_t
523svm_inout_str_count(struct svm_regctx *regs, int rep)
524{
525	uint64_t val;
526
527	val = rep ? regs->sctx_rcx : 1;
528
529	return (val);
530}
531
532static void
533svm_inout_str_seginfo(struct svm_softc *svm_sc, int vcpu, int64_t info1,
534    int in, struct vm_inout_str *vis)
535{
536	int error, s;
537
538	if (in) {
539		vis->seg_name = VM_REG_GUEST_ES;
540	} else {
541		/* The segment field has standard encoding */
542		s = (info1 >> 10) & 0x7;
543		vis->seg_name = vm_segment_name(s);
544	}
545
546	error = svm_getdesc(svm_sc, vcpu, vis->seg_name, &vis->seg_desc);
547	KASSERT(error == 0, ("%s: svm_getdesc error %d", __func__, error));
548}
549
550static int
551svm_inout_str_addrsize(uint64_t info1)
552{
553        uint32_t size;
554
555        size = (info1 >> 7) & 0x7;
556        switch (size) {
557        case 1:
558                return (2);     /* 16 bit */
559        case 2:
560                return (4);     /* 32 bit */
561        case 4:
562                return (8);     /* 64 bit */
563        default:
564                panic("%s: invalid size encoding %d", __func__, size);
565        }
566}
567
568static void
569svm_paging_info(struct vmcb *vmcb, struct vm_guest_paging *paging)
570{
571	struct vmcb_state *state;
572
573	state = &vmcb->state;
574	paging->cr3 = state->cr3;
575	paging->cpl = svm_cpl(state);
576	paging->cpu_mode = svm_vcpu_mode(vmcb);
577	paging->paging_mode = svm_paging_mode(state->cr0, state->cr4,
578	    state->efer);
579}
580
581
582/*
583 * Handle guest I/O intercept.
584 */
585static bool
586svm_handle_io(struct svm_softc *svm_sc, int vcpu, struct vm_exit *vmexit)
587{
588	struct vmcb_ctrl *ctrl;
589	struct vmcb_state *state;
590	struct svm_regctx *regs;
591	struct vm_inout_str *vis;
592	uint64_t info1;
593
594	state = svm_get_vmcb_state(svm_sc, vcpu);
595	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
596	regs  = svm_get_guest_regctx(svm_sc, vcpu);
597	info1 = ctrl->exitinfo1;
598
599	vmexit->exitcode 	= VM_EXITCODE_INOUT;
600	vmexit->u.inout.in 	= (info1 & BIT(0)) ? 1 : 0;
601	vmexit->u.inout.string 	= (info1 & BIT(2)) ? 1 : 0;
602	vmexit->u.inout.rep 	= (info1 & BIT(3)) ? 1 : 0;
603	vmexit->u.inout.bytes 	= (info1 >> 4) & 0x7;
604	vmexit->u.inout.port 	= (uint16_t)(info1 >> 16);
605	vmexit->u.inout.eax 	= (uint32_t)(state->rax);
606
607	if (vmexit->u.inout.string) {
608		vmexit->exitcode = VM_EXITCODE_INOUT_STR;
609		vis = &vmexit->u.inout_str;
610		svm_paging_info(svm_get_vmcb(svm_sc, vcpu), &vis->paging);
611		vis->rflags = state->rflags;
612		vis->cr0 = state->cr0;
613		vis->index = svm_inout_str_index(regs, vmexit->u.inout.in);
614		vis->count = svm_inout_str_count(regs, vmexit->u.inout.rep);
615		vis->addrsize = svm_inout_str_addrsize(info1);
616		svm_inout_str_seginfo(svm_sc, vcpu, info1,
617		    vmexit->u.inout.in, vis);
618	}
619
620	return (false);
621}
622
623static int
624svm_npf_paging(uint64_t exitinfo1)
625{
626
627	if (exitinfo1 & VMCB_NPF_INFO1_W)
628		return (VM_PROT_WRITE);
629
630	return (VM_PROT_READ);
631}
632
633static bool
634svm_npf_emul_fault(uint64_t exitinfo1)
635{
636
637	if (exitinfo1 & VMCB_NPF_INFO1_ID) {
638		return (false);
639	}
640
641	if (exitinfo1 & VMCB_NPF_INFO1_GPT) {
642		return (false);
643	}
644
645	if ((exitinfo1 & VMCB_NPF_INFO1_GPA) == 0) {
646		return (false);
647	}
648
649	return (true);
650}
651
652static void
653svm_handle_inst_emul(struct vmcb *vmcb, uint64_t gpa, struct vm_exit *vmexit)
654{
655	struct vm_guest_paging *paging;
656	struct vmcb_segment *seg;
657
658	paging = &vmexit->u.inst_emul.paging;
659	vmexit->exitcode = VM_EXITCODE_INST_EMUL;
660	vmexit->u.inst_emul.gpa = gpa;
661	vmexit->u.inst_emul.gla = VIE_INVALID_GLA;
662	svm_paging_info(vmcb, paging);
663
664	/*
665	 * If DecodeAssist SVM feature doesn't exist, we don't have NPF
666	 * instuction length. RIP will be calculated based on the length
667	 * determined by instruction emulation.
668	 */
669	vmexit->inst_length = VIE_INST_SIZE;
670
671	seg = vmcb_seg(vmcb, VM_REG_GUEST_CS);
672	switch(paging->cpu_mode) {
673	case CPU_MODE_PROTECTED:
674	case CPU_MODE_COMPATIBILITY:
675		/*
676		 * Section 4.8.1 of APM2, Default Operand Size or D bit.
677		 */
678		vmexit->u.inst_emul.cs_d = (seg->attrib & VMCB_CS_ATTRIB_D) ?
679		    1 : 0;
680		break;
681	default:
682		vmexit->u.inst_emul.cs_d = 0;
683		break;
684	}
685}
686
687/*
688 * Special handling of EFER MSR.
689 * SVM guest must have SVM EFER bit set, prohibit guest from cleareing SVM
690 * enable bit in EFER.
691 */
692static void
693svm_efer(struct svm_softc *svm_sc, int vcpu, boolean_t write)
694{
695	struct svm_regctx *swctx;
696	struct vmcb_state *state;
697
698	state = svm_get_vmcb_state(svm_sc, vcpu);
699	swctx = svm_get_guest_regctx(svm_sc, vcpu);
700
701	if (write) {
702		state->efer = ((swctx->e.g.sctx_rdx & (uint32_t)~0) << 32) |
703				((uint32_t)state->rax) | EFER_SVM;
704	} else {
705		state->rax = (uint32_t)state->efer;
706		swctx->e.g.sctx_rdx = (uint32_t)(state->efer >> 32);
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				VCPU_CTR0(svm_sc->vm, vcpu,"VMEXIT EFER\n");
782				svm_efer(svm_sc, vcpu, info1);
783				break;
784			}
785
786			retu = false;
787			if (info1) {
788				/* VM exited because of write MSR */
789				vmm_stat_incr(svm_sc->vm, vcpu,
790					VMEXIT_WRMSR, 1);
791				vmexit->exitcode = VM_EXITCODE_WRMSR;
792				vmexit->u.msr.code = ecx;
793				val = (uint64_t)edx << 32 | eax;
794				if (emulate_wrmsr(svm_sc->vm, vcpu, ecx, val,
795					&retu)) {
796					vmexit->u.msr.wval = val;
797					loop = false;
798				} else
799					loop = retu ? false : true;
800
801				VCPU_CTR3(svm_sc->vm, vcpu,
802					"VMEXIT WRMSR(%s handling) 0x%lx @0x%x",
803					loop ? "kernel" : "user", val, ecx);
804			} else {
805				vmm_stat_incr(svm_sc->vm, vcpu,
806					VMEXIT_RDMSR, 1);
807				vmexit->exitcode = VM_EXITCODE_RDMSR;
808				vmexit->u.msr.code = ecx;
809				if (emulate_rdmsr(svm_sc->vm, vcpu, ecx,
810					&retu)) {
811					loop = false;
812				} else
813					loop = retu ? false : true;
814				VCPU_CTR3(svm_sc->vm, vcpu, "SVM:VMEXIT RDMSR"
815					" MSB=0x%08x, LSB=%08x @0x%x",
816					ctx->e.g.sctx_rdx, state->rax, ecx);
817			}
818
819#define MSR_AMDK8_IPM           0xc0010055
820			/*
821			 * We can't hide AMD C1E idle capability since its
822			 * based on CPU generation, for now ignore access to
823			 * this MSR by vcpus
824			 * XXX: special handling of AMD C1E - Ignore.
825			 */
826			 if (ecx == MSR_AMDK8_IPM)
827				loop = true;
828			break;
829
830		case VMCB_EXIT_INTR:
831			/*
832			 * Exit on External Interrupt.
833			 * Give host interrupt handler to run and if its guest
834			 * interrupt, local APIC will inject event in guest.
835			 */
836			update_rip = false;
837			VCPU_CTR1(svm_sc->vm, vcpu, "SVM:VMEXIT ExtInt"
838				" RIP:0x%lx.\n", state->rip);
839			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_EXTINT, 1);
840			break;
841
842		case VMCB_EXIT_IO:
843			loop = svm_handle_io(svm_sc, vcpu, vmexit);
844			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_INOUT, 1);
845			break;
846
847		case VMCB_EXIT_CPUID:
848			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_CPUID, 1);
849			(void)x86_emulate_cpuid(svm_sc->vm, vcpu,
850					(uint32_t *)&state->rax,
851					(uint32_t *)&ctx->sctx_rbx,
852					(uint32_t *)&ctx->sctx_rcx,
853					(uint32_t *)&ctx->e.g.sctx_rdx);
854			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:VMEXIT CPUID\n");
855			break;
856
857		case VMCB_EXIT_HLT:
858			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_HLT, 1);
859 			if (ctrl->v_irq) {
860				 /* Interrupt is pending, can't halt guest. */
861				vmm_stat_incr(svm_sc->vm, vcpu,
862					VMEXIT_HLT_IGNORED, 1);
863				VCPU_CTR0(svm_sc->vm, vcpu,
864					"VMEXIT halt ignored.");
865			} else {
866				VCPU_CTR0(svm_sc->vm, vcpu,
867					"VMEXIT halted CPU.");
868				vmexit->exitcode = VM_EXITCODE_HLT;
869				vmexit->u.hlt.rflags = state->rflags;
870				loop = false;
871
872			}
873			break;
874
875		case VMCB_EXIT_PAUSE:
876			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:VMEXIT pause");
877			vmexit->exitcode = VM_EXITCODE_PAUSE;
878			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_PAUSE, 1);
879
880			break;
881
882		case VMCB_EXIT_NPF:
883			loop = false;
884			update_rip = false;
885
886        		if (info1 & VMCB_NPF_INFO1_RSV) {
887 				VCPU_CTR2(svm_sc->vm, vcpu, "SVM_ERR:NPT"
888					" reserved bit is set,"
889					"INFO1:0x%lx INFO2:0x%lx .\n",
890					info1, info2);
891        			break;
892			}
893
894			 /* EXITINFO2 has the physical fault address (GPA). */
895			if(vm_mem_allocated(svm_sc->vm, info2)) {
896 				VCPU_CTR3(svm_sc->vm, vcpu, "SVM:NPF-paging,"
897					"RIP:0x%lx INFO1:0x%lx INFO2:0x%lx .\n",
898				 	state->rip, info1, info2);
899				vmexit->exitcode = VM_EXITCODE_PAGING;
900				vmexit->u.paging.gpa = info2;
901				vmexit->u.paging.fault_type =
902					svm_npf_paging(info1);
903				vmm_stat_incr(svm_sc->vm, vcpu,
904					VMEXIT_NESTED_FAULT, 1);
905			} else if (svm_npf_emul_fault(info1)) {
906 				VCPU_CTR3(svm_sc->vm, vcpu, "SVM:NPF inst_emul,"
907					"RIP:0x%lx INFO1:0x%lx INFO2:0x%lx .\n",
908					state->rip, info1, info2);
909				svm_handle_inst_emul(svm_get_vmcb(svm_sc, vcpu),
910					info2, vmexit);
911				vmm_stat_incr(svm_sc->vm, vcpu,
912					VMEXIT_INST_EMUL, 1);
913			}
914
915			break;
916
917		case VMCB_EXIT_SHUTDOWN:
918			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:VMEXIT shutdown.");
919			loop = false;
920			break;
921
922		case VMCB_EXIT_INVALID:
923			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:VMEXIT INVALID.");
924			loop = false;
925			break;
926
927		default:
928			 /* Return to user space. */
929			loop = false;
930			update_rip = false;
931			VCPU_CTR3(svm_sc->vm, vcpu, "VMEXIT=0x%lx"
932				" EXITINFO1: 0x%lx EXITINFO2:0x%lx\n",
933		 		ctrl->exitcode, info1, info2);
934			VCPU_CTR3(svm_sc->vm, vcpu, "SVM:RIP: 0x%lx nRIP:0x%lx"
935				" Inst decoder len:%d\n", state->rip,
936				ctrl->nrip, ctrl->inst_decode_size);
937			vmm_stat_incr(svm_sc->vm, vcpu, VMEXIT_UNKNOWN, 1);
938			break;
939	}
940
941	vmexit->rip = state->rip;
942	if (update_rip) {
943		if (ctrl->nrip == 0) {
944 			VCPU_CTR1(svm_sc->vm, vcpu, "SVM_ERR:nRIP is not set "
945				 "for RIP0x%lx.\n", state->rip);
946			vmexit->exitcode = VM_EXITCODE_VMX;
947		} else
948			vmexit->rip = ctrl->nrip;
949	}
950
951	/* If vcpu execution is continued, update RIP. */
952	if (loop) {
953		state->rip = vmexit->rip;
954	}
955
956	if (state->rip == 0) {
957		VCPU_CTR0(svm_sc->vm, vcpu, "SVM_ERR:RIP is NULL\n");
958		vmexit->exitcode = VM_EXITCODE_VMX;
959	}
960
961	return (loop);
962}
963
964/*
965 * Inject NMI to virtual cpu.
966 */
967static int
968svm_inject_nmi(struct svm_softc *svm_sc, int vcpu)
969{
970	struct vmcb_ctrl *ctrl;
971
972	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
973
974	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
975	 /* Can't inject another NMI if last one is pending.*/
976	if (!vm_nmi_pending(svm_sc->vm, vcpu))
977		return (0);
978
979	/* Inject NMI, vector number is not used.*/
980	vmcb_eventinject(ctrl, VMCB_EVENTINJ_TYPE_NMI, IDT_NMI, 0, false);
981
982	/* Acknowledge the request is accepted.*/
983	vm_nmi_clear(svm_sc->vm, vcpu);
984
985	VCPU_CTR0(svm_sc->vm, vcpu, "SVM:Injected NMI.\n");
986
987	return (1);
988}
989
990static void
991svm_inj_intinfo(struct svm_softc *svm_sc, int vcpu)
992{
993	struct vmcb_ctrl *ctrl;
994	uint64_t intinfo;
995
996	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
997
998	if (!vm_entry_intinfo(svm_sc->vm, vcpu, &intinfo))
999		return;
1000
1001	KASSERT(VMCB_EXITINTINFO_VALID(intinfo), ("%s: entry intinfo is not "
1002	    "valid: %#lx", __func__, intinfo));
1003
1004	vmcb_eventinject(ctrl, VMCB_EXITINTINFO_TYPE(intinfo),
1005		VMCB_EXITINTINFO_VECTOR(intinfo),
1006		VMCB_EXITINTINFO_EC(intinfo),
1007		VMCB_EXITINTINFO_EC_VALID(intinfo));
1008	vmm_stat_incr(svm_sc->vm, vcpu, VCPU_INTINFO_INJECTED, 1);
1009	VCPU_CTR1(svm_sc->vm, vcpu, "Injected entry intinfo: %#lx", intinfo);
1010}
1011
1012/*
1013 * Inject event to virtual cpu.
1014 */
1015static void
1016svm_inj_interrupts(struct svm_softc *svm_sc, int vcpu, struct vlapic *vlapic)
1017{
1018	struct vmcb_ctrl *ctrl;
1019	struct vmcb_state *state;
1020	int extint_pending;
1021	int vector;
1022
1023	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1024
1025	state = svm_get_vmcb_state(svm_sc, vcpu);
1026	ctrl  = svm_get_vmcb_ctrl(svm_sc, vcpu);
1027
1028	svm_inj_intinfo(svm_sc, vcpu);
1029
1030	/* Can't inject multiple events at once. */
1031	if (ctrl->eventinj & VMCB_EVENTINJ_VALID) {
1032		VCPU_CTR1(svm_sc->vm, vcpu,
1033			"SVM:Last event(0x%lx) is pending.\n", ctrl->eventinj);
1034		return ;
1035	}
1036
1037	/* Wait for guest to come out of interrupt shadow. */
1038	if (ctrl->intr_shadow) {
1039		VCPU_CTR0(svm_sc->vm, vcpu, "SVM:Guest in interrupt shadow.\n");
1040		return;
1041	}
1042
1043	/* NMI event has priority over interrupts.*/
1044	if (svm_inject_nmi(svm_sc, vcpu)) {
1045		return;
1046	}
1047
1048	extint_pending = vm_extint_pending(svm_sc->vm, vcpu);
1049
1050	if (!extint_pending) {
1051		/* Ask the local apic for a vector to inject */
1052		if (!vlapic_pending_intr(vlapic, &vector))
1053			return;
1054	} else {
1055                /* Ask the legacy pic for a vector to inject */
1056                vatpic_pending_intr(svm_sc->vm, &vector);
1057	}
1058
1059	if (vector < 32 || vector > 255) {
1060		VCPU_CTR1(svm_sc->vm, vcpu, "SVM_ERR:Event injection"
1061			"invalid vector=%d.\n", vector);
1062		ERR("SVM_ERR:Event injection invalid vector=%d.\n", vector);
1063		return;
1064	}
1065
1066	if ((state->rflags & PSL_I) == 0) {
1067		VCPU_CTR0(svm_sc->vm, vcpu, "SVM:Interrupt is disabled\n");
1068		return;
1069	}
1070
1071	vmcb_eventinject(ctrl, VMCB_EVENTINJ_TYPE_INTR, vector, 0, false);
1072
1073        if (!extint_pending) {
1074                /* Update the Local APIC ISR */
1075                vlapic_intr_accepted(vlapic, vector);
1076        } else {
1077                vm_extint_clear(svm_sc->vm, vcpu);
1078                vatpic_intr_accepted(svm_sc->vm, vector);
1079
1080                /*
1081		 * XXX need to recheck exting_pending ala VT-x
1082		 */
1083        }
1084
1085	VCPU_CTR1(svm_sc->vm, vcpu, "SVM:event injected,vector=%d.\n", vector);
1086}
1087
1088static void
1089restore_host_tss(void)
1090{
1091	struct system_segment_descriptor *tss_sd;
1092
1093	/*
1094	 * The TSS descriptor was in use prior to launching the guest so it
1095	 * has been marked busy.
1096	 *
1097	 * 'ltr' requires the descriptor to be marked available so change the
1098	 * type to "64-bit available TSS".
1099	 */
1100	tss_sd = PCPU_GET(tss);
1101	tss_sd->sd_type = SDT_SYSTSS;
1102	ltr(GSEL(GPROC0_SEL, SEL_KPL));
1103}
1104
1105/*
1106 * Start vcpu with specified RIP.
1107 */
1108static int
1109svm_vmrun(void *arg, int vcpu, register_t rip, pmap_t pmap,
1110	void *rend_cookie, void *suspended_cookie)
1111{
1112	struct svm_regctx *hctx, *gctx;
1113	struct svm_softc *svm_sc;
1114	struct svm_vcpu *vcpustate;
1115	struct vmcb_state *state;
1116	struct vmcb_ctrl *ctrl;
1117	struct vm_exit *vmexit;
1118	struct vlapic *vlapic;
1119	struct vm *vm;
1120	uint64_t vmcb_pa;
1121	bool loop;	/* Continue vcpu execution loop. */
1122
1123	loop = true;
1124	svm_sc = arg;
1125	vm = svm_sc->vm;
1126
1127	vcpustate = svm_get_vcpu(svm_sc, vcpu);
1128	state = svm_get_vmcb_state(svm_sc, vcpu);
1129	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1130	vmexit = vm_exitinfo(vm, vcpu);
1131	vlapic = vm_lapic(vm, vcpu);
1132
1133	gctx = svm_get_guest_regctx(svm_sc, vcpu);
1134	hctx = &host_ctx[curcpu];
1135	vmcb_pa = svm_sc->vcpu[vcpu].vmcb_pa;
1136
1137	if (vcpustate->lastcpu != curcpu) {
1138		/* Virtual CPU is running on a diiferent CPU now.*/
1139		vmm_stat_incr(vm, vcpu, VCPU_MIGRATIONS, 1);
1140
1141		/*
1142		 * Flush all TLB mappings for this guest on this CPU,
1143		 * it might have stale entries since vcpu has migrated
1144		 * or vmm is restarted.
1145		 */
1146		ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1147
1148		/* Can't use any cached VMCB state by cpu.*/
1149		ctrl->vmcb_clean = VMCB_CACHE_NONE;
1150	} else {
1151		/*
1152		 * XXX: Using same ASID for all vcpus of a VM will cause TLB
1153		 * corruption. This can easily be produced by muxing two vcpus
1154		 * on same core.
1155		 * For now, flush guest TLB for every vmrun.
1156		 */
1157		ctrl->tlb_ctrl = VMCB_TLB_FLUSH_GUEST;
1158
1159		/*
1160		 * This is the same cpu on which vcpu last ran so don't
1161		 * need to reload all VMCB state.
1162		 * ASID is unique for a guest.
1163		 * IOPM is unchanged.
1164		 * RVI/EPT is unchanged.
1165		 *
1166		 */
1167		ctrl->vmcb_clean = VMCB_CACHE_ASID |
1168				VMCB_CACHE_IOPM |
1169				VMCB_CACHE_NP;
1170	}
1171
1172	vcpustate->lastcpu = curcpu;
1173	VCPU_CTR3(vm, vcpu, "SVM:Enter vmrun RIP:0x%lx"
1174		" inst len=%d/%d\n",
1175		rip, vmexit->inst_length,
1176		vmexit->u.inst_emul.vie.num_valid);
1177	/* Update Guest RIP */
1178	state->rip = rip;
1179
1180	do {
1181		vmexit->inst_length = 0;
1182
1183		/*
1184		 * Disable global interrupts to guarantee atomicity during
1185		 * loading of guest state. This includes not only the state
1186		 * loaded by the "vmrun" instruction but also software state
1187		 * maintained by the hypervisor: suspended and rendezvous
1188		 * state, NPT generation number, vlapic interrupts etc.
1189		 */
1190		disable_gintr();
1191
1192		if (vcpu_suspended(suspended_cookie)) {
1193			enable_gintr();
1194			vm_exit_suspended(vm, vcpu, state->rip);
1195			break;
1196		}
1197
1198		if (vcpu_rendezvous_pending(rend_cookie)) {
1199			enable_gintr();
1200			vmexit->exitcode = VM_EXITCODE_RENDEZVOUS;
1201			vmm_stat_incr(vm, vcpu, VMEXIT_RENDEZVOUS, 1);
1202			VCPU_CTR1(vm, vcpu,
1203				"SVM: VCPU rendezvous, RIP:0x%lx\n",
1204				state->rip);
1205			vmexit->rip = state->rip;
1206			break;
1207		}
1208
1209		/* We are asked to give the cpu by scheduler. */
1210		if (curthread->td_flags & (TDF_ASTPENDING | TDF_NEEDRESCHED)) {
1211			enable_gintr();
1212			vmexit->exitcode = VM_EXITCODE_BOGUS;
1213			vmm_stat_incr(vm, vcpu, VMEXIT_ASTPENDING, 1);
1214			VCPU_CTR1(vm, vcpu,
1215				"SVM: ASTPENDING, RIP:0x%lx\n", state->rip);
1216			vmexit->rip = state->rip;
1217			break;
1218		}
1219
1220		svm_inj_interrupts(svm_sc, vcpu, vlapic);
1221
1222		/* Launch Virtual Machine. */
1223		svm_launch(vmcb_pa, gctx, hctx);
1224
1225		/*
1226		 * Restore MSR_GSBASE to point to the pcpu data area.
1227		 *
1228		 * Note that accesses done via PCPU_GET/PCPU_SET will work
1229		 * only after MSR_GSBASE is restored.
1230		 *
1231		 * Also note that we don't bother restoring MSR_KGSBASE
1232		 * since it is not used in the kernel and will be restored
1233		 * when the VMRUN ioctl returns to userspace.
1234		 */
1235		wrmsr(MSR_GSBASE, (uint64_t)&__pcpu[vcpustate->lastcpu]);
1236
1237		/*
1238		 * The host GDTR and IDTR is saved by VMRUN and restored
1239		 * automatically on #VMEXIT. However, the host TSS needs
1240		 * to be restored explicitly.
1241		 */
1242		restore_host_tss();
1243
1244		/* #VMEXIT disables interrupts so re-enable them here. */
1245		enable_gintr();
1246
1247		/* Handle #VMEXIT and if required return to user space. */
1248		loop = svm_vmexit(svm_sc, vcpu, vmexit);
1249		vcpustate->loop++;
1250		vmm_stat_incr(vm, vcpu, VMEXIT_COUNT, 1);
1251	} while (loop);
1252
1253	return (0);
1254}
1255
1256/*
1257 * Cleanup for virtual machine.
1258 */
1259static void
1260svm_vmcleanup(void *arg)
1261{
1262	struct svm_softc *svm_sc;
1263
1264	svm_sc = arg;
1265
1266	VCPU_CTR0(svm_sc->vm, 0, "SVM:cleanup\n");
1267
1268	free(svm_sc, M_SVM);
1269}
1270
1271/*
1272 * Return pointer to hypervisor saved register state.
1273 */
1274static register_t *
1275swctx_regptr(struct svm_regctx *regctx, int reg)
1276{
1277
1278	switch (reg) {
1279		case VM_REG_GUEST_RBX:
1280			return (&regctx->sctx_rbx);
1281		case VM_REG_GUEST_RCX:
1282			return (&regctx->sctx_rcx);
1283		case VM_REG_GUEST_RDX:
1284			return (&regctx->e.g.sctx_rdx);
1285		case VM_REG_GUEST_RDI:
1286			return (&regctx->e.g.sctx_rdi);
1287		case VM_REG_GUEST_RSI:
1288			return (&regctx->e.g.sctx_rsi);
1289		case VM_REG_GUEST_RBP:
1290			return (&regctx->sctx_rbp);
1291		case VM_REG_GUEST_R8:
1292			return (&regctx->sctx_r8);
1293		case VM_REG_GUEST_R9:
1294			return (&regctx->sctx_r9);
1295		case VM_REG_GUEST_R10:
1296			return (&regctx->sctx_r10);
1297		case VM_REG_GUEST_R11:
1298			return (&regctx->sctx_r11);
1299		case VM_REG_GUEST_R12:
1300			return (&regctx->sctx_r12);
1301		case VM_REG_GUEST_R13:
1302			return (&regctx->sctx_r13);
1303		case VM_REG_GUEST_R14:
1304			return (&regctx->sctx_r14);
1305		case VM_REG_GUEST_R15:
1306			return (&regctx->sctx_r15);
1307		default:
1308			ERR("Unknown register requested, reg=%d.\n", reg);
1309			break;
1310	}
1311
1312	return (NULL);
1313}
1314
1315/*
1316 * Interface to read guest registers.
1317 * This can be SVM h/w saved or hypervisor saved register.
1318 */
1319static int
1320svm_getreg(void *arg, int vcpu, int ident, uint64_t *val)
1321{
1322	struct svm_softc *svm_sc;
1323	struct vmcb *vmcb;
1324	register_t *reg;
1325
1326	svm_sc = arg;
1327	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1328
1329	vmcb = svm_get_vmcb(svm_sc, vcpu);
1330
1331	if (vmcb_read(vmcb, ident, val) == 0) {
1332		return (0);
1333	}
1334
1335	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
1336
1337	if (reg != NULL) {
1338		*val = *reg;
1339		return (0);
1340	}
1341
1342 	ERR("SVM_ERR:reg type %x is not saved in VMCB.\n", ident);
1343	return (EINVAL);
1344}
1345
1346/*
1347 * Interface to write to guest registers.
1348 * This can be SVM h/w saved or hypervisor saved register.
1349 */
1350static int
1351svm_setreg(void *arg, int vcpu, int ident, uint64_t val)
1352{
1353	struct svm_softc *svm_sc;
1354	struct vmcb *vmcb;
1355	register_t *reg;
1356
1357	svm_sc = arg;
1358	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1359
1360	vmcb = svm_get_vmcb(svm_sc, vcpu);
1361	if (vmcb_write(vmcb, ident, val) == 0) {
1362		return (0);
1363	}
1364
1365	reg = swctx_regptr(svm_get_guest_regctx(svm_sc, vcpu), ident);
1366
1367	if (reg != NULL) {
1368		*reg = val;
1369		return (0);
1370	}
1371
1372 	ERR("SVM_ERR:reg type %x is not saved in VMCB.\n", ident);
1373	return (EINVAL);
1374}
1375
1376
1377/*
1378 * Inteface to set various descriptors.
1379 */
1380static int
1381svm_setdesc(void *arg, int vcpu, int type, struct seg_desc *desc)
1382{
1383	struct svm_softc *svm_sc;
1384	struct vmcb *vmcb;
1385	struct vmcb_segment *seg;
1386	uint16_t attrib;
1387
1388	svm_sc = arg;
1389	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1390
1391	vmcb = svm_get_vmcb(svm_sc, vcpu);
1392
1393	VCPU_CTR1(svm_sc->vm, vcpu, "SVM:set_desc: Type%d\n", type);
1394
1395	seg = vmcb_seg(vmcb, type);
1396	if (seg == NULL) {
1397		ERR("SVM_ERR:Unsupported segment type%d\n", type);
1398		return (EINVAL);
1399	}
1400
1401	/* Map seg_desc access to VMCB attribute format.*/
1402	attrib = ((desc->access & 0xF000) >> 4) | (desc->access & 0xFF);
1403	VCPU_CTR3(svm_sc->vm, vcpu, "SVM:[sel %d attribute 0x%x limit:0x%x]\n",
1404		type, desc->access, desc->limit);
1405	seg->attrib = attrib;
1406	seg->base = desc->base;
1407	seg->limit = desc->limit;
1408
1409	return (0);
1410}
1411
1412/*
1413 * Interface to get guest descriptor.
1414 */
1415static int
1416svm_getdesc(void *arg, int vcpu, int type, struct seg_desc *desc)
1417{
1418	struct svm_softc *svm_sc;
1419	struct vmcb_segment	*seg;
1420
1421	svm_sc = arg;
1422	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1423
1424	VCPU_CTR1(svm_sc->vm, vcpu, "SVM:get_desc: Type%d\n", type);
1425
1426	seg = vmcb_seg(svm_get_vmcb(svm_sc, vcpu), type);
1427	if (!seg) {
1428		ERR("SVM_ERR:Unsupported segment type%d\n", type);
1429		return (EINVAL);
1430	}
1431
1432	/* Map seg_desc access to VMCB attribute format.*/
1433	desc->access = ((seg->attrib & 0xF00) << 4) | (seg->attrib & 0xFF);
1434	desc->base = seg->base;
1435	desc->limit = seg->limit;
1436
1437	/*
1438	 * VT-x uses bit 16 (Unusable) to indicate a segment that has been
1439	 * loaded with a NULL segment selector. The 'desc->access' field is
1440	 * interpreted in the VT-x format by the processor-independent code.
1441	 *
1442	 * SVM uses the 'P' bit to convey the same information so convert it
1443	 * into the VT-x format. For more details refer to section
1444	 * "Segment State in the VMCB" in APMv2.
1445	 */
1446	if (type == VM_REG_GUEST_CS && type == VM_REG_GUEST_TR)
1447		desc->access |= 0x80;		/* CS and TS always present */
1448
1449	if (!(desc->access & 0x80))
1450		desc->access |= 0x10000;	/* Unusable segment */
1451
1452	return (0);
1453}
1454
1455static int
1456svm_setcap(void *arg, int vcpu, int type, int val)
1457{
1458	struct svm_softc *svm_sc;
1459	struct vmcb_ctrl *ctrl;
1460	int ret = ENOENT;
1461
1462	svm_sc = arg;
1463	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1464
1465	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1466
1467	switch (type) {
1468		case VM_CAP_HALT_EXIT:
1469			if (val)
1470				ctrl->ctrl1 |= VMCB_INTCPT_HLT;
1471			else
1472				ctrl->ctrl1 &= ~VMCB_INTCPT_HLT;
1473			ret = 0;
1474			VCPU_CTR1(svm_sc->vm, vcpu, "SVM:Set_gap:Halt exit %s.\n",
1475				val ? "enabled": "disabled");
1476			break;
1477
1478		case VM_CAP_PAUSE_EXIT:
1479			if (val)
1480				ctrl->ctrl1 |= VMCB_INTCPT_PAUSE;
1481			else
1482				ctrl->ctrl1 &= ~VMCB_INTCPT_PAUSE;
1483			ret = 0;
1484			VCPU_CTR1(svm_sc->vm, vcpu, "SVM:Set_gap:Pause exit %s.\n",
1485				val ? "enabled": "disabled");
1486			break;
1487
1488		case VM_CAP_MTRAP_EXIT:
1489			if (val)
1490				ctrl->exception |= BIT(IDT_MC);
1491			else
1492				ctrl->exception &= ~BIT(IDT_MC);
1493			ret = 0;
1494			VCPU_CTR1(svm_sc->vm, vcpu, "SVM:Set_gap:MC exit %s.\n",
1495				val ? "enabled": "disabled");
1496			break;
1497
1498		case VM_CAP_UNRESTRICTED_GUEST:
1499			/* SVM doesn't need special capability for SMP.*/
1500			VCPU_CTR0(svm_sc->vm, vcpu, "SVM:Set_gap:Unrestricted "
1501			"always enabled.\n");
1502			ret = 0;
1503			break;
1504
1505		default:
1506			break;
1507		}
1508
1509	return (ret);
1510}
1511
1512static int
1513svm_getcap(void *arg, int vcpu, int type, int *retval)
1514{
1515	struct svm_softc *svm_sc;
1516	struct vmcb_ctrl *ctrl;
1517
1518	svm_sc = arg;
1519	KASSERT(vcpu < svm_sc->vcpu_cnt, ("Guest doesn't have VCPU%d", vcpu));
1520
1521	ctrl = svm_get_vmcb_ctrl(svm_sc, vcpu);
1522
1523	switch (type) {
1524		case VM_CAP_HALT_EXIT:
1525		*retval = (ctrl->ctrl1 & VMCB_INTCPT_HLT) ? 1 : 0;
1526		VCPU_CTR1(svm_sc->vm, vcpu, "SVM:get_cap:Halt exit %s.\n",
1527			*retval ? "enabled": "disabled");
1528		break;
1529
1530		case VM_CAP_PAUSE_EXIT:
1531		*retval = (ctrl->ctrl1 & VMCB_INTCPT_PAUSE) ? 1 : 0;
1532		VCPU_CTR1(svm_sc->vm, vcpu, "SVM:get_cap:Pause exit %s.\n",
1533			*retval ? "enabled": "disabled");
1534		break;
1535
1536		case VM_CAP_MTRAP_EXIT:
1537		*retval = (ctrl->exception & BIT(IDT_MC)) ? 1 : 0;
1538		VCPU_CTR1(svm_sc->vm, vcpu, "SVM:get_cap:MC exit %s.\n",
1539			*retval ? "enabled": "disabled");
1540		break;
1541
1542	case VM_CAP_UNRESTRICTED_GUEST:
1543		VCPU_CTR0(svm_sc->vm, vcpu, "SVM:get_cap:Unrestricted.\n");
1544		*retval = 1;
1545		break;
1546		default:
1547		break;
1548	}
1549
1550	return (0);
1551}
1552
1553static struct vlapic *
1554svm_vlapic_init(void *arg, int vcpuid)
1555{
1556	struct svm_softc *svm_sc;
1557	struct vlapic *vlapic;
1558
1559	svm_sc = arg;
1560	vlapic = malloc(sizeof(struct vlapic), M_SVM_VLAPIC, M_WAITOK | M_ZERO);
1561	vlapic->vm = svm_sc->vm;
1562	vlapic->vcpuid = vcpuid;
1563	vlapic->apic_page = (struct LAPIC *)&svm_sc->apic_page[vcpuid];
1564
1565	vlapic_init(vlapic);
1566
1567	return (vlapic);
1568}
1569
1570static void
1571svm_vlapic_cleanup(void *arg, struct vlapic *vlapic)
1572{
1573
1574        vlapic_cleanup(vlapic);
1575        free(vlapic, M_SVM_VLAPIC);
1576}
1577
1578struct vmm_ops vmm_ops_amd = {
1579	svm_init,
1580	svm_cleanup,
1581	svm_restore,
1582	svm_vminit,
1583	svm_vmrun,
1584	svm_vmcleanup,
1585	svm_getreg,
1586	svm_setreg,
1587	svm_getdesc,
1588	svm_setdesc,
1589	svm_getcap,
1590	svm_setcap,
1591	svm_npt_alloc,
1592	svm_npt_free,
1593	svm_vlapic_init,
1594	svm_vlapic_cleanup
1595};
1596