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