i2c: imx: don't leak the i2c adapter on error
[muen/linux.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
18 #define pr_fmt(fmt) "SVM: " fmt
19
20 #include <linux/kvm_host.h>
21
22 #include "irq.h"
23 #include "mmu.h"
24 #include "kvm_cache_regs.h"
25 #include "x86.h"
26 #include "cpuid.h"
27 #include "pmu.h"
28
29 #include <linux/module.h>
30 #include <linux/mod_devicetable.h>
31 #include <linux/kernel.h>
32 #include <linux/vmalloc.h>
33 #include <linux/highmem.h>
34 #include <linux/sched.h>
35 #include <linux/trace_events.h>
36 #include <linux/slab.h>
37 #include <linux/amd-iommu.h>
38 #include <linux/hashtable.h>
39 #include <linux/frame.h>
40 #include <linux/psp-sev.h>
41 #include <linux/file.h>
42 #include <linux/pagemap.h>
43 #include <linux/swap.h>
44
45 #include <asm/apic.h>
46 #include <asm/perf_event.h>
47 #include <asm/tlbflush.h>
48 #include <asm/desc.h>
49 #include <asm/debugreg.h>
50 #include <asm/kvm_para.h>
51 #include <asm/irq_remapping.h>
52 #include <asm/spec-ctrl.h>
53
54 #include <asm/virtext.h>
55 #include "trace.h"
56
57 #define __ex(x) __kvm_handle_fault_on_reboot(x)
58
59 MODULE_AUTHOR("Qumranet");
60 MODULE_LICENSE("GPL");
61
62 static const struct x86_cpu_id svm_cpu_id[] = {
63         X86_FEATURE_MATCH(X86_FEATURE_SVM),
64         {}
65 };
66 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
67
68 #define IOPM_ALLOC_ORDER 2
69 #define MSRPM_ALLOC_ORDER 1
70
71 #define SEG_TYPE_LDT 2
72 #define SEG_TYPE_BUSY_TSS16 3
73
74 #define SVM_FEATURE_NPT            (1 <<  0)
75 #define SVM_FEATURE_LBRV           (1 <<  1)
76 #define SVM_FEATURE_SVML           (1 <<  2)
77 #define SVM_FEATURE_NRIP           (1 <<  3)
78 #define SVM_FEATURE_TSC_RATE       (1 <<  4)
79 #define SVM_FEATURE_VMCB_CLEAN     (1 <<  5)
80 #define SVM_FEATURE_FLUSH_ASID     (1 <<  6)
81 #define SVM_FEATURE_DECODE_ASSIST  (1 <<  7)
82 #define SVM_FEATURE_PAUSE_FILTER   (1 << 10)
83
84 #define SVM_AVIC_DOORBELL       0xc001011b
85
86 #define NESTED_EXIT_HOST        0       /* Exit handled on host level */
87 #define NESTED_EXIT_DONE        1       /* Exit caused nested vmexit  */
88 #define NESTED_EXIT_CONTINUE    2       /* Further checks needed      */
89
90 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
91
92 #define TSC_RATIO_RSVD          0xffffff0000000000ULL
93 #define TSC_RATIO_MIN           0x0000000000000001ULL
94 #define TSC_RATIO_MAX           0x000000ffffffffffULL
95
96 #define AVIC_HPA_MASK   ~((0xFFFULL << 52) | 0xFFF)
97
98 /*
99  * 0xff is broadcast, so the max index allowed for physical APIC ID
100  * table is 0xfe.  APIC IDs above 0xff are reserved.
101  */
102 #define AVIC_MAX_PHYSICAL_ID_COUNT      255
103
104 #define AVIC_UNACCEL_ACCESS_WRITE_MASK          1
105 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK         0xFF0
106 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK         0xFFFFFFFF
107
108 /* AVIC GATAG is encoded using VM and VCPU IDs */
109 #define AVIC_VCPU_ID_BITS               8
110 #define AVIC_VCPU_ID_MASK               ((1 << AVIC_VCPU_ID_BITS) - 1)
111
112 #define AVIC_VM_ID_BITS                 24
113 #define AVIC_VM_ID_NR                   (1 << AVIC_VM_ID_BITS)
114 #define AVIC_VM_ID_MASK                 ((1 << AVIC_VM_ID_BITS) - 1)
115
116 #define AVIC_GATAG(x, y)                (((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
117                                                 (y & AVIC_VCPU_ID_MASK))
118 #define AVIC_GATAG_TO_VMID(x)           ((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
119 #define AVIC_GATAG_TO_VCPUID(x)         (x & AVIC_VCPU_ID_MASK)
120
121 static bool erratum_383_found __read_mostly;
122
123 static const u32 host_save_user_msrs[] = {
124 #ifdef CONFIG_X86_64
125         MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
126         MSR_FS_BASE,
127 #endif
128         MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
129         MSR_TSC_AUX,
130 };
131
132 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
133
134 struct kvm_sev_info {
135         bool active;            /* SEV enabled guest */
136         unsigned int asid;      /* ASID used for this guest */
137         unsigned int handle;    /* SEV firmware handle */
138         int fd;                 /* SEV device fd */
139         unsigned long pages_locked; /* Number of pages locked */
140         struct list_head regions_list;  /* List of registered regions */
141 };
142
143 struct kvm_svm {
144         struct kvm kvm;
145
146         /* Struct members for AVIC */
147         u32 avic_vm_id;
148         struct page *avic_logical_id_table_page;
149         struct page *avic_physical_id_table_page;
150         struct hlist_node hnode;
151
152         struct kvm_sev_info sev_info;
153 };
154
155 struct kvm_vcpu;
156
157 struct nested_state {
158         struct vmcb *hsave;
159         u64 hsave_msr;
160         u64 vm_cr_msr;
161         u64 vmcb;
162
163         /* These are the merged vectors */
164         u32 *msrpm;
165
166         /* gpa pointers to the real vectors */
167         u64 vmcb_msrpm;
168         u64 vmcb_iopm;
169
170         /* A VMEXIT is required but not yet emulated */
171         bool exit_required;
172
173         /* cache for intercepts of the guest */
174         u32 intercept_cr;
175         u32 intercept_dr;
176         u32 intercept_exceptions;
177         u64 intercept;
178
179         /* Nested Paging related state */
180         u64 nested_cr3;
181 };
182
183 #define MSRPM_OFFSETS   16
184 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
185
186 /*
187  * Set osvw_len to higher value when updated Revision Guides
188  * are published and we know what the new status bits are
189  */
190 static uint64_t osvw_len = 4, osvw_status;
191
192 struct vcpu_svm {
193         struct kvm_vcpu vcpu;
194         struct vmcb *vmcb;
195         unsigned long vmcb_pa;
196         struct svm_cpu_data *svm_data;
197         uint64_t asid_generation;
198         uint64_t sysenter_esp;
199         uint64_t sysenter_eip;
200         uint64_t tsc_aux;
201
202         u64 msr_decfg;
203
204         u64 next_rip;
205
206         u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
207         struct {
208                 u16 fs;
209                 u16 gs;
210                 u16 ldt;
211                 u64 gs_base;
212         } host;
213
214         u64 spec_ctrl;
215         /*
216          * Contains guest-controlled bits of VIRT_SPEC_CTRL, which will be
217          * translated into the appropriate L2_CFG bits on the host to
218          * perform speculative control.
219          */
220         u64 virt_spec_ctrl;
221
222         u32 *msrpm;
223
224         ulong nmi_iret_rip;
225
226         struct nested_state nested;
227
228         bool nmi_singlestep;
229         u64 nmi_singlestep_guest_rflags;
230
231         unsigned int3_injected;
232         unsigned long int3_rip;
233
234         /* cached guest cpuid flags for faster access */
235         bool nrips_enabled      : 1;
236
237         u32 ldr_reg;
238         u32 dfr_reg;
239         struct page *avic_backing_page;
240         u64 *avic_physical_id_cache;
241         bool avic_is_running;
242
243         /*
244          * Per-vcpu list of struct amd_svm_iommu_ir:
245          * This is used mainly to store interrupt remapping information used
246          * when update the vcpu affinity. This avoids the need to scan for
247          * IRTE and try to match ga_tag in the IOMMU driver.
248          */
249         struct list_head ir_list;
250         spinlock_t ir_list_lock;
251
252         /* which host CPU was used for running this vcpu */
253         unsigned int last_cpu;
254 };
255
256 /*
257  * This is a wrapper of struct amd_iommu_ir_data.
258  */
259 struct amd_svm_iommu_ir {
260         struct list_head node;  /* Used by SVM for per-vcpu ir_list */
261         void *data;             /* Storing pointer to struct amd_ir_data */
262 };
263
264 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK    (0xFF)
265 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK                (1 << 31)
266
267 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK    (0xFFULL)
268 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK        (0xFFFFFFFFFFULL << 12)
269 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK          (1ULL << 62)
270 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK               (1ULL << 63)
271
272 static DEFINE_PER_CPU(u64, current_tsc_ratio);
273 #define TSC_RATIO_DEFAULT       0x0100000000ULL
274
275 #define MSR_INVALID                     0xffffffffU
276
277 static const struct svm_direct_access_msrs {
278         u32 index;   /* Index of the MSR */
279         bool always; /* True if intercept is always on */
280 } direct_access_msrs[] = {
281         { .index = MSR_STAR,                            .always = true  },
282         { .index = MSR_IA32_SYSENTER_CS,                .always = true  },
283 #ifdef CONFIG_X86_64
284         { .index = MSR_GS_BASE,                         .always = true  },
285         { .index = MSR_FS_BASE,                         .always = true  },
286         { .index = MSR_KERNEL_GS_BASE,                  .always = true  },
287         { .index = MSR_LSTAR,                           .always = true  },
288         { .index = MSR_CSTAR,                           .always = true  },
289         { .index = MSR_SYSCALL_MASK,                    .always = true  },
290 #endif
291         { .index = MSR_IA32_SPEC_CTRL,                  .always = false },
292         { .index = MSR_IA32_PRED_CMD,                   .always = false },
293         { .index = MSR_IA32_LASTBRANCHFROMIP,           .always = false },
294         { .index = MSR_IA32_LASTBRANCHTOIP,             .always = false },
295         { .index = MSR_IA32_LASTINTFROMIP,              .always = false },
296         { .index = MSR_IA32_LASTINTTOIP,                .always = false },
297         { .index = MSR_INVALID,                         .always = false },
298 };
299
300 /* enable NPT for AMD64 and X86 with PAE */
301 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
302 static bool npt_enabled = true;
303 #else
304 static bool npt_enabled;
305 #endif
306
307 /*
308  * These 2 parameters are used to config the controls for Pause-Loop Exiting:
309  * pause_filter_count: On processors that support Pause filtering(indicated
310  *      by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
311  *      count value. On VMRUN this value is loaded into an internal counter.
312  *      Each time a pause instruction is executed, this counter is decremented
313  *      until it reaches zero at which time a #VMEXIT is generated if pause
314  *      intercept is enabled. Refer to  AMD APM Vol 2 Section 15.14.4 Pause
315  *      Intercept Filtering for more details.
316  *      This also indicate if ple logic enabled.
317  *
318  * pause_filter_thresh: In addition, some processor families support advanced
319  *      pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
320  *      the amount of time a guest is allowed to execute in a pause loop.
321  *      In this mode, a 16-bit pause filter threshold field is added in the
322  *      VMCB. The threshold value is a cycle count that is used to reset the
323  *      pause counter. As with simple pause filtering, VMRUN loads the pause
324  *      count value from VMCB into an internal counter. Then, on each pause
325  *      instruction the hardware checks the elapsed number of cycles since
326  *      the most recent pause instruction against the pause filter threshold.
327  *      If the elapsed cycle count is greater than the pause filter threshold,
328  *      then the internal pause count is reloaded from the VMCB and execution
329  *      continues. If the elapsed cycle count is less than the pause filter
330  *      threshold, then the internal pause count is decremented. If the count
331  *      value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
332  *      triggered. If advanced pause filtering is supported and pause filter
333  *      threshold field is set to zero, the filter will operate in the simpler,
334  *      count only mode.
335  */
336
337 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
338 module_param(pause_filter_thresh, ushort, 0444);
339
340 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
341 module_param(pause_filter_count, ushort, 0444);
342
343 /* Default doubles per-vcpu window every exit. */
344 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
345 module_param(pause_filter_count_grow, ushort, 0444);
346
347 /* Default resets per-vcpu window every exit to pause_filter_count. */
348 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
349 module_param(pause_filter_count_shrink, ushort, 0444);
350
351 /* Default is to compute the maximum so we can never overflow. */
352 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
353 module_param(pause_filter_count_max, ushort, 0444);
354
355 /* allow nested paging (virtualized MMU) for all guests */
356 static int npt = true;
357 module_param(npt, int, S_IRUGO);
358
359 /* allow nested virtualization in KVM/SVM */
360 static int nested = true;
361 module_param(nested, int, S_IRUGO);
362
363 /* enable / disable AVIC */
364 static int avic;
365 #ifdef CONFIG_X86_LOCAL_APIC
366 module_param(avic, int, S_IRUGO);
367 #endif
368
369 /* enable/disable Virtual VMLOAD VMSAVE */
370 static int vls = true;
371 module_param(vls, int, 0444);
372
373 /* enable/disable Virtual GIF */
374 static int vgif = true;
375 module_param(vgif, int, 0444);
376
377 /* enable/disable SEV support */
378 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
379 module_param(sev, int, 0444);
380
381 static u8 rsm_ins_bytes[] = "\x0f\xaa";
382
383 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
384 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
385 static void svm_complete_interrupts(struct vcpu_svm *svm);
386
387 static int nested_svm_exit_handled(struct vcpu_svm *svm);
388 static int nested_svm_intercept(struct vcpu_svm *svm);
389 static int nested_svm_vmexit(struct vcpu_svm *svm);
390 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
391                                       bool has_error_code, u32 error_code);
392
393 enum {
394         VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
395                             pause filter count */
396         VMCB_PERM_MAP,   /* IOPM Base and MSRPM Base */
397         VMCB_ASID,       /* ASID */
398         VMCB_INTR,       /* int_ctl, int_vector */
399         VMCB_NPT,        /* npt_en, nCR3, gPAT */
400         VMCB_CR,         /* CR0, CR3, CR4, EFER */
401         VMCB_DR,         /* DR6, DR7 */
402         VMCB_DT,         /* GDT, IDT */
403         VMCB_SEG,        /* CS, DS, SS, ES, CPL */
404         VMCB_CR2,        /* CR2 only */
405         VMCB_LBR,        /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
406         VMCB_AVIC,       /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
407                           * AVIC PHYSICAL_TABLE pointer,
408                           * AVIC LOGICAL_TABLE pointer
409                           */
410         VMCB_DIRTY_MAX,
411 };
412
413 /* TPR and CR2 are always written before VMRUN */
414 #define VMCB_ALWAYS_DIRTY_MASK  ((1U << VMCB_INTR) | (1U << VMCB_CR2))
415
416 #define VMCB_AVIC_APIC_BAR_MASK         0xFFFFFFFFFF000ULL
417
418 static unsigned int max_sev_asid;
419 static unsigned int min_sev_asid;
420 static unsigned long *sev_asid_bitmap;
421 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
422
423 struct enc_region {
424         struct list_head list;
425         unsigned long npages;
426         struct page **pages;
427         unsigned long uaddr;
428         unsigned long size;
429 };
430
431
432 static inline struct kvm_svm *to_kvm_svm(struct kvm *kvm)
433 {
434         return container_of(kvm, struct kvm_svm, kvm);
435 }
436
437 static inline bool svm_sev_enabled(void)
438 {
439         return IS_ENABLED(CONFIG_KVM_AMD_SEV) ? max_sev_asid : 0;
440 }
441
442 static inline bool sev_guest(struct kvm *kvm)
443 {
444 #ifdef CONFIG_KVM_AMD_SEV
445         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
446
447         return sev->active;
448 #else
449         return false;
450 #endif
451 }
452
453 static inline int sev_get_asid(struct kvm *kvm)
454 {
455         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
456
457         return sev->asid;
458 }
459
460 static inline void mark_all_dirty(struct vmcb *vmcb)
461 {
462         vmcb->control.clean = 0;
463 }
464
465 static inline void mark_all_clean(struct vmcb *vmcb)
466 {
467         vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
468                                & ~VMCB_ALWAYS_DIRTY_MASK;
469 }
470
471 static inline void mark_dirty(struct vmcb *vmcb, int bit)
472 {
473         vmcb->control.clean &= ~(1 << bit);
474 }
475
476 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
477 {
478         return container_of(vcpu, struct vcpu_svm, vcpu);
479 }
480
481 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
482 {
483         svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
484         mark_dirty(svm->vmcb, VMCB_AVIC);
485 }
486
487 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
488 {
489         struct vcpu_svm *svm = to_svm(vcpu);
490         u64 *entry = svm->avic_physical_id_cache;
491
492         if (!entry)
493                 return false;
494
495         return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
496 }
497
498 static void recalc_intercepts(struct vcpu_svm *svm)
499 {
500         struct vmcb_control_area *c, *h;
501         struct nested_state *g;
502
503         mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
504
505         if (!is_guest_mode(&svm->vcpu))
506                 return;
507
508         c = &svm->vmcb->control;
509         h = &svm->nested.hsave->control;
510         g = &svm->nested;
511
512         c->intercept_cr = h->intercept_cr | g->intercept_cr;
513         c->intercept_dr = h->intercept_dr | g->intercept_dr;
514         c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
515         c->intercept = h->intercept | g->intercept;
516 }
517
518 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
519 {
520         if (is_guest_mode(&svm->vcpu))
521                 return svm->nested.hsave;
522         else
523                 return svm->vmcb;
524 }
525
526 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
527 {
528         struct vmcb *vmcb = get_host_vmcb(svm);
529
530         vmcb->control.intercept_cr |= (1U << bit);
531
532         recalc_intercepts(svm);
533 }
534
535 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
536 {
537         struct vmcb *vmcb = get_host_vmcb(svm);
538
539         vmcb->control.intercept_cr &= ~(1U << bit);
540
541         recalc_intercepts(svm);
542 }
543
544 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
545 {
546         struct vmcb *vmcb = get_host_vmcb(svm);
547
548         return vmcb->control.intercept_cr & (1U << bit);
549 }
550
551 static inline void set_dr_intercepts(struct vcpu_svm *svm)
552 {
553         struct vmcb *vmcb = get_host_vmcb(svm);
554
555         vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
556                 | (1 << INTERCEPT_DR1_READ)
557                 | (1 << INTERCEPT_DR2_READ)
558                 | (1 << INTERCEPT_DR3_READ)
559                 | (1 << INTERCEPT_DR4_READ)
560                 | (1 << INTERCEPT_DR5_READ)
561                 | (1 << INTERCEPT_DR6_READ)
562                 | (1 << INTERCEPT_DR7_READ)
563                 | (1 << INTERCEPT_DR0_WRITE)
564                 | (1 << INTERCEPT_DR1_WRITE)
565                 | (1 << INTERCEPT_DR2_WRITE)
566                 | (1 << INTERCEPT_DR3_WRITE)
567                 | (1 << INTERCEPT_DR4_WRITE)
568                 | (1 << INTERCEPT_DR5_WRITE)
569                 | (1 << INTERCEPT_DR6_WRITE)
570                 | (1 << INTERCEPT_DR7_WRITE);
571
572         recalc_intercepts(svm);
573 }
574
575 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
576 {
577         struct vmcb *vmcb = get_host_vmcb(svm);
578
579         vmcb->control.intercept_dr = 0;
580
581         recalc_intercepts(svm);
582 }
583
584 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
585 {
586         struct vmcb *vmcb = get_host_vmcb(svm);
587
588         vmcb->control.intercept_exceptions |= (1U << bit);
589
590         recalc_intercepts(svm);
591 }
592
593 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
594 {
595         struct vmcb *vmcb = get_host_vmcb(svm);
596
597         vmcb->control.intercept_exceptions &= ~(1U << bit);
598
599         recalc_intercepts(svm);
600 }
601
602 static inline void set_intercept(struct vcpu_svm *svm, int bit)
603 {
604         struct vmcb *vmcb = get_host_vmcb(svm);
605
606         vmcb->control.intercept |= (1ULL << bit);
607
608         recalc_intercepts(svm);
609 }
610
611 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
612 {
613         struct vmcb *vmcb = get_host_vmcb(svm);
614
615         vmcb->control.intercept &= ~(1ULL << bit);
616
617         recalc_intercepts(svm);
618 }
619
620 static inline bool vgif_enabled(struct vcpu_svm *svm)
621 {
622         return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
623 }
624
625 static inline void enable_gif(struct vcpu_svm *svm)
626 {
627         if (vgif_enabled(svm))
628                 svm->vmcb->control.int_ctl |= V_GIF_MASK;
629         else
630                 svm->vcpu.arch.hflags |= HF_GIF_MASK;
631 }
632
633 static inline void disable_gif(struct vcpu_svm *svm)
634 {
635         if (vgif_enabled(svm))
636                 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
637         else
638                 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
639 }
640
641 static inline bool gif_set(struct vcpu_svm *svm)
642 {
643         if (vgif_enabled(svm))
644                 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
645         else
646                 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
647 }
648
649 static unsigned long iopm_base;
650
651 struct kvm_ldttss_desc {
652         u16 limit0;
653         u16 base0;
654         unsigned base1:8, type:5, dpl:2, p:1;
655         unsigned limit1:4, zero0:3, g:1, base2:8;
656         u32 base3;
657         u32 zero1;
658 } __attribute__((packed));
659
660 struct svm_cpu_data {
661         int cpu;
662
663         u64 asid_generation;
664         u32 max_asid;
665         u32 next_asid;
666         u32 min_asid;
667         struct kvm_ldttss_desc *tss_desc;
668
669         struct page *save_area;
670         struct vmcb *current_vmcb;
671
672         /* index = sev_asid, value = vmcb pointer */
673         struct vmcb **sev_vmcbs;
674 };
675
676 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
677
678 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
679
680 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
681 #define MSRS_RANGE_SIZE 2048
682 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
683
684 static u32 svm_msrpm_offset(u32 msr)
685 {
686         u32 offset;
687         int i;
688
689         for (i = 0; i < NUM_MSR_MAPS; i++) {
690                 if (msr < msrpm_ranges[i] ||
691                     msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
692                         continue;
693
694                 offset  = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
695                 offset += (i * MSRS_RANGE_SIZE);       /* add range offset */
696
697                 /* Now we have the u8 offset - but need the u32 offset */
698                 return offset / 4;
699         }
700
701         /* MSR not in any range */
702         return MSR_INVALID;
703 }
704
705 #define MAX_INST_SIZE 15
706
707 static inline void clgi(void)
708 {
709         asm volatile (__ex("clgi"));
710 }
711
712 static inline void stgi(void)
713 {
714         asm volatile (__ex("stgi"));
715 }
716
717 static inline void invlpga(unsigned long addr, u32 asid)
718 {
719         asm volatile (__ex("invlpga %1, %0") : : "c"(asid), "a"(addr));
720 }
721
722 static int get_npt_level(struct kvm_vcpu *vcpu)
723 {
724 #ifdef CONFIG_X86_64
725         return PT64_ROOT_4LEVEL;
726 #else
727         return PT32E_ROOT_LEVEL;
728 #endif
729 }
730
731 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
732 {
733         vcpu->arch.efer = efer;
734         if (!npt_enabled && !(efer & EFER_LMA))
735                 efer &= ~EFER_LME;
736
737         to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
738         mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
739 }
740
741 static int is_external_interrupt(u32 info)
742 {
743         info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
744         return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
745 }
746
747 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
748 {
749         struct vcpu_svm *svm = to_svm(vcpu);
750         u32 ret = 0;
751
752         if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
753                 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
754         return ret;
755 }
756
757 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
758 {
759         struct vcpu_svm *svm = to_svm(vcpu);
760
761         if (mask == 0)
762                 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
763         else
764                 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
765
766 }
767
768 static void skip_emulated_instruction(struct kvm_vcpu *vcpu)
769 {
770         struct vcpu_svm *svm = to_svm(vcpu);
771
772         if (svm->vmcb->control.next_rip != 0) {
773                 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
774                 svm->next_rip = svm->vmcb->control.next_rip;
775         }
776
777         if (!svm->next_rip) {
778                 if (kvm_emulate_instruction(vcpu, EMULTYPE_SKIP) !=
779                                 EMULATE_DONE)
780                         printk(KERN_DEBUG "%s: NOP\n", __func__);
781                 return;
782         }
783         if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
784                 printk(KERN_ERR "%s: ip 0x%lx next 0x%llx\n",
785                        __func__, kvm_rip_read(vcpu), svm->next_rip);
786
787         kvm_rip_write(vcpu, svm->next_rip);
788         svm_set_interrupt_shadow(vcpu, 0);
789 }
790
791 static void svm_queue_exception(struct kvm_vcpu *vcpu)
792 {
793         struct vcpu_svm *svm = to_svm(vcpu);
794         unsigned nr = vcpu->arch.exception.nr;
795         bool has_error_code = vcpu->arch.exception.has_error_code;
796         bool reinject = vcpu->arch.exception.injected;
797         u32 error_code = vcpu->arch.exception.error_code;
798
799         /*
800          * If we are within a nested VM we'd better #VMEXIT and let the guest
801          * handle the exception
802          */
803         if (!reinject &&
804             nested_svm_check_exception(svm, nr, has_error_code, error_code))
805                 return;
806
807         kvm_deliver_exception_payload(&svm->vcpu);
808
809         if (nr == BP_VECTOR && !static_cpu_has(X86_FEATURE_NRIPS)) {
810                 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
811
812                 /*
813                  * For guest debugging where we have to reinject #BP if some
814                  * INT3 is guest-owned:
815                  * Emulate nRIP by moving RIP forward. Will fail if injection
816                  * raises a fault that is not intercepted. Still better than
817                  * failing in all cases.
818                  */
819                 skip_emulated_instruction(&svm->vcpu);
820                 rip = kvm_rip_read(&svm->vcpu);
821                 svm->int3_rip = rip + svm->vmcb->save.cs.base;
822                 svm->int3_injected = rip - old_rip;
823         }
824
825         svm->vmcb->control.event_inj = nr
826                 | SVM_EVTINJ_VALID
827                 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
828                 | SVM_EVTINJ_TYPE_EXEPT;
829         svm->vmcb->control.event_inj_err = error_code;
830 }
831
832 static void svm_init_erratum_383(void)
833 {
834         u32 low, high;
835         int err;
836         u64 val;
837
838         if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
839                 return;
840
841         /* Use _safe variants to not break nested virtualization */
842         val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
843         if (err)
844                 return;
845
846         val |= (1ULL << 47);
847
848         low  = lower_32_bits(val);
849         high = upper_32_bits(val);
850
851         native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
852
853         erratum_383_found = true;
854 }
855
856 static void svm_init_osvw(struct kvm_vcpu *vcpu)
857 {
858         /*
859          * Guests should see errata 400 and 415 as fixed (assuming that
860          * HLT and IO instructions are intercepted).
861          */
862         vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
863         vcpu->arch.osvw.status = osvw_status & ~(6ULL);
864
865         /*
866          * By increasing VCPU's osvw.length to 3 we are telling the guest that
867          * all osvw.status bits inside that length, including bit 0 (which is
868          * reserved for erratum 298), are valid. However, if host processor's
869          * osvw_len is 0 then osvw_status[0] carries no information. We need to
870          * be conservative here and therefore we tell the guest that erratum 298
871          * is present (because we really don't know).
872          */
873         if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
874                 vcpu->arch.osvw.status |= 1;
875 }
876
877 static int has_svm(void)
878 {
879         const char *msg;
880
881         if (!cpu_has_svm(&msg)) {
882                 printk(KERN_INFO "has_svm: %s\n", msg);
883                 return 0;
884         }
885
886         return 1;
887 }
888
889 static void svm_hardware_disable(void)
890 {
891         /* Make sure we clean up behind us */
892         if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
893                 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
894
895         cpu_svm_disable();
896
897         amd_pmu_disable_virt();
898 }
899
900 static int svm_hardware_enable(void)
901 {
902
903         struct svm_cpu_data *sd;
904         uint64_t efer;
905         struct desc_struct *gdt;
906         int me = raw_smp_processor_id();
907
908         rdmsrl(MSR_EFER, efer);
909         if (efer & EFER_SVME)
910                 return -EBUSY;
911
912         if (!has_svm()) {
913                 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
914                 return -EINVAL;
915         }
916         sd = per_cpu(svm_data, me);
917         if (!sd) {
918                 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
919                 return -EINVAL;
920         }
921
922         sd->asid_generation = 1;
923         sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
924         sd->next_asid = sd->max_asid + 1;
925         sd->min_asid = max_sev_asid + 1;
926
927         gdt = get_current_gdt_rw();
928         sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
929
930         wrmsrl(MSR_EFER, efer | EFER_SVME);
931
932         wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
933
934         if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
935                 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
936                 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
937         }
938
939
940         /*
941          * Get OSVW bits.
942          *
943          * Note that it is possible to have a system with mixed processor
944          * revisions and therefore different OSVW bits. If bits are not the same
945          * on different processors then choose the worst case (i.e. if erratum
946          * is present on one processor and not on another then assume that the
947          * erratum is present everywhere).
948          */
949         if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
950                 uint64_t len, status = 0;
951                 int err;
952
953                 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
954                 if (!err)
955                         status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
956                                                       &err);
957
958                 if (err)
959                         osvw_status = osvw_len = 0;
960                 else {
961                         if (len < osvw_len)
962                                 osvw_len = len;
963                         osvw_status |= status;
964                         osvw_status &= (1ULL << osvw_len) - 1;
965                 }
966         } else
967                 osvw_status = osvw_len = 0;
968
969         svm_init_erratum_383();
970
971         amd_pmu_enable_virt();
972
973         return 0;
974 }
975
976 static void svm_cpu_uninit(int cpu)
977 {
978         struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
979
980         if (!sd)
981                 return;
982
983         per_cpu(svm_data, raw_smp_processor_id()) = NULL;
984         kfree(sd->sev_vmcbs);
985         __free_page(sd->save_area);
986         kfree(sd);
987 }
988
989 static int svm_cpu_init(int cpu)
990 {
991         struct svm_cpu_data *sd;
992         int r;
993
994         sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
995         if (!sd)
996                 return -ENOMEM;
997         sd->cpu = cpu;
998         r = -ENOMEM;
999         sd->save_area = alloc_page(GFP_KERNEL);
1000         if (!sd->save_area)
1001                 goto err_1;
1002
1003         if (svm_sev_enabled()) {
1004                 r = -ENOMEM;
1005                 sd->sev_vmcbs = kmalloc_array(max_sev_asid + 1,
1006                                               sizeof(void *),
1007                                               GFP_KERNEL);
1008                 if (!sd->sev_vmcbs)
1009                         goto err_1;
1010         }
1011
1012         per_cpu(svm_data, cpu) = sd;
1013
1014         return 0;
1015
1016 err_1:
1017         kfree(sd);
1018         return r;
1019
1020 }
1021
1022 static bool valid_msr_intercept(u32 index)
1023 {
1024         int i;
1025
1026         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
1027                 if (direct_access_msrs[i].index == index)
1028                         return true;
1029
1030         return false;
1031 }
1032
1033 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
1034 {
1035         u8 bit_write;
1036         unsigned long tmp;
1037         u32 offset;
1038         u32 *msrpm;
1039
1040         msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
1041                                       to_svm(vcpu)->msrpm;
1042
1043         offset    = svm_msrpm_offset(msr);
1044         bit_write = 2 * (msr & 0x0f) + 1;
1045         tmp       = msrpm[offset];
1046
1047         BUG_ON(offset == MSR_INVALID);
1048
1049         return !!test_bit(bit_write,  &tmp);
1050 }
1051
1052 static void set_msr_interception(u32 *msrpm, unsigned msr,
1053                                  int read, int write)
1054 {
1055         u8 bit_read, bit_write;
1056         unsigned long tmp;
1057         u32 offset;
1058
1059         /*
1060          * If this warning triggers extend the direct_access_msrs list at the
1061          * beginning of the file
1062          */
1063         WARN_ON(!valid_msr_intercept(msr));
1064
1065         offset    = svm_msrpm_offset(msr);
1066         bit_read  = 2 * (msr & 0x0f);
1067         bit_write = 2 * (msr & 0x0f) + 1;
1068         tmp       = msrpm[offset];
1069
1070         BUG_ON(offset == MSR_INVALID);
1071
1072         read  ? clear_bit(bit_read,  &tmp) : set_bit(bit_read,  &tmp);
1073         write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
1074
1075         msrpm[offset] = tmp;
1076 }
1077
1078 static void svm_vcpu_init_msrpm(u32 *msrpm)
1079 {
1080         int i;
1081
1082         memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
1083
1084         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1085                 if (!direct_access_msrs[i].always)
1086                         continue;
1087
1088                 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1089         }
1090 }
1091
1092 static void add_msr_offset(u32 offset)
1093 {
1094         int i;
1095
1096         for (i = 0; i < MSRPM_OFFSETS; ++i) {
1097
1098                 /* Offset already in list? */
1099                 if (msrpm_offsets[i] == offset)
1100                         return;
1101
1102                 /* Slot used by another offset? */
1103                 if (msrpm_offsets[i] != MSR_INVALID)
1104                         continue;
1105
1106                 /* Add offset to list */
1107                 msrpm_offsets[i] = offset;
1108
1109                 return;
1110         }
1111
1112         /*
1113          * If this BUG triggers the msrpm_offsets table has an overflow. Just
1114          * increase MSRPM_OFFSETS in this case.
1115          */
1116         BUG();
1117 }
1118
1119 static void init_msrpm_offsets(void)
1120 {
1121         int i;
1122
1123         memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1124
1125         for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1126                 u32 offset;
1127
1128                 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1129                 BUG_ON(offset == MSR_INVALID);
1130
1131                 add_msr_offset(offset);
1132         }
1133 }
1134
1135 static void svm_enable_lbrv(struct vcpu_svm *svm)
1136 {
1137         u32 *msrpm = svm->msrpm;
1138
1139         svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1140         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1141         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1142         set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1143         set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1144 }
1145
1146 static void svm_disable_lbrv(struct vcpu_svm *svm)
1147 {
1148         u32 *msrpm = svm->msrpm;
1149
1150         svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1151         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1152         set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1153         set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1154         set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1155 }
1156
1157 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1158 {
1159         svm->nmi_singlestep = false;
1160
1161         if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1162                 /* Clear our flags if they were not set by the guest */
1163                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1164                         svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1165                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1166                         svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1167         }
1168 }
1169
1170 /* Note:
1171  * This hash table is used to map VM_ID to a struct kvm_svm,
1172  * when handling AMD IOMMU GALOG notification to schedule in
1173  * a particular vCPU.
1174  */
1175 #define SVM_VM_DATA_HASH_BITS   8
1176 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1177 static u32 next_vm_id = 0;
1178 static bool next_vm_id_wrapped = 0;
1179 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1180
1181 /* Note:
1182  * This function is called from IOMMU driver to notify
1183  * SVM to schedule in a particular vCPU of a particular VM.
1184  */
1185 static int avic_ga_log_notifier(u32 ga_tag)
1186 {
1187         unsigned long flags;
1188         struct kvm_svm *kvm_svm;
1189         struct kvm_vcpu *vcpu = NULL;
1190         u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1191         u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1192
1193         pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1194
1195         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1196         hash_for_each_possible(svm_vm_data_hash, kvm_svm, hnode, vm_id) {
1197                 if (kvm_svm->avic_vm_id != vm_id)
1198                         continue;
1199                 vcpu = kvm_get_vcpu_by_id(&kvm_svm->kvm, vcpu_id);
1200                 break;
1201         }
1202         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1203
1204         /* Note:
1205          * At this point, the IOMMU should have already set the pending
1206          * bit in the vAPIC backing page. So, we just need to schedule
1207          * in the vcpu.
1208          */
1209         if (vcpu)
1210                 kvm_vcpu_wake_up(vcpu);
1211
1212         return 0;
1213 }
1214
1215 static __init int sev_hardware_setup(void)
1216 {
1217         struct sev_user_data_status *status;
1218         int rc;
1219
1220         /* Maximum number of encrypted guests supported simultaneously */
1221         max_sev_asid = cpuid_ecx(0x8000001F);
1222
1223         if (!max_sev_asid)
1224                 return 1;
1225
1226         /* Minimum ASID value that should be used for SEV guest */
1227         min_sev_asid = cpuid_edx(0x8000001F);
1228
1229         /* Initialize SEV ASID bitmap */
1230         sev_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1231         if (!sev_asid_bitmap)
1232                 return 1;
1233
1234         status = kmalloc(sizeof(*status), GFP_KERNEL);
1235         if (!status)
1236                 return 1;
1237
1238         /*
1239          * Check SEV platform status.
1240          *
1241          * PLATFORM_STATUS can be called in any state, if we failed to query
1242          * the PLATFORM status then either PSP firmware does not support SEV
1243          * feature or SEV firmware is dead.
1244          */
1245         rc = sev_platform_status(status, NULL);
1246         if (rc)
1247                 goto err;
1248
1249         pr_info("SEV supported\n");
1250
1251 err:
1252         kfree(status);
1253         return rc;
1254 }
1255
1256 static void grow_ple_window(struct kvm_vcpu *vcpu)
1257 {
1258         struct vcpu_svm *svm = to_svm(vcpu);
1259         struct vmcb_control_area *control = &svm->vmcb->control;
1260         int old = control->pause_filter_count;
1261
1262         control->pause_filter_count = __grow_ple_window(old,
1263                                                         pause_filter_count,
1264                                                         pause_filter_count_grow,
1265                                                         pause_filter_count_max);
1266
1267         if (control->pause_filter_count != old)
1268                 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1269
1270         trace_kvm_ple_window_grow(vcpu->vcpu_id,
1271                                   control->pause_filter_count, old);
1272 }
1273
1274 static void shrink_ple_window(struct kvm_vcpu *vcpu)
1275 {
1276         struct vcpu_svm *svm = to_svm(vcpu);
1277         struct vmcb_control_area *control = &svm->vmcb->control;
1278         int old = control->pause_filter_count;
1279
1280         control->pause_filter_count =
1281                                 __shrink_ple_window(old,
1282                                                     pause_filter_count,
1283                                                     pause_filter_count_shrink,
1284                                                     pause_filter_count);
1285         if (control->pause_filter_count != old)
1286                 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1287
1288         trace_kvm_ple_window_shrink(vcpu->vcpu_id,
1289                                     control->pause_filter_count, old);
1290 }
1291
1292 static __init int svm_hardware_setup(void)
1293 {
1294         int cpu;
1295         struct page *iopm_pages;
1296         void *iopm_va;
1297         int r;
1298
1299         iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1300
1301         if (!iopm_pages)
1302                 return -ENOMEM;
1303
1304         iopm_va = page_address(iopm_pages);
1305         memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1306         iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1307
1308         init_msrpm_offsets();
1309
1310         if (boot_cpu_has(X86_FEATURE_NX))
1311                 kvm_enable_efer_bits(EFER_NX);
1312
1313         if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1314                 kvm_enable_efer_bits(EFER_FFXSR);
1315
1316         if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1317                 kvm_has_tsc_control = true;
1318                 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1319                 kvm_tsc_scaling_ratio_frac_bits = 32;
1320         }
1321
1322         /* Check for pause filtering support */
1323         if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1324                 pause_filter_count = 0;
1325                 pause_filter_thresh = 0;
1326         } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
1327                 pause_filter_thresh = 0;
1328         }
1329
1330         if (nested) {
1331                 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1332                 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1333         }
1334
1335         if (sev) {
1336                 if (boot_cpu_has(X86_FEATURE_SEV) &&
1337                     IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1338                         r = sev_hardware_setup();
1339                         if (r)
1340                                 sev = false;
1341                 } else {
1342                         sev = false;
1343                 }
1344         }
1345
1346         for_each_possible_cpu(cpu) {
1347                 r = svm_cpu_init(cpu);
1348                 if (r)
1349                         goto err;
1350         }
1351
1352         if (!boot_cpu_has(X86_FEATURE_NPT))
1353                 npt_enabled = false;
1354
1355         if (npt_enabled && !npt) {
1356                 printk(KERN_INFO "kvm: Nested Paging disabled\n");
1357                 npt_enabled = false;
1358         }
1359
1360         if (npt_enabled) {
1361                 printk(KERN_INFO "kvm: Nested Paging enabled\n");
1362                 kvm_enable_tdp();
1363         } else
1364                 kvm_disable_tdp();
1365
1366         if (avic) {
1367                 if (!npt_enabled ||
1368                     !boot_cpu_has(X86_FEATURE_AVIC) ||
1369                     !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1370                         avic = false;
1371                 } else {
1372                         pr_info("AVIC enabled\n");
1373
1374                         amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1375                 }
1376         }
1377
1378         if (vls) {
1379                 if (!npt_enabled ||
1380                     !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1381                     !IS_ENABLED(CONFIG_X86_64)) {
1382                         vls = false;
1383                 } else {
1384                         pr_info("Virtual VMLOAD VMSAVE supported\n");
1385                 }
1386         }
1387
1388         if (vgif) {
1389                 if (!boot_cpu_has(X86_FEATURE_VGIF))
1390                         vgif = false;
1391                 else
1392                         pr_info("Virtual GIF supported\n");
1393         }
1394
1395         return 0;
1396
1397 err:
1398         __free_pages(iopm_pages, IOPM_ALLOC_ORDER);
1399         iopm_base = 0;
1400         return r;
1401 }
1402
1403 static __exit void svm_hardware_unsetup(void)
1404 {
1405         int cpu;
1406
1407         if (svm_sev_enabled())
1408                 bitmap_free(sev_asid_bitmap);
1409
1410         for_each_possible_cpu(cpu)
1411                 svm_cpu_uninit(cpu);
1412
1413         __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1414         iopm_base = 0;
1415 }
1416
1417 static void init_seg(struct vmcb_seg *seg)
1418 {
1419         seg->selector = 0;
1420         seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1421                       SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1422         seg->limit = 0xffff;
1423         seg->base = 0;
1424 }
1425
1426 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1427 {
1428         seg->selector = 0;
1429         seg->attrib = SVM_SELECTOR_P_MASK | type;
1430         seg->limit = 0xffff;
1431         seg->base = 0;
1432 }
1433
1434 static u64 svm_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1435 {
1436         struct vcpu_svm *svm = to_svm(vcpu);
1437
1438         if (is_guest_mode(vcpu))
1439                 return svm->nested.hsave->control.tsc_offset;
1440
1441         return vcpu->arch.tsc_offset;
1442 }
1443
1444 static u64 svm_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1445 {
1446         struct vcpu_svm *svm = to_svm(vcpu);
1447         u64 g_tsc_offset = 0;
1448
1449         if (is_guest_mode(vcpu)) {
1450                 /* Write L1's TSC offset.  */
1451                 g_tsc_offset = svm->vmcb->control.tsc_offset -
1452                                svm->nested.hsave->control.tsc_offset;
1453                 svm->nested.hsave->control.tsc_offset = offset;
1454         }
1455
1456         trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1457                                    svm->vmcb->control.tsc_offset - g_tsc_offset,
1458                                    offset);
1459
1460         svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1461
1462         mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1463         return svm->vmcb->control.tsc_offset;
1464 }
1465
1466 static void avic_init_vmcb(struct vcpu_svm *svm)
1467 {
1468         struct vmcb *vmcb = svm->vmcb;
1469         struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
1470         phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1471         phys_addr_t lpa = __sme_set(page_to_phys(kvm_svm->avic_logical_id_table_page));
1472         phys_addr_t ppa = __sme_set(page_to_phys(kvm_svm->avic_physical_id_table_page));
1473
1474         vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1475         vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1476         vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1477         vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1478         vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1479 }
1480
1481 static void init_vmcb(struct vcpu_svm *svm)
1482 {
1483         struct vmcb_control_area *control = &svm->vmcb->control;
1484         struct vmcb_save_area *save = &svm->vmcb->save;
1485
1486         svm->vcpu.arch.hflags = 0;
1487
1488         set_cr_intercept(svm, INTERCEPT_CR0_READ);
1489         set_cr_intercept(svm, INTERCEPT_CR3_READ);
1490         set_cr_intercept(svm, INTERCEPT_CR4_READ);
1491         set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1492         set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1493         set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1494         if (!kvm_vcpu_apicv_active(&svm->vcpu))
1495                 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1496
1497         set_dr_intercepts(svm);
1498
1499         set_exception_intercept(svm, PF_VECTOR);
1500         set_exception_intercept(svm, UD_VECTOR);
1501         set_exception_intercept(svm, MC_VECTOR);
1502         set_exception_intercept(svm, AC_VECTOR);
1503         set_exception_intercept(svm, DB_VECTOR);
1504         /*
1505          * Guest access to VMware backdoor ports could legitimately
1506          * trigger #GP because of TSS I/O permission bitmap.
1507          * We intercept those #GP and allow access to them anyway
1508          * as VMware does.
1509          */
1510         if (enable_vmware_backdoor)
1511                 set_exception_intercept(svm, GP_VECTOR);
1512
1513         set_intercept(svm, INTERCEPT_INTR);
1514         set_intercept(svm, INTERCEPT_NMI);
1515         set_intercept(svm, INTERCEPT_SMI);
1516         set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1517         set_intercept(svm, INTERCEPT_RDPMC);
1518         set_intercept(svm, INTERCEPT_CPUID);
1519         set_intercept(svm, INTERCEPT_INVD);
1520         set_intercept(svm, INTERCEPT_INVLPG);
1521         set_intercept(svm, INTERCEPT_INVLPGA);
1522         set_intercept(svm, INTERCEPT_IOIO_PROT);
1523         set_intercept(svm, INTERCEPT_MSR_PROT);
1524         set_intercept(svm, INTERCEPT_TASK_SWITCH);
1525         set_intercept(svm, INTERCEPT_SHUTDOWN);
1526         set_intercept(svm, INTERCEPT_VMRUN);
1527         set_intercept(svm, INTERCEPT_VMMCALL);
1528         set_intercept(svm, INTERCEPT_VMLOAD);
1529         set_intercept(svm, INTERCEPT_VMSAVE);
1530         set_intercept(svm, INTERCEPT_STGI);
1531         set_intercept(svm, INTERCEPT_CLGI);
1532         set_intercept(svm, INTERCEPT_SKINIT);
1533         set_intercept(svm, INTERCEPT_WBINVD);
1534         set_intercept(svm, INTERCEPT_XSETBV);
1535         set_intercept(svm, INTERCEPT_RSM);
1536
1537         if (!kvm_mwait_in_guest(svm->vcpu.kvm)) {
1538                 set_intercept(svm, INTERCEPT_MONITOR);
1539                 set_intercept(svm, INTERCEPT_MWAIT);
1540         }
1541
1542         if (!kvm_hlt_in_guest(svm->vcpu.kvm))
1543                 set_intercept(svm, INTERCEPT_HLT);
1544
1545         control->iopm_base_pa = __sme_set(iopm_base);
1546         control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1547         control->int_ctl = V_INTR_MASKING_MASK;
1548
1549         init_seg(&save->es);
1550         init_seg(&save->ss);
1551         init_seg(&save->ds);
1552         init_seg(&save->fs);
1553         init_seg(&save->gs);
1554
1555         save->cs.selector = 0xf000;
1556         save->cs.base = 0xffff0000;
1557         /* Executable/Readable Code Segment */
1558         save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1559                 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1560         save->cs.limit = 0xffff;
1561
1562         save->gdtr.limit = 0xffff;
1563         save->idtr.limit = 0xffff;
1564
1565         init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1566         init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1567
1568         svm_set_efer(&svm->vcpu, 0);
1569         save->dr6 = 0xffff0ff0;
1570         kvm_set_rflags(&svm->vcpu, 2);
1571         save->rip = 0x0000fff0;
1572         svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1573
1574         /*
1575          * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1576          * It also updates the guest-visible cr0 value.
1577          */
1578         svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1579         kvm_mmu_reset_context(&svm->vcpu);
1580
1581         save->cr4 = X86_CR4_PAE;
1582         /* rdx = ?? */
1583
1584         if (npt_enabled) {
1585                 /* Setup VMCB for Nested Paging */
1586                 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1587                 clr_intercept(svm, INTERCEPT_INVLPG);
1588                 clr_exception_intercept(svm, PF_VECTOR);
1589                 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1590                 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1591                 save->g_pat = svm->vcpu.arch.pat;
1592                 save->cr3 = 0;
1593                 save->cr4 = 0;
1594         }
1595         svm->asid_generation = 0;
1596
1597         svm->nested.vmcb = 0;
1598         svm->vcpu.arch.hflags = 0;
1599
1600         if (pause_filter_count) {
1601                 control->pause_filter_count = pause_filter_count;
1602                 if (pause_filter_thresh)
1603                         control->pause_filter_thresh = pause_filter_thresh;
1604                 set_intercept(svm, INTERCEPT_PAUSE);
1605         } else {
1606                 clr_intercept(svm, INTERCEPT_PAUSE);
1607         }
1608
1609         if (kvm_vcpu_apicv_active(&svm->vcpu))
1610                 avic_init_vmcb(svm);
1611
1612         /*
1613          * If hardware supports Virtual VMLOAD VMSAVE then enable it
1614          * in VMCB and clear intercepts to avoid #VMEXIT.
1615          */
1616         if (vls) {
1617                 clr_intercept(svm, INTERCEPT_VMLOAD);
1618                 clr_intercept(svm, INTERCEPT_VMSAVE);
1619                 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1620         }
1621
1622         if (vgif) {
1623                 clr_intercept(svm, INTERCEPT_STGI);
1624                 clr_intercept(svm, INTERCEPT_CLGI);
1625                 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1626         }
1627
1628         if (sev_guest(svm->vcpu.kvm)) {
1629                 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1630                 clr_exception_intercept(svm, UD_VECTOR);
1631         }
1632
1633         mark_all_dirty(svm->vmcb);
1634
1635         enable_gif(svm);
1636
1637 }
1638
1639 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1640                                        unsigned int index)
1641 {
1642         u64 *avic_physical_id_table;
1643         struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
1644
1645         if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1646                 return NULL;
1647
1648         avic_physical_id_table = page_address(kvm_svm->avic_physical_id_table_page);
1649
1650         return &avic_physical_id_table[index];
1651 }
1652
1653 /**
1654  * Note:
1655  * AVIC hardware walks the nested page table to check permissions,
1656  * but does not use the SPA address specified in the leaf page
1657  * table entry since it uses  address in the AVIC_BACKING_PAGE pointer
1658  * field of the VMCB. Therefore, we set up the
1659  * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1660  */
1661 static int avic_init_access_page(struct kvm_vcpu *vcpu)
1662 {
1663         struct kvm *kvm = vcpu->kvm;
1664         int ret = 0;
1665
1666         mutex_lock(&kvm->slots_lock);
1667         if (kvm->arch.apic_access_page_done)
1668                 goto out;
1669
1670         ret = __x86_set_memory_region(kvm,
1671                                       APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1672                                       APIC_DEFAULT_PHYS_BASE,
1673                                       PAGE_SIZE);
1674         if (ret)
1675                 goto out;
1676
1677         kvm->arch.apic_access_page_done = true;
1678 out:
1679         mutex_unlock(&kvm->slots_lock);
1680         return ret;
1681 }
1682
1683 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1684 {
1685         int ret;
1686         u64 *entry, new_entry;
1687         int id = vcpu->vcpu_id;
1688         struct vcpu_svm *svm = to_svm(vcpu);
1689
1690         ret = avic_init_access_page(vcpu);
1691         if (ret)
1692                 return ret;
1693
1694         if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1695                 return -EINVAL;
1696
1697         if (!svm->vcpu.arch.apic->regs)
1698                 return -EINVAL;
1699
1700         svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1701
1702         /* Setting AVIC backing page address in the phy APIC ID table */
1703         entry = avic_get_physical_id_entry(vcpu, id);
1704         if (!entry)
1705                 return -EINVAL;
1706
1707         new_entry = READ_ONCE(*entry);
1708         new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1709                               AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1710                               AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1711         WRITE_ONCE(*entry, new_entry);
1712
1713         svm->avic_physical_id_cache = entry;
1714
1715         return 0;
1716 }
1717
1718 static void __sev_asid_free(int asid)
1719 {
1720         struct svm_cpu_data *sd;
1721         int cpu, pos;
1722
1723         pos = asid - 1;
1724         clear_bit(pos, sev_asid_bitmap);
1725
1726         for_each_possible_cpu(cpu) {
1727                 sd = per_cpu(svm_data, cpu);
1728                 sd->sev_vmcbs[pos] = NULL;
1729         }
1730 }
1731
1732 static void sev_asid_free(struct kvm *kvm)
1733 {
1734         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1735
1736         __sev_asid_free(sev->asid);
1737 }
1738
1739 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1740 {
1741         struct sev_data_decommission *decommission;
1742         struct sev_data_deactivate *data;
1743
1744         if (!handle)
1745                 return;
1746
1747         data = kzalloc(sizeof(*data), GFP_KERNEL);
1748         if (!data)
1749                 return;
1750
1751         /* deactivate handle */
1752         data->handle = handle;
1753         sev_guest_deactivate(data, NULL);
1754
1755         wbinvd_on_all_cpus();
1756         sev_guest_df_flush(NULL);
1757         kfree(data);
1758
1759         decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1760         if (!decommission)
1761                 return;
1762
1763         /* decommission handle */
1764         decommission->handle = handle;
1765         sev_guest_decommission(decommission, NULL);
1766
1767         kfree(decommission);
1768 }
1769
1770 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1771                                     unsigned long ulen, unsigned long *n,
1772                                     int write)
1773 {
1774         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1775         unsigned long npages, npinned, size;
1776         unsigned long locked, lock_limit;
1777         struct page **pages;
1778         unsigned long first, last;
1779
1780         if (ulen == 0 || uaddr + ulen < uaddr)
1781                 return NULL;
1782
1783         /* Calculate number of pages. */
1784         first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1785         last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1786         npages = (last - first + 1);
1787
1788         locked = sev->pages_locked + npages;
1789         lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1790         if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1791                 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1792                 return NULL;
1793         }
1794
1795         /* Avoid using vmalloc for smaller buffers. */
1796         size = npages * sizeof(struct page *);
1797         if (size > PAGE_SIZE)
1798                 pages = __vmalloc(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO,
1799                                   PAGE_KERNEL);
1800         else
1801                 pages = kmalloc(size, GFP_KERNEL_ACCOUNT);
1802
1803         if (!pages)
1804                 return NULL;
1805
1806         /* Pin the user virtual address. */
1807         npinned = get_user_pages_fast(uaddr, npages, write ? FOLL_WRITE : 0, pages);
1808         if (npinned != npages) {
1809                 pr_err("SEV: Failure locking %lu pages.\n", npages);
1810                 goto err;
1811         }
1812
1813         *n = npages;
1814         sev->pages_locked = locked;
1815
1816         return pages;
1817
1818 err:
1819         if (npinned > 0)
1820                 release_pages(pages, npinned);
1821
1822         kvfree(pages);
1823         return NULL;
1824 }
1825
1826 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1827                              unsigned long npages)
1828 {
1829         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1830
1831         release_pages(pages, npages);
1832         kvfree(pages);
1833         sev->pages_locked -= npages;
1834 }
1835
1836 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1837 {
1838         uint8_t *page_virtual;
1839         unsigned long i;
1840
1841         if (npages == 0 || pages == NULL)
1842                 return;
1843
1844         for (i = 0; i < npages; i++) {
1845                 page_virtual = kmap_atomic(pages[i]);
1846                 clflush_cache_range(page_virtual, PAGE_SIZE);
1847                 kunmap_atomic(page_virtual);
1848         }
1849 }
1850
1851 static void __unregister_enc_region_locked(struct kvm *kvm,
1852                                            struct enc_region *region)
1853 {
1854         /*
1855          * The guest may change the memory encryption attribute from C=0 -> C=1
1856          * or vice versa for this memory range. Lets make sure caches are
1857          * flushed to ensure that guest data gets written into memory with
1858          * correct C-bit.
1859          */
1860         sev_clflush_pages(region->pages, region->npages);
1861
1862         sev_unpin_memory(kvm, region->pages, region->npages);
1863         list_del(&region->list);
1864         kfree(region);
1865 }
1866
1867 static struct kvm *svm_vm_alloc(void)
1868 {
1869         struct kvm_svm *kvm_svm = __vmalloc(sizeof(struct kvm_svm),
1870                                             GFP_KERNEL_ACCOUNT | __GFP_ZERO,
1871                                             PAGE_KERNEL);
1872         return &kvm_svm->kvm;
1873 }
1874
1875 static void svm_vm_free(struct kvm *kvm)
1876 {
1877         vfree(to_kvm_svm(kvm));
1878 }
1879
1880 static void sev_vm_destroy(struct kvm *kvm)
1881 {
1882         struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1883         struct list_head *head = &sev->regions_list;
1884         struct list_head *pos, *q;
1885
1886         if (!sev_guest(kvm))
1887                 return;
1888
1889         mutex_lock(&kvm->lock);
1890
1891         /*
1892          * if userspace was terminated before unregistering the memory regions
1893          * then lets unpin all the registered memory.
1894          */
1895         if (!list_empty(head)) {
1896                 list_for_each_safe(pos, q, head) {
1897                         __unregister_enc_region_locked(kvm,
1898                                 list_entry(pos, struct enc_region, list));
1899                 }
1900         }
1901
1902         mutex_unlock(&kvm->lock);
1903
1904         sev_unbind_asid(kvm, sev->handle);
1905         sev_asid_free(kvm);
1906 }
1907
1908 static void avic_vm_destroy(struct kvm *kvm)
1909 {
1910         unsigned long flags;
1911         struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1912
1913         if (!avic)
1914                 return;
1915
1916         if (kvm_svm->avic_logical_id_table_page)
1917                 __free_page(kvm_svm->avic_logical_id_table_page);
1918         if (kvm_svm->avic_physical_id_table_page)
1919                 __free_page(kvm_svm->avic_physical_id_table_page);
1920
1921         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1922         hash_del(&kvm_svm->hnode);
1923         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1924 }
1925
1926 static void svm_vm_destroy(struct kvm *kvm)
1927 {
1928         avic_vm_destroy(kvm);
1929         sev_vm_destroy(kvm);
1930 }
1931
1932 static int avic_vm_init(struct kvm *kvm)
1933 {
1934         unsigned long flags;
1935         int err = -ENOMEM;
1936         struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1937         struct kvm_svm *k2;
1938         struct page *p_page;
1939         struct page *l_page;
1940         u32 vm_id;
1941
1942         if (!avic)
1943                 return 0;
1944
1945         /* Allocating physical APIC ID table (4KB) */
1946         p_page = alloc_page(GFP_KERNEL_ACCOUNT);
1947         if (!p_page)
1948                 goto free_avic;
1949
1950         kvm_svm->avic_physical_id_table_page = p_page;
1951         clear_page(page_address(p_page));
1952
1953         /* Allocating logical APIC ID table (4KB) */
1954         l_page = alloc_page(GFP_KERNEL_ACCOUNT);
1955         if (!l_page)
1956                 goto free_avic;
1957
1958         kvm_svm->avic_logical_id_table_page = l_page;
1959         clear_page(page_address(l_page));
1960
1961         spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1962  again:
1963         vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
1964         if (vm_id == 0) { /* id is 1-based, zero is not okay */
1965                 next_vm_id_wrapped = 1;
1966                 goto again;
1967         }
1968         /* Is it still in use? Only possible if wrapped at least once */
1969         if (next_vm_id_wrapped) {
1970                 hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
1971                         if (k2->avic_vm_id == vm_id)
1972                                 goto again;
1973                 }
1974         }
1975         kvm_svm->avic_vm_id = vm_id;
1976         hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
1977         spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1978
1979         return 0;
1980
1981 free_avic:
1982         avic_vm_destroy(kvm);
1983         return err;
1984 }
1985
1986 static inline int
1987 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
1988 {
1989         int ret = 0;
1990         unsigned long flags;
1991         struct amd_svm_iommu_ir *ir;
1992         struct vcpu_svm *svm = to_svm(vcpu);
1993
1994         if (!kvm_arch_has_assigned_device(vcpu->kvm))
1995                 return 0;
1996
1997         /*
1998          * Here, we go through the per-vcpu ir_list to update all existing
1999          * interrupt remapping table entry targeting this vcpu.
2000          */
2001         spin_lock_irqsave(&svm->ir_list_lock, flags);
2002
2003         if (list_empty(&svm->ir_list))
2004                 goto out;
2005
2006         list_for_each_entry(ir, &svm->ir_list, node) {
2007                 ret = amd_iommu_update_ga(cpu, r, ir->data);
2008                 if (ret)
2009                         break;
2010         }
2011 out:
2012         spin_unlock_irqrestore(&svm->ir_list_lock, flags);
2013         return ret;
2014 }
2015
2016 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2017 {
2018         u64 entry;
2019         /* ID = 0xff (broadcast), ID > 0xff (reserved) */
2020         int h_physical_id = kvm_cpu_get_apicid(cpu);
2021         struct vcpu_svm *svm = to_svm(vcpu);
2022
2023         if (!kvm_vcpu_apicv_active(vcpu))
2024                 return;
2025
2026         if (WARN_ON(h_physical_id >= AVIC_MAX_PHYSICAL_ID_COUNT))
2027                 return;
2028
2029         entry = READ_ONCE(*(svm->avic_physical_id_cache));
2030         WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
2031
2032         entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
2033         entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
2034
2035         entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2036         if (svm->avic_is_running)
2037                 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2038
2039         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2040         avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
2041                                         svm->avic_is_running);
2042 }
2043
2044 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
2045 {
2046         u64 entry;
2047         struct vcpu_svm *svm = to_svm(vcpu);
2048
2049         if (!kvm_vcpu_apicv_active(vcpu))
2050                 return;
2051
2052         entry = READ_ONCE(*(svm->avic_physical_id_cache));
2053         if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
2054                 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
2055
2056         entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2057         WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2058 }
2059
2060 /**
2061  * This function is called during VCPU halt/unhalt.
2062  */
2063 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
2064 {
2065         struct vcpu_svm *svm = to_svm(vcpu);
2066
2067         svm->avic_is_running = is_run;
2068         if (is_run)
2069                 avic_vcpu_load(vcpu, vcpu->cpu);
2070         else
2071                 avic_vcpu_put(vcpu);
2072 }
2073
2074 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
2075 {
2076         struct vcpu_svm *svm = to_svm(vcpu);
2077         u32 dummy;
2078         u32 eax = 1;
2079
2080         vcpu->arch.microcode_version = 0x01000065;
2081         svm->spec_ctrl = 0;
2082         svm->virt_spec_ctrl = 0;
2083
2084         if (!init_event) {
2085                 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
2086                                            MSR_IA32_APICBASE_ENABLE;
2087                 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
2088                         svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
2089         }
2090         init_vmcb(svm);
2091
2092         kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
2093         kvm_register_write(vcpu, VCPU_REGS_RDX, eax);
2094
2095         if (kvm_vcpu_apicv_active(vcpu) && !init_event)
2096                 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
2097 }
2098
2099 static int avic_init_vcpu(struct vcpu_svm *svm)
2100 {
2101         int ret;
2102
2103         if (!kvm_vcpu_apicv_active(&svm->vcpu))
2104                 return 0;
2105
2106         ret = avic_init_backing_page(&svm->vcpu);
2107         if (ret)
2108                 return ret;
2109
2110         INIT_LIST_HEAD(&svm->ir_list);
2111         spin_lock_init(&svm->ir_list_lock);
2112         svm->dfr_reg = APIC_DFR_FLAT;
2113
2114         return ret;
2115 }
2116
2117 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
2118 {
2119         struct vcpu_svm *svm;
2120         struct page *page;
2121         struct page *msrpm_pages;
2122         struct page *hsave_page;
2123         struct page *nested_msrpm_pages;
2124         int err;
2125
2126         svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
2127         if (!svm) {
2128                 err = -ENOMEM;
2129                 goto out;
2130         }
2131
2132         svm->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
2133                                                      GFP_KERNEL_ACCOUNT);
2134         if (!svm->vcpu.arch.guest_fpu) {
2135                 printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
2136                 err = -ENOMEM;
2137                 goto free_partial_svm;
2138         }
2139
2140         err = kvm_vcpu_init(&svm->vcpu, kvm, id);
2141         if (err)
2142                 goto free_svm;
2143
2144         err = -ENOMEM;
2145         page = alloc_page(GFP_KERNEL_ACCOUNT);
2146         if (!page)
2147                 goto uninit;
2148
2149         msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2150         if (!msrpm_pages)
2151                 goto free_page1;
2152
2153         nested_msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2154         if (!nested_msrpm_pages)
2155                 goto free_page2;
2156
2157         hsave_page = alloc_page(GFP_KERNEL_ACCOUNT);
2158         if (!hsave_page)
2159                 goto free_page3;
2160
2161         err = avic_init_vcpu(svm);
2162         if (err)
2163                 goto free_page4;
2164
2165         /* We initialize this flag to true to make sure that the is_running
2166          * bit would be set the first time the vcpu is loaded.
2167          */
2168         svm->avic_is_running = true;
2169
2170         svm->nested.hsave = page_address(hsave_page);
2171
2172         svm->msrpm = page_address(msrpm_pages);
2173         svm_vcpu_init_msrpm(svm->msrpm);
2174
2175         svm->nested.msrpm = page_address(nested_msrpm_pages);
2176         svm_vcpu_init_msrpm(svm->nested.msrpm);
2177
2178         svm->vmcb = page_address(page);
2179         clear_page(svm->vmcb);
2180         svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
2181         svm->asid_generation = 0;
2182         init_vmcb(svm);
2183
2184         svm_init_osvw(&svm->vcpu);
2185
2186         return &svm->vcpu;
2187
2188 free_page4:
2189         __free_page(hsave_page);
2190 free_page3:
2191         __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2192 free_page2:
2193         __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2194 free_page1:
2195         __free_page(page);
2196 uninit:
2197         kvm_vcpu_uninit(&svm->vcpu);
2198 free_svm:
2199         kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.guest_fpu);
2200 free_partial_svm:
2201         kmem_cache_free(kvm_vcpu_cache, svm);
2202 out:
2203         return ERR_PTR(err);
2204 }
2205
2206 static void svm_clear_current_vmcb(struct vmcb *vmcb)
2207 {
2208         int i;
2209
2210         for_each_online_cpu(i)
2211                 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
2212 }
2213
2214 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2215 {
2216         struct vcpu_svm *svm = to_svm(vcpu);
2217
2218         /*
2219          * The vmcb page can be recycled, causing a false negative in
2220          * svm_vcpu_load(). So, ensure that no logical CPU has this
2221          * vmcb page recorded as its current vmcb.
2222          */
2223         svm_clear_current_vmcb(svm->vmcb);
2224
2225         __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2226         __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2227         __free_page(virt_to_page(svm->nested.hsave));
2228         __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2229         kvm_vcpu_uninit(vcpu);
2230         kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.guest_fpu);
2231         kmem_cache_free(kvm_vcpu_cache, svm);
2232 }
2233
2234 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2235 {
2236         struct vcpu_svm *svm = to_svm(vcpu);
2237         struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2238         int i;
2239
2240         if (unlikely(cpu != vcpu->cpu)) {
2241                 svm->asid_generation = 0;
2242                 mark_all_dirty(svm->vmcb);
2243         }
2244
2245 #ifdef CONFIG_X86_64
2246         rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2247 #endif
2248         savesegment(fs, svm->host.fs);
2249         savesegment(gs, svm->host.gs);
2250         svm->host.ldt = kvm_read_ldt();
2251
2252         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2253                 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2254
2255         if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2256                 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2257                 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2258                         __this_cpu_write(current_tsc_ratio, tsc_ratio);
2259                         wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2260                 }
2261         }
2262         /* This assumes that the kernel never uses MSR_TSC_AUX */
2263         if (static_cpu_has(X86_FEATURE_RDTSCP))
2264                 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2265
2266         if (sd->current_vmcb != svm->vmcb) {
2267                 sd->current_vmcb = svm->vmcb;
2268                 indirect_branch_prediction_barrier();
2269         }
2270         avic_vcpu_load(vcpu, cpu);
2271 }
2272
2273 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2274 {
2275         struct vcpu_svm *svm = to_svm(vcpu);
2276         int i;
2277
2278         avic_vcpu_put(vcpu);
2279
2280         ++vcpu->stat.host_state_reload;
2281         kvm_load_ldt(svm->host.ldt);
2282 #ifdef CONFIG_X86_64
2283         loadsegment(fs, svm->host.fs);
2284         wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2285         load_gs_index(svm->host.gs);
2286 #else
2287 #ifdef CONFIG_X86_32_LAZY_GS
2288         loadsegment(gs, svm->host.gs);
2289 #endif
2290 #endif
2291         for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2292                 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2293 }
2294
2295 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2296 {
2297         avic_set_running(vcpu, false);
2298 }
2299
2300 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2301 {
2302         avic_set_running(vcpu, true);
2303 }
2304
2305 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2306 {
2307         struct vcpu_svm *svm = to_svm(vcpu);
2308         unsigned long rflags = svm->vmcb->save.rflags;
2309
2310         if (svm->nmi_singlestep) {
2311                 /* Hide our flags if they were not set by the guest */
2312                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2313                         rflags &= ~X86_EFLAGS_TF;
2314                 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2315                         rflags &= ~X86_EFLAGS_RF;
2316         }
2317         return rflags;
2318 }
2319
2320 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2321 {
2322         if (to_svm(vcpu)->nmi_singlestep)
2323                 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2324
2325        /*
2326         * Any change of EFLAGS.VM is accompanied by a reload of SS
2327         * (caused by either a task switch or an inter-privilege IRET),
2328         * so we do not need to update the CPL here.
2329         */
2330         to_svm(vcpu)->vmcb->save.rflags = rflags;
2331 }
2332
2333 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2334 {
2335         switch (reg) {
2336         case VCPU_EXREG_PDPTR:
2337                 BUG_ON(!npt_enabled);
2338                 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2339                 break;
2340         default:
2341                 BUG();
2342         }
2343 }
2344
2345 static void svm_set_vintr(struct vcpu_svm *svm)
2346 {
2347         set_intercept(svm, INTERCEPT_VINTR);
2348 }
2349
2350 static void svm_clear_vintr(struct vcpu_svm *svm)
2351 {
2352         clr_intercept(svm, INTERCEPT_VINTR);
2353 }
2354
2355 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2356 {
2357         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2358
2359         switch (seg) {
2360         case VCPU_SREG_CS: return &save->cs;
2361         case VCPU_SREG_DS: return &save->ds;
2362         case VCPU_SREG_ES: return &save->es;
2363         case VCPU_SREG_FS: return &save->fs;
2364         case VCPU_SREG_GS: return &save->gs;
2365         case VCPU_SREG_SS: return &save->ss;
2366         case VCPU_SREG_TR: return &save->tr;
2367         case VCPU_SREG_LDTR: return &save->ldtr;
2368         }
2369         BUG();
2370         return NULL;
2371 }
2372
2373 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2374 {
2375         struct vmcb_seg *s = svm_seg(vcpu, seg);
2376
2377         return s->base;
2378 }
2379
2380 static void svm_get_segment(struct kvm_vcpu *vcpu,
2381                             struct kvm_segment *var, int seg)
2382 {
2383         struct vmcb_seg *s = svm_seg(vcpu, seg);
2384
2385         var->base = s->base;
2386         var->limit = s->limit;
2387         var->selector = s->selector;
2388         var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2389         var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2390         var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2391         var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2392         var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2393         var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2394         var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2395
2396         /*
2397          * AMD CPUs circa 2014 track the G bit for all segments except CS.
2398          * However, the SVM spec states that the G bit is not observed by the
2399          * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2400          * So let's synthesize a legal G bit for all segments, this helps
2401          * running KVM nested. It also helps cross-vendor migration, because
2402          * Intel's vmentry has a check on the 'G' bit.
2403          */
2404         var->g = s->limit > 0xfffff;
2405
2406         /*
2407          * AMD's VMCB does not have an explicit unusable field, so emulate it
2408          * for cross vendor migration purposes by "not present"
2409          */
2410         var->unusable = !var->present;
2411
2412         switch (seg) {
2413         case VCPU_SREG_TR:
2414                 /*
2415                  * Work around a bug where the busy flag in the tr selector
2416                  * isn't exposed
2417                  */
2418                 var->type |= 0x2;
2419                 break;
2420         case VCPU_SREG_DS:
2421         case VCPU_SREG_ES:
2422         case VCPU_SREG_FS:
2423         case VCPU_SREG_GS:
2424                 /*
2425                  * The accessed bit must always be set in the segment
2426                  * descriptor cache, although it can be cleared in the
2427                  * descriptor, the cached bit always remains at 1. Since
2428                  * Intel has a check on this, set it here to support
2429                  * cross-vendor migration.
2430                  */
2431                 if (!var->unusable)
2432                         var->type |= 0x1;
2433                 break;
2434         case VCPU_SREG_SS:
2435                 /*
2436                  * On AMD CPUs sometimes the DB bit in the segment
2437                  * descriptor is left as 1, although the whole segment has
2438                  * been made unusable. Clear it here to pass an Intel VMX
2439                  * entry check when cross vendor migrating.
2440                  */
2441                 if (var->unusable)
2442                         var->db = 0;
2443                 /* This is symmetric with svm_set_segment() */
2444                 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2445                 break;
2446         }
2447 }
2448
2449 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2450 {
2451         struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2452
2453         return save->cpl;
2454 }
2455
2456 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2457 {
2458         struct vcpu_svm *svm = to_svm(vcpu);
2459
2460         dt->size = svm->vmcb->save.idtr.limit;
2461         dt->address = svm->vmcb->save.idtr.base;
2462 }
2463
2464 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2465 {
2466         struct vcpu_svm *svm = to_svm(vcpu);
2467
2468         svm->vmcb->save.idtr.limit = dt->size;
2469         svm->vmcb->save.idtr.base = dt->address ;
2470         mark_dirty(svm->vmcb, VMCB_DT);
2471 }
2472
2473 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2474 {
2475         struct vcpu_svm *svm = to_svm(vcpu);
2476
2477         dt->size = svm->vmcb->save.gdtr.limit;
2478         dt->address = svm->vmcb->save.gdtr.base;
2479 }
2480
2481 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2482 {
2483         struct vcpu_svm *svm = to_svm(vcpu);
2484
2485         svm->vmcb->save.gdtr.limit = dt->size;
2486         svm->vmcb->save.gdtr.base = dt->address ;
2487         mark_dirty(svm->vmcb, VMCB_DT);
2488 }
2489
2490 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2491 {
2492 }
2493
2494 static void svm_decache_cr3(struct kvm_vcpu *vcpu)
2495 {
2496 }
2497
2498 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2499 {
2500 }
2501
2502 static void update_cr0_intercept(struct vcpu_svm *svm)
2503 {
2504         ulong gcr0 = svm->vcpu.arch.cr0;
2505         u64 *hcr0 = &svm->vmcb->save.cr0;
2506
2507         *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2508                 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2509
2510         mark_dirty(svm->vmcb, VMCB_CR);
2511
2512         if (gcr0 == *hcr0) {
2513                 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2514                 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2515         } else {
2516                 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2517                 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2518         }
2519 }
2520
2521 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2522 {
2523         struct vcpu_svm *svm = to_svm(vcpu);
2524
2525 #ifdef CONFIG_X86_64
2526         if (vcpu->arch.efer & EFER_LME) {
2527                 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2528                         vcpu->arch.efer |= EFER_LMA;
2529                         svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2530                 }
2531
2532                 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2533                         vcpu->arch.efer &= ~EFER_LMA;
2534                         svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2535                 }
2536         }
2537 #endif
2538         vcpu->arch.cr0 = cr0;
2539
2540         if (!npt_enabled)
2541                 cr0 |= X86_CR0_PG | X86_CR0_WP;
2542
2543         /*
2544          * re-enable caching here because the QEMU bios
2545          * does not do it - this results in some delay at
2546          * reboot
2547          */
2548         if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2549                 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2550         svm->vmcb->save.cr0 = cr0;
2551         mark_dirty(svm->vmcb, VMCB_CR);
2552         update_cr0_intercept(svm);
2553 }
2554
2555 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2556 {
2557         unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2558         unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2559
2560         if (cr4 & X86_CR4_VMXE)
2561                 return 1;
2562
2563         if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2564                 svm_flush_tlb(vcpu, true);
2565
2566         vcpu->arch.cr4 = cr4;
2567         if (!npt_enabled)
2568                 cr4 |= X86_CR4_PAE;
2569         cr4 |= host_cr4_mce;
2570         to_svm(vcpu)->vmcb->save.cr4 = cr4;
2571         mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2572         return 0;
2573 }
2574
2575 static void svm_set_segment(struct kvm_vcpu *vcpu,
2576                             struct kvm_segment *var, int seg)
2577 {
2578         struct vcpu_svm *svm = to_svm(vcpu);
2579         struct vmcb_seg *s = svm_seg(vcpu, seg);
2580
2581         s->base = var->base;
2582         s->limit = var->limit;
2583         s->selector = var->selector;
2584         s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2585         s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2586         s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2587         s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2588         s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2589         s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2590         s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2591         s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2592
2593         /*
2594          * This is always accurate, except if SYSRET returned to a segment
2595          * with SS.DPL != 3.  Intel does not have this quirk, and always
2596          * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2597          * would entail passing the CPL to userspace and back.
2598          */
2599         if (seg == VCPU_SREG_SS)
2600                 /* This is symmetric with svm_get_segment() */
2601                 svm->vmcb->save.cpl = (var->dpl & 3);
2602
2603         mark_dirty(svm->vmcb, VMCB_SEG);
2604 }
2605
2606 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2607 {
2608         struct vcpu_svm *svm = to_svm(vcpu);
2609
2610         clr_exception_intercept(svm, BP_VECTOR);
2611
2612         if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2613                 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2614                         set_exception_intercept(svm, BP_VECTOR);
2615         } else
2616                 vcpu->guest_debug = 0;
2617 }
2618
2619 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2620 {
2621         if (sd->next_asid > sd->max_asid) {
2622                 ++sd->asid_generation;
2623                 sd->next_asid = sd->min_asid;
2624                 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2625         }
2626
2627         svm->asid_generation = sd->asid_generation;
2628         svm->vmcb->control.asid = sd->next_asid++;
2629
2630         mark_dirty(svm->vmcb, VMCB_ASID);
2631 }
2632
2633 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2634 {
2635         return to_svm(vcpu)->vmcb->save.dr6;
2636 }
2637
2638 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2639 {
2640         struct vcpu_svm *svm = to_svm(vcpu);
2641
2642         svm->vmcb->save.dr6 = value;
2643         mark_dirty(svm->vmcb, VMCB_DR);
2644 }
2645
2646 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2647 {
2648         struct vcpu_svm *svm = to_svm(vcpu);
2649
2650         get_debugreg(vcpu->arch.db[0], 0);
2651         get_debugreg(vcpu->arch.db[1], 1);
2652         get_debugreg(vcpu->arch.db[2], 2);
2653         get_debugreg(vcpu->arch.db[3], 3);
2654         vcpu->arch.dr6 = svm_get_dr6(vcpu);
2655         vcpu->arch.dr7 = svm->vmcb->save.dr7;
2656
2657         vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2658         set_dr_intercepts(svm);
2659 }
2660
2661 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2662 {
2663         struct vcpu_svm *svm = to_svm(vcpu);
2664
2665         svm->vmcb->save.dr7 = value;
2666         mark_dirty(svm->vmcb, VMCB_DR);
2667 }
2668
2669 static int pf_interception(struct vcpu_svm *svm)
2670 {
2671         u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2672         u64 error_code = svm->vmcb->control.exit_info_1;
2673
2674         return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2675                         static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2676                         svm->vmcb->control.insn_bytes : NULL,
2677                         svm->vmcb->control.insn_len);
2678 }
2679
2680 static int npf_interception(struct vcpu_svm *svm)
2681 {
2682         u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2683         u64 error_code = svm->vmcb->control.exit_info_1;
2684
2685         trace_kvm_page_fault(fault_address, error_code);
2686         return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2687                         static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2688                         svm->vmcb->control.insn_bytes : NULL,
2689                         svm->vmcb->control.insn_len);
2690 }
2691
2692 static int db_interception(struct vcpu_svm *svm)
2693 {
2694         struct kvm_run *kvm_run = svm->vcpu.run;
2695
2696         if (!(svm->vcpu.guest_debug &
2697               (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2698                 !svm->nmi_singlestep) {
2699                 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2700                 return 1;
2701         }
2702
2703         if (svm->nmi_singlestep) {
2704                 disable_nmi_singlestep(svm);
2705         }
2706
2707         if (svm->vcpu.guest_debug &
2708             (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2709                 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2710                 kvm_run->debug.arch.pc =
2711                         svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2712                 kvm_run->debug.arch.exception = DB_VECTOR;
2713                 return 0;
2714         }
2715
2716         return 1;
2717 }
2718
2719 static int bp_interception(struct vcpu_svm *svm)
2720 {
2721         struct kvm_run *kvm_run = svm->vcpu.run;
2722
2723         kvm_run->exit_reason = KVM_EXIT_DEBUG;
2724         kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2725         kvm_run->debug.arch.exception = BP_VECTOR;
2726         return 0;
2727 }
2728
2729 static int ud_interception(struct vcpu_svm *svm)
2730 {
2731         return handle_ud(&svm->vcpu);
2732 }
2733
2734 static int ac_interception(struct vcpu_svm *svm)
2735 {
2736         kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2737         return 1;
2738 }
2739
2740 static int gp_interception(struct vcpu_svm *svm)
2741 {
2742         struct kvm_vcpu *vcpu = &svm->vcpu;
2743         u32 error_code = svm->vmcb->control.exit_info_1;
2744         int er;
2745
2746         WARN_ON_ONCE(!enable_vmware_backdoor);
2747
2748         er = kvm_emulate_instruction(vcpu,
2749                 EMULTYPE_VMWARE | EMULTYPE_NO_UD_ON_FAIL);
2750         if (er == EMULATE_USER_EXIT)
2751                 return 0;
2752         else if (er != EMULATE_DONE)
2753                 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2754         return 1;
2755 }
2756
2757 static bool is_erratum_383(void)
2758 {
2759         int err, i;
2760         u64 value;
2761
2762         if (!erratum_383_found)
2763                 return false;
2764
2765         value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2766         if (err)
2767                 return false;
2768
2769         /* Bit 62 may or may not be set for this mce */
2770         value &= ~(1ULL << 62);
2771
2772         if (value != 0xb600000000010015ULL)
2773                 return false;
2774
2775         /* Clear MCi_STATUS registers */
2776         for (i = 0; i < 6; ++i)
2777                 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2778
2779         value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2780         if (!err) {
2781                 u32 low, high;
2782
2783                 value &= ~(1ULL << 2);
2784                 low    = lower_32_bits(value);
2785                 high   = upper_32_bits(value);
2786
2787                 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2788         }
2789
2790         /* Flush tlb to evict multi-match entries */
2791         __flush_tlb_all();
2792
2793         return true;
2794 }
2795
2796 static void svm_handle_mce(struct vcpu_svm *svm)
2797 {
2798         if (is_erratum_383()) {
2799                 /*
2800                  * Erratum 383 triggered. Guest state is corrupt so kill the
2801                  * guest.
2802                  */
2803                 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2804
2805                 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2806
2807                 return;
2808         }
2809
2810         /*
2811          * On an #MC intercept the MCE handler is not called automatically in
2812          * the host. So do it by hand here.
2813          */
2814         asm volatile (
2815                 "int $0x12\n");
2816         /* not sure if we ever come back to this point */
2817
2818         return;
2819 }
2820
2821 static int mc_interception(struct vcpu_svm *svm)
2822 {
2823         return 1;
2824 }
2825
2826 static int shutdown_interception(struct vcpu_svm *svm)
2827 {
2828         struct kvm_run *kvm_run = svm->vcpu.run;
2829
2830         /*
2831          * VMCB is undefined after a SHUTDOWN intercept
2832          * so reinitialize it.
2833          */
2834         clear_page(svm->vmcb);
2835         init_vmcb(svm);
2836
2837         kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2838         return 0;
2839 }
2840
2841 static int io_interception(struct vcpu_svm *svm)
2842 {
2843         struct kvm_vcpu *vcpu = &svm->vcpu;
2844         u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2845         int size, in, string;
2846         unsigned port;
2847
2848         ++svm->vcpu.stat.io_exits;
2849         string = (io_info & SVM_IOIO_STR_MASK) != 0;
2850         in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2851         if (string)
2852                 return kvm_emulate_instruction(vcpu, 0) == EMULATE_DONE;
2853
2854         port = io_info >> 16;
2855         size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2856         svm->next_rip = svm->vmcb->control.exit_info_2;
2857
2858         return kvm_fast_pio(&svm->vcpu, size, port, in);
2859 }
2860
2861 static int nmi_interception(struct vcpu_svm *svm)
2862 {
2863         return 1;
2864 }
2865
2866 static int intr_interception(struct vcpu_svm *svm)
2867 {
2868         ++svm->vcpu.stat.irq_exits;
2869         return 1;
2870 }
2871
2872 static int nop_on_interception(struct vcpu_svm *svm)
2873 {
2874         return 1;
2875 }
2876
2877 static int halt_interception(struct vcpu_svm *svm)
2878 {
2879         svm->next_rip = kvm_rip_read(&svm->vcpu) + 1;
2880         return kvm_emulate_halt(&svm->vcpu);
2881 }
2882
2883 static int vmmcall_interception(struct vcpu_svm *svm)
2884 {
2885         svm->next_rip = kvm_rip_read(&svm->vcpu) + 3;
2886         return kvm_emulate_hypercall(&svm->vcpu);
2887 }
2888
2889 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2890 {
2891         struct vcpu_svm *svm = to_svm(vcpu);
2892
2893         return svm->nested.nested_cr3;
2894 }
2895
2896 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2897 {
2898         struct vcpu_svm *svm = to_svm(vcpu);
2899         u64 cr3 = svm->nested.nested_cr3;
2900         u64 pdpte;
2901         int ret;
2902
2903         ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2904                                        offset_in_page(cr3) + index * 8, 8);
2905         if (ret)
2906                 return 0;
2907         return pdpte;
2908 }
2909
2910 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2911                                    unsigned long root)
2912 {
2913         struct vcpu_svm *svm = to_svm(vcpu);
2914
2915         svm->vmcb->control.nested_cr3 = __sme_set(root);
2916         mark_dirty(svm->vmcb, VMCB_NPT);
2917 }
2918
2919 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2920                                        struct x86_exception *fault)
2921 {
2922         struct vcpu_svm *svm = to_svm(vcpu);
2923
2924         if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2925                 /*
2926                  * TODO: track the cause of the nested page fault, and
2927                  * correctly fill in the high bits of exit_info_1.
2928                  */
2929                 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
2930                 svm->vmcb->control.exit_code_hi = 0;
2931                 svm->vmcb->control.exit_info_1 = (1ULL << 32);
2932                 svm->vmcb->control.exit_info_2 = fault->address;
2933         }
2934
2935         svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
2936         svm->vmcb->control.exit_info_1 |= fault->error_code;
2937
2938         /*
2939          * The present bit is always zero for page structure faults on real
2940          * hardware.
2941          */
2942         if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
2943                 svm->vmcb->control.exit_info_1 &= ~1;
2944
2945         nested_svm_vmexit(svm);
2946 }
2947
2948 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2949 {
2950         WARN_ON(mmu_is_nested(vcpu));
2951
2952         vcpu->arch.mmu = &vcpu->arch.guest_mmu;
2953         kvm_init_shadow_mmu(vcpu);
2954         vcpu->arch.mmu->set_cr3           = nested_svm_set_tdp_cr3;
2955         vcpu->arch.mmu->get_cr3           = nested_svm_get_tdp_cr3;
2956         vcpu->arch.mmu->get_pdptr         = nested_svm_get_tdp_pdptr;
2957         vcpu->arch.mmu->inject_page_fault = nested_svm_inject_npf_exit;
2958         vcpu->arch.mmu->shadow_root_level = get_npt_level(vcpu);
2959         reset_shadow_zero_bits_mask(vcpu, vcpu->arch.mmu);
2960         vcpu->arch.walk_mmu              = &vcpu->arch.nested_mmu;
2961 }
2962
2963 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
2964 {
2965         vcpu->arch.mmu = &vcpu->arch.root_mmu;
2966         vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
2967 }
2968
2969 static int nested_svm_check_permissions(struct vcpu_svm *svm)
2970 {
2971         if (!(svm->vcpu.arch.efer & EFER_SVME) ||
2972             !is_paging(&svm->vcpu)) {
2973                 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
2974                 return 1;
2975         }
2976
2977         if (svm->vmcb->save.cpl) {
2978                 kvm_inject_gp(&svm->vcpu, 0);
2979                 return 1;
2980         }
2981
2982         return 0;
2983 }
2984
2985 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
2986                                       bool has_error_code, u32 error_code)
2987 {
2988         int vmexit;
2989
2990         if (!is_guest_mode(&svm->vcpu))
2991                 return 0;
2992
2993         vmexit = nested_svm_intercept(svm);
2994         if (vmexit != NESTED_EXIT_DONE)
2995                 return 0;
2996
2997         svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
2998         svm->vmcb->control.exit_code_hi = 0;
2999         svm->vmcb->control.exit_info_1 = error_code;
3000
3001         /*
3002          * EXITINFO2 is undefined for all exception intercepts other
3003          * than #PF.
3004          */
3005         if (svm->vcpu.arch.exception.nested_apf)
3006                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
3007         else if (svm->vcpu.arch.exception.has_payload)
3008                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.exception.payload;
3009         else
3010                 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
3011
3012         svm->nested.exit_required = true;
3013         return vmexit;
3014 }
3015
3016 /* This function returns true if it is save to enable the irq window */
3017 static inline bool nested_svm_intr(struct vcpu_svm *svm)
3018 {
3019         if (!is_guest_mode(&svm->vcpu))
3020                 return true;
3021
3022         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3023                 return true;
3024
3025         if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
3026                 return false;
3027
3028         /*
3029          * if vmexit was already requested (by intercepted exception
3030          * for instance) do not overwrite it with "external interrupt"
3031          * vmexit.
3032          */
3033         if (svm->nested.exit_required)
3034                 return false;
3035
3036         svm->vmcb->control.exit_code   = SVM_EXIT_INTR;
3037         svm->vmcb->control.exit_info_1 = 0;
3038         svm->vmcb->control.exit_info_2 = 0;
3039
3040         if (svm->nested.intercept & 1ULL) {
3041                 /*
3042                  * The #vmexit can't be emulated here directly because this
3043                  * code path runs with irqs and preemption disabled. A
3044                  * #vmexit emulation might sleep. Only signal request for
3045                  * the #vmexit here.
3046                  */
3047                 svm->nested.exit_required = true;
3048                 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
3049                 return false;
3050         }
3051
3052         return true;
3053 }
3054
3055 /* This function returns true if it is save to enable the nmi window */
3056 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
3057 {
3058         if (!is_guest_mode(&svm->vcpu))
3059                 return true;
3060
3061         if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
3062                 return true;
3063
3064         svm->vmcb->control.exit_code = SVM_EXIT_NMI;
3065         svm->nested.exit_required = true;
3066
3067         return false;
3068 }
3069
3070 static void *nested_svm_map(struct vcpu_svm *svm, u64 gpa, struct page **_page)
3071 {
3072         struct page *page;
3073
3074         might_sleep();
3075
3076         page = kvm_vcpu_gfn_to_page(&svm->vcpu, gpa >> PAGE_SHIFT);
3077         if (is_error_page(page))
3078                 goto error;
3079
3080         *_page = page;
3081
3082         return kmap(page);
3083
3084 error:
3085         kvm_inject_gp(&svm->vcpu, 0);
3086
3087         return NULL;
3088 }
3089
3090 static void nested_svm_unmap(struct page *page)
3091 {
3092         kunmap(page);
3093         kvm_release_page_dirty(page);
3094 }
3095
3096 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
3097 {
3098         unsigned port, size, iopm_len;
3099         u16 val, mask;
3100         u8 start_bit;
3101         u64 gpa;
3102
3103         if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
3104                 return NESTED_EXIT_HOST;
3105
3106         port = svm->vmcb->control.exit_info_1 >> 16;
3107         size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
3108                 SVM_IOIO_SIZE_SHIFT;
3109         gpa  = svm->nested.vmcb_iopm + (port / 8);
3110         start_bit = port % 8;
3111         iopm_len = (start_bit + size > 8) ? 2 : 1;
3112         mask = (0xf >> (4 - size)) << start_bit;
3113         val = 0;
3114
3115         if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
3116                 return NESTED_EXIT_DONE;
3117
3118         return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3119 }
3120
3121 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
3122 {
3123         u32 offset, msr, value;
3124         int write, mask;
3125
3126         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3127                 return NESTED_EXIT_HOST;
3128
3129         msr    = svm->vcpu.arch.regs[VCPU_REGS_RCX];
3130         offset = svm_msrpm_offset(msr);
3131         write  = svm->vmcb->control.exit_info_1 & 1;
3132         mask   = 1 << ((2 * (msr & 0xf)) + write);
3133
3134         if (offset == MSR_INVALID)
3135                 return NESTED_EXIT_DONE;
3136
3137         /* Offset is in 32 bit units but need in 8 bit units */
3138         offset *= 4;
3139
3140         if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
3141                 return NESTED_EXIT_DONE;
3142
3143         return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3144 }
3145
3146 /* DB exceptions for our internal use must not cause vmexit */
3147 static int nested_svm_intercept_db(struct vcpu_svm *svm)
3148 {
3149         unsigned long dr6;
3150
3151         /* if we're not singlestepping, it's not ours */
3152         if (!svm->nmi_singlestep)
3153                 return NESTED_EXIT_DONE;
3154
3155         /* if it's not a singlestep exception, it's not ours */
3156         if (kvm_get_dr(&svm->vcpu, 6, &dr6))
3157                 return NESTED_EXIT_DONE;
3158         if (!(dr6 & DR6_BS))
3159                 return NESTED_EXIT_DONE;
3160
3161         /* if the guest is singlestepping, it should get the vmexit */
3162         if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
3163                 disable_nmi_singlestep(svm);
3164                 return NESTED_EXIT_DONE;
3165         }
3166
3167         /* it's ours, the nested hypervisor must not see this one */
3168         return NESTED_EXIT_HOST;
3169 }
3170
3171 static int nested_svm_exit_special(struct vcpu_svm *svm)
3172 {
3173         u32 exit_code = svm->vmcb->control.exit_code;
3174
3175         switch (exit_code) {
3176         case SVM_EXIT_INTR:
3177         case SVM_EXIT_NMI:
3178         case SVM_EXIT_EXCP_BASE + MC_VECTOR:
3179                 return NESTED_EXIT_HOST;
3180         case SVM_EXIT_NPF:
3181                 /* For now we are always handling NPFs when using them */
3182                 if (npt_enabled)
3183                         return NESTED_EXIT_HOST;
3184                 break;
3185         case SVM_EXIT_EXCP_BASE + PF_VECTOR:
3186                 /* When we're shadowing, trap PFs, but not async PF */
3187                 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
3188                         return NESTED_EXIT_HOST;
3189                 break;
3190         default:
3191                 break;
3192         }
3193
3194         return NESTED_EXIT_CONTINUE;
3195 }
3196
3197 /*
3198  * If this function returns true, this #vmexit was already handled
3199  */
3200 static int nested_svm_intercept(struct vcpu_svm *svm)
3201 {
3202         u32 exit_code = svm->vmcb->control.exit_code;
3203         int vmexit = NESTED_EXIT_HOST;
3204
3205         switch (exit_code) {
3206         case SVM_EXIT_MSR:
3207                 vmexit = nested_svm_exit_handled_msr(svm);
3208                 break;
3209         case SVM_EXIT_IOIO:
3210                 vmexit = nested_svm_intercept_ioio(svm);
3211                 break;
3212         case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3213                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3214                 if (svm->nested.intercept_cr & bit)
3215                         vmexit = NESTED_EXIT_DONE;
3216                 break;
3217         }
3218         case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3219                 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3220                 if (svm->nested.intercept_dr & bit)
3221                         vmexit = NESTED_EXIT_DONE;
3222                 break;
3223         }
3224         case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3225                 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3226                 if (svm->nested.intercept_exceptions & excp_bits) {
3227                         if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3228                                 vmexit = nested_svm_intercept_db(svm);
3229                         else
3230                                 vmexit = NESTED_EXIT_DONE;
3231                 }
3232                 /* async page fault always cause vmexit */
3233                 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3234                          svm->vcpu.arch.exception.nested_apf != 0)
3235                         vmexit = NESTED_EXIT_DONE;
3236                 break;
3237         }
3238         case SVM_EXIT_ERR: {
3239                 vmexit = NESTED_EXIT_DONE;
3240                 break;
3241         }
3242         default: {
3243                 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3244                 if (svm->nested.intercept & exit_bits)
3245                         vmexit = NESTED_EXIT_DONE;
3246         }
3247         }
3248
3249         return vmexit;
3250 }
3251
3252 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3253 {
3254         int vmexit;
3255
3256         vmexit = nested_svm_intercept(svm);
3257
3258         if (vmexit == NESTED_EXIT_DONE)
3259                 nested_svm_vmexit(svm);
3260
3261         return vmexit;
3262 }
3263
3264 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3265 {
3266         struct vmcb_control_area *dst  = &dst_vmcb->control;
3267         struct vmcb_control_area *from = &from_vmcb->control;
3268
3269         dst->intercept_cr         = from->intercept_cr;
3270         dst->intercept_dr         = from->intercept_dr;
3271         dst->intercept_exceptions = from->intercept_exceptions;
3272         dst->intercept            = from->intercept;
3273         dst->iopm_base_pa         = from->iopm_base_pa;
3274         dst->msrpm_base_pa        = from->msrpm_base_pa;
3275         dst->tsc_offset           = from->tsc_offset;
3276         dst->asid                 = from->asid;
3277         dst->tlb_ctl              = from->tlb_ctl;
3278         dst->int_ctl              = from->int_ctl;
3279         dst->int_vector           = from->int_vector;
3280         dst->int_state            = from->int_state;
3281         dst->exit_code            = from->exit_code;
3282         dst->exit_code_hi         = from->exit_code_hi;
3283         dst->exit_info_1          = from->exit_info_1;
3284         dst->exit_info_2          = from->exit_info_2;
3285         dst->exit_int_info        = from->exit_int_info;
3286         dst->exit_int_info_err    = from->exit_int_info_err;
3287         dst->nested_ctl           = from->nested_ctl;
3288         dst->event_inj            = from->event_inj;
3289         dst->event_inj_err        = from->event_inj_err;
3290         dst->nested_cr3           = from->nested_cr3;
3291         dst->virt_ext              = from->virt_ext;
3292         dst->pause_filter_count   = from->pause_filter_count;
3293         dst->pause_filter_thresh  = from->pause_filter_thresh;
3294 }
3295
3296 static int nested_svm_vmexit(struct vcpu_svm *svm)
3297 {
3298         struct vmcb *nested_vmcb;
3299         struct vmcb *hsave = svm->nested.hsave;
3300         struct vmcb *vmcb = svm->vmcb;
3301         struct page *page;
3302
3303         trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3304                                        vmcb->control.exit_info_1,
3305                                        vmcb->control.exit_info_2,
3306                                        vmcb->control.exit_int_info,
3307                                        vmcb->control.exit_int_info_err,
3308                                        KVM_ISA_SVM);
3309
3310         nested_vmcb = nested_svm_map(svm, svm->nested.vmcb, &page);
3311         if (!nested_vmcb)
3312                 return 1;
3313
3314         /* Exit Guest-Mode */
3315         leave_guest_mode(&svm->vcpu);
3316         svm->nested.vmcb = 0;
3317
3318         /* Give the current vmcb to the guest */
3319         disable_gif(svm);
3320
3321         nested_vmcb->save.es     = vmcb->save.es;
3322         nested_vmcb->save.cs     = vmcb->save.cs;
3323         nested_vmcb->save.ss     = vmcb->save.ss;
3324         nested_vmcb->save.ds     = vmcb->save.ds;
3325         nested_vmcb->save.gdtr   = vmcb->save.gdtr;
3326         nested_vmcb->save.idtr   = vmcb->save.idtr;
3327         nested_vmcb->save.efer   = svm->vcpu.arch.efer;
3328         nested_vmcb->save.cr0    = kvm_read_cr0(&svm->vcpu);
3329         nested_vmcb->save.cr3    = kvm_read_cr3(&svm->vcpu);
3330         nested_vmcb->save.cr2    = vmcb->save.cr2;
3331         nested_vmcb->save.cr4    = svm->vcpu.arch.cr4;
3332         nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3333         nested_vmcb->save.rip    = vmcb->save.rip;
3334         nested_vmcb->save.rsp    = vmcb->save.rsp;
3335         nested_vmcb->save.rax    = vmcb->save.rax;
3336         nested_vmcb->save.dr7    = vmcb->save.dr7;
3337         nested_vmcb->save.dr6    = vmcb->save.dr6;
3338         nested_vmcb->save.cpl    = vmcb->save.cpl;
3339
3340         nested_vmcb->control.int_ctl           = vmcb->control.int_ctl;
3341         nested_vmcb->control.int_vector        = vmcb->control.int_vector;
3342         nested_vmcb->control.int_state         = vmcb->control.int_state;
3343         nested_vmcb->control.exit_code         = vmcb->control.exit_code;
3344         nested_vmcb->control.exit_code_hi      = vmcb->control.exit_code_hi;
3345         nested_vmcb->control.exit_info_1       = vmcb->control.exit_info_1;
3346         nested_vmcb->control.exit_info_2       = vmcb->control.exit_info_2;
3347         nested_vmcb->control.exit_int_info     = vmcb->control.exit_int_info;
3348         nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3349
3350         if (svm->nrips_enabled)
3351                 nested_vmcb->control.next_rip  = vmcb->control.next_rip;
3352
3353         /*
3354          * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3355          * to make sure that we do not lose injected events. So check event_inj
3356          * here and copy it to exit_int_info if it is valid.
3357          * Exit_int_info and event_inj can't be both valid because the case
3358          * below only happens on a VMRUN instruction intercept which has
3359          * no valid exit_int_info set.
3360          */
3361         if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3362                 struct vmcb_control_area *nc = &nested_vmcb->control;
3363
3364                 nc->exit_int_info     = vmcb->control.event_inj;
3365                 nc->exit_int_info_err = vmcb->control.event_inj_err;
3366         }
3367
3368         nested_vmcb->control.tlb_ctl           = 0;
3369         nested_vmcb->control.event_inj         = 0;
3370         nested_vmcb->control.event_inj_err     = 0;
3371
3372         nested_vmcb->control.pause_filter_count =
3373                 svm->vmcb->control.pause_filter_count;
3374         nested_vmcb->control.pause_filter_thresh =
3375                 svm->vmcb->control.pause_filter_thresh;
3376
3377         /* We always set V_INTR_MASKING and remember the old value in hflags */
3378         if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3379                 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3380
3381         /* Restore the original control entries */
3382         copy_vmcb_control_area(vmcb, hsave);
3383
3384         svm->vcpu.arch.tsc_offset = svm->vmcb->control.tsc_offset;
3385         kvm_clear_exception_queue(&svm->vcpu);
3386         kvm_clear_interrupt_queue(&svm->vcpu);
3387
3388         svm->nested.nested_cr3 = 0;
3389
3390         /* Restore selected save entries */
3391         svm->vmcb->save.es = hsave->save.es;
3392         svm->vmcb->save.cs = hsave->save.cs;
3393         svm->vmcb->save.ss = hsave->save.ss;
3394         svm->vmcb->save.ds = hsave->save.ds;
3395         svm->vmcb->save.gdtr = hsave->save.gdtr;
3396         svm->vmcb->save.idtr = hsave->save.idtr;
3397         kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3398         svm_set_efer(&svm->vcpu, hsave->save.efer);
3399         svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3400         svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3401         if (npt_enabled) {
3402                 svm->vmcb->save.cr3 = hsave->save.cr3;
3403                 svm->vcpu.arch.cr3 = hsave->save.cr3;
3404         } else {
3405                 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3406         }
3407         kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, hsave->save.rax);
3408         kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, hsave->save.rsp);
3409         kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, hsave->save.rip);
3410         svm->vmcb->save.dr7 = 0;
3411         svm->vmcb->save.cpl = 0;
3412         svm->vmcb->control.exit_int_info = 0;
3413
3414         mark_all_dirty(svm->vmcb);
3415
3416         nested_svm_unmap(page);
3417
3418         nested_svm_uninit_mmu_context(&svm->vcpu);
3419         kvm_mmu_reset_context(&svm->vcpu);
3420         kvm_mmu_load(&svm->vcpu);
3421
3422         /*
3423          * Drop what we picked up for L2 via svm_complete_interrupts() so it
3424          * doesn't end up in L1.
3425          */
3426         svm->vcpu.arch.nmi_injected = false;
3427         kvm_clear_exception_queue(&svm->vcpu);
3428         kvm_clear_interrupt_queue(&svm->vcpu);
3429
3430         return 0;
3431 }
3432
3433 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3434 {
3435         /*
3436          * This function merges the msr permission bitmaps of kvm and the
3437          * nested vmcb. It is optimized in that it only merges the parts where
3438          * the kvm msr permission bitmap may contain zero bits
3439          */
3440         int i;
3441
3442         if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3443                 return true;
3444
3445         for (i = 0; i < MSRPM_OFFSETS; i++) {
3446                 u32 value, p;
3447                 u64 offset;
3448
3449                 if (msrpm_offsets[i] == 0xffffffff)
3450                         break;
3451
3452                 p      = msrpm_offsets[i];
3453                 offset = svm->nested.vmcb_msrpm + (p * 4);
3454
3455                 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3456                         return false;
3457
3458                 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3459         }
3460
3461         svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3462
3463         return true;
3464 }
3465
3466 static bool nested_vmcb_checks(struct vmcb *vmcb)
3467 {
3468         if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3469                 return false;
3470
3471         if (vmcb->control.asid == 0)
3472                 return false;
3473
3474         if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3475             !npt_enabled)
3476                 return false;
3477
3478         return true;
3479 }
3480
3481 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3482                                  struct vmcb *nested_vmcb, struct page *page)
3483 {
3484         if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3485                 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3486         else
3487                 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3488
3489         if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3490                 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3491                 nested_svm_init_mmu_context(&svm->vcpu);
3492         }
3493
3494         /* Load the nested guest state */
3495         svm->vmcb->save.es = nested_vmcb->save.es;
3496         svm->vmcb->save.cs = nested_vmcb->save.cs;
3497         svm->vmcb->save.ss = nested_vmcb->save.ss;
3498         svm->vmcb->save.ds = nested_vmcb->save.ds;
3499         svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3500         svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3501         kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3502         svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3503         svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3504         svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3505         if (npt_enabled) {
3506                 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3507                 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3508         } else
3509                 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3510
3511         /* Guest paging mode is active - reset mmu */
3512         kvm_mmu_reset_context(&svm->vcpu);
3513
3514         svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3515         kvm_register_write(&svm->vcpu, VCPU_REGS_RAX, nested_vmcb->save.rax);
3516         kvm_register_write(&svm->vcpu, VCPU_REGS_RSP, nested_vmcb->save.rsp);
3517         kvm_register_write(&svm->vcpu, VCPU_REGS_RIP, nested_vmcb->save.rip);
3518
3519         /* In case we don't even reach vcpu_run, the fields are not updated */
3520         svm->vmcb->save.rax = nested_vmcb->save.rax;
3521         svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3522         svm->vmcb->save.rip = nested_vmcb->save.rip;
3523         svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3524         svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3525         svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3526
3527         svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3528         svm->nested.vmcb_iopm  = nested_vmcb->control.iopm_base_pa  & ~0x0fffULL;
3529
3530         /* cache intercepts */
3531         svm->nested.intercept_cr         = nested_vmcb->control.intercept_cr;
3532         svm->nested.intercept_dr         = nested_vmcb->control.intercept_dr;
3533         svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3534         svm->nested.intercept            = nested_vmcb->control.intercept;
3535
3536         svm_flush_tlb(&svm->vcpu, true);
3537         svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3538         if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3539                 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3540         else
3541                 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3542
3543         if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3544                 /* We only want the cr8 intercept bits of the guest */
3545                 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3546                 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3547         }
3548
3549         /* We don't want to see VMMCALLs from a nested guest */
3550         clr_intercept(svm, INTERCEPT_VMMCALL);
3551
3552         svm->vcpu.arch.tsc_offset += nested_vmcb->control.tsc_offset;
3553         svm->vmcb->control.tsc_offset = svm->vcpu.arch.tsc_offset;
3554
3555         svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3556         svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3557         svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3558         svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3559         svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3560
3561         svm->vmcb->control.pause_filter_count =
3562                 nested_vmcb->control.pause_filter_count;
3563         svm->vmcb->control.pause_filter_thresh =
3564                 nested_vmcb->control.pause_filter_thresh;
3565
3566         nested_svm_unmap(page);
3567
3568         /* Enter Guest-Mode */
3569         enter_guest_mode(&svm->vcpu);
3570
3571         /*
3572          * Merge guest and host intercepts - must be called  with vcpu in
3573          * guest-mode to take affect here
3574          */
3575         recalc_intercepts(svm);
3576
3577         svm->nested.vmcb = vmcb_gpa;
3578
3579         enable_gif(svm);
3580
3581         mark_all_dirty(svm->vmcb);
3582 }
3583
3584 static bool nested_svm_vmrun(struct vcpu_svm *svm)
3585 {
3586         struct vmcb *nested_vmcb;
3587         struct vmcb *hsave = svm->nested.hsave;
3588         struct vmcb *vmcb = svm->vmcb;
3589         struct page *page;
3590         u64 vmcb_gpa;
3591
3592         vmcb_gpa = svm->vmcb->save.rax;
3593
3594         nested_vmcb = nested_svm_map(svm, svm->vmcb->save.rax, &page);
3595         if (!nested_vmcb)
3596                 return false;
3597
3598         if (!nested_vmcb_checks(nested_vmcb)) {
3599                 nested_vmcb->control.exit_code    = SVM_EXIT_ERR;
3600                 nested_vmcb->control.exit_code_hi = 0;
3601                 nested_vmcb->control.exit_info_1  = 0;
3602                 nested_vmcb->control.exit_info_2  = 0;
3603
3604                 nested_svm_unmap(page);
3605
3606                 return false;
3607         }
3608
3609         trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3610                                nested_vmcb->save.rip,
3611                                nested_vmcb->control.int_ctl,
3612                                nested_vmcb->control.event_inj,
3613                                nested_vmcb->control.nested_ctl);
3614
3615         trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3616                                     nested_vmcb->control.intercept_cr >> 16,
3617                                     nested_vmcb->control.intercept_exceptions,
3618                                     nested_vmcb->control.intercept);
3619
3620         /* Clear internal status */
3621         kvm_clear_exception_queue(&svm->vcpu);
3622         kvm_clear_interrupt_queue(&svm->vcpu);
3623
3624         /*
3625          * Save the old vmcb, so we don't need to pick what we save, but can
3626          * restore everything when a VMEXIT occurs
3627          */
3628         hsave->save.es     = vmcb->save.es;
3629         hsave->save.cs     = vmcb->save.cs;
3630         hsave->save.ss     = vmcb->save.ss;
3631         hsave->save.ds     = vmcb->save.ds;
3632         hsave->save.gdtr   = vmcb->save.gdtr;
3633         hsave->save.idtr   = vmcb->save.idtr;
3634         hsave->save.efer   = svm->vcpu.arch.efer;
3635         hsave->save.cr0    = kvm_read_cr0(&svm->vcpu);
3636         hsave->save.cr4    = svm->vcpu.arch.cr4;
3637         hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3638         hsave->save.rip    = kvm_rip_read(&svm->vcpu);
3639         hsave->save.rsp    = vmcb->save.rsp;
3640         hsave->save.rax    = vmcb->save.rax;
3641         if (npt_enabled)
3642                 hsave->save.cr3    = vmcb->save.cr3;
3643         else
3644                 hsave->save.cr3    = kvm_read_cr3(&svm->vcpu);
3645
3646         copy_vmcb_control_area(hsave, vmcb);
3647
3648         enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, page);
3649
3650         return true;
3651 }
3652