OSDN Git Service

KVM: x86: Refactor picdev_write() to prevent Spectre-v1/L1TF attacks
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / arch / x86 / kvm / svm.c
1 /*
2  * Kernel-based Virtual Machine driver for Linux
3  *
4  * AMD SVM support
5  *
6  * Copyright (C) 2006 Qumranet, Inc.
7  * Copyright 2010 Red Hat, Inc. and/or its affiliates.
8  *
9  * Authors:
10  *   Yaniv Kamay  <yaniv@qumranet.com>
11  *   Avi Kivity   <avi@qumranet.com>
12  *
13  * This work is licensed under the terms of the GNU GPL, version 2.  See
14  * the COPYING file in the top-level directory.
15  *
16  */
17 #include <linux/kvm_host.h>
18
19 #include "irq.h"
20 #include "mmu.h"
21 #include "kvm_cache_regs.h"
22 #include "x86.h"
23 #include "cpuid.h"
24 #include "pmu.h"
25
26 #include <linux/module.h>
27 #include <linux/mod_devicetable.h>
28 #include <linux/kernel.h>
29 #include <linux/vmalloc.h>
30 #include <linux/highmem.h>
31 #include <linux/sched.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34
35 #include <asm/perf_event.h>
36 #include <asm/tlbflush.h>
37 #include <asm/desc.h>
38 #include <asm/debugreg.h>
39 #include <asm/kvm_para.h>
40 #include <asm/microcode.h>
41 #include <asm/spec-ctrl.h>
42
43 #include <asm/virtext.h>
44 #include "trace.h"
45
46 #define __ex(x) __kvm_handle_fault_on_reboot(x)
47
48 MODULE_AUTHOR("Qumranet");
49 MODULE_LICENSE("GPL");
50
51 static const struct x86_cpu_id svm_cpu_id[] = {
52         X86_FEATURE_MATCH(X86_FEATURE_SVM),
53         {}
54 };
55 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
56
57 #define IOPM_ALLOC_ORDER 2
58 #define MSRPM_ALLOC_ORDER 1
59
60 #define SEG_TYPE_LDT 2
61 #define SEG_TYPE_BUSY_TSS16 3
62
63 #define SVM_FEATURE_NPT            (1 <<  0)
64 #define SVM_FEATURE_LBRV           (1 <<  1)
65 #define SVM_FEATURE_SVML           (1 <<  2)
66 #define SVM_FEATURE_NRIP           (1 <<  3)
67 #define SVM_FEATURE_TSC_RATE       (1 <<  4)
68 #define SVM_FEATURE_VMCB_CLEAN     (1 <<  5)
69 #define SVM_FEATURE_FLUSH_ASID     (1 <<  6)
70 #define SVM_FEATURE_DECODE_ASSIST  (1 <<  7)
71 #define SVM_FEATURE_PAUSE_FILTER   (1 << 10)
72
73 #define NESTED_EXIT_HOST        0       /* Exit handled on host level */
74 #define NESTED_EXIT_DONE        1       /* Exit caused nested vmexit  */
75 #define NESTED_EXIT_CONTINUE    2       /* Further checks needed      */
76
77 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
78
79 #define TSC_RATIO_RSVD          0xffffff0000000000ULL
80 #define TSC_RATIO_MIN           0x0000000000000001ULL
81 #define TSC_RATIO_MAX           0x000000ffffffffffULL
82
83 static bool erratum_383_found __read_mostly;
84
85 static const u32 host_save_user_msrs[] = {
86 #ifdef CONFIG_X86_64
87         MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
88         MSR_FS_BASE,
89 #endif
90         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
91 };
92
93 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
94
95 struct kvm_vcpu;
96
97 struct nested_state {
98         struct vmcb *hsave;
99         u64 hsave_msr;
100         u64 vm_cr_msr;
101         u64 vmcb;
102
103         /* These are the merged vectors */
104         u32 *msrpm;
105
106         /* gpa pointers to the real vectors */
107         u64 vmcb_msrpm;
108         u64 vmcb_iopm;
109
110         /* A VMEXIT is required but not yet emulated */
111         bool exit_required;
112
113         /* cache for intercepts of the guest */
114         u32 intercept_cr;
115         u32 intercept_dr;
116         u32 intercept_exceptions;
117         u64 intercept;
118
119         /* Nested Paging related state */
120         u64 nested_cr3;
121 };
122
123 #define MSRPM_OFFSETS   16
124 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
125
126 /*
127  * Set osvw_len to higher value when updated Revision Guides
128  * are published and we know what the new status bits are
129  */
130 static uint64_t osvw_len = 4, osvw_status;
131
132 struct vcpu_svm {
133         struct kvm_vcpu vcpu;
134         struct vmcb *vmcb;
135         unsigned long vmcb_pa;
136         struct svm_cpu_data *svm_data;
137         uint64_t asid_generation;
138         uint64_t sysenter_esp;
139         uint64_t sysenter_eip;
140
141         u64 next_rip;
142
143         u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
144         struct {
145                 u16 fs;
146                 u16 gs;
147                 u16 ldt;
148                 u64 gs_base;
149         } host;
150
151         u64 spec_ctrl;
152         /*
153          * Contains guest-controlled bits of VIRT_SPEC_CTRL, which will be
154          * translated into the appropriate L2_CFG bits on the host to
155          * perform speculative control.
156          */
157         u64 virt_spec_ctrl;
158
159         u32 *msrpm;
160
161         ulong nmi_iret_rip;
162
163         struct nested_state nested;
164
165         bool nmi_singlestep;
166
167         unsigned int3_injected;
168         unsigned long int3_rip;
169         u32 apf_reason;
170
171         /* cached guest cpuid flags for faster access */
172         bool nrips_enabled      : 1;
173 };
174
175 static DEFINE_PER_CPU(u64, current_tsc_ratio);
176 #define TSC_RATIO_DEFAULT       0x0100000000ULL
177
178 #define MSR_INVALID                     0xffffffffU
179
180 static const struct svm_direct_access_msrs {
181         u32 index;   /* Index of the MSR */
182         bool always; /* True if intercept is always on */
183 } direct_access_msrs[] = {
184         { .index = MSR_STAR,                            .always = true  },
185         { .index = MSR_IA32_SYSENTER_CS,                .always = true  },
186 #ifdef CONFIG_X86_64
187         { .index = MSR_GS_BASE,                         .always = true  },
188         { .index = MSR_FS_BASE,                         .always = true  },
189         { .index = MSR_KERNEL_GS_BASE,                  .always = true  },
190         { .index = MSR_LSTAR,                           .always = true  },
191         { .index = MSR_CSTAR,                           .always = true  },
192         { .index = MSR_SYSCALL_MASK,                    .always = true  },
193 #endif
194         { .index = MSR_IA32_SPEC_CTRL,                  .always = false },
195         { .index = MSR_IA32_PRED_CMD,                   .always = false },
196         { .index = MSR_IA32_LASTBRANCHFROMIP,           .always = false },
197         { .index = MSR_IA32_LASTBRANCHTOIP,             .always = false },
198         { .index = MSR_IA32_LASTINTFROMIP,              .always = false },
199         { .index = MSR_IA32_LASTINTTOIP,                .always = false },
200         { .index = MSR_INVALID,                         .always = false },
201 };
202
203 /* enable NPT for AMD64 and X86 with PAE */
204 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
205 static bool npt_enabled = true;
206 #else
207 static bool npt_enabled;
208 #endif
209
210 /* allow nested paging (virtualized MMU) for all guests */
211 static int npt = true;
212 module_param(npt, int, S_IRUGO);
213
214 /* allow nested virtualization in KVM/SVM */
215 static int nested = true;
216 module_param(nested, int, S_IRUGO);
217
218 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
219 static void svm_flush_tlb(struct kvm_vcpu *vcpu);
220 static void svm_complete_interrupts(struct vcpu_svm *svm);
221
222 static int nested_svm_exit_handled(struct vcpu_svm *svm);
223 static int nested_svm_intercept(struct vcpu_svm *svm);
224 static int nested_svm_vmexit(struct vcpu_svm *svm);
225 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
226                                       bool has_error_code, u32 error_code);
227
228 enum {
229         VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
230                             pause filter count */
231         VMCB_PERM_MAP,   /* IOPM Base and MSRPM Base */
232         VMCB_ASID,       /* ASID */
233         VMCB_INTR,       /* int_ctl, int_vector */
234         VMCB_NPT,        /* npt_en, nCR3, gPAT */
235         VMCB_CR,         /* CR0, CR3, CR4, EFER */
236         VMCB_DR,         /* DR6, DR7 */
237         VMCB_DT,         /* GDT, IDT */
238         VMCB_SEG,        /* CS, DS, SS, ES, CPL */
239         VMCB_CR2,        /* CR2 only */
240         VMCB_LBR,        /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
241         VMCB_DIRTY_MAX,
242 };
243
244 /* TPR and CR2 are always written before VMRUN */
245 #define VMCB_ALWAYS_DIRTY_MASK  ((1U << VMCB_INTR) | (1U << VMCB_CR2))
246
247 static inline void mark_all_dirty(struct vmcb *vmcb)
248 {
249         vmcb->control.clean = 0;
250 }
251
252 static inline void mark_all_clean(struct vmcb *vmcb)
253 {
254         vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
255                                & ~VMCB_ALWAYS_DIRTY_MASK;
256 }
257
258 static inline void mark_dirty(struct vmcb *vmcb, int bit)
259 {
260         vmcb->control.clean &= ~(1 << bit);
261 }
262
263 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
264 {
265         return container_of(vcpu, struct vcpu_svm, vcpu);
266 }
267
268 static void recalc_intercepts(struct vcpu_svm *svm)
269 {
270         struct vmcb_control_area *c, *h;
271         struct nested_state *g;
272
273         mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
274
275         if (!is_guest_mode(&svm->vcpu))
276                 return;
277
278         c = &svm->vmcb->control;
279         h = &svm->nested.hsave->control;
280         g = &svm->nested;
281
282         c->intercept_cr = h->intercept_cr | g->intercept_cr;
283         c->intercept_dr = h->intercept_dr | g->intercept_dr;
284         c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
285         c->intercept = h->intercept | g->intercept;
286 }
287
288 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
289 {
290         if (is_guest_mode(&svm->vcpu))
291                 return svm->nested.hsave;
292         else
293                 return svm->vmcb;
294 }
295
296 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
297 {
298         struct vmcb *vmcb = get_host_vmcb(svm);
299
300         vmcb->control.intercept_cr |= (1U << bit);
301
302         recalc_intercepts(svm);
303 }
304
305 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
306 {
307         struct vmcb *vmcb = get_host_vmcb(svm);
308
309         vmcb->control.intercept_cr &= ~(1U << bit);
310
311         recalc_intercepts(svm);
312 }
313
314 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
315 {
316         struct vmcb *vmcb = get_host_vmcb(svm);
317
318         return vmcb->control.intercept_cr & (1U << bit);
319 }
320
321 static inline void set_dr_intercepts(struct vcpu_svm *svm)
322 {
323         struct vmcb *vmcb = get_host_vmcb(svm);
324
325         vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
326                 | (1 << INTERCEPT_DR1_READ)
327                 | (1 << INTERCEPT_DR2_READ)
328                 | (1 << INTERCEPT_DR3_READ)
329                 | (1 << INTERCEPT_DR4_READ)
330                 | (1 << INTERCEPT_DR5_READ)
331                 | (1 << INTERCEPT_DR6_READ)
332                 | (1 << INTERCEPT_DR7_READ)
333                 | (1 << INTERCEPT_DR0_WRITE)
334                 | (1 << INTERCEPT_DR1_WRITE)
335                 | (1 << INTERCEPT_DR2_WRITE)
336                 | (1 << INTERCEPT_DR3_WRITE)
337                 | (1 << INTERCEPT_DR4_WRITE)
338                 | (1 << INTERCEPT_DR5_WRITE)
339                 | (1 << INTERCEPT_DR6_WRITE)
340                 | (1 << INTERCEPT_DR7_WRITE);
341
342         recalc_intercepts(svm);
343 }
344
345 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
346 {
347         struct vmcb *vmcb = get_host_vmcb(svm);
348
349         vmcb->control.intercept_dr = 0;
350
351         recalc_intercepts(svm);
352 }
353
354 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
355 {
356         struct vmcb *vmcb = get_host_vmcb(svm);
357
358         vmcb->control.intercept_exceptions |= (1U << bit);
359
360         recalc_intercepts(svm);
361 }
362
363 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
364 {
365         struct vmcb *vmcb = get_host_vmcb(svm);
366
367         vmcb->control.intercept_exceptions &= ~(1U << bit);
368
369         recalc_intercepts(svm);
370 }
371
372 static inline void set_intercept(struct vcpu_svm *svm, int bit)
373 {
374         struct vmcb *vmcb = get_host_vmcb(svm);
375
376         vmcb->control.intercept |= (1ULL << bit);
377
378         recalc_intercepts(svm);
379 }
380
381 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
382 {
383         struct vmcb *vmcb = get_host_vmcb(svm);
384
385         vmcb->control.intercept &= ~(1ULL << bit);
386
387         recalc_intercepts(svm);
388 }
389
390 static inline void enable_gif(struct vcpu_svm *svm)
391 {
392         svm->vcpu.arch.hflags |= HF_GIF_MASK;
393 }
394
395 static inline void disable_gif(struct vcpu_svm *svm)
396 {
397         svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
398 }
399
400 static inline bool gif_set(struct vcpu_svm *svm)
401 {
402         return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
403 }
404
405 static unsigned long iopm_base;
406
407 struct kvm_ldttss_desc {
408         u16 limit0;
409         u16 base0;
410         unsigned base1:8, type:5, dpl:2, p:1;
411         unsigned limit1:4, zero0:3, g:1, base2:8;
412         u32 base3;
413         u32 zero1;
414 } __attribute__((packed));
415
416 struct svm_cpu_data {
417         int cpu;
418
419         u64 asid_generation;
420         u32 max_asid;
421         u32 next_asid;
422         struct kvm_ldttss_desc *tss_desc;
423
424         struct page *save_area;
425         struct vmcb *current_vmcb;
426 };
427
428 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
429
430 struct svm_init_data {
431         int cpu;
432         int r;
433 };
434
435 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
436
437 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
438 #define MSRS_RANGE_SIZE 2048
439 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
440
441 static u32 svm_msrpm_offset(u32 msr)
442 {
443         u32 offset;
444         int i;
445
446         for (i = 0; i < NUM_MSR_MAPS; i++) {
447                 if (msr < msrpm_ranges[i] ||
448                     msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
449                         continue;
450
451                 offset  = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
452                 offset += (i * MSRS_RANGE_SIZE);       /* add range offset */
453
454                 /* Now we have the u8 offset - but need the u32 offset */
455                 return offset / 4;
456         }
457
458         /* MSR not in any range */
459         return MSR_INVALID;
460 }
461
462 #define MAX_INST_SIZE 15
463
464 static inline void clgi(void)
465 {
466         asm volatile (__ex(SVM_CLGI));
467 }
468
469 static inline void stgi(void)
470 {
471         asm volatile (__ex(SVM_STGI));
472 }
473
474 static inline void invlpga(unsigned long addr, u32 asid)
475 {
476         asm volatile (__ex(SVM_INVLPGA) : : "a"(addr), "c"(asid));
477 }
478
479 static int get_npt_level(void)
480 {
481 #ifdef CONFIG_X86_64
482         return PT64_ROOT_LEVEL;
483 #else
484         return PT32E_ROOT_LEVEL;
485 #endif
486 }
487
488 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
489 {
490         vcpu->arch.efer = efer;
491         if (!npt_enabled && !(efer & EFER_LMA))
492                 efer &= ~EFER_LME;
493
494         to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
495         mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
496 }
497
498 static int is_external_interrupt(u32 info)
499 {
500         info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
501         return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
502 }
503
504 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
505 {
506         struct vcpu_svm *svm = to_svm(vcpu);
507         u32 ret = 0;
508
509         if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
510                 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
511         return ret;
512 }
513
514 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
515 {
516         struct vcpu_svm *svm = to_svm(vcpu);
517
518         if (mask == 0)
519                 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
520         else
521                 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
522
523 }
524
525 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
526 {
527         struct vcpu_svm *svm = to_svm(vcpu);
528
529         if (svm->vmcb->control.next_rip != 0) {
530                 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
531                 svm->next_rip = svm->vmcb->control.next_rip;
532         }
533
534         if (!svm->next_rip) {
535                 if (emulate_instruction(vcpu, EMULTYPE_SKIP) !=
536                                 EMULATE_DONE)
537                         printk(KERN_DEBUG "%s: NOP\n", __func__);
538                 return;
539         }
540         if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
541                 printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
542                        __func__, kvm_rip_read(vcpu), svm->next_rip);
543
544         kvm_rip_write(vcpu, svm->next_rip);
545         svm_set_interrupt_shadow(vcpu, 0);
546 }
547
548 static void svm_queue_exception(struct kvm_vcpu *vcpu, unsigned nr,
549                                 bool has_error_code, u32 error_code,
550                                 bool reinject)
551 {
552         struct vcpu_svm *svm = to_svm(vcpu);
553
554         /*
555          * If we are within a nested VM we'd better #VMEXIT and let the guest
556          * handle the exception
557          */
558         if (!reinject &&
559             nested_svm_check_exception(svm, nr, has_error_code, error_code))
560                 return;
561
562         if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
563                 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
564
565                 /*
566                  * For guest debugging where we have to reinject #BP if some
567                  * INT3 is guest-owned:
568                  * Emulate nRIP by moving RIP forward. Will fail if injection
569                  * raises a fault that is not intercepted. Still better than
570                  * failing in all cases.
571                  */
572                 skip_emulated_instruction(&svm->vcpu);
573                 rip = kvm_rip_read(&svm->vcpu);
574                 svm->int3_rip = rip + svm->vmcb->save.cs.base;
575                 svm->int3_injected = rip - old_rip;
576         }
577
578         svm->vmcb->control.event_inj = nr
579                 | SVM_EVTINJ_VALID
580                 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
581                 | SVM_EVTINJ_TYPE_EXEPT;
582         svm->vmcb->control.event_inj_err = error_code;
583 }
584
585 static void svm_init_erratum_383(void)
586 {
587         u32 low, high;
588         int err;
589         u64 val;
590
591         if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
592                 return;
593
594         /* Use _safe variants to not break nested virtualization */
595         val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
596         if (err)
597                 return;
598
599         val |= (1ULL << 47);
600
601         low  = lower_32_bits(val);
602         high = upper_32_bits(val);
603
604         native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
605
606         erratum_383_found = true;
607 }
608
609 static void svm_init_osvw(struct kvm_vcpu *vcpu)
610 {
611         /*
612          * Guests should see errata 400 and 415 as fixed (assuming that
613          * HLT and IO instructions are intercepted).
614          */
615         vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
616         vcpu->arch.osvw.status = osvw_status & ~(6ULL);
617
618         /*
619          * By increasing VCPU's osvw.length to 3 we are telling the guest that
620          * all osvw.status bits inside that length, including bit 0 (which is
621          * reserved for erratum 298), are valid. However, if host processor's
622          * osvw_len is 0 then osvw_status[0] carries no information. We need to
623          * be conservative here and therefore we tell the guest that erratum 298
624          * is present (because we really don't know).
625          */
626         if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
627                 vcpu->arch.osvw.status |= 1;
628 }
629
630 static int has_svm(void)
631 {
632         const char *msg;
633
634         if (!cpu_has_svm(&msg)) {
635                 printk(KERN_INFO "has_svm: %s\n", msg);
636                 return 0;
637         }
638
639         return 1;
640 }
641
642 static void svm_hardware_disable(void)
643 {
644         /* Make sure we clean up behind us */
645         if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
646                 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
647
648         cpu_svm_disable();
649
650         amd_pmu_disable_virt();
651 }
652
653 static int svm_hardware_enable(void)
654 {
655
656         struct svm_cpu_data *sd;
657         uint64_t efer;
658         struct desc_ptr gdt_descr;
659         struct desc_struct *gdt;
660         int me = raw_smp_processor_id();
661
662         rdmsrl(MSR_EFER, efer);
663         if (efer & EFER_SVME)
664                 return -EBUSY;
665
666         if (!has_svm()) {
667                 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
668                 return -EINVAL;
669         }
670         sd = per_cpu(svm_data, me);
671         if (!sd) {
672                 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
673                 return -EINVAL;
674         }
675
676         sd->asid_generation = 1;
677         sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
678         sd->next_asid = sd->max_asid + 1;
679
680         native_store_gdt(&gdt_descr);
681         gdt = (struct desc_struct *)gdt_descr.address;
682         sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
683
684         wrmsrl(MSR_EFER, efer | EFER_SVME);
685
686         wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
687
688         if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
689                 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
690                 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
691         }
692
693
694         /*
695          * Get OSVW bits.
696          *
697          * Note that it is possible to have a system with mixed processor
698          * revisions and therefore different OSVW bits. If bits are not the same
699          * on different processors then choose the worst case (i.e. if erratum
700          * is present on one processor and not on another then assume that the
701          * erratum is present everywhere).
702          */
703         if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
704                 uint64_t len, status = 0;
705                 int err;
706
707                 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
708                 if (!err)
709                         status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
710                                                       &err);
711
712                 if (err)
713                         osvw_status = osvw_len = 0;
714                 else {
715                         if (len < osvw_len)
716                                 osvw_len = len;
717                         osvw_status |= status;
718                         osvw_status &= (1ULL << osvw_len) - 1;
719                 }
720         } else
721                 osvw_status = osvw_len = 0;
722
723         svm_init_erratum_383();
724
725         amd_pmu_enable_virt();
726
727         return 0;
728 }
729
730 static void svm_cpu_uninit(int cpu)
731 {
732         struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
733
734         if (!sd)
735                 return;
736
737         per_cpu(svm_data, raw_smp_processor_id()) = NULL;
738         __free_page(sd->save_area);
739         kfree(sd);
740 }
741
742 static int svm_cpu_init(int cpu)
743 {
744         struct svm_cpu_data *sd;
745         int r;
746
747         sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
748         if (!sd)
749                 return -ENOMEM;
750         sd->cpu = cpu;
751         sd->save_area = alloc_page(GFP_KERNEL);
752         r = -ENOMEM;
753         if (!sd->save_area)
754                 goto err_1;
755
756         per_cpu(svm_data, cpu) = sd;
757
758         return 0;
759
760 err_1:
761         kfree(sd);
762         return r;
763
764 }
765
766 static bool valid_msr_intercept(u32 index)
767 {
768         int i;
769
770         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
771                 if (direct_access_msrs[i].index == index)
772                         return true;
773
774         return false;
775 }
776
777 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
778 {
779         u8 bit_write;
780         unsigned long tmp;
781         u32 offset;
782         u32 *msrpm;
783
784         msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
785                                       to_svm(vcpu)->msrpm;
786
787         offset    = svm_msrpm_offset(msr);
788         bit_write = 2 * (msr & 0x0f) + 1;
789         tmp       = msrpm[offset];
790
791         BUG_ON(offset == MSR_INVALID);
792
793         return !!test_bit(bit_write,  &tmp);
794 }
795
796 static void set_msr_interception(u32 *msrpm, unsigned msr,
797                                  int read, int write)
798 {
799         u8 bit_read, bit_write;
800         unsigned long tmp;
801         u32 offset;
802
803         /*
804          * If this warning triggers extend the direct_access_msrs list at the
805          * beginning of the file
806          */
807         WARN_ON(!valid_msr_intercept(msr));
808
809         offset    = svm_msrpm_offset(msr);
810         bit_read  = 2 * (msr & 0x0f);
811         bit_write = 2 * (msr & 0x0f) + 1;
812         tmp       = msrpm[offset];
813
814         BUG_ON(offset == MSR_INVALID);
815
816         read  ? clear_bit(bit_read,  &tmp) : set_bit(bit_read,  &tmp);
817         write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
818
819         msrpm[offset] = tmp;
820 }
821
822 static void svm_vcpu_init_msrpm(u32 *msrpm)
823 {
824         int i;
825
826         memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
827
828         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
829                 if (!direct_access_msrs[i].always)
830                         continue;
831
832                 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
833         }
834 }
835
836 static void add_msr_offset(u32 offset)
837 {
838         int i;
839
840         for (i = 0; i < MSRPM_OFFSETS; ++i) {
841
842                 /* Offset already in list? */
843                 if (msrpm_offsets[i] == offset)
844                         return;
845
846                 /* Slot used by another offset? */
847                 if (msrpm_offsets[i] != MSR_INVALID)
848                         continue;
849
850                 /* Add offset to list */
851                 msrpm_offsets[i] = offset;
852
853                 return;
854         }
855
856         /*
857          * If this BUG triggers the msrpm_offsets table has an overflow. Just
858          * increase MSRPM_OFFSETS in this case.
859          */
860         BUG();
861 }
862
863 static void init_msrpm_offsets(void)
864 {
865         int i;
866
867         memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
868
869         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
870                 u32 offset;
871
872                 offset = svm_msrpm_offset(direct_access_msrs[i].index);
873                 BUG_ON(offset == MSR_INVALID);
874
875                 add_msr_offset(offset);
876         }
877 }
878
879 static void svm_enable_lbrv(struct vcpu_svm *svm)
880 {
881         u32 *msrpm = svm->msrpm;
882
883         svm->vmcb->control.lbr_ctl = 1;
884         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
885         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
886         set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
887         set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
888 }
889
890 static void svm_disable_lbrv(struct vcpu_svm *svm)
891 {
892         u32 *msrpm = svm->msrpm;
893
894         svm->vmcb->control.lbr_ctl = 0;
895         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
896         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
897         set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
898         set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
899 }
900
901 static __init int svm_hardware_setup(void)
902 {
903         int cpu;
904         struct page *iopm_pages;
905         void *iopm_va;
906         int r;
907
908         iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
909
910         if (!iopm_pages)
911                 return -ENOMEM;
912
913         iopm_va = page_address(iopm_pages);
914         memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
915         iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
916
917         init_msrpm_offsets();
918
919         if (boot_cpu_has(X86_FEATURE_NX))
920                 kvm_enable_efer_bits(EFER_NX);
921
922         if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
923                 kvm_enable_efer_bits(EFER_FFXSR);
924
925         if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
926                 kvm_has_tsc_control = true;
927                 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
928                 kvm_tsc_scaling_ratio_frac_bits = 32;
929         }
930
931         if (nested) {
932                 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
933                 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
934         }
935
936         for_each_possible_cpu(cpu) {
937                 r = svm_cpu_init(cpu);
938                 if (r)
939                         goto err;
940         }
941
942         if (!boot_cpu_has(X86_FEATURE_NPT))
943                 npt_enabled = false;
944
945         if (npt_enabled && !npt) {
946                 printk(KERN_INFO "kvm: Nested Paging disabled\n");
947                 npt_enabled = false;
948         }
949
950         if (npt_enabled) {
951                 printk(KERN_INFO "kvm: Nested Paging enabled\n");
952                 kvm_enable_tdp();
953         } else
954                 kvm_disable_tdp();
955
956         return 0;
957
958 err:
959         __free_pages(iopm_pages, IOPM_ALLOC_ORDER);
960         iopm_base = 0;
961         return r;
962 }
963
964 static __exit void svm_hardware_unsetup(void)
965 {
966         int cpu;
967
968         for_each_possible_cpu(cpu)
969                 svm_cpu_uninit(cpu);
970
971         __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
972         iopm_base = 0;
973 }
974
975 static void init_seg(struct vmcb_seg *seg)
976 {
977         seg->selector = 0;
978         seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
979                       SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
980         seg->limit = 0xffff;
981         seg->base = 0;
982 }
983
984 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
985 {
986         seg->selector = 0;
987         seg->attrib = SVM_SELECTOR_P_MASK | type;
988         seg->limit = 0xffff;
989         seg->base = 0;
990 }
991
992 static u64 svm_read_tsc_offset(struct kvm_vcpu *vcpu)
993 {
994         struct vcpu_svm *svm = to_svm(vcpu);
995
996         return svm->vmcb->control.tsc_offset;
997 }
998
999 static void svm_write_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1000 {
1001         struct vcpu_svm *svm = to_svm(vcpu);
1002         u64 g_tsc_offset = 0;
1003
1004         if (is_guest_mode(vcpu)) {
1005                 g_tsc_offset = svm->vmcb->control.tsc_offset -
1006                                svm->nested.hsave->control.tsc_offset;
1007                 svm->nested.hsave->control.tsc_offset = offset;
1008         } else
1009                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1010                                            svm->vmcb->control.tsc_offset,
1011                                            offset);
1012
1013         svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1014
1015         mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1016 }
1017
1018 static void svm_adjust_tsc_offset_guest(struct kvm_vcpu *vcpu, s64 adjustment)
1019 {
1020         struct vcpu_svm *svm = to_svm(vcpu);
1021
1022         svm->vmcb->control.tsc_offset += adjustment;
1023         if (is_guest_mode(vcpu))
1024                 svm->nested.hsave->control.tsc_offset += adjustment;
1025         else
1026                 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1027                                      svm->vmcb->control.tsc_offset - adjustment,
1028                                      svm->vmcb->control.tsc_offset);
1029
1030         mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1031 }
1032
1033 static void init_vmcb(struct vcpu_svm *svm)
1034 {
1035         struct vmcb_control_area *control = &svm->vmcb->control;
1036         struct vmcb_save_area *save = &svm->vmcb->save;
1037
1038         svm->vcpu.fpu_active = 1;
1039         svm->vcpu.arch.hflags = 0;
1040
1041         set_cr_intercept(svm, INTERCEPT_CR0_READ);
1042         set_cr_intercept(svm, INTERCEPT_CR3_READ);
1043         set_cr_intercept(svm, INTERCEPT_CR4_READ);
1044         set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1045         set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1046         set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1047         set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1048
1049         set_dr_intercepts(svm);
1050
1051         set_exception_intercept(svm, PF_VECTOR);
1052         set_exception_intercept(svm, UD_VECTOR);
1053         set_exception_intercept(svm, MC_VECTOR);
1054         set_exception_intercept(svm, AC_VECTOR);
1055         set_exception_intercept(svm, DB_VECTOR);
1056
1057         set_intercept(svm, INTERCEPT_INTR);
1058         set_intercept(svm, INTERCEPT_NMI);
1059         set_intercept(svm, INTERCEPT_SMI);
1060         set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1061         set_intercept(svm, INTERCEPT_RDPMC);
1062         set_intercept(svm, INTERCEPT_CPUID);
1063         set_intercept(svm, INTERCEPT_INVD);
1064         set_intercept(svm, INTERCEPT_HLT);
1065         set_intercept(svm, INTERCEPT_INVLPG);
1066         set_intercept(svm, INTERCEPT_INVLPGA);
1067         set_intercept(svm, INTERCEPT_IOIO_PROT);
1068         set_intercept(svm, INTERCEPT_MSR_PROT);
1069         set_intercept(svm, INTERCEPT_TASK_SWITCH);
1070         set_intercept(svm, INTERCEPT_SHUTDOWN);
1071         set_intercept(svm, INTERCEPT_VMRUN);
1072         set_intercept(svm, INTERCEPT_VMMCALL);
1073         set_intercept(svm, INTERCEPT_VMLOAD);
1074         set_intercept(svm, INTERCEPT_VMSAVE);
1075         set_intercept(svm, INTERCEPT_STGI);
1076         set_intercept(svm, INTERCEPT_CLGI);
1077         set_intercept(svm, INTERCEPT_SKINIT);
1078         set_intercept(svm, INTERCEPT_WBINVD);
1079         set_intercept(svm, INTERCEPT_MONITOR);
1080         set_intercept(svm, INTERCEPT_MWAIT);
1081         set_intercept(svm, INTERCEPT_XSETBV);
1082
1083         control->iopm_base_pa = iopm_base;
1084         control->msrpm_base_pa = __pa(svm->msrpm);
1085         control->int_ctl = V_INTR_MASKING_MASK;
1086
1087         init_seg(&save->es);
1088         init_seg(&save->ss);
1089         init_seg(&save->ds);
1090         init_seg(&save->fs);
1091         init_seg(&save->gs);
1092
1093         save->cs.selector = 0xf000;
1094         save->cs.base = 0xffff0000;
1095         /* Executable/Readable Code Segment */
1096         save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1097                 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1098         save->cs.limit = 0xffff;
1099
1100         save->gdtr.limit = 0xffff;
1101         save->idtr.limit = 0xffff;
1102
1103         init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1104         init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1105
1106         svm_set_efer(&svm->vcpu, 0);
1107         save->dr6 = 0xffff0ff0;
1108         kvm_set_rflags(&svm->vcpu, 2);
1109         save->rip = 0x0000fff0;
1110         svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1111
1112         /*
1113          * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1114          * It also updates the guest-visible cr0 value.
1115          */
1116         svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1117         kvm_mmu_reset_context(&svm->vcpu);
1118
1119         save->cr4 = X86_CR4_PAE;
1120         /* rdx = ?? */
1121
1122         if (npt_enabled) {
1123                 /* Setup VMCB for Nested Paging */
1124                 control->nested_ctl = 1;
1125                 clr_intercept(svm, INTERCEPT_INVLPG);
1126                 clr_exception_intercept(svm, PF_VECTOR);
1127                 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1128                 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1129                 save->g_pat = svm->vcpu.arch.pat;
1130                 save->cr3 = 0;
1131                 save->cr4 = 0;
1132         }
1133         svm->asid_generation = 0;
1134
1135         svm->nested.vmcb = 0;
1136         svm->vcpu.arch.hflags = 0;
1137
1138         if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1139                 control->pause_filter_count = 3000;
1140                 set_intercept(svm, INTERCEPT_PAUSE);
1141         }
1142
1143         mark_all_dirty(svm->vmcb);
1144
1145         enable_gif(svm);
1146 }
1147
1148 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
1149 {
1150         struct vcpu_svm *svm = to_svm(vcpu);
1151         u32 dummy;
1152         u32 eax = 1;
1153
1154         svm->spec_ctrl = 0;
1155         svm->virt_spec_ctrl = 0;
1156
1157         if (!init_event) {
1158                 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
1159                                            MSR_IA32_APICBASE_ENABLE;
1160                 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
1161                         svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
1162         }
1163         init_vmcb(svm);
1164
1165         kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy);
1166         kvm_register_write(vcpu, VCPU_REGS_RDX, eax);
1167 }
1168
1169 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
1170 {
1171         struct vcpu_svm *svm;
1172         struct page *page;
1173         struct page *msrpm_pages;
1174         struct page *hsave_page;
1175         struct page *nested_msrpm_pages;
1176         int err;
1177
1178         svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL);
1179         if (!svm) {
1180                 err = -ENOMEM;
1181                 goto out;
1182         }
1183
1184         err = kvm_vcpu_init(&svm->vcpu, kvm, id);
1185         if (err)
1186                 goto free_svm;
1187
1188         err = -ENOMEM;
1189         page = alloc_page(GFP_KERNEL);
1190         if (!page)
1191                 goto uninit;
1192
1193         msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1194         if (!msrpm_pages)
1195                 goto free_page1;
1196
1197         nested_msrpm_pages = alloc_pages(GFP_KERNEL, MSRPM_ALLOC_ORDER);
1198         if (!nested_msrpm_pages)
1199                 goto free_page2;
1200
1201         hsave_page = alloc_page(GFP_KERNEL);
1202         if (!hsave_page)
1203                 goto free_page3;
1204
1205         svm->nested.hsave = page_address(hsave_page);
1206
1207         svm->msrpm = page_address(msrpm_pages);
1208         svm_vcpu_init_msrpm(svm->msrpm);
1209
1210         svm->nested.msrpm = page_address(nested_msrpm_pages);
1211         svm_vcpu_init_msrpm(svm->nested.msrpm);
1212
1213         svm->vmcb = page_address(page);
1214         clear_page(svm->vmcb);
1215         svm->vmcb_pa = page_to_pfn(page) << PAGE_SHIFT;
1216         svm->asid_generation = 0;
1217         init_vmcb(svm);
1218
1219         svm_init_osvw(&svm->vcpu);
1220
1221         return &svm->vcpu;
1222
1223 free_page3:
1224         __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
1225 free_page2:
1226         __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
1227 free_page1:
1228         __free_page(page);
1229 uninit:
1230         kvm_vcpu_uninit(&svm->vcpu);
1231 free_svm:
1232         kmem_cache_free(kvm_vcpu_cache, svm);
1233 out:
1234         return ERR_PTR(err);
1235 }
1236
1237 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
1238 {
1239         struct vcpu_svm *svm = to_svm(vcpu);
1240
1241         __free_page(pfn_to_page(svm->vmcb_pa >> PAGE_SHIFT));
1242         __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
1243         __free_page(virt_to_page(svm->nested.hsave));
1244         __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
1245         kvm_vcpu_uninit(vcpu);
1246         kmem_cache_free(kvm_vcpu_cache, svm);
1247         /*
1248          * The vmcb page can be recycled, causing a false negative in
1249          * svm_vcpu_load(). So do a full IBPB now.
1250          */
1251         indirect_branch_prediction_barrier();
1252 }
1253
1254 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
1255 {
1256         struct vcpu_svm *svm = to_svm(vcpu);
1257         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
1258         int i;
1259
1260         if (unlikely(cpu != vcpu->cpu)) {
1261                 svm->asid_generation = 0;
1262                 mark_all_dirty(svm->vmcb);
1263         }
1264
1265 #ifdef CONFIG_X86_64
1266         rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
1267 #endif
1268         savesegment(fs, svm->host.fs);
1269         savesegment(gs, svm->host.gs);
1270         svm->host.ldt = kvm_read_ldt();
1271
1272         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
1273                 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
1274
1275         if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1276                 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
1277                 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
1278                         __this_cpu_write(current_tsc_ratio, tsc_ratio);
1279                         wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
1280                 }
1281         }
1282         if (sd->current_vmcb != svm->vmcb) {
1283                 sd->current_vmcb = svm->vmcb;
1284                 indirect_branch_prediction_barrier();
1285         }
1286 }
1287
1288 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
1289 {
1290         struct vcpu_svm *svm = to_svm(vcpu);
1291         int i;
1292
1293         ++vcpu->stat.host_state_reload;
1294         kvm_load_ldt(svm->host.ldt);
1295 #ifdef CONFIG_X86_64
1296         loadsegment(fs, svm->host.fs);
1297         wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gs);
1298         load_gs_index(svm->host.gs);
1299 #else
1300 #ifdef CONFIG_X86_32_LAZY_GS
1301         loadsegment(gs, svm->host.gs);
1302 #endif
1303 #endif
1304         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
1305                 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
1306 }
1307
1308 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
1309 {
1310         return to_svm(vcpu)->vmcb->save.rflags;
1311 }
1312
1313 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
1314 {
1315        /*
1316         * Any change of EFLAGS.VM is accompained by a reload of SS
1317         * (caused by either a task switch or an inter-privilege IRET),
1318         * so we do not need to update the CPL here.
1319         */
1320         to_svm(vcpu)->vmcb->save.rflags = rflags;
1321 }
1322
1323 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
1324 {
1325         switch (reg) {
1326         case VCPU_EXREG_PDPTR:
1327                 BUG_ON(!npt_enabled);
1328                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
1329                 break;
1330         default:
1331                 BUG();
1332         }
1333 }
1334
1335 static void svm_set_vintr(struct vcpu_svm *svm)
1336 {
1337         set_intercept(svm, INTERCEPT_VINTR);
1338 }
1339
1340 static void svm_clear_vintr(struct vcpu_svm *svm)
1341 {
1342         clr_intercept(svm, INTERCEPT_VINTR);
1343 }
1344
1345 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
1346 {
1347         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1348
1349         switch (seg) {
1350         case VCPU_SREG_CS: return &save->cs;
1351         case VCPU_SREG_DS: return &save->ds;
1352         case VCPU_SREG_ES: return &save->es;
1353         case VCPU_SREG_FS: return &save->fs;
1354         case VCPU_SREG_GS: return &save->gs;
1355         case VCPU_SREG_SS: return &save->ss;
1356         case VCPU_SREG_TR: return &save->tr;
1357         case VCPU_SREG_LDTR: return &save->ldtr;
1358         }
1359         BUG();
1360         return NULL;
1361 }
1362
1363 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
1364 {
1365         struct vmcb_seg *s = svm_seg(vcpu, seg);
1366
1367         return s->base;
1368 }
1369
1370 static void svm_get_segment(struct kvm_vcpu *vcpu,
1371                             struct kvm_segment *var, int seg)
1372 {
1373         struct vmcb_seg *s = svm_seg(vcpu, seg);
1374
1375         var->base = s->base;
1376         var->limit = s->limit;
1377         var->selector = s->selector;
1378         var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
1379         var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
1380         var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
1381         var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
1382         var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
1383         var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
1384         var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
1385
1386         /*
1387          * AMD CPUs circa 2014 track the G bit for all segments except CS.
1388          * However, the SVM spec states that the G bit is not observed by the
1389          * CPU, and some VMware virtual CPUs drop the G bit for all segments.
1390          * So let's synthesize a legal G bit for all segments, this helps
1391          * running KVM nested. It also helps cross-vendor migration, because
1392          * Intel's vmentry has a check on the 'G' bit.
1393          */
1394         var->g = s->limit > 0xfffff;
1395
1396         /*
1397          * AMD's VMCB does not have an explicit unusable field, so emulate it
1398          * for cross vendor migration purposes by "not present"
1399          */
1400         var->unusable = !var->present || (var->type == 0);
1401
1402         switch (seg) {
1403         case VCPU_SREG_TR:
1404                 /*
1405                  * Work around a bug where the busy flag in the tr selector
1406                  * isn't exposed
1407                  */
1408                 var->type |= 0x2;
1409                 break;
1410         case VCPU_SREG_DS:
1411         case VCPU_SREG_ES:
1412         case VCPU_SREG_FS:
1413         case VCPU_SREG_GS:
1414                 /*
1415                  * The accessed bit must always be set in the segment
1416                  * descriptor cache, although it can be cleared in the
1417                  * descriptor, the cached bit always remains at 1. Since
1418                  * Intel has a check on this, set it here to support
1419                  * cross-vendor migration.
1420                  */
1421                 if (!var->unusable)
1422                         var->type |= 0x1;
1423                 break;
1424         case VCPU_SREG_SS:
1425                 /*
1426                  * On AMD CPUs sometimes the DB bit in the segment
1427                  * descriptor is left as 1, although the whole segment has
1428                  * been made unusable. Clear it here to pass an Intel VMX
1429                  * entry check when cross vendor migrating.
1430                  */
1431                 if (var->unusable)
1432                         var->db = 0;
1433                 /* This is symmetric with svm_set_segment() */
1434                 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
1435                 break;
1436         }
1437 }
1438
1439 static int svm_get_cpl(struct kvm_vcpu *vcpu)
1440 {
1441         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
1442
1443         return save->cpl;
1444 }
1445
1446 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1447 {
1448         struct vcpu_svm *svm = to_svm(vcpu);
1449
1450         dt->size = svm->vmcb->save.idtr.limit;
1451         dt->address = svm->vmcb->save.idtr.base;
1452 }
1453
1454 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1455 {
1456         struct vcpu_svm *svm = to_svm(vcpu);
1457
1458         svm->vmcb->save.idtr.limit = dt->size;
1459         svm->vmcb->save.idtr.base = dt->address ;
1460         mark_dirty(svm->vmcb, VMCB_DT);
1461 }
1462
1463 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1464 {
1465         struct vcpu_svm *svm = to_svm(vcpu);
1466
1467         dt->size = svm->vmcb->save.gdtr.limit;
1468         dt->address = svm->vmcb->save.gdtr.base;
1469 }
1470
1471 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
1472 {
1473         struct vcpu_svm *svm = to_svm(vcpu);
1474
1475         svm->vmcb->save.gdtr.limit = dt->size;
1476         svm->vmcb->save.gdtr.base = dt->address ;
1477         mark_dirty(svm->vmcb, VMCB_DT);
1478 }
1479
1480 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
1481 {
1482 }
1483
1484 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
1485 {
1486 }
1487
1488 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
1489 {
1490 }
1491
1492 static void update_cr0_intercept(struct vcpu_svm *svm)
1493 {
1494         ulong gcr0 = svm->vcpu.arch.cr0;
1495         u64 *hcr0 = &svm->vmcb->save.cr0;
1496
1497         if (!svm->vcpu.fpu_active)
1498                 *hcr0 |= SVM_CR0_SELECTIVE_MASK;
1499         else
1500                 *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
1501                         | (gcr0 & SVM_CR0_SELECTIVE_MASK);
1502
1503         mark_dirty(svm->vmcb, VMCB_CR);
1504
1505         if (gcr0 == *hcr0 && svm->vcpu.fpu_active) {
1506                 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
1507                 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1508         } else {
1509                 set_cr_intercept(svm, INTERCEPT_CR0_READ);
1510                 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1511         }
1512 }
1513
1514 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
1515 {
1516         struct vcpu_svm *svm = to_svm(vcpu);
1517
1518 #ifdef CONFIG_X86_64
1519         if (vcpu->arch.efer & EFER_LME) {
1520                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
1521                         vcpu->arch.efer |= EFER_LMA;
1522                         svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
1523                 }
1524
1525                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
1526                         vcpu->arch.efer &= ~EFER_LMA;
1527                         svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
1528                 }
1529         }
1530 #endif
1531         vcpu->arch.cr0 = cr0;
1532
1533         if (!npt_enabled)
1534                 cr0 |= X86_CR0_PG | X86_CR0_WP;
1535
1536         if (!vcpu->fpu_active)
1537                 cr0 |= X86_CR0_TS;
1538         /*
1539          * re-enable caching here because the QEMU bios
1540          * does not do it - this results in some delay at
1541          * reboot
1542          */
1543         if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
1544                 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
1545         svm->vmcb->save.cr0 = cr0;
1546         mark_dirty(svm->vmcb, VMCB_CR);
1547         update_cr0_intercept(svm);
1548 }
1549
1550 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
1551 {
1552         unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
1553         unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
1554
1555         if (cr4 & X86_CR4_VMXE)
1556                 return 1;
1557
1558         if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
1559                 svm_flush_tlb(vcpu);
1560
1561         vcpu->arch.cr4 = cr4;
1562         if (!npt_enabled)
1563                 cr4 |= X86_CR4_PAE;
1564         cr4 |= host_cr4_mce;
1565         to_svm(vcpu)->vmcb->save.cr4 = cr4;
1566         mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
1567         return 0;
1568 }
1569
1570 static void svm_set_segment(struct kvm_vcpu *vcpu,
1571                             struct kvm_segment *var, int seg)
1572 {
1573         struct vcpu_svm *svm = to_svm(vcpu);
1574         struct vmcb_seg *s = svm_seg(vcpu, seg);
1575
1576         s->base = var->base;
1577         s->limit = var->limit;
1578         s->selector = var->selector;
1579         s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
1580         s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
1581         s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
1582         s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
1583         s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
1584         s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
1585         s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
1586         s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
1587
1588         /*
1589          * This is always accurate, except if SYSRET returned to a segment
1590          * with SS.DPL != 3.  Intel does not have this quirk, and always
1591          * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
1592          * would entail passing the CPL to userspace and back.
1593          */
1594         if (seg == VCPU_SREG_SS)
1595                 /* This is symmetric with svm_get_segment() */
1596                 svm->vmcb->save.cpl = (var->dpl & 3);
1597
1598         mark_dirty(svm->vmcb, VMCB_SEG);
1599 }
1600
1601 static void update_bp_intercept(struct kvm_vcpu *vcpu)
1602 {
1603         struct vcpu_svm *svm = to_svm(vcpu);
1604
1605         clr_exception_intercept(svm, BP_VECTOR);
1606
1607         if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
1608                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
1609                         set_exception_intercept(svm, BP_VECTOR);
1610         } else
1611                 vcpu->guest_debug = 0;
1612 }
1613
1614 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
1615 {
1616         if (sd->next_asid > sd->max_asid) {
1617                 ++sd->asid_generation;
1618                 sd->next_asid = 1;
1619                 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
1620         }
1621
1622         svm->asid_generation = sd->asid_generation;
1623         svm->vmcb->control.asid = sd->next_asid++;
1624
1625         mark_dirty(svm->vmcb, VMCB_ASID);
1626 }
1627
1628 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
1629 {
1630         return to_svm(vcpu)->vmcb->save.dr6;
1631 }
1632
1633 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
1634 {
1635         struct vcpu_svm *svm = to_svm(vcpu);
1636
1637         svm->vmcb->save.dr6 = value;
1638         mark_dirty(svm->vmcb, VMCB_DR);
1639 }
1640
1641 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
1642 {
1643         struct vcpu_svm *svm = to_svm(vcpu);
1644
1645         get_debugreg(vcpu->arch.db[0], 0);
1646         get_debugreg(vcpu->arch.db[1], 1);
1647         get_debugreg(vcpu->arch.db[2], 2);
1648         get_debugreg(vcpu->arch.db[3], 3);
1649         vcpu->arch.dr6 = svm_get_dr6(vcpu);
1650         vcpu->arch.dr7 = svm->vmcb->save.dr7;
1651
1652         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
1653         set_dr_intercepts(svm);
1654 }
1655
1656 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
1657 {
1658         struct vcpu_svm *svm = to_svm(vcpu);
1659
1660         svm->vmcb->save.dr7 = value;
1661         mark_dirty(svm->vmcb, VMCB_DR);
1662 }
1663
1664 static int pf_interception(struct vcpu_svm *svm)
1665 {
1666         u64 fault_address = svm->vmcb->control.exit_info_2;
1667         u32 error_code;
1668         int r = 1;
1669
1670         switch (svm->apf_reason) {
1671         default:
1672                 error_code = svm->vmcb->control.exit_info_1;
1673
1674                 trace_kvm_page_fault(fault_address, error_code);
1675                 if (!npt_enabled && kvm_event_needs_reinjection(&svm->vcpu))
1676                         kvm_mmu_unprotect_page_virt(&svm->vcpu, fault_address);
1677                 r = kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
1678                         svm->vmcb->control.insn_bytes,
1679                         svm->vmcb->control.insn_len);
1680                 break;
1681         case KVM_PV_REASON_PAGE_NOT_PRESENT:
1682                 svm->apf_reason = 0;
1683                 local_irq_disable();
1684                 kvm_async_pf_task_wait(fault_address);
1685                 local_irq_enable();
1686                 break;
1687         case KVM_PV_REASON_PAGE_READY:
1688                 svm->apf_reason = 0;
1689                 local_irq_disable();
1690                 kvm_async_pf_task_wake(fault_address);
1691                 local_irq_enable();
1692                 break;
1693         }
1694         return r;
1695 }
1696
1697 static int db_interception(struct vcpu_svm *svm)
1698 {
1699         struct kvm_run *kvm_run = svm->vcpu.run;
1700
1701         if (!(svm->vcpu.guest_debug &
1702               (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
1703                 !svm->nmi_singlestep) {
1704                 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
1705                 return 1;
1706         }
1707
1708         if (svm->nmi_singlestep) {
1709                 svm->nmi_singlestep = false;
1710                 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP))
1711                         svm->vmcb->save.rflags &=
1712                                 ~(X86_EFLAGS_TF | X86_EFLAGS_RF);
1713         }
1714
1715         if (svm->vcpu.guest_debug &
1716             (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
1717                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
1718                 kvm_run->debug.arch.pc =
1719                         svm->vmcb->save.cs.base + svm->vmcb->save.rip;
1720                 kvm_run->debug.arch.exception = DB_VECTOR;
1721                 return 0;
1722         }
1723
1724         return 1;
1725 }
1726
1727 static int bp_interception(struct vcpu_svm *svm)
1728 {
1729         struct kvm_run *kvm_run = svm->vcpu.run;
1730
1731         kvm_run->exit_reason = KVM_EXIT_DEBUG;
1732         kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
1733         kvm_run->debug.arch.exception = BP_VECTOR;
1734         return 0;
1735 }
1736
1737 static int ud_interception(struct vcpu_svm *svm)
1738 {
1739         int er;
1740
1741         er = emulate_instruction(&svm->vcpu, EMULTYPE_TRAP_UD);
1742         if (er == EMULATE_USER_EXIT)
1743                 return 0;
1744         if (er != EMULATE_DONE)
1745                 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
1746         return 1;
1747 }
1748
1749 static int ac_interception(struct vcpu_svm *svm)
1750 {
1751         kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
1752         return 1;
1753 }
1754
1755 static void svm_fpu_activate(struct kvm_vcpu *vcpu)
1756 {
1757         struct vcpu_svm *svm = to_svm(vcpu);
1758
1759         clr_exception_intercept(svm, NM_VECTOR);
1760
1761         svm->vcpu.fpu_active = 1;
1762         update_cr0_intercept(svm);
1763 }
1764
1765 static int nm_interception(struct vcpu_svm *svm)
1766 {
1767         svm_fpu_activate(&svm->vcpu);
1768         return 1;
1769 }
1770
1771 static bool is_erratum_383(void)
1772 {
1773         int err, i;
1774         u64 value;
1775
1776         if (!erratum_383_found)
1777                 return false;
1778
1779         value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
1780         if (err)
1781                 return false;
1782
1783         /* Bit 62 may or may not be set for this mce */
1784         value &= ~(1ULL << 62);
1785
1786         if (value != 0xb600000000010015ULL)
1787                 return false;
1788
1789         /* Clear MCi_STATUS registers */
1790         for (i = 0; i < 6; ++i)
1791                 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
1792
1793         value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
1794         if (!err) {
1795                 u32 low, high;
1796
1797                 value &= ~(1ULL << 2);
1798                 low    = lower_32_bits(value);
1799                 high   = upper_32_bits(value);
1800
1801                 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
1802         }
1803
1804         /* Flush tlb to evict multi-match entries */
1805         __flush_tlb_all();
1806
1807         return true;
1808 }
1809
1810 static void svm_handle_mce(struct vcpu_svm *svm)
1811 {
1812         if (is_erratum_383()) {
1813                 /*
1814                  * Erratum 383 triggered. Guest state is corrupt so kill the
1815                  * guest.
1816                  */
1817                 pr_err("KVM: Guest triggered AMD Erratum 383\n");
1818
1819                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
1820
1821                 return;
1822         }
1823
1824         /*
1825          * On an #MC intercept the MCE handler is not called automatically in
1826          * the host. So do it by hand here.
1827          */
1828         asm volatile (
1829                 "int $0x12\n");
1830         /* not sure if we ever come back to this point */
1831
1832         return;
1833 }
1834
1835 static int mc_interception(struct vcpu_svm *svm)
1836 {
1837         return 1;
1838 }
1839
1840 static int shutdown_interception(struct vcpu_svm *svm)
1841 {
1842         struct kvm_run *kvm_run = svm->vcpu.run;
1843
1844         /*
1845          * VMCB is undefined after a SHUTDOWN intercept
1846          * so reinitialize it.
1847          */
1848         clear_page(svm->vmcb);
1849         init_vmcb(svm);
1850
1851         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
1852         return 0;
1853 }
1854
1855 static int io_interception(struct vcpu_svm *svm)
1856 {
1857         struct kvm_vcpu *vcpu = &svm->vcpu;
1858         u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
1859         int size, in, string;
1860         unsigned port;
1861
1862         ++svm->vcpu.stat.io_exits;
1863         string = (io_info & SVM_IOIO_STR_MASK) != 0;
1864         in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
1865         if (string || in)
1866                 return emulate_instruction(vcpu, 0) == EMULATE_DONE;
1867
1868         port = io_info >> 16;
1869         size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
1870         svm->next_rip = svm->vmcb->control.exit_info_2;
1871         skip_emulated_instruction(&svm->vcpu);
1872
1873         return kvm_fast_pio_out(vcpu, size, port);
1874 }
1875
1876 static int nmi_interception(struct vcpu_svm *svm)
1877 {
1878         return 1;
1879 }
1880
1881 static int intr_interception(struct vcpu_svm *svm)
1882 {
1883         ++svm->vcpu.stat.irq_exits;
1884         return 1;
1885 }
1886
1887 static int nop_on_interception(struct vcpu_svm *svm)
1888 {
1889         return 1;
1890 }
1891
1892 static int halt_interception(struct vcpu_svm *svm)
1893 {
1894         svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
1895         return kvm_emulate_halt(&svm->vcpu);
1896 }
1897
1898 static int vmmcall_interception(struct vcpu_svm *svm)
1899 {
1900         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
1901         kvm_emulate_hypercall(&svm->vcpu);
1902         return 1;
1903 }
1904
1905 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
1906 {
1907         struct vcpu_svm *svm = to_svm(vcpu);
1908
1909         return svm->nested.nested_cr3;
1910 }
1911
1912 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
1913 {
1914         struct vcpu_svm *svm = to_svm(vcpu);
1915         u64 cr3 = svm->nested.nested_cr3;
1916         u64 pdpte;
1917         int ret;
1918
1919         ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(cr3), &pdpte,
1920                                        offset_in_page(cr3) + index * 8, 8);
1921         if (ret)
1922                 return 0;
1923         return pdpte;
1924 }
1925
1926 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
1927                                    unsigned long root)
1928 {
1929         struct vcpu_svm *svm = to_svm(vcpu);
1930
1931         svm->vmcb->control.nested_cr3 = root;
1932         mark_dirty(svm->vmcb, VMCB_NPT);
1933         svm_flush_tlb(vcpu);
1934 }
1935
1936 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
1937                                        struct x86_exception *fault)
1938 {
1939         struct vcpu_svm *svm = to_svm(vcpu);
1940
1941         if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
1942                 /*
1943                  * TODO: track the cause of the nested page fault, and
1944                  * correctly fill in the high bits of exit_info_1.
1945                  */
1946                 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
1947                 svm->vmcb->control.exit_code_hi = 0;
1948                 svm->vmcb->control.exit_info_1 = (1ULL << 32);
1949                 svm->vmcb->control.exit_info_2 = fault->address;
1950         }
1951
1952         svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
1953         svm->vmcb->control.exit_info_1 |= fault->error_code;
1954
1955         /*
1956          * The present bit is always zero for page structure faults on real
1957          * hardware.
1958          */
1959         if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
1960                 svm->vmcb->control.exit_info_1 &= ~1;
1961
1962         nested_svm_vmexit(svm);
1963 }
1964
1965 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
1966 {
1967         WARN_ON(mmu_is_nested(vcpu));
1968         kvm_init_shadow_mmu(vcpu);
1969         vcpu->arch.mmu.set_cr3           = nested_svm_set_tdp_cr3;
1970         vcpu->arch.mmu.get_cr3           = nested_svm_get_tdp_cr3;
1971         vcpu->arch.mmu.get_pdptr         = nested_svm_get_tdp_pdptr;
1972         vcpu->arch.mmu.inject_page_fault = nested_svm_inject_npf_exit;
1973         vcpu->arch.mmu.shadow_root_level = get_npt_level();
1974         reset_shadow_zero_bits_mask(vcpu, &vcpu->arch.mmu);
1975         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
1976 }
1977
1978 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
1979 {
1980         vcpu->arch.walk_mmu = &vcpu->arch.mmu;
1981 }
1982
1983 static int nested_svm_check_permissions(struct vcpu_svm *svm)
1984 {
1985         if (!(svm->vcpu.arch.efer & EFER_SVME)
1986             || !is_paging(&svm->vcpu)) {
1987                 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
1988                 return 1;
1989         }
1990
1991         if (svm->vmcb->save.cpl) {
1992                 kvm_inject_gp(&svm->vcpu, 0);
1993                 return 1;
1994         }
1995
1996        return 0;
1997 }
1998
1999 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
2000                                       bool has_error_code, u32 error_code)
2001 {
2002         int vmexit;
2003
2004         if (!is_guest_mode(&svm->vcpu))
2005                 return 0;
2006
2007         svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
2008         svm->vmcb->control.exit_code_hi = 0;
2009         svm->vmcb->control.exit_info_1 = error_code;
2010         svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
2011
2012         vmexit = nested_svm_intercept(svm);
2013         if (vmexit == NESTED_EXIT_DONE)
2014                 svm->nested.exit_required = true;
2015
2016         return vmexit;
2017 }
2018
2019 /* This function returns true if it is save to enable the irq window */
2020 static inline bool nested_svm_intr(struct vcpu_svm *svm)
2021 {
2022         if (!is_guest_mode(&svm->vcpu))
2023                 return true;
2024
2025         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
2026                 return true;
2027
2028         if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
2029                 return false;
2030
2031         /*
2032          * if vmexit was already requested (by intercepted exception
2033          * for instance) do not overwrite it with "external interrupt"
2034          * vmexit.
2035          */
2036         if (svm->nested.exit_required)
2037                 return false;
2038
2039         svm->vmcb->control.exit_code   = SVM_EXIT_INTR;
2040         svm->vmcb->control.exit_info_1 = 0;
2041         svm->vmcb->control.exit_info_2 = 0;
2042
2043         if (svm->nested.intercept & 1ULL) {
2044                 /*
2045                  * The #vmexit can't be emulated here directly because this
2046                  * code path runs with irqs and preemption disabled. A
2047                  * #vmexit emulation might sleep. Only signal request for
2048                  * the #vmexit here.
2049                  */
2050                 svm->nested.exit_required = true;
2051                 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
2052                 return false;
2053         }
2054
2055         return true;
2056 }
2057
2058 /* This function returns true if it is save to enable the nmi window */
2059 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
2060 {
2061         if (!is_guest_mode(&svm->vcpu))
2062                 return true;
2063
2064         if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
2065                 return true;
2066
2067         svm->vmcb->control.exit_code = SVM_EXIT_NMI;
2068         svm->nested.exit_required = true;
2069
2070         return false;
2071 }
2072
2073 static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
2074 {
2075         struct page *page;
2076
2077         might_sleep();
2078
2079         page = kvm_vcpu_gfn_to_page(&svm->vcpu, gpa >> PAGE_SHIFT);
2080         if (is_error_page(page))
2081                 goto error;
2082
2083         *_page = page;
2084
2085         return kmap(page);
2086
2087 error:
2088         kvm_inject_gp(&svm->vcpu, 0);
2089
2090         return NULL;
2091 }
2092
2093 static void nested_svm_unmap(struct page *page)
2094 {
2095         kunmap(page);
2096         kvm_release_page_dirty(page);
2097 }
2098
2099 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
2100 {
2101         unsigned port, size, iopm_len;
2102         u16 val, mask;
2103         u8 start_bit;
2104         u64 gpa;
2105
2106         if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
2107                 return NESTED_EXIT_HOST;
2108
2109         port = svm->vmcb->control.exit_info_1 >> 16;
2110         size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
2111                 SVM_IOIO_SIZE_SHIFT;
2112         gpa  = svm->nested.vmcb_iopm + (port / 8);
2113         start_bit = port % 8;
2114         iopm_len = (start_bit + size > 8) ? 2 : 1;
2115         mask = (0xf >> (4 - size)) << start_bit;
2116         val = 0;
2117
2118         if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
2119                 return NESTED_EXIT_DONE;
2120
2121         return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2122 }
2123
2124 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
2125 {
2126         u32 offset, msr, value;
2127         int write, mask;
2128
2129         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
2130                 return NESTED_EXIT_HOST;
2131
2132         msr    = svm->vcpu.arch.regs[VCPU_REGS_RCX];
2133         offset = svm_msrpm_offset(msr);
2134         write  = svm->vmcb->control.exit_info_1 & 1;
2135         mask   = 1 << ((2 * (msr & 0xf)) + write);
2136
2137         if (offset == MSR_INVALID)
2138                 return NESTED_EXIT_DONE;
2139
2140         /* Offset is in 32 bit units but need in 8 bit units */
2141         offset *= 4;
2142
2143         if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
2144                 return NESTED_EXIT_DONE;
2145
2146         return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
2147 }
2148
2149 static int nested_svm_exit_special(struct vcpu_svm *svm)
2150 {
2151         u32 exit_code = svm->vmcb->control.exit_code;
2152
2153         switch (exit_code) {
2154         case SVM_EXIT_INTR:
2155         case SVM_EXIT_NMI:
2156         case SVM_EXIT_EXCP_BASE + MC_VECTOR:
2157                 return NESTED_EXIT_HOST;
2158         case SVM_EXIT_NPF:
2159                 /* For now we are always handling NPFs when using them */
2160                 if (npt_enabled)
2161                         return NESTED_EXIT_HOST;
2162                 break;
2163         case SVM_EXIT_EXCP_BASE + PF_VECTOR:
2164                 /* When we're shadowing, trap PFs, but not async PF */
2165                 if (!npt_enabled && svm->apf_reason == 0)
2166                         return NESTED_EXIT_HOST;
2167                 break;
2168         case SVM_EXIT_EXCP_BASE + NM_VECTOR:
2169                 nm_interception(svm);
2170                 break;
2171         default:
2172                 break;
2173         }
2174
2175         return NESTED_EXIT_CONTINUE;
2176 }
2177
2178 /*
2179  * If this function returns true, this #vmexit was already handled
2180  */
2181 static int nested_svm_intercept(struct vcpu_svm *svm)
2182 {
2183         u32 exit_code = svm->vmcb->control.exit_code;
2184         int vmexit = NESTED_EXIT_HOST;
2185
2186         switch (exit_code) {
2187         case SVM_EXIT_MSR:
2188                 vmexit = nested_svm_exit_handled_msr(svm);
2189                 break;
2190         case SVM_EXIT_IOIO:
2191                 vmexit = nested_svm_intercept_ioio(svm);
2192                 break;
2193         case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
2194                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
2195                 if (svm->nested.intercept_cr & bit)
2196                         vmexit = NESTED_EXIT_DONE;
2197                 break;
2198         }
2199         case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
2200                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
2201                 if (svm->nested.intercept_dr & bit)
2202                         vmexit = NESTED_EXIT_DONE;
2203                 break;
2204         }
2205         case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
2206                 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
2207                 if (svm->nested.intercept_exceptions & excp_bits)
2208                         vmexit = NESTED_EXIT_DONE;
2209                 /* async page fault always cause vmexit */
2210                 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
2211                          svm->apf_reason != 0)
2212                         vmexit = NESTED_EXIT_DONE;
2213                 break;
2214         }
2215         case SVM_EXIT_ERR: {
2216                 vmexit = NESTED_EXIT_DONE;
2217                 break;
2218         }
2219         default: {
2220                 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
2221                 if (svm->nested.intercept & exit_bits)
2222                         vmexit = NESTED_EXIT_DONE;
2223         }
2224         }
2225
2226         return vmexit;
2227 }
2228
2229 static int nested_svm_exit_handled(struct vcpu_svm *svm)
2230 {
2231         int vmexit;
2232
2233         vmexit = nested_svm_intercept(svm);
2234
2235         if (vmexit == NESTED_EXIT_DONE)
2236                 nested_svm_vmexit(svm);
2237
2238         return vmexit;
2239 }
2240
2241 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
2242 {
2243         struct vmcb_control_area *dst  = &dst_vmcb->control;
2244         struct vmcb_control_area *from = &from_vmcb->control;
2245
2246         dst->intercept_cr         = from->intercept_cr;
2247         dst->intercept_dr         = from->intercept_dr;
2248         dst->intercept_exceptions = from->intercept_exceptions;
2249         dst->intercept            = from->intercept;
2250         dst->iopm_base_pa         = from->iopm_base_pa;
2251         dst->msrpm_base_pa        = from->msrpm_base_pa;
2252         dst->tsc_offset           = from->tsc_offset;
2253         dst->asid                 = from->asid;
2254         dst->tlb_ctl              = from->tlb_ctl;
2255         dst->int_ctl              = from->int_ctl;
2256         dst->int_vector           = from->int_vector;
2257         dst->int_state            = from->int_state;
2258         dst->exit_code            = from->exit_code;
2259         dst->exit_code_hi         = from->exit_code_hi;
2260         dst->exit_info_1          = from->exit_info_1;
2261         dst->exit_info_2          = from->exit_info_2;
2262         dst->exit_int_info        = from->exit_int_info;
2263         dst->exit_int_info_err    = from->exit_int_info_err;
2264         dst->nested_ctl           = from->nested_ctl;
2265         dst->event_inj            = from->event_inj;
2266         dst->event_inj_err        = from->event_inj_err;
2267         dst->nested_cr3           = from->nested_cr3;
2268         dst->lbr_ctl              = from->lbr_ctl;
2269 }
2270
2271 static int nested_svm_vmexit(struct vcpu_svm *svm)
2272 {
2273         struct vmcb *nested_vmcb;
2274         struct vmcb *hsave = svm->nested.hsave;
2275         struct vmcb *vmcb = svm->vmcb;
2276         struct page *page;
2277
2278         trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
2279                                        vmcb->control.exit_info_1,
2280                                        vmcb->control.exit_info_2,
2281                                        vmcb->control.exit_int_info,
2282                                        vmcb->control.exit_int_info_err,
2283                                        KVM_ISA_SVM);
2284
2285         nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
2286         if (!nested_vmcb)
2287                 return 1;
2288
2289         /* Exit Guest-Mode */
2290         leave_guest_mode(&svm->vcpu);
2291         svm->nested.vmcb = 0;
2292
2293         /* Give the current vmcb to the guest */
2294         disable_gif(svm);
2295
2296         nested_vmcb->save.es     = vmcb->save.es;
2297         nested_vmcb->save.cs     = vmcb->save.cs;
2298         nested_vmcb->save.ss     = vmcb->save.ss;
2299         nested_vmcb->save.ds     = vmcb->save.ds;
2300         nested_vmcb->save.gdtr   = vmcb->save.gdtr;
2301         nested_vmcb->save.idtr   = vmcb->save.idtr;
2302         nested_vmcb->save.efer   = svm->vcpu.arch.efer;
2303         nested_vmcb->save.cr0    = kvm_read_cr0(&svm->vcpu);
2304         nested_vmcb->save.cr3    = kvm_read_cr3(&svm->vcpu);
2305         nested_vmcb->save.cr2    = vmcb->save.cr2;
2306         nested_vmcb->save.cr4    = svm->vcpu.arch.cr4;
2307         nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
2308         nested_vmcb->save.rip    = vmcb->save.rip;
2309         nested_vmcb->save.rsp    = vmcb->save.rsp;
2310         nested_vmcb->save.rax    = vmcb->save.rax;
2311         nested_vmcb->save.dr7    = vmcb->save.dr7;
2312         nested_vmcb->save.dr6    = vmcb->save.dr6;
2313         nested_vmcb->save.cpl    = vmcb->save.cpl;
2314
2315         nested_vmcb->control.int_ctl           = vmcb->control.int_ctl;
2316         nested_vmcb->control.int_vector        = vmcb->control.int_vector;
2317         nested_vmcb->control.int_state         = vmcb->control.int_state;
2318         nested_vmcb->control.exit_code         = vmcb->control.exit_code;
2319         nested_vmcb->control.exit_code_hi      = vmcb->control.exit_code_hi;
2320         nested_vmcb->control.exit_info_1       = vmcb->control.exit_info_1;
2321         nested_vmcb->control.exit_info_2       = vmcb->control.exit_info_2;
2322         nested_vmcb->control.exit_int_info     = vmcb->control.exit_int_info;
2323         nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
2324
2325         if (svm->nrips_enabled)
2326                 nested_vmcb->control.next_rip  = vmcb->control.next_rip;
2327
2328         /*
2329          * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
2330          * to make sure that we do not lose injected events. So check event_inj
2331          * here and copy it to exit_int_info if it is valid.
2332          * Exit_int_info and event_inj can't be both valid because the case
2333          * below only happens on a VMRUN instruction intercept which has
2334          * no valid exit_int_info set.
2335          */
2336         if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
2337                 struct vmcb_control_area *nc = &nested_vmcb->control;
2338
2339                 nc->exit_int_info     = vmcb->control.event_inj;
2340                 nc->exit_int_info_err = vmcb->control.event_inj_err;
2341         }
2342
2343         nested_vmcb->control.tlb_ctl           = 0;
2344         nested_vmcb->control.event_inj         = 0;
2345         nested_vmcb->control.event_inj_err     = 0;
2346
2347         /* We always set V_INTR_MASKING and remember the old value in hflags */
2348         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
2349                 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
2350
2351         /* Restore the original control entries */
2352         copy_vmcb_control_area(vmcb, hsave);
2353
2354         kvm_clear_exception_queue(&svm->vcpu);
2355         kvm_clear_interrupt_queue(&svm->vcpu);
2356
2357         svm->nested.nested_cr3 = 0;
2358
2359         /* Restore selected save entries */
2360         svm->vmcb->save.es = hsave->save.es;
2361         svm->vmcb->save.cs = hsave->save.cs;
2362         svm->vmcb->save.ss = hsave->save.ss;
2363         svm->vmcb->save.ds = hsave->save.ds;
2364         svm->vmcb->save.gdtr = hsave->save.gdtr;
2365         svm->vmcb->save.idtr = hsave->save.idtr;
2366         kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
2367         svm_set_efer(&svm->vcpu, hsave->save.efer);
2368         svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
2369         svm_set_cr4(&svm->vcpu, hsave->save.cr4);
2370         if (npt_enabled) {
2371                 svm->vmcb->save.cr3 = hsave->save.cr3;
2372                 svm->vcpu.arch.cr3 = hsave->save.cr3;
2373         } else {
2374                 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
2375         }
2376         kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
2377         kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
2378         kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
2379         svm->vmcb->save.dr7 = 0;
2380         svm->vmcb->save.cpl = 0;
2381         svm->vmcb->control.exit_int_info = 0;
2382
2383         mark_all_dirty(svm->vmcb);
2384
2385         nested_svm_unmap(page);
2386
2387         nested_svm_uninit_mmu_context(&svm->vcpu);
2388         kvm_mmu_reset_context(&svm->vcpu);
2389         kvm_mmu_load(&svm->vcpu);
2390
2391         /*
2392          * Drop what we picked up for L2 via svm_complete_interrupts() so it
2393          * doesn't end up in L1.
2394          */
2395         svm->vcpu.arch.nmi_injected = false;
2396         kvm_clear_exception_queue(&svm->vcpu);
2397         kvm_clear_interrupt_queue(&svm->vcpu);
2398
2399         return 0;
2400 }
2401
2402 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
2403 {
2404         /*
2405          * This function merges the msr permission bitmaps of kvm and the
2406          * nested vmcb. It is optimized in that it only merges the parts where
2407          * the kvm msr permission bitmap may contain zero bits
2408          */
2409         int i;
2410
2411         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
2412                 return true;
2413
2414         for (i = 0; i < MSRPM_OFFSETS; i++) {
2415                 u32 value, p;
2416                 u64 offset;
2417
2418                 if (msrpm_offsets[i] == 0xffffffff)
2419                         break;
2420
2421                 p      = msrpm_offsets[i];
2422                 offset = svm->nested.vmcb_msrpm + (p * 4);
2423
2424                 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
2425                         return false;
2426
2427                 svm->nested.msrpm[p] = svm->msrpm[p] | value;
2428         }
2429
2430         svm->vmcb->control.msrpm_base_pa = __pa(svm->nested.msrpm);
2431
2432         return true;
2433 }
2434
2435 static bool nested_vmcb_checks(struct vmcb *vmcb)
2436 {
2437         if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
2438                 return false;
2439
2440         if (vmcb->control.asid == 0)
2441                 return false;
2442
2443         if (vmcb->control.nested_ctl && !npt_enabled)
2444                 return false;
2445
2446         return true;
2447 }
2448
2449 static bool nested_svm_vmrun(struct vcpu_svm *svm)
2450 {
2451         struct vmcb *nested_vmcb;
2452         struct vmcb *hsave = svm->nested.hsave;
2453         struct vmcb *vmcb = svm->vmcb;
2454         struct page *page;
2455         u64 vmcb_gpa;
2456
2457         vmcb_gpa = svm->vmcb->save.rax;
2458
2459         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
2460         if (!nested_vmcb)
2461                 return false;
2462
2463         if (!nested_vmcb_checks(nested_vmcb)) {
2464                 nested_vmcb->control.exit_code    = SVM_EXIT_ERR;
2465                 nested_vmcb->control.exit_code_hi = 0;
2466                 nested_vmcb->control.exit_info_1  = 0;
2467                 nested_vmcb->control.exit_info_2  = 0;
2468
2469                 nested_svm_unmap(page);
2470
2471                 return false;
2472         }
2473
2474         trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
2475                                nested_vmcb->save.rip,
2476                                nested_vmcb->control.int_ctl,
2477                                nested_vmcb->control.event_inj,
2478                                nested_vmcb->control.nested_ctl);
2479
2480         trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
2481                                     nested_vmcb->control.intercept_cr >> 16,
2482                                     nested_vmcb->control.intercept_exceptions,
2483                                     nested_vmcb->control.intercept);
2484
2485         /* Clear internal status */
2486         kvm_clear_exception_queue(&svm->vcpu);
2487         kvm_clear_interrupt_queue(&svm->vcpu);
2488
2489         /*
2490          * Save the old vmcb, so we don't need to pick what we save, but can
2491          * restore everything when a VMEXIT occurs
2492          */
2493         hsave->save.es     = vmcb->save.es;
2494         hsave->save.cs     = vmcb->save.cs;
2495         hsave->save.ss     = vmcb->save.ss;
2496         hsave->save.ds     = vmcb->save.ds;
2497         hsave->save.gdtr   = vmcb->save.gdtr;
2498         hsave->save.idtr   = vmcb->save.idtr;
2499         hsave->save.efer   = svm->vcpu.arch.efer;
2500         hsave->save.cr0    = kvm_read_cr0(&svm->vcpu);
2501         hsave->save.cr4    = svm->vcpu.arch.cr4;
2502         hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
2503         hsave->save.rip    = kvm_rip_read(&svm->vcpu);
2504         hsave->save.rsp    = vmcb->save.rsp;
2505         hsave->save.rax    = vmcb->save.rax;
2506         if (npt_enabled)
2507                 hsave->save.cr3    = vmcb->save.cr3;
2508         else
2509                 hsave->save.cr3    = kvm_read_cr3(&svm->vcpu);
2510
2511         copy_vmcb_control_area(hsave, vmcb);
2512
2513         if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
2514                 svm->vcpu.arch.hflags |= HF_HIF_MASK;
2515         else
2516                 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
2517
2518         if (nested_vmcb->control.nested_ctl) {
2519                 kvm_mmu_unload(&svm->vcpu);
2520                 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
2521                 nested_svm_init_mmu_context(&svm->vcpu);
2522         }
2523
2524         /* Load the nested guest state */
2525         svm->vmcb->save.es = nested_vmcb->save.es;
2526         svm->vmcb->save.cs = nested_vmcb->save.cs;
2527         svm->vmcb->save.ss = nested_vmcb->save.ss;
2528         svm->vmcb->save.ds = nested_vmcb->save.ds;
2529         svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
2530         svm->vmcb->save.idtr = nested_vmcb->save.idtr;
2531         kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
2532         svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
2533         svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
2534         svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
2535         if (npt_enabled) {
2536                 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
2537                 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
2538         } else
2539                 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
2540
2541         /* Guest paging mode is active - reset mmu */
2542         kvm_mmu_reset_context(&svm->vcpu);
2543
2544         svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
2545         kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
2546         kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
2547         kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
2548
2549         /* In case we don't even reach vcpu_run, the fields are not updated */
2550         svm->vmcb->save.rax = nested_vmcb->save.rax;
2551         svm->vmcb->save.rsp = nested_vmcb->save.rsp;
2552         svm->vmcb->save.rip = nested_vmcb->save.rip;
2553         svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
2554         svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
2555         svm->vmcb->save.cpl = nested_vmcb->save.cpl;
2556
2557         svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
2558         svm->nested.vmcb_iopm  = nested_vmcb->control.iopm_base_pa  & ~0x0fffULL;
2559
2560         /* cache intercepts */
2561         svm->nested.intercept_cr         = nested_vmcb->control.intercept_cr;
2562         svm->nested.intercept_dr         = nested_vmcb->control.intercept_dr;
2563         svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
2564         svm->nested.intercept            = nested_vmcb->control.intercept;
2565
2566         svm_flush_tlb(&svm->vcpu);
2567         svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
2568         if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
2569                 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
2570         else
2571                 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
2572
2573         if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
2574                 /* We only want the cr8 intercept bits of the guest */
2575                 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
2576                 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
2577         }
2578
2579         /* We don't want to see VMMCALLs from a nested guest */
2580         clr_intercept(svm, INTERCEPT_VMMCALL);
2581
2582         svm->vmcb->control.lbr_ctl = nested_vmcb->control.lbr_ctl;
2583         svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
2584         svm->vmcb->control.int_state = nested_vmcb->control.int_state;
2585         svm->vmcb->control.tsc_offset += nested_vmcb->control.tsc_offset;
2586         svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
2587         svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
2588
2589         nested_svm_unmap(page);
2590
2591         /* Enter Guest-Mode */
2592         enter_guest_mode(&svm->vcpu);
2593
2594         /*
2595          * Merge guest and host intercepts - must be called  with vcpu in
2596          * guest-mode to take affect here
2597          */
2598         recalc_intercepts(svm);
2599
2600         svm->nested.vmcb = vmcb_gpa;
2601
2602         enable_gif(svm);
2603
2604         mark_all_dirty(svm->vmcb);
2605
2606         return true;
2607 }
2608
2609 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
2610 {
2611         to_vmcb->save.fs = from_vmcb->save.fs;
2612         to_vmcb->save.gs = from_vmcb->save.gs;
2613         to_vmcb->save.tr = from_vmcb->save.tr;
2614         to_vmcb->save.ldtr = from_vmcb->save.ldtr;
2615         to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
2616         to_vmcb->save.star = from_vmcb->save.star;
2617         to_vmcb->save.lstar = from_vmcb->save.lstar;
2618         to_vmcb->save.cstar = from_vmcb->save.cstar;
2619         to_vmcb->save.sfmask = from_vmcb->save.sfmask;
2620         to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
2621         to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
2622         to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
2623 }
2624
2625 static int vmload_interception(struct vcpu_svm *svm)
2626 {
2627         struct vmcb *nested_vmcb;
2628         struct page *page;
2629
2630         if (nested_svm_check_permissions(svm))
2631                 return 1;
2632
2633         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
2634         if (!nested_vmcb)
2635                 return 1;
2636
2637         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2638         skip_emulated_instruction(&svm->vcpu);
2639
2640         nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
2641         nested_svm_unmap(page);
2642
2643         return 1;
2644 }
2645
2646 static int vmsave_interception(struct vcpu_svm *svm)
2647 {
2648         struct vmcb *nested_vmcb;
2649         struct page *page;
2650
2651         if (nested_svm_check_permissions(svm))
2652                 return 1;
2653
2654         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
2655         if (!nested_vmcb)
2656                 return 1;
2657
2658         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2659         skip_emulated_instruction(&svm->vcpu);
2660
2661         nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
2662         nested_svm_unmap(page);
2663
2664         return 1;
2665 }
2666
2667 static int vmrun_interception(struct vcpu_svm *svm)
2668 {
2669         if (nested_svm_check_permissions(svm))
2670                 return 1;
2671
2672         /* Save rip after vmrun instruction */
2673         kvm_rip_write(&svm->vcpu, kvm_rip_read(&svm->vcpu) + 3);
2674
2675         if (!nested_svm_vmrun(svm))
2676                 return 1;
2677
2678         if (!nested_svm_vmrun_msrpm(svm))
2679                 goto failed;
2680
2681         return 1;
2682
2683 failed:
2684
2685         svm->vmcb->control.exit_code    = SVM_EXIT_ERR;
2686         svm->vmcb->control.exit_code_hi = 0;
2687         svm->vmcb->control.exit_info_1  = 0;
2688         svm->vmcb->control.exit_info_2  = 0;
2689
2690         nested_svm_vmexit(svm);
2691
2692         return 1;
2693 }
2694
2695 static int stgi_interception(struct vcpu_svm *svm)
2696 {
2697         if (nested_svm_check_permissions(svm))
2698                 return 1;
2699
2700         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2701         skip_emulated_instruction(&svm->vcpu);
2702         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
2703
2704         enable_gif(svm);
2705
2706         return 1;
2707 }
2708
2709 static int clgi_interception(struct vcpu_svm *svm)
2710 {
2711         if (nested_svm_check_permissions(svm))
2712                 return 1;
2713
2714         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2715         skip_emulated_instruction(&svm->vcpu);
2716
2717         disable_gif(svm);
2718
2719         /* After a CLGI no interrupts should come */
2720         svm_clear_vintr(svm);
2721         svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
2722
2723         mark_dirty(svm->vmcb, VMCB_INTR);
2724
2725         return 1;
2726 }
2727
2728 static int invlpga_interception(struct vcpu_svm *svm)
2729 {
2730         struct kvm_vcpu *vcpu = &svm->vcpu;
2731
2732         trace_kvm_invlpga(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RCX),
2733                           kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
2734
2735         /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
2736         kvm_mmu_invlpg(vcpu, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
2737
2738         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2739         skip_emulated_instruction(&svm->vcpu);
2740         return 1;
2741 }
2742
2743 static int skinit_interception(struct vcpu_svm *svm)
2744 {
2745         trace_kvm_skinit(svm->vmcb->save.rip, kvm_register_read(&svm->vcpu, VCPU_REGS_RAX));
2746
2747         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2748         return 1;
2749 }
2750
2751 static int wbinvd_interception(struct vcpu_svm *svm)
2752 {
2753         kvm_emulate_wbinvd(&svm->vcpu);
2754         return 1;
2755 }
2756
2757 static int xsetbv_interception(struct vcpu_svm *svm)
2758 {
2759         u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
2760         u32 index = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
2761
2762         if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
2763                 svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2764                 skip_emulated_instruction(&svm->vcpu);
2765         }
2766
2767         return 1;
2768 }
2769
2770 static int task_switch_interception(struct vcpu_svm *svm)
2771 {
2772         u16 tss_selector;
2773         int reason;
2774         int int_type = svm->vmcb->control.exit_int_info &
2775                 SVM_EXITINTINFO_TYPE_MASK;
2776         int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
2777         uint32_t type =
2778                 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
2779         uint32_t idt_v =
2780                 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
2781         bool has_error_code = false;
2782         u32 error_code = 0;
2783
2784         tss_selector = (u16)svm->vmcb->control.exit_info_1;
2785
2786         if (svm->vmcb->control.exit_info_2 &
2787             (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
2788                 reason = TASK_SWITCH_IRET;
2789         else if (svm->vmcb->control.exit_info_2 &
2790                  (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
2791                 reason = TASK_SWITCH_JMP;
2792         else if (idt_v)
2793                 reason = TASK_SWITCH_GATE;
2794         else
2795                 reason = TASK_SWITCH_CALL;
2796
2797         if (reason == TASK_SWITCH_GATE) {
2798                 switch (type) {
2799                 case SVM_EXITINTINFO_TYPE_NMI:
2800                         svm->vcpu.arch.nmi_injected = false;
2801                         break;
2802                 case SVM_EXITINTINFO_TYPE_EXEPT:
2803                         if (svm->vmcb->control.exit_info_2 &
2804                             (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
2805                                 has_error_code = true;
2806                                 error_code =
2807                                         (u32)svm->vmcb->control.exit_info_2;
2808                         }
2809                         kvm_clear_exception_queue(&svm->vcpu);
2810                         break;
2811                 case SVM_EXITINTINFO_TYPE_INTR:
2812                         kvm_clear_interrupt_queue(&svm->vcpu);
2813                         break;
2814                 default:
2815                         break;
2816                 }
2817         }
2818
2819         if (reason != TASK_SWITCH_GATE ||
2820             int_type == SVM_EXITINTINFO_TYPE_SOFT ||
2821             (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
2822              (int_vec == OF_VECTOR || int_vec == BP_VECTOR)))
2823                 skip_emulated_instruction(&svm->vcpu);
2824
2825         if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
2826                 int_vec = -1;
2827
2828         if (kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
2829                                 has_error_code, error_code) == EMULATE_FAIL) {
2830                 svm->vcpu.run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
2831                 svm->vcpu.run->internal.suberror = KVM_INTERNAL_ERROR_EMULATION;
2832                 svm->vcpu.run->internal.ndata = 0;
2833                 return 0;
2834         }
2835         return 1;
2836 }
2837
2838 static int cpuid_interception(struct vcpu_svm *svm)
2839 {
2840         svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
2841         kvm_emulate_cpuid(&svm->vcpu);
2842         return 1;
2843 }
2844
2845 static int iret_interception(struct vcpu_svm *svm)
2846 {
2847         ++svm->vcpu.stat.nmi_window_exits;
2848         clr_intercept(svm, INTERCEPT_IRET);
2849         svm->vcpu.arch.hflags |= HF_IRET_MASK;
2850         svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
2851         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
2852         return 1;
2853 }
2854
2855 static int invlpg_interception(struct vcpu_svm *svm)
2856 {
2857         if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2858                 return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
2859
2860         kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
2861         skip_emulated_instruction(&svm->vcpu);
2862         return 1;
2863 }
2864
2865 static int emulate_on_interception(struct vcpu_svm *svm)
2866 {
2867         return emulate_instruction(&svm->vcpu, 0) == EMULATE_DONE;
2868 }
2869
2870 static int rdpmc_interception(struct vcpu_svm *svm)
2871 {
2872         int err;
2873
2874         if (!static_cpu_has(X86_FEATURE_NRIPS))
2875                 return emulate_on_interception(svm);
2876
2877         err = kvm_rdpmc(&svm->vcpu);
2878         kvm_complete_insn_gp(&svm->vcpu, err);
2879
2880         return 1;
2881 }
2882
2883 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
2884                                             unsigned long val)
2885 {
2886         unsigned long cr0 = svm->vcpu.arch.cr0;
2887         bool ret = false;
2888         u64 intercept;
2889
2890         intercept = svm->nested.intercept;
2891
2892         if (!is_guest_mode(&svm->vcpu) ||
2893             (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
2894                 return false;
2895
2896         cr0 &= ~SVM_CR0_SELECTIVE_MASK;
2897         val &= ~SVM_CR0_SELECTIVE_MASK;
2898
2899         if (cr0 ^ val) {
2900                 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
2901                 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
2902         }
2903
2904         return ret;
2905 }
2906
2907 #define CR_VALID (1ULL << 63)
2908
2909 static int cr_interception(struct vcpu_svm *svm)
2910 {
2911         int reg, cr;
2912         unsigned long val;
2913         int err;
2914
2915         if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
2916                 return emulate_on_interception(svm);
2917
2918         if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
2919                 return emulate_on_interception(svm);
2920
2921         reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
2922         if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
2923                 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
2924         else
2925                 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
2926
2927         err = 0;
2928         if (cr >= 16) { /* mov to cr */
2929                 cr -= 16;
2930                 val = kvm_register_read(&svm->vcpu, reg);
2931                 switch (cr) {
2932                 case 0:
2933                         if (!check_selective_cr0_intercepted(svm, val))
2934                                 err = kvm_set_cr0(&svm->vcpu, val);
2935                         else
2936                                 return 1;
2937
2938                         break;
2939                 case 3:
2940                         err = kvm_set_cr3(&svm->vcpu, val);
2941                         break;
2942                 case 4:
2943                         err = kvm_set_cr4(&svm->vcpu, val);
2944                         break;
2945                 case 8:
2946                         err = kvm_set_cr8(&svm->vcpu, val);
2947                         break;
2948                 default:
2949                         WARN(1, "unhandled write to CR%d", cr);
2950                         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2951                         return 1;
2952                 }
2953         } else { /* mov from cr */
2954                 switch (cr) {
2955                 case 0:
2956                         val = kvm_read_cr0(&svm->vcpu);
2957                         break;
2958                 case 2:
2959                         val = svm->vcpu.arch.cr2;
2960                         break;
2961                 case 3:
2962                         val = kvm_read_cr3(&svm->vcpu);
2963                         break;
2964                 case 4:
2965                         val = kvm_read_cr4(&svm->vcpu);
2966                         break;
2967                 case 8:
2968                         val = kvm_get_cr8(&svm->vcpu);
2969                         break;
2970                 default:
2971                         WARN(1, "unhandled read from CR%d", cr);
2972                         kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2973                         return 1;
2974                 }
2975                 kvm_register_write(&svm->vcpu, reg, val);
2976         }
2977         kvm_complete_insn_gp(&svm->vcpu, err);
2978
2979         return 1;
2980 }
2981
2982 static int dr_interception(struct vcpu_svm *svm)
2983 {
2984         int reg, dr;
2985         unsigned long val;
2986
2987         if (svm->vcpu.guest_debug == 0) {
2988                 /*
2989                  * No more DR vmexits; force a reload of the debug registers
2990                  * and reenter on this instruction.  The next vmexit will
2991                  * retrieve the full state of the debug registers.
2992                  */
2993                 clr_dr_intercepts(svm);
2994                 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
2995                 return 1;
2996         }
2997
2998         if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
2999                 return emulate_on_interception(svm);
3000
3001         reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3002         dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
3003
3004         if (dr >= 16) { /* mov to DRn */
3005                 if (!kvm_require_dr(&svm->vcpu, dr - 16))
3006                         return 1;
3007                 val = kvm_register_read(&svm->vcpu, reg);
3008                 kvm_set_dr(&svm->vcpu, dr - 16, val);
3009         } else {
3010                 if (!kvm_require_dr(&svm->vcpu, dr))
3011                         return 1;
3012                 kvm_get_dr(&svm->vcpu, dr, &val);
3013                 kvm_register_write(&svm->vcpu, reg, val);
3014         }
3015
3016         skip_emulated_instruction(&svm->vcpu);
3017
3018         return 1;
3019 }
3020
3021 static int cr8_write_interception(struct vcpu_svm *svm)
3022 {
3023         struct kvm_run *kvm_run = svm->vcpu.run;
3024         int r;
3025
3026         u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
3027         /* instruction emulation calls kvm_set_cr8() */
3028         r = cr_interception(svm);
3029         if (lapic_in_kernel(&svm->vcpu))
3030                 return r;
3031         if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
3032                 return r;
3033         kvm_run->exit_reason = KVM_EXIT_SET_TPR;
3034         return 0;
3035 }
3036
3037 static u64 svm_read_l1_tsc(struct kvm_vcpu *vcpu, u64 host_tsc)
3038 {
3039         struct vmcb *vmcb = get_host_vmcb(to_svm(vcpu));
3040         return vmcb->control.tsc_offset + host_tsc;
3041 }
3042
3043 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
3044 {
3045         struct vcpu_svm *svm = to_svm(vcpu);
3046
3047         switch (msr_info->index) {
3048         case MSR_IA32_TSC: {
3049                 msr_info->data = svm->vmcb->control.tsc_offset +
3050                         kvm_scale_tsc(vcpu, rdtsc());
3051
3052                 break;
3053         }
3054         case MSR_STAR:
3055                 msr_info->data = svm->vmcb->save.star;
3056                 break;
3057 #ifdef CONFIG_X86_64
3058         case MSR_LSTAR:
3059                 msr_info->data = svm->vmcb->save.lstar;
3060                 break;
3061         case MSR_CSTAR:
3062                 msr_info->data = svm->vmcb->save.cstar;
3063                 break;
3064         case MSR_KERNEL_GS_BASE:
3065                 msr_info->data = svm->vmcb->save.kernel_gs_base;
3066                 break;
3067         case MSR_SYSCALL_MASK:
3068                 msr_info->data = svm->vmcb->save.sfmask;
3069                 break;
3070 #endif
3071         case MSR_IA32_SYSENTER_CS:
3072                 msr_info->data = svm->vmcb->save.sysenter_cs;
3073                 break;
3074         case MSR_IA32_SYSENTER_EIP:
3075                 msr_info->data = svm->sysenter_eip;
3076                 break;
3077         case MSR_IA32_SYSENTER_ESP:
3078                 msr_info->data = svm->sysenter_esp;
3079                 break;
3080         /*
3081          * Nobody will change the following 5 values in the VMCB so we can
3082          * safely return them on rdmsr. They will always be 0 until LBRV is
3083          * implemented.
3084          */
3085         case MSR_IA32_DEBUGCTLMSR:
3086                 msr_info->data = svm->vmcb->save.dbgctl;
3087                 break;
3088         case MSR_IA32_LASTBRANCHFROMIP:
3089                 msr_info->data = svm->vmcb->save.br_from;
3090                 break;
3091         case MSR_IA32_LASTBRANCHTOIP:
3092                 msr_info->data = svm->vmcb->save.br_to;
3093                 break;
3094         case MSR_IA32_LASTINTFROMIP:
3095                 msr_info->data = svm->vmcb->save.last_excp_from;
3096                 break;
3097         case MSR_IA32_LASTINTTOIP:
3098                 msr_info->data = svm->vmcb->save.last_excp_to;
3099                 break;
3100         case MSR_VM_HSAVE_PA:
3101                 msr_info->data = svm->nested.hsave_msr;
3102                 break;
3103         case MSR_VM_CR:
3104                 msr_info->data = svm->nested.vm_cr_msr;
3105                 break;
3106         case MSR_IA32_SPEC_CTRL:
3107                 if (!msr_info->host_initiated &&
3108                     !guest_cpuid_has_spec_ctrl(vcpu))
3109                         return 1;
3110
3111                 msr_info->data = svm->spec_ctrl;
3112                 break;
3113         case MSR_AMD64_VIRT_SPEC_CTRL:
3114                 if (!msr_info->host_initiated &&
3115                     !guest_cpuid_has_virt_ssbd(vcpu))
3116                         return 1;
3117
3118                 msr_info->data = svm->virt_spec_ctrl;
3119                 break;
3120         case MSR_IA32_UCODE_REV:
3121                 msr_info->data = 0x01000065;
3122                 break;
3123         default:
3124                 return kvm_get_msr_common(vcpu, msr_info);
3125         }
3126         return 0;
3127 }
3128
3129 static int rdmsr_interception(struct vcpu_svm *svm)
3130 {
3131         u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3132         struct msr_data msr_info;
3133
3134         msr_info.index = ecx;
3135         msr_info.host_initiated = false;
3136         if (svm_get_msr(&svm->vcpu, &msr_info)) {
3137                 trace_kvm_msr_read_ex(ecx);
3138                 kvm_inject_gp(&svm->vcpu, 0);
3139         } else {
3140                 trace_kvm_msr_read(ecx, msr_info.data);
3141
3142                 kvm_register_write(&svm->vcpu, VCPU_REGS_RAX,
3143                                    msr_info.data & 0xffffffff);
3144                 kvm_register_write(&svm->vcpu, VCPU_REGS_RDX,
3145                                    msr_info.data >> 32);
3146                 svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3147                 skip_emulated_instruction(&svm->vcpu);
3148         }
3149         return 1;
3150 }
3151
3152 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
3153 {
3154         struct vcpu_svm *svm = to_svm(vcpu);
3155         int svm_dis, chg_mask;
3156
3157         if (data & ~SVM_VM_CR_VALID_MASK)
3158                 return 1;
3159
3160         chg_mask = SVM_VM_CR_VALID_MASK;
3161
3162         if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
3163                 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
3164
3165         svm->nested.vm_cr_msr &= ~chg_mask;
3166         svm->nested.vm_cr_msr |= (data & chg_mask);
3167
3168         svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
3169
3170         /* check for svm_disable while efer.svme is set */
3171         if (svm_dis && (vcpu->arch.efer & EFER_SVME))
3172                 return 1;
3173
3174         return 0;
3175 }
3176
3177 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
3178 {
3179         struct vcpu_svm *svm = to_svm(vcpu);
3180
3181         u32 ecx = msr->index;
3182         u64 data = msr->data;
3183         switch (ecx) {
3184         case MSR_IA32_CR_PAT:
3185                 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
3186                         return 1;
3187                 vcpu->arch.pat = data;
3188                 svm->vmcb->save.g_pat = data;
3189                 mark_dirty(svm->vmcb, VMCB_NPT);
3190                 break;
3191         case MSR_IA32_TSC:
3192                 kvm_write_tsc(vcpu, msr);
3193                 break;
3194         case MSR_IA32_SPEC_CTRL:
3195                 if (!msr->host_initiated &&
3196                     !guest_cpuid_has_spec_ctrl(vcpu))
3197                         return 1;
3198
3199                 /* The STIBP bit doesn't fault even if it's not advertised */
3200                 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
3201                         return 1;
3202
3203                 svm->spec_ctrl = data;
3204
3205                 if (!data)
3206                         break;
3207
3208                 /*
3209                  * For non-nested:
3210                  * When it's written (to non-zero) for the first time, pass
3211                  * it through.
3212                  *
3213                  * For nested:
3214                  * The handling of the MSR bitmap for L2 guests is done in
3215                  * nested_svm_vmrun_msrpm.
3216                  * We update the L1 MSR bit as well since it will end up
3217                  * touching the MSR anyway now.
3218                  */
3219                 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
3220                 break;
3221         case MSR_IA32_PRED_CMD:
3222                 if (!msr->host_initiated &&
3223                     !guest_cpuid_has_ibpb(vcpu))
3224                         return 1;
3225
3226                 if (data & ~PRED_CMD_IBPB)
3227                         return 1;
3228
3229                 if (!data)
3230                         break;
3231
3232                 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
3233                 if (is_guest_mode(vcpu))
3234                         break;
3235                 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
3236                 break;
3237         case MSR_AMD64_VIRT_SPEC_CTRL:
3238                 if (!msr->host_initiated &&
3239                     !guest_cpuid_has_virt_ssbd(vcpu))
3240                         return 1;
3241
3242                 if (data & ~SPEC_CTRL_SSBD)
3243                         return 1;
3244
3245                 svm->virt_spec_ctrl = data;
3246                 break;
3247         case MSR_STAR:
3248                 svm->vmcb->save.star = data;
3249                 break;
3250 #ifdef CONFIG_X86_64
3251         case MSR_LSTAR:
3252                 svm->vmcb->save.lstar = data;
3253                 break;
3254         case MSR_CSTAR:
3255                 svm->vmcb->save.cstar = data;
3256                 break;
3257         case MSR_KERNEL_GS_BASE:
3258                 svm->vmcb->save.kernel_gs_base = data;
3259                 break;
3260         case MSR_SYSCALL_MASK:
3261                 svm->vmcb->save.sfmask = data;
3262                 break;
3263 #endif
3264         case MSR_IA32_SYSENTER_CS:
3265                 svm->vmcb->save.sysenter_cs = data;
3266                 break;
3267         case MSR_IA32_SYSENTER_EIP:
3268                 svm->sysenter_eip = data;
3269                 svm->vmcb->save.sysenter_eip = data;
3270                 break;
3271         case MSR_IA32_SYSENTER_ESP:
3272                 svm->sysenter_esp = data;
3273                 svm->vmcb->save.sysenter_esp = data;
3274                 break;
3275         case MSR_IA32_DEBUGCTLMSR:
3276                 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
3277                         vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
3278                                     __func__, data);
3279                         break;
3280                 }
3281                 if (data & DEBUGCTL_RESERVED_BITS)
3282                         return 1;
3283
3284                 svm->vmcb->save.dbgctl = data;
3285                 mark_dirty(svm->vmcb, VMCB_LBR);
3286                 if (data & (1ULL<<0))
3287                         svm_enable_lbrv(svm);
3288                 else
3289                         svm_disable_lbrv(svm);
3290                 break;
3291         case MSR_VM_HSAVE_PA:
3292                 svm->nested.hsave_msr = data;
3293                 break;
3294         case MSR_VM_CR:
3295                 return svm_set_vm_cr(vcpu, data);
3296         case MSR_VM_IGNNE:
3297                 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
3298                 break;
3299         default:
3300                 return kvm_set_msr_common(vcpu, msr);
3301         }
3302         return 0;
3303 }
3304
3305 static int wrmsr_interception(struct vcpu_svm *svm)
3306 {
3307         struct msr_data msr;
3308         u32 ecx = kvm_register_read(&svm->vcpu, VCPU_REGS_RCX);
3309         u64 data = kvm_read_edx_eax(&svm->vcpu);
3310
3311         msr.data = data;
3312         msr.index = ecx;
3313         msr.host_initiated = false;
3314
3315         svm->next_rip = kvm_rip_read(&svm->vcpu) + 2;
3316         if (kvm_set_msr(&svm->vcpu, &msr)) {
3317                 trace_kvm_msr_write_ex(ecx, data);
3318                 kvm_inject_gp(&svm->vcpu, 0);
3319         } else {
3320                 trace_kvm_msr_write(ecx, data);
3321                 skip_emulated_instruction(&svm->vcpu);
3322         }
3323         return 1;
3324 }
3325
3326 static int msr_interception(struct vcpu_svm *svm)
3327 {
3328         if (svm->vmcb->control.exit_info_1)
3329                 return wrmsr_interception(svm);
3330         else
3331                 return rdmsr_interception(svm);
3332 }
3333
3334 static int interrupt_window_interception(struct vcpu_svm *svm)
3335 {
3336         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3337         svm_clear_vintr(svm);
3338         svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3339         mark_dirty(svm->vmcb, VMCB_INTR);
3340         ++svm->vcpu.stat.irq_window_exits;
3341         return 1;
3342 }
3343
3344 static int pause_interception(struct vcpu_svm *svm)
3345 {
3346         kvm_vcpu_on_spin(&(svm->vcpu));
3347         return 1;
3348 }
3349
3350 static int nop_interception(struct vcpu_svm *svm)
3351 {
3352         skip_emulated_instruction(&(svm->vcpu));
3353         return 1;
3354 }
3355
3356 static int monitor_interception(struct vcpu_svm *svm)
3357 {
3358         printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
3359         return nop_interception(svm);
3360 }
3361
3362 static int mwait_interception(struct vcpu_svm *svm)
3363 {
3364         printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
3365         return nop_interception(svm);
3366 }
3367
3368 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
3369         [SVM_EXIT_READ_CR0]                     = cr_interception,
3370         [SVM_EXIT_READ_CR3]                     = cr_interception,
3371         [SVM_EXIT_READ_CR4]                     = cr_interception,
3372         [SVM_EXIT_READ_CR8]                     = cr_interception,
3373         [SVM_EXIT_CR0_SEL_WRITE]                = cr_interception,
3374         [SVM_EXIT_WRITE_CR0]                    = cr_interception,
3375         [SVM_EXIT_WRITE_CR3]                    = cr_interception,
3376         [SVM_EXIT_WRITE_CR4]                    = cr_interception,
3377         [SVM_EXIT_WRITE_CR8]                    = cr8_write_interception,
3378         [SVM_EXIT_READ_DR0]                     = dr_interception,
3379         [SVM_EXIT_READ_DR1]                     = dr_interception,
3380         [SVM_EXIT_READ_DR2]                     = dr_interception,
3381         [SVM_EXIT_READ_DR3]                     = dr_interception,
3382         [SVM_EXIT_READ_DR4]                     = dr_interception,
3383         [SVM_EXIT_READ_DR5]                     = dr_interception,
3384         [SVM_EXIT_READ_DR6]                     = dr_interception,
3385         [SVM_EXIT_READ_DR7]                     = dr_interception,
3386         [SVM_EXIT_WRITE_DR0]                    = dr_interception,
3387         [SVM_EXIT_WRITE_DR1]                    = dr_interception,
3388         [SVM_EXIT_WRITE_DR2]                    = dr_interception,
3389         [SVM_EXIT_WRITE_DR3]                    = dr_interception,
3390         [SVM_EXIT_WRITE_DR4]                    = dr_interception,
3391         [SVM_EXIT_WRITE_DR5]                    = dr_interception,
3392         [SVM_EXIT_WRITE_DR6]                    = dr_interception,
3393         [SVM_EXIT_WRITE_DR7]                    = dr_interception,
3394         [SVM_EXIT_EXCP_BASE + DB_VECTOR]        = db_interception,
3395         [SVM_EXIT_EXCP_BASE + BP_VECTOR]        = bp_interception,
3396         [SVM_EXIT_EXCP_BASE + UD_VECTOR]        = ud_interception,
3397         [SVM_EXIT_EXCP_BASE + PF_VECTOR]        = pf_interception,
3398         [SVM_EXIT_EXCP_BASE + NM_VECTOR]        = nm_interception,
3399         [SVM_EXIT_EXCP_BASE + MC_VECTOR]        = mc_interception,
3400         [SVM_EXIT_EXCP_BASE + AC_VECTOR]        = ac_interception,
3401         [SVM_EXIT_INTR]                         = intr_interception,
3402         [SVM_EXIT_NMI]                          = nmi_interception,
3403         [SVM_EXIT_SMI]                          = nop_on_interception,
3404         [SVM_EXIT_INIT]                         = nop_on_interception,
3405         [SVM_EXIT_VINTR]                        = interrupt_window_interception,
3406         [SVM_EXIT_RDPMC]                        = rdpmc_interception,
3407         [SVM_EXIT_CPUID]                        = cpuid_interception,
3408         [SVM_EXIT_IRET]                         = iret_interception,
3409         [SVM_EXIT_INVD]                         = emulate_on_interception,
3410         [SVM_EXIT_PAUSE]                        = pause_interception,
3411         [SVM_EXIT_HLT]                          = halt_interception,
3412         [SVM_EXIT_INVLPG]                       = invlpg_interception,
3413         [SVM_EXIT_INVLPGA]                      = invlpga_interception,
3414         [SVM_EXIT_IOIO]                         = io_interception,
3415         [SVM_EXIT_MSR]                          = msr_interception,
3416         [SVM_EXIT_TASK_SWITCH]                  = task_switch_interception,
3417         [SVM_EXIT_SHUTDOWN]                     = shutdown_interception,
3418         [SVM_EXIT_VMRUN]                        = vmrun_interception,
3419         [SVM_EXIT_VMMCALL]                      = vmmcall_interception,
3420         [SVM_EXIT_VMLOAD]                       = vmload_interception,
3421         [SVM_EXIT_VMSAVE]                       = vmsave_interception,
3422         [SVM_EXIT_STGI]                         = stgi_interception,
3423         [SVM_EXIT_CLGI]                         = clgi_interception,
3424         [SVM_EXIT_SKINIT]                       = skinit_interception,
3425         [SVM_EXIT_WBINVD]                       = wbinvd_interception,
3426         [SVM_EXIT_MONITOR]                      = monitor_interception,
3427         [SVM_EXIT_MWAIT]                        = mwait_interception,
3428         [SVM_EXIT_XSETBV]                       = xsetbv_interception,
3429         [SVM_EXIT_NPF]                          = pf_interception,
3430         [SVM_EXIT_RSM]                          = emulate_on_interception,
3431 };
3432
3433 static void dump_vmcb(struct kvm_vcpu *vcpu)
3434 {
3435         struct vcpu_svm *svm = to_svm(vcpu);
3436         struct vmcb_control_area *control = &svm->vmcb->control;
3437         struct vmcb_save_area *save = &svm->vmcb->save;
3438
3439         pr_err("VMCB Control Area:\n");
3440         pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
3441         pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
3442         pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
3443         pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
3444         pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
3445         pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
3446         pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
3447         pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
3448         pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
3449         pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
3450         pr_err("%-20s%d\n", "asid:", control->asid);
3451         pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
3452         pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
3453         pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
3454         pr_err("%-20s%08x\n", "int_state:", control->int_state);
3455         pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
3456         pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
3457         pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
3458         pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
3459         pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
3460         pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
3461         pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
3462         pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
3463         pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
3464         pr_err("%-20s%lld\n", "lbr_ctl:", control->lbr_ctl);
3465         pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
3466         pr_err("VMCB State Save Area:\n");
3467         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3468                "es:",
3469                save->es.selector, save->es.attrib,
3470                save->es.limit, save->es.base);
3471         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3472                "cs:",
3473                save->cs.selector, save->cs.attrib,
3474                save->cs.limit, save->cs.base);
3475         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3476                "ss:",
3477                save->ss.selector, save->ss.attrib,
3478                save->ss.limit, save->ss.base);
3479         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3480                "ds:",
3481                save->ds.selector, save->ds.attrib,
3482                save->ds.limit, save->ds.base);
3483         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3484                "fs:",
3485                save->fs.selector, save->fs.attrib,
3486                save->fs.limit, save->fs.base);
3487         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3488                "gs:",
3489                save->gs.selector, save->gs.attrib,
3490                save->gs.limit, save->gs.base);
3491         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3492                "gdtr:",
3493                save->gdtr.selector, save->gdtr.attrib,
3494                save->gdtr.limit, save->gdtr.base);
3495         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3496                "ldtr:",
3497                save->ldtr.selector, save->ldtr.attrib,
3498                save->ldtr.limit, save->ldtr.base);
3499         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3500                "idtr:",
3501                save->idtr.selector, save->idtr.attrib,
3502                save->idtr.limit, save->idtr.base);
3503         pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
3504                "tr:",
3505                save->tr.selector, save->tr.attrib,
3506                save->tr.limit, save->tr.base);
3507         pr_err("cpl:            %d                efer:         %016llx\n",
3508                 save->cpl, save->efer);
3509         pr_err("%-15s %016llx %-13s %016llx\n",
3510                "cr0:", save->cr0, "cr2:", save->cr2);
3511         pr_err("%-15s %016llx %-13s %016llx\n",
3512                "cr3:", save->cr3, "cr4:", save->cr4);
3513         pr_err("%-15s %016llx %-13s %016llx\n",
3514                "dr6:", save->dr6, "dr7:", save->dr7);
3515         pr_err("%-15s %016llx %-13s %016llx\n",
3516                "rip:", save->rip, "rflags:", save->rflags);
3517         pr_err("%-15s %016llx %-13s %016llx\n",
3518                "rsp:", save->rsp, "rax:", save->rax);
3519         pr_err("%-15s %016llx %-13s %016llx\n",
3520                "star:", save->star, "lstar:", save->lstar);
3521         pr_err("%-15s %016llx %-13s %016llx\n",
3522                "cstar:", save->cstar, "sfmask:", save->sfmask);
3523         pr_err("%-15s %016llx %-13s %016llx\n",
3524                "kernel_gs_base:", save->kernel_gs_base,
3525                "sysenter_cs:", save->sysenter_cs);
3526         pr_err("%-15s %016llx %-13s %016llx\n",
3527                "sysenter_esp:", save->sysenter_esp,
3528                "sysenter_eip:", save->sysenter_eip);
3529         pr_err("%-15s %016llx %-13s %016llx\n",
3530                "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
3531         pr_err("%-15s %016llx %-13s %016llx\n",
3532                "br_from:", save->br_from, "br_to:", save->br_to);
3533         pr_err("%-15s %016llx %-13s %016llx\n",
3534                "excp_from:", save->last_excp_from,
3535                "excp_to:", save->last_excp_to);
3536 }
3537
3538 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
3539 {
3540         struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
3541
3542         *info1 = control->exit_info_1;
3543         *info2 = control->exit_info_2;
3544 }
3545
3546 static int handle_exit(struct kvm_vcpu *vcpu)
3547 {
3548         struct vcpu_svm *svm = to_svm(vcpu);
3549         struct kvm_run *kvm_run = vcpu->run;
3550         u32 exit_code = svm->vmcb->control.exit_code;
3551
3552         trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
3553
3554         if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
3555                 vcpu->arch.cr0 = svm->vmcb->save.cr0;
3556         if (npt_enabled)
3557                 vcpu->arch.cr3 = svm->vmcb->save.cr3;
3558
3559         if (unlikely(svm->nested.exit_required)) {
3560                 nested_svm_vmexit(svm);
3561                 svm->nested.exit_required = false;
3562
3563                 return 1;
3564         }
3565
3566         if (is_guest_mode(vcpu)) {
3567                 int vmexit;
3568
3569                 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
3570                                         svm->vmcb->control.exit_info_1,
3571                                         svm->vmcb->control.exit_info_2,
3572                                         svm->vmcb->control.exit_int_info,
3573                                         svm->vmcb->control.exit_int_info_err,
3574                                         KVM_ISA_SVM);
3575
3576                 vmexit = nested_svm_exit_special(svm);
3577
3578                 if (vmexit == NESTED_EXIT_CONTINUE)
3579                         vmexit = nested_svm_exit_handled(svm);
3580
3581                 if (vmexit == NESTED_EXIT_DONE)
3582                         return 1;
3583         }
3584
3585         svm_complete_interrupts(svm);
3586
3587         if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
3588                 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
3589                 kvm_run->fail_entry.hardware_entry_failure_reason
3590                         = svm->vmcb->control.exit_code;
3591                 pr_err("KVM: FAILED VMRUN WITH VMCB:\n");
3592                 dump_vmcb(vcpu);
3593                 return 0;
3594         }
3595
3596         if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
3597             exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
3598             exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
3599             exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
3600                 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
3601                        "exit_code 0x%x\n",
3602                        __func__, svm->vmcb->control.exit_int_info,
3603                        exit_code);
3604
3605         if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
3606             || !svm_exit_handlers[exit_code]) {
3607                 WARN_ONCE(1, "svm: unexpected exit reason 0x%x\n", exit_code);
3608                 kvm_queue_exception(vcpu, UD_VECTOR);
3609                 return 1;
3610         }
3611
3612         return svm_exit_handlers[exit_code](svm);
3613 }
3614
3615 static void reload_tss(struct kvm_vcpu *vcpu)
3616 {
3617         int cpu = raw_smp_processor_id();
3618
3619         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
3620         sd->tss_desc->type = 9; /* available 32/64-bit TSS */
3621         load_TR_desc();
3622 }
3623
3624 static void pre_svm_run(struct vcpu_svm *svm)
3625 {
3626         int cpu = raw_smp_processor_id();
3627
3628         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
3629
3630         /* FIXME: handle wraparound of asid_generation */
3631         if (svm->asid_generation != sd->asid_generation)
3632                 new_asid(svm, sd);
3633 }
3634
3635 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
3636 {
3637         struct vcpu_svm *svm = to_svm(vcpu);
3638
3639         svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
3640         vcpu->arch.hflags |= HF_NMI_MASK;
3641         set_intercept(svm, INTERCEPT_IRET);
3642         ++vcpu->stat.nmi_injections;
3643 }
3644
3645 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
3646 {
3647         struct vmcb_control_area *control;
3648
3649         control = &svm->vmcb->control;
3650         control->int_vector = irq;
3651         control->int_ctl &= ~V_INTR_PRIO_MASK;
3652         control->int_ctl |= V_IRQ_MASK |
3653                 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
3654         mark_dirty(svm->vmcb, VMCB_INTR);
3655 }
3656
3657 static void svm_set_irq(struct kvm_vcpu *vcpu)
3658 {
3659         struct vcpu_svm *svm = to_svm(vcpu);
3660
3661         BUG_ON(!(gif_set(svm)));
3662
3663         trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
3664         ++vcpu->stat.irq_injections;
3665
3666         svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
3667                 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
3668 }
3669
3670 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
3671 {
3672         struct vcpu_svm *svm = to_svm(vcpu);
3673
3674         if (is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK))
3675                 return;
3676
3677         clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3678
3679         if (irr == -1)
3680                 return;
3681
3682         if (tpr >= irr)
3683                 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3684 }
3685
3686 static void svm_set_virtual_x2apic_mode(struct kvm_vcpu *vcpu, bool set)
3687 {
3688         return;
3689 }
3690
3691 static int svm_cpu_uses_apicv(struct kvm_vcpu *vcpu)
3692 {
3693         return 0;
3694 }
3695
3696 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu)
3697 {
3698         return;
3699 }
3700
3701 static void svm_sync_pir_to_irr(struct kvm_vcpu *vcpu)
3702 {
3703         return;
3704 }
3705
3706 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
3707 {
3708         struct vcpu_svm *svm = to_svm(vcpu);
3709         struct vmcb *vmcb = svm->vmcb;
3710         int ret;
3711         ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
3712               !(svm->vcpu.arch.hflags & HF_NMI_MASK);
3713         ret = ret && gif_set(svm) && nested_svm_nmi(svm);
3714
3715         return ret;
3716 }
3717
3718 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
3719 {
3720         struct vcpu_svm *svm = to_svm(vcpu);
3721
3722         return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
3723 }
3724
3725 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
3726 {
3727         struct vcpu_svm *svm = to_svm(vcpu);
3728
3729         if (masked) {
3730                 svm->vcpu.arch.hflags |= HF_NMI_MASK;
3731                 set_intercept(svm, INTERCEPT_IRET);
3732         } else {
3733                 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
3734                 clr_intercept(svm, INTERCEPT_IRET);
3735         }
3736 }
3737
3738 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
3739 {
3740         struct vcpu_svm *svm = to_svm(vcpu);
3741         struct vmcb *vmcb = svm->vmcb;
3742         int ret;
3743
3744         if (!gif_set(svm) ||
3745              (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
3746                 return 0;
3747
3748         ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
3749
3750         if (is_guest_mode(vcpu))
3751                 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
3752
3753         return ret;
3754 }
3755
3756 static void enable_irq_window(struct kvm_vcpu *vcpu)
3757 {
3758         struct vcpu_svm *svm = to_svm(vcpu);
3759
3760         /*
3761          * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
3762          * 1, because that's a separate STGI/VMRUN intercept.  The next time we
3763          * get that intercept, this function will be called again though and
3764          * we'll get the vintr intercept.
3765          */
3766         if (gif_set(svm) && nested_svm_intr(svm)) {
3767                 svm_set_vintr(svm);
3768                 svm_inject_irq(svm, 0x0);
3769         }
3770 }
3771
3772 static void enable_nmi_window(struct kvm_vcpu *vcpu)
3773 {
3774         struct vcpu_svm *svm = to_svm(vcpu);
3775
3776         if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
3777             == HF_NMI_MASK)
3778                 return; /* IRET will cause a vm exit */
3779
3780         /*
3781          * Something prevents NMI from been injected. Single step over possible
3782          * problem (IRET or exception injection or interrupt shadow)
3783          */
3784         svm->nmi_singlestep = true;
3785         svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
3786 }
3787
3788 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
3789 {
3790         return 0;
3791 }
3792
3793 static void svm_flush_tlb(struct kvm_vcpu *vcpu)
3794 {
3795         struct vcpu_svm *svm = to_svm(vcpu);
3796
3797         if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
3798                 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
3799         else
3800                 svm->asid_generation--;
3801 }
3802
3803 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
3804 {
3805 }
3806
3807 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
3808 {
3809         struct vcpu_svm *svm = to_svm(vcpu);
3810
3811         if (is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK))
3812                 return;
3813
3814         if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
3815                 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
3816                 kvm_set_cr8(vcpu, cr8);
3817         }
3818 }
3819
3820 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
3821 {
3822         struct vcpu_svm *svm = to_svm(vcpu);
3823         u64 cr8;
3824
3825         if (is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK))
3826                 return;
3827
3828         cr8 = kvm_get_cr8(vcpu);
3829         svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
3830         svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
3831 }
3832
3833 static void svm_complete_interrupts(struct vcpu_svm *svm)
3834 {
3835         u8 vector;
3836         int type;
3837         u32 exitintinfo = svm->vmcb->control.exit_int_info;
3838         unsigned int3_injected = svm->int3_injected;
3839
3840         svm->int3_injected = 0;
3841
3842         /*
3843          * If we've made progress since setting HF_IRET_MASK, we've
3844          * executed an IRET and can allow NMI injection.
3845          */
3846         if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
3847             && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
3848                 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
3849                 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3850         }
3851
3852         svm->vcpu.arch.nmi_injected = false;
3853         kvm_clear_exception_queue(&svm->vcpu);
3854         kvm_clear_interrupt_queue(&svm->vcpu);
3855
3856         if (!(exitintinfo & SVM_EXITINTINFO_VALID))
3857                 return;
3858
3859         kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3860
3861         vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
3862         type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
3863
3864         switch (type) {
3865         case SVM_EXITINTINFO_TYPE_NMI:
3866                 svm->vcpu.arch.nmi_injected = true;
3867                 break;
3868         case SVM_EXITINTINFO_TYPE_EXEPT:
3869                 /*
3870                  * In case of software exceptions, do not reinject the vector,
3871                  * but re-execute the instruction instead. Rewind RIP first
3872                  * if we emulated INT3 before.
3873                  */
3874                 if (kvm_exception_is_soft(vector)) {
3875                         if (vector == BP_VECTOR && int3_injected &&
3876                             kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
3877                                 kvm_rip_write(&svm->vcpu,
3878                                               kvm_rip_read(&svm->vcpu) -
3879                                               int3_injected);
3880                         break;
3881                 }
3882                 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
3883                         u32 err = svm->vmcb->control.exit_int_info_err;
3884                         kvm_requeue_exception_e(&svm->vcpu, vector, err);
3885
3886                 } else
3887                         kvm_requeue_exception(&svm->vcpu, vector);
3888                 break;
3889         case SVM_EXITINTINFO_TYPE_INTR:
3890                 kvm_queue_interrupt(&svm->vcpu, vector, false);
3891                 break;
3892         default:
3893                 break;
3894         }
3895 }
3896
3897 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
3898 {
3899         struct vcpu_svm *svm = to_svm(vcpu);
3900         struct vmcb_control_area *control = &svm->vmcb->control;
3901
3902         control->exit_int_info = control->event_inj;
3903         control->exit_int_info_err = control->event_inj_err;
3904         control->event_inj = 0;
3905         svm_complete_interrupts(svm);
3906 }
3907
3908 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
3909 {
3910         struct vcpu_svm *svm = to_svm(vcpu);
3911
3912         svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
3913         svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
3914         svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
3915
3916         /*
3917          * A vmexit emulation is required before the vcpu can be executed
3918          * again.
3919          */
3920         if (unlikely(svm->nested.exit_required))
3921                 return;
3922
3923         pre_svm_run(svm);
3924
3925         sync_lapic_to_cr8(vcpu);
3926
3927         svm->vmcb->save.cr2 = vcpu->arch.cr2;
3928
3929         clgi();
3930
3931         /*
3932          * If this vCPU has touched SPEC_CTRL, restore the guest's value if
3933          * it's non-zero. Since vmentry is serialising on affected CPUs, there
3934          * is no need to worry about the conditional branch over the wrmsr
3935          * being speculatively taken.
3936          */
3937         x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
3938
3939         local_irq_enable();
3940
3941         asm volatile (
3942                 "push %%" _ASM_BP "; \n\t"
3943                 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
3944                 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
3945                 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
3946                 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
3947                 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
3948                 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
3949 #ifdef CONFIG_X86_64
3950                 "mov %c[r8](%[svm]),  %%r8  \n\t"
3951                 "mov %c[r9](%[svm]),  %%r9  \n\t"
3952                 "mov %c[r10](%[svm]), %%r10 \n\t"
3953                 "mov %c[r11](%[svm]), %%r11 \n\t"
3954                 "mov %c[r12](%[svm]), %%r12 \n\t"
3955                 "mov %c[r13](%[svm]), %%r13 \n\t"
3956                 "mov %c[r14](%[svm]), %%r14 \n\t"
3957                 "mov %c[r15](%[svm]), %%r15 \n\t"
3958 #endif
3959
3960                 /* Enter guest mode */
3961                 "push %%" _ASM_AX " \n\t"
3962                 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
3963                 __ex(SVM_VMLOAD) "\n\t"
3964                 __ex(SVM_VMRUN) "\n\t"
3965                 __ex(SVM_VMSAVE) "\n\t"
3966                 "pop %%" _ASM_AX " \n\t"
3967
3968                 /* Save guest registers, load host registers */
3969                 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
3970                 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
3971                 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
3972                 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
3973                 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
3974                 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
3975 #ifdef CONFIG_X86_64
3976                 "mov %%r8,  %c[r8](%[svm]) \n\t"
3977                 "mov %%r9,  %c[r9](%[svm]) \n\t"
3978                 "mov %%r10, %c[r10](%[svm]) \n\t"
3979                 "mov %%r11, %c[r11](%[svm]) \n\t"
3980                 "mov %%r12, %c[r12](%[svm]) \n\t"
3981                 "mov %%r13, %c[r13](%[svm]) \n\t"
3982                 "mov %%r14, %c[r14](%[svm]) \n\t"
3983                 "mov %%r15, %c[r15](%[svm]) \n\t"
3984 #endif
3985                 /*
3986                 * Clear host registers marked as clobbered to prevent
3987                 * speculative use.
3988                 */
3989                 "xor %%" _ASM_BX ", %%" _ASM_BX " \n\t"
3990                 "xor %%" _ASM_CX ", %%" _ASM_CX " \n\t"
3991                 "xor %%" _ASM_DX ", %%" _ASM_DX " \n\t"
3992                 "xor %%" _ASM_SI ", %%" _ASM_SI " \n\t"
3993                 "xor %%" _ASM_DI ", %%" _ASM_DI " \n\t"
3994 #ifdef CONFIG_X86_64
3995                 "xor %%r8, %%r8 \n\t"
3996                 "xor %%r9, %%r9 \n\t"
3997                 "xor %%r10, %%r10 \n\t"
3998                 "xor %%r11, %%r11 \n\t"
3999                 "xor %%r12, %%r12 \n\t"
4000                 "xor %%r13, %%r13 \n\t"
4001                 "xor %%r14, %%r14 \n\t"
4002                 "xor %%r15, %%r15 \n\t"
4003 #endif
4004                 "pop %%" _ASM_BP
4005                 :
4006                 : [svm]"a"(svm),
4007                   [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
4008                   [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
4009                   [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
4010                   [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
4011                   [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
4012                   [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
4013                   [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
4014 #ifdef CONFIG_X86_64
4015                   , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
4016                   [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
4017                   [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
4018                   [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
4019                   [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
4020                   [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
4021                   [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
4022                   [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
4023 #endif
4024                 : "cc", "memory"
4025 #ifdef CONFIG_X86_64
4026                 , "rbx", "rcx", "rdx", "rsi", "rdi"
4027                 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
4028 #else
4029                 , "ebx", "ecx", "edx", "esi", "edi"
4030 #endif
4031                 );
4032
4033         /* Eliminate branch target predictions from guest mode */
4034         vmexit_fill_RSB();
4035
4036 #ifdef CONFIG_X86_64
4037         wrmsrl(MSR_GS_BASE, svm->host.gs_base);
4038 #else
4039         loadsegment(fs, svm->host.fs);
4040 #ifndef CONFIG_X86_32_LAZY_GS
4041         loadsegment(gs, svm->host.gs);
4042 #endif
4043 #endif
4044
4045         /*
4046          * We do not use IBRS in the kernel. If this vCPU has used the
4047          * SPEC_CTRL MSR it may have left it on; save the value and
4048          * turn it off. This is much more efficient than blindly adding
4049          * it to the atomic save/restore list. Especially as the former
4050          * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
4051          *
4052          * For non-nested case:
4053          * If the L01 MSR bitmap does not intercept the MSR, then we need to
4054          * save it.
4055          *
4056          * For nested case:
4057          * If the L02 MSR bitmap does not intercept the MSR, then we need to
4058          * save it.
4059          */
4060         if (!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL))
4061                 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
4062
4063         reload_tss(vcpu);
4064
4065         local_irq_disable();
4066
4067         x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
4068
4069         vcpu->arch.cr2 = svm->vmcb->save.cr2;
4070         vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
4071         vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
4072         vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
4073
4074         if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
4075                 kvm_before_handle_nmi(&svm->vcpu);
4076
4077         stgi();
4078
4079         /* Any pending NMI will happen here */
4080
4081         if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
4082                 kvm_after_handle_nmi(&svm->vcpu);
4083
4084         sync_cr8_to_lapic(vcpu);
4085
4086         svm->next_rip = 0;
4087
4088         svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
4089
4090         /* if exit due to PF check for async PF */
4091         if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
4092                 svm->apf_reason = kvm_read_and_reset_pf_reason();
4093
4094         if (npt_enabled) {
4095                 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
4096                 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
4097         }
4098
4099         /*
4100          * We need to handle MC intercepts here before the vcpu has a chance to
4101          * change the physical cpu
4102          */
4103         if (unlikely(svm->vmcb->control.exit_code ==
4104                      SVM_EXIT_EXCP_BASE + MC_VECTOR))
4105                 svm_handle_mce(svm);
4106
4107         mark_all_clean(svm->vmcb);
4108 }
4109
4110 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
4111 {
4112         struct vcpu_svm *svm = to_svm(vcpu);
4113
4114         svm->vmcb->save.cr3 = root;
4115         mark_dirty(svm->vmcb, VMCB_CR);
4116         svm_flush_tlb(vcpu);
4117 }
4118
4119 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
4120 {
4121         struct vcpu_svm *svm = to_svm(vcpu);
4122
4123         svm->vmcb->control.nested_cr3 = root;
4124         mark_dirty(svm->vmcb, VMCB_NPT);
4125
4126         /* Also sync guest cr3 here in case we live migrate */
4127         svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
4128         mark_dirty(svm->vmcb, VMCB_CR);
4129
4130         svm_flush_tlb(vcpu);
4131 }
4132
4133 static int is_disabled(void)
4134 {
4135         u64 vm_cr;
4136
4137         rdmsrl(MSR_VM_CR, vm_cr);
4138         if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
4139                 return 1;
4140
4141         return 0;
4142 }
4143
4144 static void
4145 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
4146 {
4147         /*
4148          * Patch in the VMMCALL instruction:
4149          */
4150         hypercall[0] = 0x0f;
4151         hypercall[1] = 0x01;
4152         hypercall[2] = 0xd9;
4153 }
4154
4155 static void svm_check_processor_compat(void *rtn)
4156 {
4157         *(int *)rtn = 0;
4158 }
4159
4160 static bool svm_cpu_has_accelerated_tpr(void)
4161 {
4162         return false;
4163 }
4164
4165 static bool svm_has_emulated_msr(int index)
4166 {
4167         switch (index) {
4168         case MSR_IA32_MCG_EXT_CTL:
4169                 return false;
4170         default:
4171                 break;
4172         }
4173
4174         return true;
4175 }
4176
4177 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
4178 {
4179         return 0;
4180 }
4181
4182 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
4183 {
4184         struct vcpu_svm *svm = to_svm(vcpu);
4185
4186         /* Update nrips enabled cache */
4187         svm->nrips_enabled = !!guest_cpuid_has_nrips(&svm->vcpu);
4188 }
4189
4190 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
4191 {
4192         switch (func) {
4193         case 0x80000001:
4194                 if (nested)
4195                         entry->ecx |= (1 << 2); /* Set SVM bit */
4196                 break;
4197         case 0x8000000A:
4198                 entry->eax = 1; /* SVM revision 1 */
4199                 entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
4200                                    ASID emulation to nested SVM */
4201                 entry->ecx = 0; /* Reserved */
4202                 entry->edx = 0; /* Per default do not support any
4203                                    additional features */
4204
4205                 /* Support next_rip if host supports it */
4206                 if (boot_cpu_has(X86_FEATURE_NRIPS))
4207                         entry->edx |= SVM_FEATURE_NRIP;
4208
4209                 /* Support NPT for the guest if enabled */
4210                 if (npt_enabled)
4211                         entry->edx |= SVM_FEATURE_NPT;
4212
4213                 break;
4214         }
4215 }
4216
4217 static int svm_get_lpage_level(void)
4218 {
4219         return PT_PDPE_LEVEL;
4220 }
4221
4222 static bool svm_rdtscp_supported(void)
4223 {
4224         return false;
4225 }
4226
4227 static bool svm_invpcid_supported(void)
4228 {
4229         return false;
4230 }
4231
4232 static bool svm_mpx_supported(void)
4233 {
4234         return false;
4235 }
4236
4237 static bool svm_xsaves_supported(void)
4238 {
4239         return false;
4240 }
4241
4242 static bool svm_has_wbinvd_exit(void)
4243 {
4244         return true;
4245 }
4246
4247 static void svm_fpu_deactivate(struct kvm_vcpu *vcpu)
4248 {
4249         struct vcpu_svm *svm = to_svm(vcpu);
4250
4251         set_exception_intercept(svm, NM_VECTOR);
4252         update_cr0_intercept(svm);
4253 }
4254
4255 #define PRE_EX(exit)  { .exit_code = (exit), \
4256                         .stage = X86_ICPT_PRE_EXCEPT, }
4257 #define POST_EX(exit) { .exit_code = (exit), \
4258                         .stage = X86_ICPT_POST_EXCEPT, }
4259 #define POST_MEM(exit) { .exit_code = (exit), \
4260                         .stage = X86_ICPT_POST_MEMACCESS, }
4261
4262 static const struct __x86_intercept {
4263         u32 exit_code;
4264         enum x86_intercept_stage stage;
4265 } x86_intercept_map[] = {
4266         [x86_intercept_cr_read]         = POST_EX(SVM_EXIT_READ_CR0),
4267         [x86_intercept_cr_write]        = POST_EX(SVM_EXIT_WRITE_CR0),
4268         [x86_intercept_clts]            = POST_EX(SVM_EXIT_WRITE_CR0),
4269         [x86_intercept_lmsw]            = POST_EX(SVM_EXIT_WRITE_CR0),
4270         [x86_intercept_smsw]            = POST_EX(SVM_EXIT_READ_CR0),
4271         [x86_intercept_dr_read]         = POST_EX(SVM_EXIT_READ_DR0),
4272         [x86_intercept_dr_write]        = POST_EX(SVM_EXIT_WRITE_DR0),
4273         [x86_intercept_sldt]            = POST_EX(SVM_EXIT_LDTR_READ),
4274         [x86_intercept_str]             = POST_EX(SVM_EXIT_TR_READ),
4275         [x86_intercept_lldt]            = POST_EX(SVM_EXIT_LDTR_WRITE),
4276         [x86_intercept_ltr]             = POST_EX(SVM_EXIT_TR_WRITE),
4277         [x86_intercept_sgdt]            = POST_EX(SVM_EXIT_GDTR_READ),
4278         [x86_intercept_sidt]            = POST_EX(SVM_EXIT_IDTR_READ),
4279         [x86_intercept_lgdt]            = POST_EX(SVM_EXIT_GDTR_WRITE),
4280         [x86_intercept_lidt]            = POST_EX(SVM_EXIT_IDTR_WRITE),
4281         [x86_intercept_vmrun]           = POST_EX(SVM_EXIT_VMRUN),
4282         [x86_intercept_vmmcall]         = POST_EX(SVM_EXIT_VMMCALL),
4283         [x86_intercept_vmload]          = POST_EX(SVM_EXIT_VMLOAD),
4284         [x86_intercept_vmsave]          = POST_EX(SVM_EXIT_VMSAVE),
4285         [x86_intercept_stgi]            = POST_EX(SVM_EXIT_STGI),
4286         [x86_intercept_clgi]            = POST_EX(SVM_EXIT_CLGI),
4287         [x86_intercept_skinit]          = POST_EX(SVM_EXIT_SKINIT),
4288         [x86_intercept_invlpga]         = POST_EX(SVM_EXIT_INVLPGA),
4289         [x86_intercept_rdtscp]          = POST_EX(SVM_EXIT_RDTSCP),
4290         [x86_intercept_monitor]         = POST_MEM(SVM_EXIT_MONITOR),
4291         [x86_intercept_mwait]           = POST_EX(SVM_EXIT_MWAIT),
4292         [x86_intercept_invlpg]          = POST_EX(SVM_EXIT_INVLPG),
4293         [x86_intercept_invd]            = POST_EX(SVM_EXIT_INVD),
4294         [x86_intercept_wbinvd]          = POST_EX(SVM_EXIT_WBINVD),
4295         [x86_intercept_wrmsr]           = POST_EX(SVM_EXIT_MSR),
4296         [x86_intercept_rdtsc]           = POST_EX(SVM_EXIT_RDTSC),
4297         [x86_intercept_rdmsr]           = POST_EX(SVM_EXIT_MSR),
4298         [x86_intercept_rdpmc]           = POST_EX(SVM_EXIT_RDPMC),
4299         [x86_intercept_cpuid]           = PRE_EX(SVM_EXIT_CPUID),
4300         [x86_intercept_rsm]             = PRE_EX(SVM_EXIT_RSM),
4301         [x86_intercept_pause]           = PRE_EX(SVM_EXIT_PAUSE),
4302         [x86_intercept_pushf]           = PRE_EX(SVM_EXIT_PUSHF),
4303         [x86_intercept_popf]            = PRE_EX(SVM_EXIT_POPF),
4304         [x86_intercept_intn]            = PRE_EX(SVM_EXIT_SWINT),
4305         [x86_intercept_iret]            = PRE_EX(SVM_EXIT_IRET),
4306         [x86_intercept_icebp]           = PRE_EX(SVM_EXIT_ICEBP),
4307         [x86_intercept_hlt]             = POST_EX(SVM_EXIT_HLT),
4308         [x86_intercept_in]              = POST_EX(SVM_EXIT_IOIO),
4309         [x86_intercept_ins]             = POST_EX(SVM_EXIT_IOIO),
4310         [x86_intercept_out]             = POST_EX(SVM_EXIT_IOIO),
4311         [x86_intercept_outs]            = POST_EX(SVM_EXIT_IOIO),
4312 };
4313
4314 #undef PRE_EX
4315 #undef POST_EX
4316 #undef POST_MEM
4317
4318 static int svm_check_intercept(struct kvm_vcpu *vcpu,
4319                                struct x86_instruction_info *info,
4320                                enum x86_intercept_stage stage)
4321 {
4322         struct vcpu_svm *svm = to_svm(vcpu);
4323         int vmexit, ret = X86EMUL_CONTINUE;
4324         struct __x86_intercept icpt_info;
4325         struct vmcb *vmcb = svm->vmcb;
4326
4327         if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
4328                 goto out;
4329
4330         icpt_info = x86_intercept_map[info->intercept];
4331
4332         if (stage != icpt_info.stage)
4333                 goto out;
4334
4335         switch (icpt_info.exit_code) {
4336         case SVM_EXIT_READ_CR0:
4337                 if (info->intercept == x86_intercept_cr_read)
4338                         icpt_info.exit_code += info->modrm_reg;
4339                 break;
4340         case SVM_EXIT_WRITE_CR0: {
4341                 unsigned long cr0, val;
4342                 u64 intercept;
4343
4344                 if (info->intercept == x86_intercept_cr_write)
4345                         icpt_info.exit_code += info->modrm_reg;
4346
4347                 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
4348                     info->intercept == x86_intercept_clts)
4349                         break;
4350
4351                 intercept = svm->nested.intercept;
4352
4353                 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
4354                         break;
4355
4356                 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
4357                 val = info->src_val  & ~SVM_CR0_SELECTIVE_MASK;
4358
4359                 if (info->intercept == x86_intercept_lmsw) {
4360                         cr0 &= 0xfUL;
4361                         val &= 0xfUL;
4362                         /* lmsw can't clear PE - catch this here */
4363                         if (cr0 & X86_CR0_PE)
4364                                 val |= X86_CR0_PE;
4365                 }
4366
4367                 if (cr0 ^ val)
4368                         icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
4369
4370                 break;
4371         }
4372         case SVM_EXIT_READ_DR0:
4373         case SVM_EXIT_WRITE_DR0:
4374                 icpt_info.exit_code += info->modrm_reg;
4375                 break;
4376         case SVM_EXIT_MSR:
4377                 if (info->intercept == x86_intercept_wrmsr)
4378                         vmcb->control.exit_info_1 = 1;
4379                 else
4380                         vmcb->control.exit_info_1 = 0;
4381                 break;
4382         case SVM_EXIT_PAUSE:
4383                 /*
4384                  * We get this for NOP only, but pause
4385                  * is rep not, check this here
4386                  */
4387                 if (info->rep_prefix != REPE_PREFIX)
4388                         goto out;
4389         case SVM_EXIT_IOIO: {
4390                 u64 exit_info;
4391                 u32 bytes;
4392
4393                 if (info->intercept == x86_intercept_in ||
4394                     info->intercept == x86_intercept_ins) {
4395                         exit_info = ((info->src_val & 0xffff) << 16) |
4396                                 SVM_IOIO_TYPE_MASK;
4397                         bytes = info->dst_bytes;
4398                 } else {
4399                         exit_info = (info->dst_val & 0xffff) << 16;
4400                         bytes = info->src_bytes;
4401                 }
4402
4403                 if (info->intercept == x86_intercept_outs ||
4404                     info->intercept == x86_intercept_ins)
4405                         exit_info |= SVM_IOIO_STR_MASK;
4406
4407                 if (info->rep_prefix)
4408                         exit_info |= SVM_IOIO_REP_MASK;
4409
4410                 bytes = min(bytes, 4u);
4411
4412                 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
4413
4414                 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
4415
4416                 vmcb->control.exit_info_1 = exit_info;
4417                 vmcb->control.exit_info_2 = info->next_rip;
4418
4419                 break;
4420         }
4421         default:
4422                 break;
4423         }
4424
4425         /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
4426         if (static_cpu_has(X86_FEATURE_NRIPS))
4427                 vmcb->control.next_rip  = info->next_rip;
4428         vmcb->control.exit_code = icpt_info.exit_code;
4429         vmexit = nested_svm_exit_handled(svm);
4430
4431         ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
4432                                            : X86EMUL_CONTINUE;
4433
4434 out:
4435         return ret;
4436 }
4437
4438 static void svm_handle_external_intr(struct kvm_vcpu *vcpu)
4439 {
4440         local_irq_enable();
4441 }
4442
4443 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
4444 {
4445 }
4446
4447 static struct kvm_x86_ops svm_x86_ops = {
4448         .cpu_has_kvm_support = has_svm,
4449         .disabled_by_bios = is_disabled,
4450         .hardware_setup = svm_hardware_setup,
4451         .hardware_unsetup = svm_hardware_unsetup,
4452         .check_processor_compatibility = svm_check_processor_compat,
4453         .hardware_enable = svm_hardware_enable,
4454         .hardware_disable = svm_hardware_disable,
4455         .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
4456         .has_emulated_msr = svm_has_emulated_msr,
4457
4458         .vcpu_create = svm_create_vcpu,
4459         .vcpu_free = svm_free_vcpu,
4460         .vcpu_reset = svm_vcpu_reset,
4461
4462         .prepare_guest_switch = svm_prepare_guest_switch,
4463         .vcpu_load = svm_vcpu_load,
4464         .vcpu_put = svm_vcpu_put,
4465
4466         .update_bp_intercept = update_bp_intercept,
4467         .get_msr = svm_get_msr,
4468         .set_msr = svm_set_msr,
4469         .get_segment_base = svm_get_segment_base,
4470         .get_segment = svm_get_segment,
4471         .set_segment = svm_set_segment,
4472         .get_cpl = svm_get_cpl,
4473         .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
4474         .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
4475         .decache_cr3 = svm_decache_cr3,
4476         .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
4477         .set_cr0 = svm_set_cr0,
4478         .set_cr3 = svm_set_cr3,
4479         .set_cr4 = svm_set_cr4,
4480         .set_efer = svm_set_efer,
4481         .get_idt = svm_get_idt,
4482         .set_idt = svm_set_idt,
4483         .get_gdt = svm_get_gdt,
4484         .set_gdt = svm_set_gdt,
4485         .get_dr6 = svm_get_dr6,
4486         .set_dr6 = svm_set_dr6,
4487         .set_dr7 = svm_set_dr7,
4488         .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
4489         .cache_reg = svm_cache_reg,
4490         .get_rflags = svm_get_rflags,
4491         .set_rflags = svm_set_rflags,
4492         .fpu_activate = svm_fpu_activate,
4493         .fpu_deactivate = svm_fpu_deactivate,
4494
4495         .tlb_flush = svm_flush_tlb,
4496
4497         .run = svm_vcpu_run,
4498         .handle_exit = handle_exit,
4499         .skip_emulated_instruction = skip_emulated_instruction,
4500         .set_interrupt_shadow = svm_set_interrupt_shadow,
4501         .get_interrupt_shadow = svm_get_interrupt_shadow,
4502         .patch_hypercall = svm_patch_hypercall,
4503         .set_irq = svm_set_irq,
4504         .set_nmi = svm_inject_nmi,
4505         .queue_exception = svm_queue_exception,
4506         .cancel_injection = svm_cancel_injection,
4507         .interrupt_allowed = svm_interrupt_allowed,
4508         .nmi_allowed = svm_nmi_allowed,
4509         .get_nmi_mask = svm_get_nmi_mask,
4510         .set_nmi_mask = svm_set_nmi_mask,
4511         .enable_nmi_window = enable_nmi_window,
4512         .enable_irq_window = enable_irq_window,
4513         .update_cr8_intercept = update_cr8_intercept,
4514         .set_virtual_x2apic_mode = svm_set_virtual_x2apic_mode,
4515         .cpu_uses_apicv = svm_cpu_uses_apicv,
4516         .load_eoi_exitmap = svm_load_eoi_exitmap,
4517         .sync_pir_to_irr = svm_sync_pir_to_irr,
4518
4519         .set_tss_addr = svm_set_tss_addr,
4520         .get_tdp_level = get_npt_level,
4521         .get_mt_mask = svm_get_mt_mask,
4522
4523         .get_exit_info = svm_get_exit_info,
4524
4525         .get_lpage_level = svm_get_lpage_level,
4526
4527         .cpuid_update = svm_cpuid_update,
4528
4529         .rdtscp_supported = svm_rdtscp_supported,
4530         .invpcid_supported = svm_invpcid_supported,
4531         .mpx_supported = svm_mpx_supported,
4532         .xsaves_supported = svm_xsaves_supported,
4533
4534         .set_supported_cpuid = svm_set_supported_cpuid,
4535
4536         .has_wbinvd_exit = svm_has_wbinvd_exit,
4537
4538         .read_tsc_offset = svm_read_tsc_offset,
4539         .write_tsc_offset = svm_write_tsc_offset,
4540         .adjust_tsc_offset_guest = svm_adjust_tsc_offset_guest,
4541         .read_l1_tsc = svm_read_l1_tsc,
4542
4543         .set_tdp_cr3 = set_tdp_cr3,
4544
4545         .check_intercept = svm_check_intercept,
4546         .handle_external_intr = svm_handle_external_intr,
4547
4548         .sched_in = svm_sched_in,
4549
4550         .pmu_ops = &amd_pmu_ops,
4551 };
4552
4553 static int __init svm_init(void)
4554 {
4555         return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
4556                         __alignof__(struct vcpu_svm), THIS_MODULE);
4557 }
4558
4559 static void __exit svm_exit(void)
4560 {
4561         kvm_exit();
4562 }
4563
4564 module_init(svm_init)
4565 module_exit(svm_exit)