]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blob - arch/x86/kvm/svm.c
KVM: VMX: Rename {vmx,nested_vmx}_vcpu_setup()
[mirror_ubuntu-hirsute-kernel.git] / arch / x86 / kvm / svm.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Kernel-based Virtual Machine driver for Linux
4 *
5 * AMD SVM support
6 *
7 * Copyright (C) 2006 Qumranet, Inc.
8 * Copyright 2010 Red Hat, Inc. and/or its affiliates.
9 *
10 * Authors:
11 * Yaniv Kamay <yaniv@qumranet.com>
12 * Avi Kivity <avi@qumranet.com>
13 */
14
15 #define pr_fmt(fmt) "SVM: " fmt
16
17 #include <linux/kvm_host.h>
18
19 #include "irq.h"
20 #include "mmu.h"
21 #include "kvm_cache_regs.h"
22 #include "x86.h"
23 #include "cpuid.h"
24 #include "pmu.h"
25
26 #include <linux/module.h>
27 #include <linux/mod_devicetable.h>
28 #include <linux/kernel.h>
29 #include <linux/vmalloc.h>
30 #include <linux/highmem.h>
31 #include <linux/sched.h>
32 #include <linux/trace_events.h>
33 #include <linux/slab.h>
34 #include <linux/amd-iommu.h>
35 #include <linux/hashtable.h>
36 #include <linux/frame.h>
37 #include <linux/psp-sev.h>
38 #include <linux/file.h>
39 #include <linux/pagemap.h>
40 #include <linux/swap.h>
41 #include <linux/rwsem.h>
42
43 #include <asm/apic.h>
44 #include <asm/perf_event.h>
45 #include <asm/tlbflush.h>
46 #include <asm/desc.h>
47 #include <asm/debugreg.h>
48 #include <asm/kvm_para.h>
49 #include <asm/irq_remapping.h>
50 #include <asm/spec-ctrl.h>
51
52 #include <asm/virtext.h>
53 #include "trace.h"
54
55 #define __ex(x) __kvm_handle_fault_on_reboot(x)
56
57 MODULE_AUTHOR("Qumranet");
58 MODULE_LICENSE("GPL");
59
60 static const struct x86_cpu_id svm_cpu_id[] = {
61 X86_FEATURE_MATCH(X86_FEATURE_SVM),
62 {}
63 };
64 MODULE_DEVICE_TABLE(x86cpu, svm_cpu_id);
65
66 #define IOPM_ALLOC_ORDER 2
67 #define MSRPM_ALLOC_ORDER 1
68
69 #define SEG_TYPE_LDT 2
70 #define SEG_TYPE_BUSY_TSS16 3
71
72 #define SVM_FEATURE_LBRV (1 << 1)
73 #define SVM_FEATURE_SVML (1 << 2)
74 #define SVM_FEATURE_TSC_RATE (1 << 4)
75 #define SVM_FEATURE_VMCB_CLEAN (1 << 5)
76 #define SVM_FEATURE_FLUSH_ASID (1 << 6)
77 #define SVM_FEATURE_DECODE_ASSIST (1 << 7)
78 #define SVM_FEATURE_PAUSE_FILTER (1 << 10)
79
80 #define SVM_AVIC_DOORBELL 0xc001011b
81
82 #define NESTED_EXIT_HOST 0 /* Exit handled on host level */
83 #define NESTED_EXIT_DONE 1 /* Exit caused nested vmexit */
84 #define NESTED_EXIT_CONTINUE 2 /* Further checks needed */
85
86 #define DEBUGCTL_RESERVED_BITS (~(0x3fULL))
87
88 #define TSC_RATIO_RSVD 0xffffff0000000000ULL
89 #define TSC_RATIO_MIN 0x0000000000000001ULL
90 #define TSC_RATIO_MAX 0x000000ffffffffffULL
91
92 #define AVIC_HPA_MASK ~((0xFFFULL << 52) | 0xFFF)
93
94 /*
95 * 0xff is broadcast, so the max index allowed for physical APIC ID
96 * table is 0xfe. APIC IDs above 0xff are reserved.
97 */
98 #define AVIC_MAX_PHYSICAL_ID_COUNT 255
99
100 #define AVIC_UNACCEL_ACCESS_WRITE_MASK 1
101 #define AVIC_UNACCEL_ACCESS_OFFSET_MASK 0xFF0
102 #define AVIC_UNACCEL_ACCESS_VECTOR_MASK 0xFFFFFFFF
103
104 /* AVIC GATAG is encoded using VM and VCPU IDs */
105 #define AVIC_VCPU_ID_BITS 8
106 #define AVIC_VCPU_ID_MASK ((1 << AVIC_VCPU_ID_BITS) - 1)
107
108 #define AVIC_VM_ID_BITS 24
109 #define AVIC_VM_ID_NR (1 << AVIC_VM_ID_BITS)
110 #define AVIC_VM_ID_MASK ((1 << AVIC_VM_ID_BITS) - 1)
111
112 #define AVIC_GATAG(x, y) (((x & AVIC_VM_ID_MASK) << AVIC_VCPU_ID_BITS) | \
113 (y & AVIC_VCPU_ID_MASK))
114 #define AVIC_GATAG_TO_VMID(x) ((x >> AVIC_VCPU_ID_BITS) & AVIC_VM_ID_MASK)
115 #define AVIC_GATAG_TO_VCPUID(x) (x & AVIC_VCPU_ID_MASK)
116
117 static bool erratum_383_found __read_mostly;
118
119 static const u32 host_save_user_msrs[] = {
120 #ifdef CONFIG_X86_64
121 MSR_STAR, MSR_LSTAR, MSR_CSTAR, MSR_SYSCALL_MASK, MSR_KERNEL_GS_BASE,
122 MSR_FS_BASE,
123 #endif
124 MSR_IA32_SYSENTER_CS, MSR_IA32_SYSENTER_ESP, MSR_IA32_SYSENTER_EIP,
125 MSR_TSC_AUX,
126 };
127
128 #define NR_HOST_SAVE_USER_MSRS ARRAY_SIZE(host_save_user_msrs)
129
130 struct kvm_sev_info {
131 bool active; /* SEV enabled guest */
132 unsigned int asid; /* ASID used for this guest */
133 unsigned int handle; /* SEV firmware handle */
134 int fd; /* SEV device fd */
135 unsigned long pages_locked; /* Number of pages locked */
136 struct list_head regions_list; /* List of registered regions */
137 };
138
139 struct kvm_svm {
140 struct kvm kvm;
141
142 /* Struct members for AVIC */
143 u32 avic_vm_id;
144 struct page *avic_logical_id_table_page;
145 struct page *avic_physical_id_table_page;
146 struct hlist_node hnode;
147
148 struct kvm_sev_info sev_info;
149 };
150
151 struct kvm_vcpu;
152
153 struct nested_state {
154 struct vmcb *hsave;
155 u64 hsave_msr;
156 u64 vm_cr_msr;
157 u64 vmcb;
158
159 /* These are the merged vectors */
160 u32 *msrpm;
161
162 /* gpa pointers to the real vectors */
163 u64 vmcb_msrpm;
164 u64 vmcb_iopm;
165
166 /* A VMEXIT is required but not yet emulated */
167 bool exit_required;
168
169 /* cache for intercepts of the guest */
170 u32 intercept_cr;
171 u32 intercept_dr;
172 u32 intercept_exceptions;
173 u64 intercept;
174
175 /* Nested Paging related state */
176 u64 nested_cr3;
177 };
178
179 #define MSRPM_OFFSETS 16
180 static u32 msrpm_offsets[MSRPM_OFFSETS] __read_mostly;
181
182 /*
183 * Set osvw_len to higher value when updated Revision Guides
184 * are published and we know what the new status bits are
185 */
186 static uint64_t osvw_len = 4, osvw_status;
187
188 struct vcpu_svm {
189 struct kvm_vcpu vcpu;
190 struct vmcb *vmcb;
191 unsigned long vmcb_pa;
192 struct svm_cpu_data *svm_data;
193 uint64_t asid_generation;
194 uint64_t sysenter_esp;
195 uint64_t sysenter_eip;
196 uint64_t tsc_aux;
197
198 u64 msr_decfg;
199
200 u64 next_rip;
201
202 u64 host_user_msrs[NR_HOST_SAVE_USER_MSRS];
203 struct {
204 u16 fs;
205 u16 gs;
206 u16 ldt;
207 u64 gs_base;
208 } host;
209
210 u64 spec_ctrl;
211 /*
212 * Contains guest-controlled bits of VIRT_SPEC_CTRL, which will be
213 * translated into the appropriate L2_CFG bits on the host to
214 * perform speculative control.
215 */
216 u64 virt_spec_ctrl;
217
218 u32 *msrpm;
219
220 ulong nmi_iret_rip;
221
222 struct nested_state nested;
223
224 bool nmi_singlestep;
225 u64 nmi_singlestep_guest_rflags;
226
227 unsigned int3_injected;
228 unsigned long int3_rip;
229
230 /* cached guest cpuid flags for faster access */
231 bool nrips_enabled : 1;
232
233 u32 ldr_reg;
234 u32 dfr_reg;
235 struct page *avic_backing_page;
236 u64 *avic_physical_id_cache;
237 bool avic_is_running;
238
239 /*
240 * Per-vcpu list of struct amd_svm_iommu_ir:
241 * This is used mainly to store interrupt remapping information used
242 * when update the vcpu affinity. This avoids the need to scan for
243 * IRTE and try to match ga_tag in the IOMMU driver.
244 */
245 struct list_head ir_list;
246 spinlock_t ir_list_lock;
247
248 /* which host CPU was used for running this vcpu */
249 unsigned int last_cpu;
250 };
251
252 /*
253 * This is a wrapper of struct amd_iommu_ir_data.
254 */
255 struct amd_svm_iommu_ir {
256 struct list_head node; /* Used by SVM for per-vcpu ir_list */
257 void *data; /* Storing pointer to struct amd_ir_data */
258 };
259
260 #define AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK (0xFF)
261 #define AVIC_LOGICAL_ID_ENTRY_VALID_BIT 31
262 #define AVIC_LOGICAL_ID_ENTRY_VALID_MASK (1 << 31)
263
264 #define AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK (0xFFULL)
265 #define AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK (0xFFFFFFFFFFULL << 12)
266 #define AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK (1ULL << 62)
267 #define AVIC_PHYSICAL_ID_ENTRY_VALID_MASK (1ULL << 63)
268
269 static DEFINE_PER_CPU(u64, current_tsc_ratio);
270 #define TSC_RATIO_DEFAULT 0x0100000000ULL
271
272 #define MSR_INVALID 0xffffffffU
273
274 static const struct svm_direct_access_msrs {
275 u32 index; /* Index of the MSR */
276 bool always; /* True if intercept is always on */
277 } direct_access_msrs[] = {
278 { .index = MSR_STAR, .always = true },
279 { .index = MSR_IA32_SYSENTER_CS, .always = true },
280 #ifdef CONFIG_X86_64
281 { .index = MSR_GS_BASE, .always = true },
282 { .index = MSR_FS_BASE, .always = true },
283 { .index = MSR_KERNEL_GS_BASE, .always = true },
284 { .index = MSR_LSTAR, .always = true },
285 { .index = MSR_CSTAR, .always = true },
286 { .index = MSR_SYSCALL_MASK, .always = true },
287 #endif
288 { .index = MSR_IA32_SPEC_CTRL, .always = false },
289 { .index = MSR_IA32_PRED_CMD, .always = false },
290 { .index = MSR_IA32_LASTBRANCHFROMIP, .always = false },
291 { .index = MSR_IA32_LASTBRANCHTOIP, .always = false },
292 { .index = MSR_IA32_LASTINTFROMIP, .always = false },
293 { .index = MSR_IA32_LASTINTTOIP, .always = false },
294 { .index = MSR_INVALID, .always = false },
295 };
296
297 /* enable NPT for AMD64 and X86 with PAE */
298 #if defined(CONFIG_X86_64) || defined(CONFIG_X86_PAE)
299 static bool npt_enabled = true;
300 #else
301 static bool npt_enabled;
302 #endif
303
304 /*
305 * These 2 parameters are used to config the controls for Pause-Loop Exiting:
306 * pause_filter_count: On processors that support Pause filtering(indicated
307 * by CPUID Fn8000_000A_EDX), the VMCB provides a 16 bit pause filter
308 * count value. On VMRUN this value is loaded into an internal counter.
309 * Each time a pause instruction is executed, this counter is decremented
310 * until it reaches zero at which time a #VMEXIT is generated if pause
311 * intercept is enabled. Refer to AMD APM Vol 2 Section 15.14.4 Pause
312 * Intercept Filtering for more details.
313 * This also indicate if ple logic enabled.
314 *
315 * pause_filter_thresh: In addition, some processor families support advanced
316 * pause filtering (indicated by CPUID Fn8000_000A_EDX) upper bound on
317 * the amount of time a guest is allowed to execute in a pause loop.
318 * In this mode, a 16-bit pause filter threshold field is added in the
319 * VMCB. The threshold value is a cycle count that is used to reset the
320 * pause counter. As with simple pause filtering, VMRUN loads the pause
321 * count value from VMCB into an internal counter. Then, on each pause
322 * instruction the hardware checks the elapsed number of cycles since
323 * the most recent pause instruction against the pause filter threshold.
324 * If the elapsed cycle count is greater than the pause filter threshold,
325 * then the internal pause count is reloaded from the VMCB and execution
326 * continues. If the elapsed cycle count is less than the pause filter
327 * threshold, then the internal pause count is decremented. If the count
328 * value is less than zero and PAUSE intercept is enabled, a #VMEXIT is
329 * triggered. If advanced pause filtering is supported and pause filter
330 * threshold field is set to zero, the filter will operate in the simpler,
331 * count only mode.
332 */
333
334 static unsigned short pause_filter_thresh = KVM_DEFAULT_PLE_GAP;
335 module_param(pause_filter_thresh, ushort, 0444);
336
337 static unsigned short pause_filter_count = KVM_SVM_DEFAULT_PLE_WINDOW;
338 module_param(pause_filter_count, ushort, 0444);
339
340 /* Default doubles per-vcpu window every exit. */
341 static unsigned short pause_filter_count_grow = KVM_DEFAULT_PLE_WINDOW_GROW;
342 module_param(pause_filter_count_grow, ushort, 0444);
343
344 /* Default resets per-vcpu window every exit to pause_filter_count. */
345 static unsigned short pause_filter_count_shrink = KVM_DEFAULT_PLE_WINDOW_SHRINK;
346 module_param(pause_filter_count_shrink, ushort, 0444);
347
348 /* Default is to compute the maximum so we can never overflow. */
349 static unsigned short pause_filter_count_max = KVM_SVM_DEFAULT_PLE_WINDOW_MAX;
350 module_param(pause_filter_count_max, ushort, 0444);
351
352 /* allow nested paging (virtualized MMU) for all guests */
353 static int npt = true;
354 module_param(npt, int, S_IRUGO);
355
356 /* allow nested virtualization in KVM/SVM */
357 static int nested = true;
358 module_param(nested, int, S_IRUGO);
359
360 /* enable / disable AVIC */
361 static int avic;
362 #ifdef CONFIG_X86_LOCAL_APIC
363 module_param(avic, int, S_IRUGO);
364 #endif
365
366 /* enable/disable Next RIP Save */
367 static int nrips = true;
368 module_param(nrips, int, 0444);
369
370 /* enable/disable Virtual VMLOAD VMSAVE */
371 static int vls = true;
372 module_param(vls, int, 0444);
373
374 /* enable/disable Virtual GIF */
375 static int vgif = true;
376 module_param(vgif, int, 0444);
377
378 /* enable/disable SEV support */
379 static int sev = IS_ENABLED(CONFIG_AMD_MEM_ENCRYPT_ACTIVE_BY_DEFAULT);
380 module_param(sev, int, 0444);
381
382 static bool __read_mostly dump_invalid_vmcb = 0;
383 module_param(dump_invalid_vmcb, bool, 0644);
384
385 static u8 rsm_ins_bytes[] = "\x0f\xaa";
386
387 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0);
388 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa);
389 static void svm_complete_interrupts(struct vcpu_svm *svm);
390
391 static int nested_svm_exit_handled(struct vcpu_svm *svm);
392 static int nested_svm_intercept(struct vcpu_svm *svm);
393 static int nested_svm_vmexit(struct vcpu_svm *svm);
394 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
395 bool has_error_code, u32 error_code);
396
397 enum {
398 VMCB_INTERCEPTS, /* Intercept vectors, TSC offset,
399 pause filter count */
400 VMCB_PERM_MAP, /* IOPM Base and MSRPM Base */
401 VMCB_ASID, /* ASID */
402 VMCB_INTR, /* int_ctl, int_vector */
403 VMCB_NPT, /* npt_en, nCR3, gPAT */
404 VMCB_CR, /* CR0, CR3, CR4, EFER */
405 VMCB_DR, /* DR6, DR7 */
406 VMCB_DT, /* GDT, IDT */
407 VMCB_SEG, /* CS, DS, SS, ES, CPL */
408 VMCB_CR2, /* CR2 only */
409 VMCB_LBR, /* DBGCTL, BR_FROM, BR_TO, LAST_EX_FROM, LAST_EX_TO */
410 VMCB_AVIC, /* AVIC APIC_BAR, AVIC APIC_BACKING_PAGE,
411 * AVIC PHYSICAL_TABLE pointer,
412 * AVIC LOGICAL_TABLE pointer
413 */
414 VMCB_DIRTY_MAX,
415 };
416
417 /* TPR and CR2 are always written before VMRUN */
418 #define VMCB_ALWAYS_DIRTY_MASK ((1U << VMCB_INTR) | (1U << VMCB_CR2))
419
420 #define VMCB_AVIC_APIC_BAR_MASK 0xFFFFFFFFFF000ULL
421
422 static int sev_flush_asids(void);
423 static DECLARE_RWSEM(sev_deactivate_lock);
424 static DEFINE_MUTEX(sev_bitmap_lock);
425 static unsigned int max_sev_asid;
426 static unsigned int min_sev_asid;
427 static unsigned long *sev_asid_bitmap;
428 static unsigned long *sev_reclaim_asid_bitmap;
429 #define __sme_page_pa(x) __sme_set(page_to_pfn(x) << PAGE_SHIFT)
430
431 struct enc_region {
432 struct list_head list;
433 unsigned long npages;
434 struct page **pages;
435 unsigned long uaddr;
436 unsigned long size;
437 };
438
439
440 static inline struct kvm_svm *to_kvm_svm(struct kvm *kvm)
441 {
442 return container_of(kvm, struct kvm_svm, kvm);
443 }
444
445 static inline bool svm_sev_enabled(void)
446 {
447 return IS_ENABLED(CONFIG_KVM_AMD_SEV) ? max_sev_asid : 0;
448 }
449
450 static inline bool sev_guest(struct kvm *kvm)
451 {
452 #ifdef CONFIG_KVM_AMD_SEV
453 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
454
455 return sev->active;
456 #else
457 return false;
458 #endif
459 }
460
461 static inline int sev_get_asid(struct kvm *kvm)
462 {
463 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
464
465 return sev->asid;
466 }
467
468 static inline void mark_all_dirty(struct vmcb *vmcb)
469 {
470 vmcb->control.clean = 0;
471 }
472
473 static inline void mark_all_clean(struct vmcb *vmcb)
474 {
475 vmcb->control.clean = ((1 << VMCB_DIRTY_MAX) - 1)
476 & ~VMCB_ALWAYS_DIRTY_MASK;
477 }
478
479 static inline void mark_dirty(struct vmcb *vmcb, int bit)
480 {
481 vmcb->control.clean &= ~(1 << bit);
482 }
483
484 static inline struct vcpu_svm *to_svm(struct kvm_vcpu *vcpu)
485 {
486 return container_of(vcpu, struct vcpu_svm, vcpu);
487 }
488
489 static inline void avic_update_vapic_bar(struct vcpu_svm *svm, u64 data)
490 {
491 svm->vmcb->control.avic_vapic_bar = data & VMCB_AVIC_APIC_BAR_MASK;
492 mark_dirty(svm->vmcb, VMCB_AVIC);
493 }
494
495 static inline bool avic_vcpu_is_running(struct kvm_vcpu *vcpu)
496 {
497 struct vcpu_svm *svm = to_svm(vcpu);
498 u64 *entry = svm->avic_physical_id_cache;
499
500 if (!entry)
501 return false;
502
503 return (READ_ONCE(*entry) & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
504 }
505
506 static void recalc_intercepts(struct vcpu_svm *svm)
507 {
508 struct vmcb_control_area *c, *h;
509 struct nested_state *g;
510
511 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
512
513 if (!is_guest_mode(&svm->vcpu))
514 return;
515
516 c = &svm->vmcb->control;
517 h = &svm->nested.hsave->control;
518 g = &svm->nested;
519
520 c->intercept_cr = h->intercept_cr | g->intercept_cr;
521 c->intercept_dr = h->intercept_dr | g->intercept_dr;
522 c->intercept_exceptions = h->intercept_exceptions | g->intercept_exceptions;
523 c->intercept = h->intercept | g->intercept;
524 }
525
526 static inline struct vmcb *get_host_vmcb(struct vcpu_svm *svm)
527 {
528 if (is_guest_mode(&svm->vcpu))
529 return svm->nested.hsave;
530 else
531 return svm->vmcb;
532 }
533
534 static inline void set_cr_intercept(struct vcpu_svm *svm, int bit)
535 {
536 struct vmcb *vmcb = get_host_vmcb(svm);
537
538 vmcb->control.intercept_cr |= (1U << bit);
539
540 recalc_intercepts(svm);
541 }
542
543 static inline void clr_cr_intercept(struct vcpu_svm *svm, int bit)
544 {
545 struct vmcb *vmcb = get_host_vmcb(svm);
546
547 vmcb->control.intercept_cr &= ~(1U << bit);
548
549 recalc_intercepts(svm);
550 }
551
552 static inline bool is_cr_intercept(struct vcpu_svm *svm, int bit)
553 {
554 struct vmcb *vmcb = get_host_vmcb(svm);
555
556 return vmcb->control.intercept_cr & (1U << bit);
557 }
558
559 static inline void set_dr_intercepts(struct vcpu_svm *svm)
560 {
561 struct vmcb *vmcb = get_host_vmcb(svm);
562
563 vmcb->control.intercept_dr = (1 << INTERCEPT_DR0_READ)
564 | (1 << INTERCEPT_DR1_READ)
565 | (1 << INTERCEPT_DR2_READ)
566 | (1 << INTERCEPT_DR3_READ)
567 | (1 << INTERCEPT_DR4_READ)
568 | (1 << INTERCEPT_DR5_READ)
569 | (1 << INTERCEPT_DR6_READ)
570 | (1 << INTERCEPT_DR7_READ)
571 | (1 << INTERCEPT_DR0_WRITE)
572 | (1 << INTERCEPT_DR1_WRITE)
573 | (1 << INTERCEPT_DR2_WRITE)
574 | (1 << INTERCEPT_DR3_WRITE)
575 | (1 << INTERCEPT_DR4_WRITE)
576 | (1 << INTERCEPT_DR5_WRITE)
577 | (1 << INTERCEPT_DR6_WRITE)
578 | (1 << INTERCEPT_DR7_WRITE);
579
580 recalc_intercepts(svm);
581 }
582
583 static inline void clr_dr_intercepts(struct vcpu_svm *svm)
584 {
585 struct vmcb *vmcb = get_host_vmcb(svm);
586
587 vmcb->control.intercept_dr = 0;
588
589 recalc_intercepts(svm);
590 }
591
592 static inline void set_exception_intercept(struct vcpu_svm *svm, int bit)
593 {
594 struct vmcb *vmcb = get_host_vmcb(svm);
595
596 vmcb->control.intercept_exceptions |= (1U << bit);
597
598 recalc_intercepts(svm);
599 }
600
601 static inline void clr_exception_intercept(struct vcpu_svm *svm, int bit)
602 {
603 struct vmcb *vmcb = get_host_vmcb(svm);
604
605 vmcb->control.intercept_exceptions &= ~(1U << bit);
606
607 recalc_intercepts(svm);
608 }
609
610 static inline void set_intercept(struct vcpu_svm *svm, int bit)
611 {
612 struct vmcb *vmcb = get_host_vmcb(svm);
613
614 vmcb->control.intercept |= (1ULL << bit);
615
616 recalc_intercepts(svm);
617 }
618
619 static inline void clr_intercept(struct vcpu_svm *svm, int bit)
620 {
621 struct vmcb *vmcb = get_host_vmcb(svm);
622
623 vmcb->control.intercept &= ~(1ULL << bit);
624
625 recalc_intercepts(svm);
626 }
627
628 static inline bool vgif_enabled(struct vcpu_svm *svm)
629 {
630 return !!(svm->vmcb->control.int_ctl & V_GIF_ENABLE_MASK);
631 }
632
633 static inline void enable_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 void disable_gif(struct vcpu_svm *svm)
642 {
643 if (vgif_enabled(svm))
644 svm->vmcb->control.int_ctl &= ~V_GIF_MASK;
645 else
646 svm->vcpu.arch.hflags &= ~HF_GIF_MASK;
647 }
648
649 static inline bool gif_set(struct vcpu_svm *svm)
650 {
651 if (vgif_enabled(svm))
652 return !!(svm->vmcb->control.int_ctl & V_GIF_MASK);
653 else
654 return !!(svm->vcpu.arch.hflags & HF_GIF_MASK);
655 }
656
657 static unsigned long iopm_base;
658
659 struct kvm_ldttss_desc {
660 u16 limit0;
661 u16 base0;
662 unsigned base1:8, type:5, dpl:2, p:1;
663 unsigned limit1:4, zero0:3, g:1, base2:8;
664 u32 base3;
665 u32 zero1;
666 } __attribute__((packed));
667
668 struct svm_cpu_data {
669 int cpu;
670
671 u64 asid_generation;
672 u32 max_asid;
673 u32 next_asid;
674 u32 min_asid;
675 struct kvm_ldttss_desc *tss_desc;
676
677 struct page *save_area;
678 struct vmcb *current_vmcb;
679
680 /* index = sev_asid, value = vmcb pointer */
681 struct vmcb **sev_vmcbs;
682 };
683
684 static DEFINE_PER_CPU(struct svm_cpu_data *, svm_data);
685
686 static const u32 msrpm_ranges[] = {0, 0xc0000000, 0xc0010000};
687
688 #define NUM_MSR_MAPS ARRAY_SIZE(msrpm_ranges)
689 #define MSRS_RANGE_SIZE 2048
690 #define MSRS_IN_RANGE (MSRS_RANGE_SIZE * 8 / 2)
691
692 static u32 svm_msrpm_offset(u32 msr)
693 {
694 u32 offset;
695 int i;
696
697 for (i = 0; i < NUM_MSR_MAPS; i++) {
698 if (msr < msrpm_ranges[i] ||
699 msr >= msrpm_ranges[i] + MSRS_IN_RANGE)
700 continue;
701
702 offset = (msr - msrpm_ranges[i]) / 4; /* 4 msrs per u8 */
703 offset += (i * MSRS_RANGE_SIZE); /* add range offset */
704
705 /* Now we have the u8 offset - but need the u32 offset */
706 return offset / 4;
707 }
708
709 /* MSR not in any range */
710 return MSR_INVALID;
711 }
712
713 #define MAX_INST_SIZE 15
714
715 static inline void clgi(void)
716 {
717 asm volatile (__ex("clgi"));
718 }
719
720 static inline void stgi(void)
721 {
722 asm volatile (__ex("stgi"));
723 }
724
725 static inline void invlpga(unsigned long addr, u32 asid)
726 {
727 asm volatile (__ex("invlpga %1, %0") : : "c"(asid), "a"(addr));
728 }
729
730 static int get_npt_level(struct kvm_vcpu *vcpu)
731 {
732 #ifdef CONFIG_X86_64
733 return PT64_ROOT_4LEVEL;
734 #else
735 return PT32E_ROOT_LEVEL;
736 #endif
737 }
738
739 static void svm_set_efer(struct kvm_vcpu *vcpu, u64 efer)
740 {
741 vcpu->arch.efer = efer;
742 if (!npt_enabled && !(efer & EFER_LMA))
743 efer &= ~EFER_LME;
744
745 to_svm(vcpu)->vmcb->save.efer = efer | EFER_SVME;
746 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
747 }
748
749 static int is_external_interrupt(u32 info)
750 {
751 info &= SVM_EVTINJ_TYPE_MASK | SVM_EVTINJ_VALID;
752 return info == (SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR);
753 }
754
755 static u32 svm_get_interrupt_shadow(struct kvm_vcpu *vcpu)
756 {
757 struct vcpu_svm *svm = to_svm(vcpu);
758 u32 ret = 0;
759
760 if (svm->vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK)
761 ret = KVM_X86_SHADOW_INT_STI | KVM_X86_SHADOW_INT_MOV_SS;
762 return ret;
763 }
764
765 static void svm_set_interrupt_shadow(struct kvm_vcpu *vcpu, int mask)
766 {
767 struct vcpu_svm *svm = to_svm(vcpu);
768
769 if (mask == 0)
770 svm->vmcb->control.int_state &= ~SVM_INTERRUPT_SHADOW_MASK;
771 else
772 svm->vmcb->control.int_state |= SVM_INTERRUPT_SHADOW_MASK;
773
774 }
775
776 static int skip_emulated_instruction(struct kvm_vcpu *vcpu)
777 {
778 struct vcpu_svm *svm = to_svm(vcpu);
779
780 if (nrips && svm->vmcb->control.next_rip != 0) {
781 WARN_ON_ONCE(!static_cpu_has(X86_FEATURE_NRIPS));
782 svm->next_rip = svm->vmcb->control.next_rip;
783 }
784
785 if (!svm->next_rip) {
786 if (!kvm_emulate_instruction(vcpu, EMULTYPE_SKIP))
787 return 0;
788 } else {
789 if (svm->next_rip - kvm_rip_read(vcpu) > MAX_INST_SIZE)
790 pr_err("%s: ip 0x%lx next 0x%llx\n",
791 __func__, kvm_rip_read(vcpu), svm->next_rip);
792 kvm_rip_write(vcpu, svm->next_rip);
793 }
794 svm_set_interrupt_shadow(vcpu, 0);
795
796 return 1;
797 }
798
799 static void svm_queue_exception(struct kvm_vcpu *vcpu)
800 {
801 struct vcpu_svm *svm = to_svm(vcpu);
802 unsigned nr = vcpu->arch.exception.nr;
803 bool has_error_code = vcpu->arch.exception.has_error_code;
804 bool reinject = vcpu->arch.exception.injected;
805 u32 error_code = vcpu->arch.exception.error_code;
806
807 /*
808 * If we are within a nested VM we'd better #VMEXIT and let the guest
809 * handle the exception
810 */
811 if (!reinject &&
812 nested_svm_check_exception(svm, nr, has_error_code, error_code))
813 return;
814
815 kvm_deliver_exception_payload(&svm->vcpu);
816
817 if (nr == BP_VECTOR && !nrips) {
818 unsigned long rip, old_rip = kvm_rip_read(&svm->vcpu);
819
820 /*
821 * For guest debugging where we have to reinject #BP if some
822 * INT3 is guest-owned:
823 * Emulate nRIP by moving RIP forward. Will fail if injection
824 * raises a fault that is not intercepted. Still better than
825 * failing in all cases.
826 */
827 (void)skip_emulated_instruction(&svm->vcpu);
828 rip = kvm_rip_read(&svm->vcpu);
829 svm->int3_rip = rip + svm->vmcb->save.cs.base;
830 svm->int3_injected = rip - old_rip;
831 }
832
833 svm->vmcb->control.event_inj = nr
834 | SVM_EVTINJ_VALID
835 | (has_error_code ? SVM_EVTINJ_VALID_ERR : 0)
836 | SVM_EVTINJ_TYPE_EXEPT;
837 svm->vmcb->control.event_inj_err = error_code;
838 }
839
840 static void svm_init_erratum_383(void)
841 {
842 u32 low, high;
843 int err;
844 u64 val;
845
846 if (!static_cpu_has_bug(X86_BUG_AMD_TLB_MMATCH))
847 return;
848
849 /* Use _safe variants to not break nested virtualization */
850 val = native_read_msr_safe(MSR_AMD64_DC_CFG, &err);
851 if (err)
852 return;
853
854 val |= (1ULL << 47);
855
856 low = lower_32_bits(val);
857 high = upper_32_bits(val);
858
859 native_write_msr_safe(MSR_AMD64_DC_CFG, low, high);
860
861 erratum_383_found = true;
862 }
863
864 static void svm_init_osvw(struct kvm_vcpu *vcpu)
865 {
866 /*
867 * Guests should see errata 400 and 415 as fixed (assuming that
868 * HLT and IO instructions are intercepted).
869 */
870 vcpu->arch.osvw.length = (osvw_len >= 3) ? (osvw_len) : 3;
871 vcpu->arch.osvw.status = osvw_status & ~(6ULL);
872
873 /*
874 * By increasing VCPU's osvw.length to 3 we are telling the guest that
875 * all osvw.status bits inside that length, including bit 0 (which is
876 * reserved for erratum 298), are valid. However, if host processor's
877 * osvw_len is 0 then osvw_status[0] carries no information. We need to
878 * be conservative here and therefore we tell the guest that erratum 298
879 * is present (because we really don't know).
880 */
881 if (osvw_len == 0 && boot_cpu_data.x86 == 0x10)
882 vcpu->arch.osvw.status |= 1;
883 }
884
885 static int has_svm(void)
886 {
887 const char *msg;
888
889 if (!cpu_has_svm(&msg)) {
890 printk(KERN_INFO "has_svm: %s\n", msg);
891 return 0;
892 }
893
894 return 1;
895 }
896
897 static void svm_hardware_disable(void)
898 {
899 /* Make sure we clean up behind us */
900 if (static_cpu_has(X86_FEATURE_TSCRATEMSR))
901 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
902
903 cpu_svm_disable();
904
905 amd_pmu_disable_virt();
906 }
907
908 static int svm_hardware_enable(void)
909 {
910
911 struct svm_cpu_data *sd;
912 uint64_t efer;
913 struct desc_struct *gdt;
914 int me = raw_smp_processor_id();
915
916 rdmsrl(MSR_EFER, efer);
917 if (efer & EFER_SVME)
918 return -EBUSY;
919
920 if (!has_svm()) {
921 pr_err("%s: err EOPNOTSUPP on %d\n", __func__, me);
922 return -EINVAL;
923 }
924 sd = per_cpu(svm_data, me);
925 if (!sd) {
926 pr_err("%s: svm_data is NULL on %d\n", __func__, me);
927 return -EINVAL;
928 }
929
930 sd->asid_generation = 1;
931 sd->max_asid = cpuid_ebx(SVM_CPUID_FUNC) - 1;
932 sd->next_asid = sd->max_asid + 1;
933 sd->min_asid = max_sev_asid + 1;
934
935 gdt = get_current_gdt_rw();
936 sd->tss_desc = (struct kvm_ldttss_desc *)(gdt + GDT_ENTRY_TSS);
937
938 wrmsrl(MSR_EFER, efer | EFER_SVME);
939
940 wrmsrl(MSR_VM_HSAVE_PA, page_to_pfn(sd->save_area) << PAGE_SHIFT);
941
942 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
943 wrmsrl(MSR_AMD64_TSC_RATIO, TSC_RATIO_DEFAULT);
944 __this_cpu_write(current_tsc_ratio, TSC_RATIO_DEFAULT);
945 }
946
947
948 /*
949 * Get OSVW bits.
950 *
951 * Note that it is possible to have a system with mixed processor
952 * revisions and therefore different OSVW bits. If bits are not the same
953 * on different processors then choose the worst case (i.e. if erratum
954 * is present on one processor and not on another then assume that the
955 * erratum is present everywhere).
956 */
957 if (cpu_has(&boot_cpu_data, X86_FEATURE_OSVW)) {
958 uint64_t len, status = 0;
959 int err;
960
961 len = native_read_msr_safe(MSR_AMD64_OSVW_ID_LENGTH, &err);
962 if (!err)
963 status = native_read_msr_safe(MSR_AMD64_OSVW_STATUS,
964 &err);
965
966 if (err)
967 osvw_status = osvw_len = 0;
968 else {
969 if (len < osvw_len)
970 osvw_len = len;
971 osvw_status |= status;
972 osvw_status &= (1ULL << osvw_len) - 1;
973 }
974 } else
975 osvw_status = osvw_len = 0;
976
977 svm_init_erratum_383();
978
979 amd_pmu_enable_virt();
980
981 return 0;
982 }
983
984 static void svm_cpu_uninit(int cpu)
985 {
986 struct svm_cpu_data *sd = per_cpu(svm_data, raw_smp_processor_id());
987
988 if (!sd)
989 return;
990
991 per_cpu(svm_data, raw_smp_processor_id()) = NULL;
992 kfree(sd->sev_vmcbs);
993 __free_page(sd->save_area);
994 kfree(sd);
995 }
996
997 static int svm_cpu_init(int cpu)
998 {
999 struct svm_cpu_data *sd;
1000 int r;
1001
1002 sd = kzalloc(sizeof(struct svm_cpu_data), GFP_KERNEL);
1003 if (!sd)
1004 return -ENOMEM;
1005 sd->cpu = cpu;
1006 r = -ENOMEM;
1007 sd->save_area = alloc_page(GFP_KERNEL);
1008 if (!sd->save_area)
1009 goto err_1;
1010
1011 if (svm_sev_enabled()) {
1012 r = -ENOMEM;
1013 sd->sev_vmcbs = kmalloc_array(max_sev_asid + 1,
1014 sizeof(void *),
1015 GFP_KERNEL);
1016 if (!sd->sev_vmcbs)
1017 goto err_1;
1018 }
1019
1020 per_cpu(svm_data, cpu) = sd;
1021
1022 return 0;
1023
1024 err_1:
1025 kfree(sd);
1026 return r;
1027
1028 }
1029
1030 static bool valid_msr_intercept(u32 index)
1031 {
1032 int i;
1033
1034 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++)
1035 if (direct_access_msrs[i].index == index)
1036 return true;
1037
1038 return false;
1039 }
1040
1041 static bool msr_write_intercepted(struct kvm_vcpu *vcpu, unsigned msr)
1042 {
1043 u8 bit_write;
1044 unsigned long tmp;
1045 u32 offset;
1046 u32 *msrpm;
1047
1048 msrpm = is_guest_mode(vcpu) ? to_svm(vcpu)->nested.msrpm:
1049 to_svm(vcpu)->msrpm;
1050
1051 offset = svm_msrpm_offset(msr);
1052 bit_write = 2 * (msr & 0x0f) + 1;
1053 tmp = msrpm[offset];
1054
1055 BUG_ON(offset == MSR_INVALID);
1056
1057 return !!test_bit(bit_write, &tmp);
1058 }
1059
1060 static void set_msr_interception(u32 *msrpm, unsigned msr,
1061 int read, int write)
1062 {
1063 u8 bit_read, bit_write;
1064 unsigned long tmp;
1065 u32 offset;
1066
1067 /*
1068 * If this warning triggers extend the direct_access_msrs list at the
1069 * beginning of the file
1070 */
1071 WARN_ON(!valid_msr_intercept(msr));
1072
1073 offset = svm_msrpm_offset(msr);
1074 bit_read = 2 * (msr & 0x0f);
1075 bit_write = 2 * (msr & 0x0f) + 1;
1076 tmp = msrpm[offset];
1077
1078 BUG_ON(offset == MSR_INVALID);
1079
1080 read ? clear_bit(bit_read, &tmp) : set_bit(bit_read, &tmp);
1081 write ? clear_bit(bit_write, &tmp) : set_bit(bit_write, &tmp);
1082
1083 msrpm[offset] = tmp;
1084 }
1085
1086 static void svm_vcpu_init_msrpm(u32 *msrpm)
1087 {
1088 int i;
1089
1090 memset(msrpm, 0xff, PAGE_SIZE * (1 << MSRPM_ALLOC_ORDER));
1091
1092 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1093 if (!direct_access_msrs[i].always)
1094 continue;
1095
1096 set_msr_interception(msrpm, direct_access_msrs[i].index, 1, 1);
1097 }
1098 }
1099
1100 static void add_msr_offset(u32 offset)
1101 {
1102 int i;
1103
1104 for (i = 0; i < MSRPM_OFFSETS; ++i) {
1105
1106 /* Offset already in list? */
1107 if (msrpm_offsets[i] == offset)
1108 return;
1109
1110 /* Slot used by another offset? */
1111 if (msrpm_offsets[i] != MSR_INVALID)
1112 continue;
1113
1114 /* Add offset to list */
1115 msrpm_offsets[i] = offset;
1116
1117 return;
1118 }
1119
1120 /*
1121 * If this BUG triggers the msrpm_offsets table has an overflow. Just
1122 * increase MSRPM_OFFSETS in this case.
1123 */
1124 BUG();
1125 }
1126
1127 static void init_msrpm_offsets(void)
1128 {
1129 int i;
1130
1131 memset(msrpm_offsets, 0xff, sizeof(msrpm_offsets));
1132
1133 for (i = 0; direct_access_msrs[i].index != MSR_INVALID; i++) {
1134 u32 offset;
1135
1136 offset = svm_msrpm_offset(direct_access_msrs[i].index);
1137 BUG_ON(offset == MSR_INVALID);
1138
1139 add_msr_offset(offset);
1140 }
1141 }
1142
1143 static void svm_enable_lbrv(struct vcpu_svm *svm)
1144 {
1145 u32 *msrpm = svm->msrpm;
1146
1147 svm->vmcb->control.virt_ext |= LBR_CTL_ENABLE_MASK;
1148 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 1, 1);
1149 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 1, 1);
1150 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 1, 1);
1151 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 1, 1);
1152 }
1153
1154 static void svm_disable_lbrv(struct vcpu_svm *svm)
1155 {
1156 u32 *msrpm = svm->msrpm;
1157
1158 svm->vmcb->control.virt_ext &= ~LBR_CTL_ENABLE_MASK;
1159 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHFROMIP, 0, 0);
1160 set_msr_interception(msrpm, MSR_IA32_LASTBRANCHTOIP, 0, 0);
1161 set_msr_interception(msrpm, MSR_IA32_LASTINTFROMIP, 0, 0);
1162 set_msr_interception(msrpm, MSR_IA32_LASTINTTOIP, 0, 0);
1163 }
1164
1165 static void disable_nmi_singlestep(struct vcpu_svm *svm)
1166 {
1167 svm->nmi_singlestep = false;
1168
1169 if (!(svm->vcpu.guest_debug & KVM_GUESTDBG_SINGLESTEP)) {
1170 /* Clear our flags if they were not set by the guest */
1171 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
1172 svm->vmcb->save.rflags &= ~X86_EFLAGS_TF;
1173 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
1174 svm->vmcb->save.rflags &= ~X86_EFLAGS_RF;
1175 }
1176 }
1177
1178 /* Note:
1179 * This hash table is used to map VM_ID to a struct kvm_svm,
1180 * when handling AMD IOMMU GALOG notification to schedule in
1181 * a particular vCPU.
1182 */
1183 #define SVM_VM_DATA_HASH_BITS 8
1184 static DEFINE_HASHTABLE(svm_vm_data_hash, SVM_VM_DATA_HASH_BITS);
1185 static u32 next_vm_id = 0;
1186 static bool next_vm_id_wrapped = 0;
1187 static DEFINE_SPINLOCK(svm_vm_data_hash_lock);
1188
1189 /* Note:
1190 * This function is called from IOMMU driver to notify
1191 * SVM to schedule in a particular vCPU of a particular VM.
1192 */
1193 static int avic_ga_log_notifier(u32 ga_tag)
1194 {
1195 unsigned long flags;
1196 struct kvm_svm *kvm_svm;
1197 struct kvm_vcpu *vcpu = NULL;
1198 u32 vm_id = AVIC_GATAG_TO_VMID(ga_tag);
1199 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(ga_tag);
1200
1201 pr_debug("SVM: %s: vm_id=%#x, vcpu_id=%#x\n", __func__, vm_id, vcpu_id);
1202
1203 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1204 hash_for_each_possible(svm_vm_data_hash, kvm_svm, hnode, vm_id) {
1205 if (kvm_svm->avic_vm_id != vm_id)
1206 continue;
1207 vcpu = kvm_get_vcpu_by_id(&kvm_svm->kvm, vcpu_id);
1208 break;
1209 }
1210 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1211
1212 /* Note:
1213 * At this point, the IOMMU should have already set the pending
1214 * bit in the vAPIC backing page. So, we just need to schedule
1215 * in the vcpu.
1216 */
1217 if (vcpu)
1218 kvm_vcpu_wake_up(vcpu);
1219
1220 return 0;
1221 }
1222
1223 static __init int sev_hardware_setup(void)
1224 {
1225 struct sev_user_data_status *status;
1226 int rc;
1227
1228 /* Maximum number of encrypted guests supported simultaneously */
1229 max_sev_asid = cpuid_ecx(0x8000001F);
1230
1231 if (!max_sev_asid)
1232 return 1;
1233
1234 /* Minimum ASID value that should be used for SEV guest */
1235 min_sev_asid = cpuid_edx(0x8000001F);
1236
1237 /* Initialize SEV ASID bitmaps */
1238 sev_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1239 if (!sev_asid_bitmap)
1240 return 1;
1241
1242 sev_reclaim_asid_bitmap = bitmap_zalloc(max_sev_asid, GFP_KERNEL);
1243 if (!sev_reclaim_asid_bitmap)
1244 return 1;
1245
1246 status = kmalloc(sizeof(*status), GFP_KERNEL);
1247 if (!status)
1248 return 1;
1249
1250 /*
1251 * Check SEV platform status.
1252 *
1253 * PLATFORM_STATUS can be called in any state, if we failed to query
1254 * the PLATFORM status then either PSP firmware does not support SEV
1255 * feature or SEV firmware is dead.
1256 */
1257 rc = sev_platform_status(status, NULL);
1258 if (rc)
1259 goto err;
1260
1261 pr_info("SEV supported\n");
1262
1263 err:
1264 kfree(status);
1265 return rc;
1266 }
1267
1268 static void grow_ple_window(struct kvm_vcpu *vcpu)
1269 {
1270 struct vcpu_svm *svm = to_svm(vcpu);
1271 struct vmcb_control_area *control = &svm->vmcb->control;
1272 int old = control->pause_filter_count;
1273
1274 control->pause_filter_count = __grow_ple_window(old,
1275 pause_filter_count,
1276 pause_filter_count_grow,
1277 pause_filter_count_max);
1278
1279 if (control->pause_filter_count != old) {
1280 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1281 trace_kvm_ple_window_update(vcpu->vcpu_id,
1282 control->pause_filter_count, old);
1283 }
1284 }
1285
1286 static void shrink_ple_window(struct kvm_vcpu *vcpu)
1287 {
1288 struct vcpu_svm *svm = to_svm(vcpu);
1289 struct vmcb_control_area *control = &svm->vmcb->control;
1290 int old = control->pause_filter_count;
1291
1292 control->pause_filter_count =
1293 __shrink_ple_window(old,
1294 pause_filter_count,
1295 pause_filter_count_shrink,
1296 pause_filter_count);
1297 if (control->pause_filter_count != old) {
1298 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1299 trace_kvm_ple_window_update(vcpu->vcpu_id,
1300 control->pause_filter_count, old);
1301 }
1302 }
1303
1304 static __init int svm_hardware_setup(void)
1305 {
1306 int cpu;
1307 struct page *iopm_pages;
1308 void *iopm_va;
1309 int r;
1310
1311 iopm_pages = alloc_pages(GFP_KERNEL, IOPM_ALLOC_ORDER);
1312
1313 if (!iopm_pages)
1314 return -ENOMEM;
1315
1316 iopm_va = page_address(iopm_pages);
1317 memset(iopm_va, 0xff, PAGE_SIZE * (1 << IOPM_ALLOC_ORDER));
1318 iopm_base = page_to_pfn(iopm_pages) << PAGE_SHIFT;
1319
1320 init_msrpm_offsets();
1321
1322 if (boot_cpu_has(X86_FEATURE_NX))
1323 kvm_enable_efer_bits(EFER_NX);
1324
1325 if (boot_cpu_has(X86_FEATURE_FXSR_OPT))
1326 kvm_enable_efer_bits(EFER_FFXSR);
1327
1328 if (boot_cpu_has(X86_FEATURE_TSCRATEMSR)) {
1329 kvm_has_tsc_control = true;
1330 kvm_max_tsc_scaling_ratio = TSC_RATIO_MAX;
1331 kvm_tsc_scaling_ratio_frac_bits = 32;
1332 }
1333
1334 /* Check for pause filtering support */
1335 if (!boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
1336 pause_filter_count = 0;
1337 pause_filter_thresh = 0;
1338 } else if (!boot_cpu_has(X86_FEATURE_PFTHRESHOLD)) {
1339 pause_filter_thresh = 0;
1340 }
1341
1342 if (nested) {
1343 printk(KERN_INFO "kvm: Nested Virtualization enabled\n");
1344 kvm_enable_efer_bits(EFER_SVME | EFER_LMSLE);
1345 }
1346
1347 if (sev) {
1348 if (boot_cpu_has(X86_FEATURE_SEV) &&
1349 IS_ENABLED(CONFIG_KVM_AMD_SEV)) {
1350 r = sev_hardware_setup();
1351 if (r)
1352 sev = false;
1353 } else {
1354 sev = false;
1355 }
1356 }
1357
1358 for_each_possible_cpu(cpu) {
1359 r = svm_cpu_init(cpu);
1360 if (r)
1361 goto err;
1362 }
1363
1364 if (!boot_cpu_has(X86_FEATURE_NPT))
1365 npt_enabled = false;
1366
1367 if (npt_enabled && !npt) {
1368 printk(KERN_INFO "kvm: Nested Paging disabled\n");
1369 npt_enabled = false;
1370 }
1371
1372 if (npt_enabled) {
1373 printk(KERN_INFO "kvm: Nested Paging enabled\n");
1374 kvm_enable_tdp();
1375 } else
1376 kvm_disable_tdp();
1377
1378 if (nrips) {
1379 if (!boot_cpu_has(X86_FEATURE_NRIPS))
1380 nrips = false;
1381 }
1382
1383 if (avic) {
1384 if (!npt_enabled ||
1385 !boot_cpu_has(X86_FEATURE_AVIC) ||
1386 !IS_ENABLED(CONFIG_X86_LOCAL_APIC)) {
1387 avic = false;
1388 } else {
1389 pr_info("AVIC enabled\n");
1390
1391 amd_iommu_register_ga_log_notifier(&avic_ga_log_notifier);
1392 }
1393 }
1394
1395 if (vls) {
1396 if (!npt_enabled ||
1397 !boot_cpu_has(X86_FEATURE_V_VMSAVE_VMLOAD) ||
1398 !IS_ENABLED(CONFIG_X86_64)) {
1399 vls = false;
1400 } else {
1401 pr_info("Virtual VMLOAD VMSAVE supported\n");
1402 }
1403 }
1404
1405 if (vgif) {
1406 if (!boot_cpu_has(X86_FEATURE_VGIF))
1407 vgif = false;
1408 else
1409 pr_info("Virtual GIF supported\n");
1410 }
1411
1412 return 0;
1413
1414 err:
1415 __free_pages(iopm_pages, IOPM_ALLOC_ORDER);
1416 iopm_base = 0;
1417 return r;
1418 }
1419
1420 static __exit void svm_hardware_unsetup(void)
1421 {
1422 int cpu;
1423
1424 if (svm_sev_enabled()) {
1425 bitmap_free(sev_asid_bitmap);
1426 bitmap_free(sev_reclaim_asid_bitmap);
1427
1428 sev_flush_asids();
1429 }
1430
1431 for_each_possible_cpu(cpu)
1432 svm_cpu_uninit(cpu);
1433
1434 __free_pages(pfn_to_page(iopm_base >> PAGE_SHIFT), IOPM_ALLOC_ORDER);
1435 iopm_base = 0;
1436 }
1437
1438 static void init_seg(struct vmcb_seg *seg)
1439 {
1440 seg->selector = 0;
1441 seg->attrib = SVM_SELECTOR_P_MASK | SVM_SELECTOR_S_MASK |
1442 SVM_SELECTOR_WRITE_MASK; /* Read/Write Data Segment */
1443 seg->limit = 0xffff;
1444 seg->base = 0;
1445 }
1446
1447 static void init_sys_seg(struct vmcb_seg *seg, uint32_t type)
1448 {
1449 seg->selector = 0;
1450 seg->attrib = SVM_SELECTOR_P_MASK | type;
1451 seg->limit = 0xffff;
1452 seg->base = 0;
1453 }
1454
1455 static u64 svm_read_l1_tsc_offset(struct kvm_vcpu *vcpu)
1456 {
1457 struct vcpu_svm *svm = to_svm(vcpu);
1458
1459 if (is_guest_mode(vcpu))
1460 return svm->nested.hsave->control.tsc_offset;
1461
1462 return vcpu->arch.tsc_offset;
1463 }
1464
1465 static u64 svm_write_l1_tsc_offset(struct kvm_vcpu *vcpu, u64 offset)
1466 {
1467 struct vcpu_svm *svm = to_svm(vcpu);
1468 u64 g_tsc_offset = 0;
1469
1470 if (is_guest_mode(vcpu)) {
1471 /* Write L1's TSC offset. */
1472 g_tsc_offset = svm->vmcb->control.tsc_offset -
1473 svm->nested.hsave->control.tsc_offset;
1474 svm->nested.hsave->control.tsc_offset = offset;
1475 }
1476
1477 trace_kvm_write_tsc_offset(vcpu->vcpu_id,
1478 svm->vmcb->control.tsc_offset - g_tsc_offset,
1479 offset);
1480
1481 svm->vmcb->control.tsc_offset = offset + g_tsc_offset;
1482
1483 mark_dirty(svm->vmcb, VMCB_INTERCEPTS);
1484 return svm->vmcb->control.tsc_offset;
1485 }
1486
1487 static void avic_init_vmcb(struct vcpu_svm *svm)
1488 {
1489 struct vmcb *vmcb = svm->vmcb;
1490 struct kvm_svm *kvm_svm = to_kvm_svm(svm->vcpu.kvm);
1491 phys_addr_t bpa = __sme_set(page_to_phys(svm->avic_backing_page));
1492 phys_addr_t lpa = __sme_set(page_to_phys(kvm_svm->avic_logical_id_table_page));
1493 phys_addr_t ppa = __sme_set(page_to_phys(kvm_svm->avic_physical_id_table_page));
1494
1495 vmcb->control.avic_backing_page = bpa & AVIC_HPA_MASK;
1496 vmcb->control.avic_logical_id = lpa & AVIC_HPA_MASK;
1497 vmcb->control.avic_physical_id = ppa & AVIC_HPA_MASK;
1498 vmcb->control.avic_physical_id |= AVIC_MAX_PHYSICAL_ID_COUNT;
1499 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
1500 }
1501
1502 static void init_vmcb(struct vcpu_svm *svm)
1503 {
1504 struct vmcb_control_area *control = &svm->vmcb->control;
1505 struct vmcb_save_area *save = &svm->vmcb->save;
1506
1507 svm->vcpu.arch.hflags = 0;
1508
1509 set_cr_intercept(svm, INTERCEPT_CR0_READ);
1510 set_cr_intercept(svm, INTERCEPT_CR3_READ);
1511 set_cr_intercept(svm, INTERCEPT_CR4_READ);
1512 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
1513 set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1514 set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
1515 if (!kvm_vcpu_apicv_active(&svm->vcpu))
1516 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
1517
1518 set_dr_intercepts(svm);
1519
1520 set_exception_intercept(svm, PF_VECTOR);
1521 set_exception_intercept(svm, UD_VECTOR);
1522 set_exception_intercept(svm, MC_VECTOR);
1523 set_exception_intercept(svm, AC_VECTOR);
1524 set_exception_intercept(svm, DB_VECTOR);
1525 /*
1526 * Guest access to VMware backdoor ports could legitimately
1527 * trigger #GP because of TSS I/O permission bitmap.
1528 * We intercept those #GP and allow access to them anyway
1529 * as VMware does.
1530 */
1531 if (enable_vmware_backdoor)
1532 set_exception_intercept(svm, GP_VECTOR);
1533
1534 set_intercept(svm, INTERCEPT_INTR);
1535 set_intercept(svm, INTERCEPT_NMI);
1536 set_intercept(svm, INTERCEPT_SMI);
1537 set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
1538 set_intercept(svm, INTERCEPT_RDPMC);
1539 set_intercept(svm, INTERCEPT_CPUID);
1540 set_intercept(svm, INTERCEPT_INVD);
1541 set_intercept(svm, INTERCEPT_INVLPG);
1542 set_intercept(svm, INTERCEPT_INVLPGA);
1543 set_intercept(svm, INTERCEPT_IOIO_PROT);
1544 set_intercept(svm, INTERCEPT_MSR_PROT);
1545 set_intercept(svm, INTERCEPT_TASK_SWITCH);
1546 set_intercept(svm, INTERCEPT_SHUTDOWN);
1547 set_intercept(svm, INTERCEPT_VMRUN);
1548 set_intercept(svm, INTERCEPT_VMMCALL);
1549 set_intercept(svm, INTERCEPT_VMLOAD);
1550 set_intercept(svm, INTERCEPT_VMSAVE);
1551 set_intercept(svm, INTERCEPT_STGI);
1552 set_intercept(svm, INTERCEPT_CLGI);
1553 set_intercept(svm, INTERCEPT_SKINIT);
1554 set_intercept(svm, INTERCEPT_WBINVD);
1555 set_intercept(svm, INTERCEPT_XSETBV);
1556 set_intercept(svm, INTERCEPT_RDPRU);
1557 set_intercept(svm, INTERCEPT_RSM);
1558
1559 if (!kvm_mwait_in_guest(svm->vcpu.kvm)) {
1560 set_intercept(svm, INTERCEPT_MONITOR);
1561 set_intercept(svm, INTERCEPT_MWAIT);
1562 }
1563
1564 if (!kvm_hlt_in_guest(svm->vcpu.kvm))
1565 set_intercept(svm, INTERCEPT_HLT);
1566
1567 control->iopm_base_pa = __sme_set(iopm_base);
1568 control->msrpm_base_pa = __sme_set(__pa(svm->msrpm));
1569 control->int_ctl = V_INTR_MASKING_MASK;
1570
1571 init_seg(&save->es);
1572 init_seg(&save->ss);
1573 init_seg(&save->ds);
1574 init_seg(&save->fs);
1575 init_seg(&save->gs);
1576
1577 save->cs.selector = 0xf000;
1578 save->cs.base = 0xffff0000;
1579 /* Executable/Readable Code Segment */
1580 save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
1581 SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
1582 save->cs.limit = 0xffff;
1583
1584 save->gdtr.limit = 0xffff;
1585 save->idtr.limit = 0xffff;
1586
1587 init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
1588 init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
1589
1590 svm_set_efer(&svm->vcpu, 0);
1591 save->dr6 = 0xffff0ff0;
1592 kvm_set_rflags(&svm->vcpu, 2);
1593 save->rip = 0x0000fff0;
1594 svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
1595
1596 /*
1597 * svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
1598 * It also updates the guest-visible cr0 value.
1599 */
1600 svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
1601 kvm_mmu_reset_context(&svm->vcpu);
1602
1603 save->cr4 = X86_CR4_PAE;
1604 /* rdx = ?? */
1605
1606 if (npt_enabled) {
1607 /* Setup VMCB for Nested Paging */
1608 control->nested_ctl |= SVM_NESTED_CTL_NP_ENABLE;
1609 clr_intercept(svm, INTERCEPT_INVLPG);
1610 clr_exception_intercept(svm, PF_VECTOR);
1611 clr_cr_intercept(svm, INTERCEPT_CR3_READ);
1612 clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
1613 save->g_pat = svm->vcpu.arch.pat;
1614 save->cr3 = 0;
1615 save->cr4 = 0;
1616 }
1617 svm->asid_generation = 0;
1618
1619 svm->nested.vmcb = 0;
1620 svm->vcpu.arch.hflags = 0;
1621
1622 if (pause_filter_count) {
1623 control->pause_filter_count = pause_filter_count;
1624 if (pause_filter_thresh)
1625 control->pause_filter_thresh = pause_filter_thresh;
1626 set_intercept(svm, INTERCEPT_PAUSE);
1627 } else {
1628 clr_intercept(svm, INTERCEPT_PAUSE);
1629 }
1630
1631 if (kvm_vcpu_apicv_active(&svm->vcpu))
1632 avic_init_vmcb(svm);
1633
1634 /*
1635 * If hardware supports Virtual VMLOAD VMSAVE then enable it
1636 * in VMCB and clear intercepts to avoid #VMEXIT.
1637 */
1638 if (vls) {
1639 clr_intercept(svm, INTERCEPT_VMLOAD);
1640 clr_intercept(svm, INTERCEPT_VMSAVE);
1641 svm->vmcb->control.virt_ext |= VIRTUAL_VMLOAD_VMSAVE_ENABLE_MASK;
1642 }
1643
1644 if (vgif) {
1645 clr_intercept(svm, INTERCEPT_STGI);
1646 clr_intercept(svm, INTERCEPT_CLGI);
1647 svm->vmcb->control.int_ctl |= V_GIF_ENABLE_MASK;
1648 }
1649
1650 if (sev_guest(svm->vcpu.kvm)) {
1651 svm->vmcb->control.nested_ctl |= SVM_NESTED_CTL_SEV_ENABLE;
1652 clr_exception_intercept(svm, UD_VECTOR);
1653 }
1654
1655 mark_all_dirty(svm->vmcb);
1656
1657 enable_gif(svm);
1658
1659 }
1660
1661 static u64 *avic_get_physical_id_entry(struct kvm_vcpu *vcpu,
1662 unsigned int index)
1663 {
1664 u64 *avic_physical_id_table;
1665 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
1666
1667 if (index >= AVIC_MAX_PHYSICAL_ID_COUNT)
1668 return NULL;
1669
1670 avic_physical_id_table = page_address(kvm_svm->avic_physical_id_table_page);
1671
1672 return &avic_physical_id_table[index];
1673 }
1674
1675 /**
1676 * Note:
1677 * AVIC hardware walks the nested page table to check permissions,
1678 * but does not use the SPA address specified in the leaf page
1679 * table entry since it uses address in the AVIC_BACKING_PAGE pointer
1680 * field of the VMCB. Therefore, we set up the
1681 * APIC_ACCESS_PAGE_PRIVATE_MEMSLOT (4KB) here.
1682 */
1683 static int avic_init_access_page(struct kvm_vcpu *vcpu)
1684 {
1685 struct kvm *kvm = vcpu->kvm;
1686 int ret = 0;
1687
1688 mutex_lock(&kvm->slots_lock);
1689 if (kvm->arch.apic_access_page_done)
1690 goto out;
1691
1692 ret = __x86_set_memory_region(kvm,
1693 APIC_ACCESS_PAGE_PRIVATE_MEMSLOT,
1694 APIC_DEFAULT_PHYS_BASE,
1695 PAGE_SIZE);
1696 if (ret)
1697 goto out;
1698
1699 kvm->arch.apic_access_page_done = true;
1700 out:
1701 mutex_unlock(&kvm->slots_lock);
1702 return ret;
1703 }
1704
1705 static int avic_init_backing_page(struct kvm_vcpu *vcpu)
1706 {
1707 int ret;
1708 u64 *entry, new_entry;
1709 int id = vcpu->vcpu_id;
1710 struct vcpu_svm *svm = to_svm(vcpu);
1711
1712 ret = avic_init_access_page(vcpu);
1713 if (ret)
1714 return ret;
1715
1716 if (id >= AVIC_MAX_PHYSICAL_ID_COUNT)
1717 return -EINVAL;
1718
1719 if (!svm->vcpu.arch.apic->regs)
1720 return -EINVAL;
1721
1722 svm->avic_backing_page = virt_to_page(svm->vcpu.arch.apic->regs);
1723
1724 /* Setting AVIC backing page address in the phy APIC ID table */
1725 entry = avic_get_physical_id_entry(vcpu, id);
1726 if (!entry)
1727 return -EINVAL;
1728
1729 new_entry = __sme_set((page_to_phys(svm->avic_backing_page) &
1730 AVIC_PHYSICAL_ID_ENTRY_BACKING_PAGE_MASK) |
1731 AVIC_PHYSICAL_ID_ENTRY_VALID_MASK);
1732 WRITE_ONCE(*entry, new_entry);
1733
1734 svm->avic_physical_id_cache = entry;
1735
1736 return 0;
1737 }
1738
1739 static void sev_asid_free(int asid)
1740 {
1741 struct svm_cpu_data *sd;
1742 int cpu, pos;
1743
1744 mutex_lock(&sev_bitmap_lock);
1745
1746 pos = asid - 1;
1747 __set_bit(pos, sev_reclaim_asid_bitmap);
1748
1749 for_each_possible_cpu(cpu) {
1750 sd = per_cpu(svm_data, cpu);
1751 sd->sev_vmcbs[pos] = NULL;
1752 }
1753
1754 mutex_unlock(&sev_bitmap_lock);
1755 }
1756
1757 static void sev_unbind_asid(struct kvm *kvm, unsigned int handle)
1758 {
1759 struct sev_data_decommission *decommission;
1760 struct sev_data_deactivate *data;
1761
1762 if (!handle)
1763 return;
1764
1765 data = kzalloc(sizeof(*data), GFP_KERNEL);
1766 if (!data)
1767 return;
1768
1769 /* deactivate handle */
1770 data->handle = handle;
1771
1772 /* Guard DEACTIVATE against WBINVD/DF_FLUSH used in ASID recycling */
1773 down_read(&sev_deactivate_lock);
1774 sev_guest_deactivate(data, NULL);
1775 up_read(&sev_deactivate_lock);
1776
1777 kfree(data);
1778
1779 decommission = kzalloc(sizeof(*decommission), GFP_KERNEL);
1780 if (!decommission)
1781 return;
1782
1783 /* decommission handle */
1784 decommission->handle = handle;
1785 sev_guest_decommission(decommission, NULL);
1786
1787 kfree(decommission);
1788 }
1789
1790 static struct page **sev_pin_memory(struct kvm *kvm, unsigned long uaddr,
1791 unsigned long ulen, unsigned long *n,
1792 int write)
1793 {
1794 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1795 unsigned long npages, npinned, size;
1796 unsigned long locked, lock_limit;
1797 struct page **pages;
1798 unsigned long first, last;
1799
1800 if (ulen == 0 || uaddr + ulen < uaddr)
1801 return NULL;
1802
1803 /* Calculate number of pages. */
1804 first = (uaddr & PAGE_MASK) >> PAGE_SHIFT;
1805 last = ((uaddr + ulen - 1) & PAGE_MASK) >> PAGE_SHIFT;
1806 npages = (last - first + 1);
1807
1808 locked = sev->pages_locked + npages;
1809 lock_limit = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1810 if (locked > lock_limit && !capable(CAP_IPC_LOCK)) {
1811 pr_err("SEV: %lu locked pages exceed the lock limit of %lu.\n", locked, lock_limit);
1812 return NULL;
1813 }
1814
1815 /* Avoid using vmalloc for smaller buffers. */
1816 size = npages * sizeof(struct page *);
1817 if (size > PAGE_SIZE)
1818 pages = __vmalloc(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO,
1819 PAGE_KERNEL);
1820 else
1821 pages = kmalloc(size, GFP_KERNEL_ACCOUNT);
1822
1823 if (!pages)
1824 return NULL;
1825
1826 /* Pin the user virtual address. */
1827 npinned = get_user_pages_fast(uaddr, npages, FOLL_WRITE, pages);
1828 if (npinned != npages) {
1829 pr_err("SEV: Failure locking %lu pages.\n", npages);
1830 goto err;
1831 }
1832
1833 *n = npages;
1834 sev->pages_locked = locked;
1835
1836 return pages;
1837
1838 err:
1839 if (npinned > 0)
1840 release_pages(pages, npinned);
1841
1842 kvfree(pages);
1843 return NULL;
1844 }
1845
1846 static void sev_unpin_memory(struct kvm *kvm, struct page **pages,
1847 unsigned long npages)
1848 {
1849 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1850
1851 release_pages(pages, npages);
1852 kvfree(pages);
1853 sev->pages_locked -= npages;
1854 }
1855
1856 static void sev_clflush_pages(struct page *pages[], unsigned long npages)
1857 {
1858 uint8_t *page_virtual;
1859 unsigned long i;
1860
1861 if (npages == 0 || pages == NULL)
1862 return;
1863
1864 for (i = 0; i < npages; i++) {
1865 page_virtual = kmap_atomic(pages[i]);
1866 clflush_cache_range(page_virtual, PAGE_SIZE);
1867 kunmap_atomic(page_virtual);
1868 }
1869 }
1870
1871 static void __unregister_enc_region_locked(struct kvm *kvm,
1872 struct enc_region *region)
1873 {
1874 /*
1875 * The guest may change the memory encryption attribute from C=0 -> C=1
1876 * or vice versa for this memory range. Lets make sure caches are
1877 * flushed to ensure that guest data gets written into memory with
1878 * correct C-bit.
1879 */
1880 sev_clflush_pages(region->pages, region->npages);
1881
1882 sev_unpin_memory(kvm, region->pages, region->npages);
1883 list_del(&region->list);
1884 kfree(region);
1885 }
1886
1887 static struct kvm *svm_vm_alloc(void)
1888 {
1889 struct kvm_svm *kvm_svm = __vmalloc(sizeof(struct kvm_svm),
1890 GFP_KERNEL_ACCOUNT | __GFP_ZERO,
1891 PAGE_KERNEL);
1892 return &kvm_svm->kvm;
1893 }
1894
1895 static void svm_vm_free(struct kvm *kvm)
1896 {
1897 vfree(to_kvm_svm(kvm));
1898 }
1899
1900 static void sev_vm_destroy(struct kvm *kvm)
1901 {
1902 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
1903 struct list_head *head = &sev->regions_list;
1904 struct list_head *pos, *q;
1905
1906 if (!sev_guest(kvm))
1907 return;
1908
1909 mutex_lock(&kvm->lock);
1910
1911 /*
1912 * if userspace was terminated before unregistering the memory regions
1913 * then lets unpin all the registered memory.
1914 */
1915 if (!list_empty(head)) {
1916 list_for_each_safe(pos, q, head) {
1917 __unregister_enc_region_locked(kvm,
1918 list_entry(pos, struct enc_region, list));
1919 }
1920 }
1921
1922 mutex_unlock(&kvm->lock);
1923
1924 sev_unbind_asid(kvm, sev->handle);
1925 sev_asid_free(sev->asid);
1926 }
1927
1928 static void avic_vm_destroy(struct kvm *kvm)
1929 {
1930 unsigned long flags;
1931 struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1932
1933 if (!avic)
1934 return;
1935
1936 if (kvm_svm->avic_logical_id_table_page)
1937 __free_page(kvm_svm->avic_logical_id_table_page);
1938 if (kvm_svm->avic_physical_id_table_page)
1939 __free_page(kvm_svm->avic_physical_id_table_page);
1940
1941 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1942 hash_del(&kvm_svm->hnode);
1943 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1944 }
1945
1946 static void svm_vm_destroy(struct kvm *kvm)
1947 {
1948 avic_vm_destroy(kvm);
1949 sev_vm_destroy(kvm);
1950 }
1951
1952 static int avic_vm_init(struct kvm *kvm)
1953 {
1954 unsigned long flags;
1955 int err = -ENOMEM;
1956 struct kvm_svm *kvm_svm = to_kvm_svm(kvm);
1957 struct kvm_svm *k2;
1958 struct page *p_page;
1959 struct page *l_page;
1960 u32 vm_id;
1961
1962 if (!avic)
1963 return 0;
1964
1965 /* Allocating physical APIC ID table (4KB) */
1966 p_page = alloc_page(GFP_KERNEL_ACCOUNT);
1967 if (!p_page)
1968 goto free_avic;
1969
1970 kvm_svm->avic_physical_id_table_page = p_page;
1971 clear_page(page_address(p_page));
1972
1973 /* Allocating logical APIC ID table (4KB) */
1974 l_page = alloc_page(GFP_KERNEL_ACCOUNT);
1975 if (!l_page)
1976 goto free_avic;
1977
1978 kvm_svm->avic_logical_id_table_page = l_page;
1979 clear_page(page_address(l_page));
1980
1981 spin_lock_irqsave(&svm_vm_data_hash_lock, flags);
1982 again:
1983 vm_id = next_vm_id = (next_vm_id + 1) & AVIC_VM_ID_MASK;
1984 if (vm_id == 0) { /* id is 1-based, zero is not okay */
1985 next_vm_id_wrapped = 1;
1986 goto again;
1987 }
1988 /* Is it still in use? Only possible if wrapped at least once */
1989 if (next_vm_id_wrapped) {
1990 hash_for_each_possible(svm_vm_data_hash, k2, hnode, vm_id) {
1991 if (k2->avic_vm_id == vm_id)
1992 goto again;
1993 }
1994 }
1995 kvm_svm->avic_vm_id = vm_id;
1996 hash_add(svm_vm_data_hash, &kvm_svm->hnode, kvm_svm->avic_vm_id);
1997 spin_unlock_irqrestore(&svm_vm_data_hash_lock, flags);
1998
1999 return 0;
2000
2001 free_avic:
2002 avic_vm_destroy(kvm);
2003 return err;
2004 }
2005
2006 static inline int
2007 avic_update_iommu_vcpu_affinity(struct kvm_vcpu *vcpu, int cpu, bool r)
2008 {
2009 int ret = 0;
2010 unsigned long flags;
2011 struct amd_svm_iommu_ir *ir;
2012 struct vcpu_svm *svm = to_svm(vcpu);
2013
2014 if (!kvm_arch_has_assigned_device(vcpu->kvm))
2015 return 0;
2016
2017 /*
2018 * Here, we go through the per-vcpu ir_list to update all existing
2019 * interrupt remapping table entry targeting this vcpu.
2020 */
2021 spin_lock_irqsave(&svm->ir_list_lock, flags);
2022
2023 if (list_empty(&svm->ir_list))
2024 goto out;
2025
2026 list_for_each_entry(ir, &svm->ir_list, node) {
2027 ret = amd_iommu_update_ga(cpu, r, ir->data);
2028 if (ret)
2029 break;
2030 }
2031 out:
2032 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
2033 return ret;
2034 }
2035
2036 static void avic_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2037 {
2038 u64 entry;
2039 /* ID = 0xff (broadcast), ID > 0xff (reserved) */
2040 int h_physical_id = kvm_cpu_get_apicid(cpu);
2041 struct vcpu_svm *svm = to_svm(vcpu);
2042
2043 if (!kvm_vcpu_apicv_active(vcpu))
2044 return;
2045
2046 /*
2047 * Since the host physical APIC id is 8 bits,
2048 * we can support host APIC ID upto 255.
2049 */
2050 if (WARN_ON(h_physical_id > AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK))
2051 return;
2052
2053 entry = READ_ONCE(*(svm->avic_physical_id_cache));
2054 WARN_ON(entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK);
2055
2056 entry &= ~AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK;
2057 entry |= (h_physical_id & AVIC_PHYSICAL_ID_ENTRY_HOST_PHYSICAL_ID_MASK);
2058
2059 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2060 if (svm->avic_is_running)
2061 entry |= AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2062
2063 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2064 avic_update_iommu_vcpu_affinity(vcpu, h_physical_id,
2065 svm->avic_is_running);
2066 }
2067
2068 static void avic_vcpu_put(struct kvm_vcpu *vcpu)
2069 {
2070 u64 entry;
2071 struct vcpu_svm *svm = to_svm(vcpu);
2072
2073 if (!kvm_vcpu_apicv_active(vcpu))
2074 return;
2075
2076 entry = READ_ONCE(*(svm->avic_physical_id_cache));
2077 if (entry & AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK)
2078 avic_update_iommu_vcpu_affinity(vcpu, -1, 0);
2079
2080 entry &= ~AVIC_PHYSICAL_ID_ENTRY_IS_RUNNING_MASK;
2081 WRITE_ONCE(*(svm->avic_physical_id_cache), entry);
2082 }
2083
2084 /**
2085 * This function is called during VCPU halt/unhalt.
2086 */
2087 static void avic_set_running(struct kvm_vcpu *vcpu, bool is_run)
2088 {
2089 struct vcpu_svm *svm = to_svm(vcpu);
2090
2091 svm->avic_is_running = is_run;
2092 if (is_run)
2093 avic_vcpu_load(vcpu, vcpu->cpu);
2094 else
2095 avic_vcpu_put(vcpu);
2096 }
2097
2098 static void svm_vcpu_reset(struct kvm_vcpu *vcpu, bool init_event)
2099 {
2100 struct vcpu_svm *svm = to_svm(vcpu);
2101 u32 dummy;
2102 u32 eax = 1;
2103
2104 vcpu->arch.microcode_version = 0x01000065;
2105 svm->spec_ctrl = 0;
2106 svm->virt_spec_ctrl = 0;
2107
2108 if (!init_event) {
2109 svm->vcpu.arch.apic_base = APIC_DEFAULT_PHYS_BASE |
2110 MSR_IA32_APICBASE_ENABLE;
2111 if (kvm_vcpu_is_reset_bsp(&svm->vcpu))
2112 svm->vcpu.arch.apic_base |= MSR_IA32_APICBASE_BSP;
2113 }
2114 init_vmcb(svm);
2115
2116 kvm_cpuid(vcpu, &eax, &dummy, &dummy, &dummy, true);
2117 kvm_rdx_write(vcpu, eax);
2118
2119 if (kvm_vcpu_apicv_active(vcpu) && !init_event)
2120 avic_update_vapic_bar(svm, APIC_DEFAULT_PHYS_BASE);
2121 }
2122
2123 static int avic_init_vcpu(struct vcpu_svm *svm)
2124 {
2125 int ret;
2126
2127 if (!kvm_vcpu_apicv_active(&svm->vcpu))
2128 return 0;
2129
2130 ret = avic_init_backing_page(&svm->vcpu);
2131 if (ret)
2132 return ret;
2133
2134 INIT_LIST_HEAD(&svm->ir_list);
2135 spin_lock_init(&svm->ir_list_lock);
2136 svm->dfr_reg = APIC_DFR_FLAT;
2137
2138 return ret;
2139 }
2140
2141 static struct kvm_vcpu *svm_create_vcpu(struct kvm *kvm, unsigned int id)
2142 {
2143 struct vcpu_svm *svm;
2144 struct page *page;
2145 struct page *msrpm_pages;
2146 struct page *hsave_page;
2147 struct page *nested_msrpm_pages;
2148 int err;
2149
2150 BUILD_BUG_ON_MSG(offsetof(struct vcpu_svm, vcpu) != 0,
2151 "struct kvm_vcpu must be at offset 0 for arch usercopy region");
2152
2153 svm = kmem_cache_zalloc(kvm_vcpu_cache, GFP_KERNEL_ACCOUNT);
2154 if (!svm) {
2155 err = -ENOMEM;
2156 goto out;
2157 }
2158
2159 svm->vcpu.arch.user_fpu = kmem_cache_zalloc(x86_fpu_cache,
2160 GFP_KERNEL_ACCOUNT);
2161 if (!svm->vcpu.arch.user_fpu) {
2162 printk(KERN_ERR "kvm: failed to allocate kvm userspace's fpu\n");
2163 err = -ENOMEM;
2164 goto free_partial_svm;
2165 }
2166
2167 svm->vcpu.arch.guest_fpu = kmem_cache_zalloc(x86_fpu_cache,
2168 GFP_KERNEL_ACCOUNT);
2169 if (!svm->vcpu.arch.guest_fpu) {
2170 printk(KERN_ERR "kvm: failed to allocate vcpu's fpu\n");
2171 err = -ENOMEM;
2172 goto free_user_fpu;
2173 }
2174
2175 err = kvm_vcpu_init(&svm->vcpu, kvm, id);
2176 if (err)
2177 goto free_svm;
2178
2179 err = -ENOMEM;
2180 page = alloc_page(GFP_KERNEL_ACCOUNT);
2181 if (!page)
2182 goto uninit;
2183
2184 msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2185 if (!msrpm_pages)
2186 goto free_page1;
2187
2188 nested_msrpm_pages = alloc_pages(GFP_KERNEL_ACCOUNT, MSRPM_ALLOC_ORDER);
2189 if (!nested_msrpm_pages)
2190 goto free_page2;
2191
2192 hsave_page = alloc_page(GFP_KERNEL_ACCOUNT);
2193 if (!hsave_page)
2194 goto free_page3;
2195
2196 err = avic_init_vcpu(svm);
2197 if (err)
2198 goto free_page4;
2199
2200 /* We initialize this flag to true to make sure that the is_running
2201 * bit would be set the first time the vcpu is loaded.
2202 */
2203 svm->avic_is_running = true;
2204
2205 svm->nested.hsave = page_address(hsave_page);
2206
2207 svm->msrpm = page_address(msrpm_pages);
2208 svm_vcpu_init_msrpm(svm->msrpm);
2209
2210 svm->nested.msrpm = page_address(nested_msrpm_pages);
2211 svm_vcpu_init_msrpm(svm->nested.msrpm);
2212
2213 svm->vmcb = page_address(page);
2214 clear_page(svm->vmcb);
2215 svm->vmcb_pa = __sme_set(page_to_pfn(page) << PAGE_SHIFT);
2216 svm->asid_generation = 0;
2217 init_vmcb(svm);
2218
2219 svm_init_osvw(&svm->vcpu);
2220
2221 return &svm->vcpu;
2222
2223 free_page4:
2224 __free_page(hsave_page);
2225 free_page3:
2226 __free_pages(nested_msrpm_pages, MSRPM_ALLOC_ORDER);
2227 free_page2:
2228 __free_pages(msrpm_pages, MSRPM_ALLOC_ORDER);
2229 free_page1:
2230 __free_page(page);
2231 uninit:
2232 kvm_vcpu_uninit(&svm->vcpu);
2233 free_svm:
2234 kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.guest_fpu);
2235 free_user_fpu:
2236 kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.user_fpu);
2237 free_partial_svm:
2238 kmem_cache_free(kvm_vcpu_cache, svm);
2239 out:
2240 return ERR_PTR(err);
2241 }
2242
2243 static void svm_clear_current_vmcb(struct vmcb *vmcb)
2244 {
2245 int i;
2246
2247 for_each_online_cpu(i)
2248 cmpxchg(&per_cpu(svm_data, i)->current_vmcb, vmcb, NULL);
2249 }
2250
2251 static void svm_free_vcpu(struct kvm_vcpu *vcpu)
2252 {
2253 struct vcpu_svm *svm = to_svm(vcpu);
2254
2255 /*
2256 * The vmcb page can be recycled, causing a false negative in
2257 * svm_vcpu_load(). So, ensure that no logical CPU has this
2258 * vmcb page recorded as its current vmcb.
2259 */
2260 svm_clear_current_vmcb(svm->vmcb);
2261
2262 __free_page(pfn_to_page(__sme_clr(svm->vmcb_pa) >> PAGE_SHIFT));
2263 __free_pages(virt_to_page(svm->msrpm), MSRPM_ALLOC_ORDER);
2264 __free_page(virt_to_page(svm->nested.hsave));
2265 __free_pages(virt_to_page(svm->nested.msrpm), MSRPM_ALLOC_ORDER);
2266 kvm_vcpu_uninit(vcpu);
2267 kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.user_fpu);
2268 kmem_cache_free(x86_fpu_cache, svm->vcpu.arch.guest_fpu);
2269 kmem_cache_free(kvm_vcpu_cache, svm);
2270 }
2271
2272 static void svm_vcpu_load(struct kvm_vcpu *vcpu, int cpu)
2273 {
2274 struct vcpu_svm *svm = to_svm(vcpu);
2275 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
2276 int i;
2277
2278 if (unlikely(cpu != vcpu->cpu)) {
2279 svm->asid_generation = 0;
2280 mark_all_dirty(svm->vmcb);
2281 }
2282
2283 #ifdef CONFIG_X86_64
2284 rdmsrl(MSR_GS_BASE, to_svm(vcpu)->host.gs_base);
2285 #endif
2286 savesegment(fs, svm->host.fs);
2287 savesegment(gs, svm->host.gs);
2288 svm->host.ldt = kvm_read_ldt();
2289
2290 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2291 rdmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2292
2293 if (static_cpu_has(X86_FEATURE_TSCRATEMSR)) {
2294 u64 tsc_ratio = vcpu->arch.tsc_scaling_ratio;
2295 if (tsc_ratio != __this_cpu_read(current_tsc_ratio)) {
2296 __this_cpu_write(current_tsc_ratio, tsc_ratio);
2297 wrmsrl(MSR_AMD64_TSC_RATIO, tsc_ratio);
2298 }
2299 }
2300 /* This assumes that the kernel never uses MSR_TSC_AUX */
2301 if (static_cpu_has(X86_FEATURE_RDTSCP))
2302 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
2303
2304 if (sd->current_vmcb != svm->vmcb) {
2305 sd->current_vmcb = svm->vmcb;
2306 indirect_branch_prediction_barrier();
2307 }
2308 avic_vcpu_load(vcpu, cpu);
2309 }
2310
2311 static void svm_vcpu_put(struct kvm_vcpu *vcpu)
2312 {
2313 struct vcpu_svm *svm = to_svm(vcpu);
2314 int i;
2315
2316 avic_vcpu_put(vcpu);
2317
2318 ++vcpu->stat.host_state_reload;
2319 kvm_load_ldt(svm->host.ldt);
2320 #ifdef CONFIG_X86_64
2321 loadsegment(fs, svm->host.fs);
2322 wrmsrl(MSR_KERNEL_GS_BASE, current->thread.gsbase);
2323 load_gs_index(svm->host.gs);
2324 #else
2325 #ifdef CONFIG_X86_32_LAZY_GS
2326 loadsegment(gs, svm->host.gs);
2327 #endif
2328 #endif
2329 for (i = 0; i < NR_HOST_SAVE_USER_MSRS; i++)
2330 wrmsrl(host_save_user_msrs[i], svm->host_user_msrs[i]);
2331 }
2332
2333 static void svm_vcpu_blocking(struct kvm_vcpu *vcpu)
2334 {
2335 avic_set_running(vcpu, false);
2336 }
2337
2338 static void svm_vcpu_unblocking(struct kvm_vcpu *vcpu)
2339 {
2340 avic_set_running(vcpu, true);
2341 }
2342
2343 static unsigned long svm_get_rflags(struct kvm_vcpu *vcpu)
2344 {
2345 struct vcpu_svm *svm = to_svm(vcpu);
2346 unsigned long rflags = svm->vmcb->save.rflags;
2347
2348 if (svm->nmi_singlestep) {
2349 /* Hide our flags if they were not set by the guest */
2350 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF))
2351 rflags &= ~X86_EFLAGS_TF;
2352 if (!(svm->nmi_singlestep_guest_rflags & X86_EFLAGS_RF))
2353 rflags &= ~X86_EFLAGS_RF;
2354 }
2355 return rflags;
2356 }
2357
2358 static void svm_set_rflags(struct kvm_vcpu *vcpu, unsigned long rflags)
2359 {
2360 if (to_svm(vcpu)->nmi_singlestep)
2361 rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
2362
2363 /*
2364 * Any change of EFLAGS.VM is accompanied by a reload of SS
2365 * (caused by either a task switch or an inter-privilege IRET),
2366 * so we do not need to update the CPL here.
2367 */
2368 to_svm(vcpu)->vmcb->save.rflags = rflags;
2369 }
2370
2371 static void svm_cache_reg(struct kvm_vcpu *vcpu, enum kvm_reg reg)
2372 {
2373 switch (reg) {
2374 case VCPU_EXREG_PDPTR:
2375 BUG_ON(!npt_enabled);
2376 load_pdptrs(vcpu, vcpu->arch.walk_mmu, kvm_read_cr3(vcpu));
2377 break;
2378 default:
2379 WARN_ON_ONCE(1);
2380 }
2381 }
2382
2383 static void svm_set_vintr(struct vcpu_svm *svm)
2384 {
2385 set_intercept(svm, INTERCEPT_VINTR);
2386 }
2387
2388 static void svm_clear_vintr(struct vcpu_svm *svm)
2389 {
2390 clr_intercept(svm, INTERCEPT_VINTR);
2391 }
2392
2393 static struct vmcb_seg *svm_seg(struct kvm_vcpu *vcpu, int seg)
2394 {
2395 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2396
2397 switch (seg) {
2398 case VCPU_SREG_CS: return &save->cs;
2399 case VCPU_SREG_DS: return &save->ds;
2400 case VCPU_SREG_ES: return &save->es;
2401 case VCPU_SREG_FS: return &save->fs;
2402 case VCPU_SREG_GS: return &save->gs;
2403 case VCPU_SREG_SS: return &save->ss;
2404 case VCPU_SREG_TR: return &save->tr;
2405 case VCPU_SREG_LDTR: return &save->ldtr;
2406 }
2407 BUG();
2408 return NULL;
2409 }
2410
2411 static u64 svm_get_segment_base(struct kvm_vcpu *vcpu, int seg)
2412 {
2413 struct vmcb_seg *s = svm_seg(vcpu, seg);
2414
2415 return s->base;
2416 }
2417
2418 static void svm_get_segment(struct kvm_vcpu *vcpu,
2419 struct kvm_segment *var, int seg)
2420 {
2421 struct vmcb_seg *s = svm_seg(vcpu, seg);
2422
2423 var->base = s->base;
2424 var->limit = s->limit;
2425 var->selector = s->selector;
2426 var->type = s->attrib & SVM_SELECTOR_TYPE_MASK;
2427 var->s = (s->attrib >> SVM_SELECTOR_S_SHIFT) & 1;
2428 var->dpl = (s->attrib >> SVM_SELECTOR_DPL_SHIFT) & 3;
2429 var->present = (s->attrib >> SVM_SELECTOR_P_SHIFT) & 1;
2430 var->avl = (s->attrib >> SVM_SELECTOR_AVL_SHIFT) & 1;
2431 var->l = (s->attrib >> SVM_SELECTOR_L_SHIFT) & 1;
2432 var->db = (s->attrib >> SVM_SELECTOR_DB_SHIFT) & 1;
2433
2434 /*
2435 * AMD CPUs circa 2014 track the G bit for all segments except CS.
2436 * However, the SVM spec states that the G bit is not observed by the
2437 * CPU, and some VMware virtual CPUs drop the G bit for all segments.
2438 * So let's synthesize a legal G bit for all segments, this helps
2439 * running KVM nested. It also helps cross-vendor migration, because
2440 * Intel's vmentry has a check on the 'G' bit.
2441 */
2442 var->g = s->limit > 0xfffff;
2443
2444 /*
2445 * AMD's VMCB does not have an explicit unusable field, so emulate it
2446 * for cross vendor migration purposes by "not present"
2447 */
2448 var->unusable = !var->present;
2449
2450 switch (seg) {
2451 case VCPU_SREG_TR:
2452 /*
2453 * Work around a bug where the busy flag in the tr selector
2454 * isn't exposed
2455 */
2456 var->type |= 0x2;
2457 break;
2458 case VCPU_SREG_DS:
2459 case VCPU_SREG_ES:
2460 case VCPU_SREG_FS:
2461 case VCPU_SREG_GS:
2462 /*
2463 * The accessed bit must always be set in the segment
2464 * descriptor cache, although it can be cleared in the
2465 * descriptor, the cached bit always remains at 1. Since
2466 * Intel has a check on this, set it here to support
2467 * cross-vendor migration.
2468 */
2469 if (!var->unusable)
2470 var->type |= 0x1;
2471 break;
2472 case VCPU_SREG_SS:
2473 /*
2474 * On AMD CPUs sometimes the DB bit in the segment
2475 * descriptor is left as 1, although the whole segment has
2476 * been made unusable. Clear it here to pass an Intel VMX
2477 * entry check when cross vendor migrating.
2478 */
2479 if (var->unusable)
2480 var->db = 0;
2481 /* This is symmetric with svm_set_segment() */
2482 var->dpl = to_svm(vcpu)->vmcb->save.cpl;
2483 break;
2484 }
2485 }
2486
2487 static int svm_get_cpl(struct kvm_vcpu *vcpu)
2488 {
2489 struct vmcb_save_area *save = &to_svm(vcpu)->vmcb->save;
2490
2491 return save->cpl;
2492 }
2493
2494 static void svm_get_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2495 {
2496 struct vcpu_svm *svm = to_svm(vcpu);
2497
2498 dt->size = svm->vmcb->save.idtr.limit;
2499 dt->address = svm->vmcb->save.idtr.base;
2500 }
2501
2502 static void svm_set_idt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2503 {
2504 struct vcpu_svm *svm = to_svm(vcpu);
2505
2506 svm->vmcb->save.idtr.limit = dt->size;
2507 svm->vmcb->save.idtr.base = dt->address ;
2508 mark_dirty(svm->vmcb, VMCB_DT);
2509 }
2510
2511 static void svm_get_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2512 {
2513 struct vcpu_svm *svm = to_svm(vcpu);
2514
2515 dt->size = svm->vmcb->save.gdtr.limit;
2516 dt->address = svm->vmcb->save.gdtr.base;
2517 }
2518
2519 static void svm_set_gdt(struct kvm_vcpu *vcpu, struct desc_ptr *dt)
2520 {
2521 struct vcpu_svm *svm = to_svm(vcpu);
2522
2523 svm->vmcb->save.gdtr.limit = dt->size;
2524 svm->vmcb->save.gdtr.base = dt->address ;
2525 mark_dirty(svm->vmcb, VMCB_DT);
2526 }
2527
2528 static void svm_decache_cr0_guest_bits(struct kvm_vcpu *vcpu)
2529 {
2530 }
2531
2532 static void svm_decache_cr4_guest_bits(struct kvm_vcpu *vcpu)
2533 {
2534 }
2535
2536 static void update_cr0_intercept(struct vcpu_svm *svm)
2537 {
2538 ulong gcr0 = svm->vcpu.arch.cr0;
2539 u64 *hcr0 = &svm->vmcb->save.cr0;
2540
2541 *hcr0 = (*hcr0 & ~SVM_CR0_SELECTIVE_MASK)
2542 | (gcr0 & SVM_CR0_SELECTIVE_MASK);
2543
2544 mark_dirty(svm->vmcb, VMCB_CR);
2545
2546 if (gcr0 == *hcr0) {
2547 clr_cr_intercept(svm, INTERCEPT_CR0_READ);
2548 clr_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2549 } else {
2550 set_cr_intercept(svm, INTERCEPT_CR0_READ);
2551 set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
2552 }
2553 }
2554
2555 static void svm_set_cr0(struct kvm_vcpu *vcpu, unsigned long cr0)
2556 {
2557 struct vcpu_svm *svm = to_svm(vcpu);
2558
2559 #ifdef CONFIG_X86_64
2560 if (vcpu->arch.efer & EFER_LME) {
2561 if (!is_paging(vcpu) && (cr0 & X86_CR0_PG)) {
2562 vcpu->arch.efer |= EFER_LMA;
2563 svm->vmcb->save.efer |= EFER_LMA | EFER_LME;
2564 }
2565
2566 if (is_paging(vcpu) && !(cr0 & X86_CR0_PG)) {
2567 vcpu->arch.efer &= ~EFER_LMA;
2568 svm->vmcb->save.efer &= ~(EFER_LMA | EFER_LME);
2569 }
2570 }
2571 #endif
2572 vcpu->arch.cr0 = cr0;
2573
2574 if (!npt_enabled)
2575 cr0 |= X86_CR0_PG | X86_CR0_WP;
2576
2577 /*
2578 * re-enable caching here because the QEMU bios
2579 * does not do it - this results in some delay at
2580 * reboot
2581 */
2582 if (kvm_check_has_quirk(vcpu->kvm, KVM_X86_QUIRK_CD_NW_CLEARED))
2583 cr0 &= ~(X86_CR0_CD | X86_CR0_NW);
2584 svm->vmcb->save.cr0 = cr0;
2585 mark_dirty(svm->vmcb, VMCB_CR);
2586 update_cr0_intercept(svm);
2587 }
2588
2589 static int svm_set_cr4(struct kvm_vcpu *vcpu, unsigned long cr4)
2590 {
2591 unsigned long host_cr4_mce = cr4_read_shadow() & X86_CR4_MCE;
2592 unsigned long old_cr4 = to_svm(vcpu)->vmcb->save.cr4;
2593
2594 if (cr4 & X86_CR4_VMXE)
2595 return 1;
2596
2597 if (npt_enabled && ((old_cr4 ^ cr4) & X86_CR4_PGE))
2598 svm_flush_tlb(vcpu, true);
2599
2600 vcpu->arch.cr4 = cr4;
2601 if (!npt_enabled)
2602 cr4 |= X86_CR4_PAE;
2603 cr4 |= host_cr4_mce;
2604 to_svm(vcpu)->vmcb->save.cr4 = cr4;
2605 mark_dirty(to_svm(vcpu)->vmcb, VMCB_CR);
2606 return 0;
2607 }
2608
2609 static void svm_set_segment(struct kvm_vcpu *vcpu,
2610 struct kvm_segment *var, int seg)
2611 {
2612 struct vcpu_svm *svm = to_svm(vcpu);
2613 struct vmcb_seg *s = svm_seg(vcpu, seg);
2614
2615 s->base = var->base;
2616 s->limit = var->limit;
2617 s->selector = var->selector;
2618 s->attrib = (var->type & SVM_SELECTOR_TYPE_MASK);
2619 s->attrib |= (var->s & 1) << SVM_SELECTOR_S_SHIFT;
2620 s->attrib |= (var->dpl & 3) << SVM_SELECTOR_DPL_SHIFT;
2621 s->attrib |= ((var->present & 1) && !var->unusable) << SVM_SELECTOR_P_SHIFT;
2622 s->attrib |= (var->avl & 1) << SVM_SELECTOR_AVL_SHIFT;
2623 s->attrib |= (var->l & 1) << SVM_SELECTOR_L_SHIFT;
2624 s->attrib |= (var->db & 1) << SVM_SELECTOR_DB_SHIFT;
2625 s->attrib |= (var->g & 1) << SVM_SELECTOR_G_SHIFT;
2626
2627 /*
2628 * This is always accurate, except if SYSRET returned to a segment
2629 * with SS.DPL != 3. Intel does not have this quirk, and always
2630 * forces SS.DPL to 3 on sysret, so we ignore that case; fixing it
2631 * would entail passing the CPL to userspace and back.
2632 */
2633 if (seg == VCPU_SREG_SS)
2634 /* This is symmetric with svm_get_segment() */
2635 svm->vmcb->save.cpl = (var->dpl & 3);
2636
2637 mark_dirty(svm->vmcb, VMCB_SEG);
2638 }
2639
2640 static void update_bp_intercept(struct kvm_vcpu *vcpu)
2641 {
2642 struct vcpu_svm *svm = to_svm(vcpu);
2643
2644 clr_exception_intercept(svm, BP_VECTOR);
2645
2646 if (vcpu->guest_debug & KVM_GUESTDBG_ENABLE) {
2647 if (vcpu->guest_debug & KVM_GUESTDBG_USE_SW_BP)
2648 set_exception_intercept(svm, BP_VECTOR);
2649 } else
2650 vcpu->guest_debug = 0;
2651 }
2652
2653 static void new_asid(struct vcpu_svm *svm, struct svm_cpu_data *sd)
2654 {
2655 if (sd->next_asid > sd->max_asid) {
2656 ++sd->asid_generation;
2657 sd->next_asid = sd->min_asid;
2658 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ALL_ASID;
2659 }
2660
2661 svm->asid_generation = sd->asid_generation;
2662 svm->vmcb->control.asid = sd->next_asid++;
2663
2664 mark_dirty(svm->vmcb, VMCB_ASID);
2665 }
2666
2667 static u64 svm_get_dr6(struct kvm_vcpu *vcpu)
2668 {
2669 return to_svm(vcpu)->vmcb->save.dr6;
2670 }
2671
2672 static void svm_set_dr6(struct kvm_vcpu *vcpu, unsigned long value)
2673 {
2674 struct vcpu_svm *svm = to_svm(vcpu);
2675
2676 svm->vmcb->save.dr6 = value;
2677 mark_dirty(svm->vmcb, VMCB_DR);
2678 }
2679
2680 static void svm_sync_dirty_debug_regs(struct kvm_vcpu *vcpu)
2681 {
2682 struct vcpu_svm *svm = to_svm(vcpu);
2683
2684 get_debugreg(vcpu->arch.db[0], 0);
2685 get_debugreg(vcpu->arch.db[1], 1);
2686 get_debugreg(vcpu->arch.db[2], 2);
2687 get_debugreg(vcpu->arch.db[3], 3);
2688 vcpu->arch.dr6 = svm_get_dr6(vcpu);
2689 vcpu->arch.dr7 = svm->vmcb->save.dr7;
2690
2691 vcpu->arch.switch_db_regs &= ~KVM_DEBUGREG_WONT_EXIT;
2692 set_dr_intercepts(svm);
2693 }
2694
2695 static void svm_set_dr7(struct kvm_vcpu *vcpu, unsigned long value)
2696 {
2697 struct vcpu_svm *svm = to_svm(vcpu);
2698
2699 svm->vmcb->save.dr7 = value;
2700 mark_dirty(svm->vmcb, VMCB_DR);
2701 }
2702
2703 static int pf_interception(struct vcpu_svm *svm)
2704 {
2705 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2706 u64 error_code = svm->vmcb->control.exit_info_1;
2707
2708 return kvm_handle_page_fault(&svm->vcpu, error_code, fault_address,
2709 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2710 svm->vmcb->control.insn_bytes : NULL,
2711 svm->vmcb->control.insn_len);
2712 }
2713
2714 static int npf_interception(struct vcpu_svm *svm)
2715 {
2716 u64 fault_address = __sme_clr(svm->vmcb->control.exit_info_2);
2717 u64 error_code = svm->vmcb->control.exit_info_1;
2718
2719 trace_kvm_page_fault(fault_address, error_code);
2720 return kvm_mmu_page_fault(&svm->vcpu, fault_address, error_code,
2721 static_cpu_has(X86_FEATURE_DECODEASSISTS) ?
2722 svm->vmcb->control.insn_bytes : NULL,
2723 svm->vmcb->control.insn_len);
2724 }
2725
2726 static int db_interception(struct vcpu_svm *svm)
2727 {
2728 struct kvm_run *kvm_run = svm->vcpu.run;
2729 struct kvm_vcpu *vcpu = &svm->vcpu;
2730
2731 if (!(svm->vcpu.guest_debug &
2732 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) &&
2733 !svm->nmi_singlestep) {
2734 kvm_queue_exception(&svm->vcpu, DB_VECTOR);
2735 return 1;
2736 }
2737
2738 if (svm->nmi_singlestep) {
2739 disable_nmi_singlestep(svm);
2740 /* Make sure we check for pending NMIs upon entry */
2741 kvm_make_request(KVM_REQ_EVENT, vcpu);
2742 }
2743
2744 if (svm->vcpu.guest_debug &
2745 (KVM_GUESTDBG_SINGLESTEP | KVM_GUESTDBG_USE_HW_BP)) {
2746 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2747 kvm_run->debug.arch.pc =
2748 svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2749 kvm_run->debug.arch.exception = DB_VECTOR;
2750 return 0;
2751 }
2752
2753 return 1;
2754 }
2755
2756 static int bp_interception(struct vcpu_svm *svm)
2757 {
2758 struct kvm_run *kvm_run = svm->vcpu.run;
2759
2760 kvm_run->exit_reason = KVM_EXIT_DEBUG;
2761 kvm_run->debug.arch.pc = svm->vmcb->save.cs.base + svm->vmcb->save.rip;
2762 kvm_run->debug.arch.exception = BP_VECTOR;
2763 return 0;
2764 }
2765
2766 static int ud_interception(struct vcpu_svm *svm)
2767 {
2768 return handle_ud(&svm->vcpu);
2769 }
2770
2771 static int ac_interception(struct vcpu_svm *svm)
2772 {
2773 kvm_queue_exception_e(&svm->vcpu, AC_VECTOR, 0);
2774 return 1;
2775 }
2776
2777 static int gp_interception(struct vcpu_svm *svm)
2778 {
2779 struct kvm_vcpu *vcpu = &svm->vcpu;
2780 u32 error_code = svm->vmcb->control.exit_info_1;
2781
2782 WARN_ON_ONCE(!enable_vmware_backdoor);
2783
2784 /*
2785 * VMware backdoor emulation on #GP interception only handles IN{S},
2786 * OUT{S}, and RDPMC, none of which generate a non-zero error code.
2787 */
2788 if (error_code) {
2789 kvm_queue_exception_e(vcpu, GP_VECTOR, error_code);
2790 return 1;
2791 }
2792 return kvm_emulate_instruction(vcpu, EMULTYPE_VMWARE_GP);
2793 }
2794
2795 static bool is_erratum_383(void)
2796 {
2797 int err, i;
2798 u64 value;
2799
2800 if (!erratum_383_found)
2801 return false;
2802
2803 value = native_read_msr_safe(MSR_IA32_MC0_STATUS, &err);
2804 if (err)
2805 return false;
2806
2807 /* Bit 62 may or may not be set for this mce */
2808 value &= ~(1ULL << 62);
2809
2810 if (value != 0xb600000000010015ULL)
2811 return false;
2812
2813 /* Clear MCi_STATUS registers */
2814 for (i = 0; i < 6; ++i)
2815 native_write_msr_safe(MSR_IA32_MCx_STATUS(i), 0, 0);
2816
2817 value = native_read_msr_safe(MSR_IA32_MCG_STATUS, &err);
2818 if (!err) {
2819 u32 low, high;
2820
2821 value &= ~(1ULL << 2);
2822 low = lower_32_bits(value);
2823 high = upper_32_bits(value);
2824
2825 native_write_msr_safe(MSR_IA32_MCG_STATUS, low, high);
2826 }
2827
2828 /* Flush tlb to evict multi-match entries */
2829 __flush_tlb_all();
2830
2831 return true;
2832 }
2833
2834 static void svm_handle_mce(struct vcpu_svm *svm)
2835 {
2836 if (is_erratum_383()) {
2837 /*
2838 * Erratum 383 triggered. Guest state is corrupt so kill the
2839 * guest.
2840 */
2841 pr_err("KVM: Guest triggered AMD Erratum 383\n");
2842
2843 kvm_make_request(KVM_REQ_TRIPLE_FAULT, &svm->vcpu);
2844
2845 return;
2846 }
2847
2848 /*
2849 * On an #MC intercept the MCE handler is not called automatically in
2850 * the host. So do it by hand here.
2851 */
2852 asm volatile (
2853 "int $0x12\n");
2854 /* not sure if we ever come back to this point */
2855
2856 return;
2857 }
2858
2859 static int mc_interception(struct vcpu_svm *svm)
2860 {
2861 return 1;
2862 }
2863
2864 static int shutdown_interception(struct vcpu_svm *svm)
2865 {
2866 struct kvm_run *kvm_run = svm->vcpu.run;
2867
2868 /*
2869 * VMCB is undefined after a SHUTDOWN intercept
2870 * so reinitialize it.
2871 */
2872 clear_page(svm->vmcb);
2873 init_vmcb(svm);
2874
2875 kvm_run->exit_reason = KVM_EXIT_SHUTDOWN;
2876 return 0;
2877 }
2878
2879 static int io_interception(struct vcpu_svm *svm)
2880 {
2881 struct kvm_vcpu *vcpu = &svm->vcpu;
2882 u32 io_info = svm->vmcb->control.exit_info_1; /* address size bug? */
2883 int size, in, string;
2884 unsigned port;
2885
2886 ++svm->vcpu.stat.io_exits;
2887 string = (io_info & SVM_IOIO_STR_MASK) != 0;
2888 in = (io_info & SVM_IOIO_TYPE_MASK) != 0;
2889 if (string)
2890 return kvm_emulate_instruction(vcpu, 0);
2891
2892 port = io_info >> 16;
2893 size = (io_info & SVM_IOIO_SIZE_MASK) >> SVM_IOIO_SIZE_SHIFT;
2894 svm->next_rip = svm->vmcb->control.exit_info_2;
2895
2896 return kvm_fast_pio(&svm->vcpu, size, port, in);
2897 }
2898
2899 static int nmi_interception(struct vcpu_svm *svm)
2900 {
2901 return 1;
2902 }
2903
2904 static int intr_interception(struct vcpu_svm *svm)
2905 {
2906 ++svm->vcpu.stat.irq_exits;
2907 return 1;
2908 }
2909
2910 static int nop_on_interception(struct vcpu_svm *svm)
2911 {
2912 return 1;
2913 }
2914
2915 static int halt_interception(struct vcpu_svm *svm)
2916 {
2917 return kvm_emulate_halt(&svm->vcpu);
2918 }
2919
2920 static int vmmcall_interception(struct vcpu_svm *svm)
2921 {
2922 return kvm_emulate_hypercall(&svm->vcpu);
2923 }
2924
2925 static unsigned long nested_svm_get_tdp_cr3(struct kvm_vcpu *vcpu)
2926 {
2927 struct vcpu_svm *svm = to_svm(vcpu);
2928
2929 return svm->nested.nested_cr3;
2930 }
2931
2932 static u64 nested_svm_get_tdp_pdptr(struct kvm_vcpu *vcpu, int index)
2933 {
2934 struct vcpu_svm *svm = to_svm(vcpu);
2935 u64 cr3 = svm->nested.nested_cr3;
2936 u64 pdpte;
2937 int ret;
2938
2939 ret = kvm_vcpu_read_guest_page(vcpu, gpa_to_gfn(__sme_clr(cr3)), &pdpte,
2940 offset_in_page(cr3) + index * 8, 8);
2941 if (ret)
2942 return 0;
2943 return pdpte;
2944 }
2945
2946 static void nested_svm_set_tdp_cr3(struct kvm_vcpu *vcpu,
2947 unsigned long root)
2948 {
2949 struct vcpu_svm *svm = to_svm(vcpu);
2950
2951 svm->vmcb->control.nested_cr3 = __sme_set(root);
2952 mark_dirty(svm->vmcb, VMCB_NPT);
2953 }
2954
2955 static void nested_svm_inject_npf_exit(struct kvm_vcpu *vcpu,
2956 struct x86_exception *fault)
2957 {
2958 struct vcpu_svm *svm = to_svm(vcpu);
2959
2960 if (svm->vmcb->control.exit_code != SVM_EXIT_NPF) {
2961 /*
2962 * TODO: track the cause of the nested page fault, and
2963 * correctly fill in the high bits of exit_info_1.
2964 */
2965 svm->vmcb->control.exit_code = SVM_EXIT_NPF;
2966 svm->vmcb->control.exit_code_hi = 0;
2967 svm->vmcb->control.exit_info_1 = (1ULL << 32);
2968 svm->vmcb->control.exit_info_2 = fault->address;
2969 }
2970
2971 svm->vmcb->control.exit_info_1 &= ~0xffffffffULL;
2972 svm->vmcb->control.exit_info_1 |= fault->error_code;
2973
2974 /*
2975 * The present bit is always zero for page structure faults on real
2976 * hardware.
2977 */
2978 if (svm->vmcb->control.exit_info_1 & (2ULL << 32))
2979 svm->vmcb->control.exit_info_1 &= ~1;
2980
2981 nested_svm_vmexit(svm);
2982 }
2983
2984 static void nested_svm_init_mmu_context(struct kvm_vcpu *vcpu)
2985 {
2986 WARN_ON(mmu_is_nested(vcpu));
2987
2988 vcpu->arch.mmu = &vcpu->arch.guest_mmu;
2989 kvm_init_shadow_mmu(vcpu);
2990 vcpu->arch.mmu->set_cr3 = nested_svm_set_tdp_cr3;
2991 vcpu->arch.mmu->get_cr3 = nested_svm_get_tdp_cr3;
2992 vcpu->arch.mmu->get_pdptr = nested_svm_get_tdp_pdptr;
2993 vcpu->arch.mmu->inject_page_fault = nested_svm_inject_npf_exit;
2994 vcpu->arch.mmu->shadow_root_level = get_npt_level(vcpu);
2995 reset_shadow_zero_bits_mask(vcpu, vcpu->arch.mmu);
2996 vcpu->arch.walk_mmu = &vcpu->arch.nested_mmu;
2997 }
2998
2999 static void nested_svm_uninit_mmu_context(struct kvm_vcpu *vcpu)
3000 {
3001 vcpu->arch.mmu = &vcpu->arch.root_mmu;
3002 vcpu->arch.walk_mmu = &vcpu->arch.root_mmu;
3003 }
3004
3005 static int nested_svm_check_permissions(struct vcpu_svm *svm)
3006 {
3007 if (!(svm->vcpu.arch.efer & EFER_SVME) ||
3008 !is_paging(&svm->vcpu)) {
3009 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3010 return 1;
3011 }
3012
3013 if (svm->vmcb->save.cpl) {
3014 kvm_inject_gp(&svm->vcpu, 0);
3015 return 1;
3016 }
3017
3018 return 0;
3019 }
3020
3021 static int nested_svm_check_exception(struct vcpu_svm *svm, unsigned nr,
3022 bool has_error_code, u32 error_code)
3023 {
3024 int vmexit;
3025
3026 if (!is_guest_mode(&svm->vcpu))
3027 return 0;
3028
3029 vmexit = nested_svm_intercept(svm);
3030 if (vmexit != NESTED_EXIT_DONE)
3031 return 0;
3032
3033 svm->vmcb->control.exit_code = SVM_EXIT_EXCP_BASE + nr;
3034 svm->vmcb->control.exit_code_hi = 0;
3035 svm->vmcb->control.exit_info_1 = error_code;
3036
3037 /*
3038 * EXITINFO2 is undefined for all exception intercepts other
3039 * than #PF.
3040 */
3041 if (svm->vcpu.arch.exception.nested_apf)
3042 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.apf.nested_apf_token;
3043 else if (svm->vcpu.arch.exception.has_payload)
3044 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.exception.payload;
3045 else
3046 svm->vmcb->control.exit_info_2 = svm->vcpu.arch.cr2;
3047
3048 svm->nested.exit_required = true;
3049 return vmexit;
3050 }
3051
3052 /* This function returns true if it is save to enable the irq window */
3053 static inline bool nested_svm_intr(struct vcpu_svm *svm)
3054 {
3055 if (!is_guest_mode(&svm->vcpu))
3056 return true;
3057
3058 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3059 return true;
3060
3061 if (!(svm->vcpu.arch.hflags & HF_HIF_MASK))
3062 return false;
3063
3064 /*
3065 * if vmexit was already requested (by intercepted exception
3066 * for instance) do not overwrite it with "external interrupt"
3067 * vmexit.
3068 */
3069 if (svm->nested.exit_required)
3070 return false;
3071
3072 svm->vmcb->control.exit_code = SVM_EXIT_INTR;
3073 svm->vmcb->control.exit_info_1 = 0;
3074 svm->vmcb->control.exit_info_2 = 0;
3075
3076 if (svm->nested.intercept & 1ULL) {
3077 /*
3078 * The #vmexit can't be emulated here directly because this
3079 * code path runs with irqs and preemption disabled. A
3080 * #vmexit emulation might sleep. Only signal request for
3081 * the #vmexit here.
3082 */
3083 svm->nested.exit_required = true;
3084 trace_kvm_nested_intr_vmexit(svm->vmcb->save.rip);
3085 return false;
3086 }
3087
3088 return true;
3089 }
3090
3091 /* This function returns true if it is save to enable the nmi window */
3092 static inline bool nested_svm_nmi(struct vcpu_svm *svm)
3093 {
3094 if (!is_guest_mode(&svm->vcpu))
3095 return true;
3096
3097 if (!(svm->nested.intercept & (1ULL << INTERCEPT_NMI)))
3098 return true;
3099
3100 svm->vmcb->control.exit_code = SVM_EXIT_NMI;
3101 svm->nested.exit_required = true;
3102
3103 return false;
3104 }
3105
3106 static int nested_svm_intercept_ioio(struct vcpu_svm *svm)
3107 {
3108 unsigned port, size, iopm_len;
3109 u16 val, mask;
3110 u8 start_bit;
3111 u64 gpa;
3112
3113 if (!(svm->nested.intercept & (1ULL << INTERCEPT_IOIO_PROT)))
3114 return NESTED_EXIT_HOST;
3115
3116 port = svm->vmcb->control.exit_info_1 >> 16;
3117 size = (svm->vmcb->control.exit_info_1 & SVM_IOIO_SIZE_MASK) >>
3118 SVM_IOIO_SIZE_SHIFT;
3119 gpa = svm->nested.vmcb_iopm + (port / 8);
3120 start_bit = port % 8;
3121 iopm_len = (start_bit + size > 8) ? 2 : 1;
3122 mask = (0xf >> (4 - size)) << start_bit;
3123 val = 0;
3124
3125 if (kvm_vcpu_read_guest(&svm->vcpu, gpa, &val, iopm_len))
3126 return NESTED_EXIT_DONE;
3127
3128 return (val & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3129 }
3130
3131 static int nested_svm_exit_handled_msr(struct vcpu_svm *svm)
3132 {
3133 u32 offset, msr, value;
3134 int write, mask;
3135
3136 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3137 return NESTED_EXIT_HOST;
3138
3139 msr = svm->vcpu.arch.regs[VCPU_REGS_RCX];
3140 offset = svm_msrpm_offset(msr);
3141 write = svm->vmcb->control.exit_info_1 & 1;
3142 mask = 1 << ((2 * (msr & 0xf)) + write);
3143
3144 if (offset == MSR_INVALID)
3145 return NESTED_EXIT_DONE;
3146
3147 /* Offset is in 32 bit units but need in 8 bit units */
3148 offset *= 4;
3149
3150 if (kvm_vcpu_read_guest(&svm->vcpu, svm->nested.vmcb_msrpm + offset, &value, 4))
3151 return NESTED_EXIT_DONE;
3152
3153 return (value & mask) ? NESTED_EXIT_DONE : NESTED_EXIT_HOST;
3154 }
3155
3156 /* DB exceptions for our internal use must not cause vmexit */
3157 static int nested_svm_intercept_db(struct vcpu_svm *svm)
3158 {
3159 unsigned long dr6;
3160
3161 /* if we're not singlestepping, it's not ours */
3162 if (!svm->nmi_singlestep)
3163 return NESTED_EXIT_DONE;
3164
3165 /* if it's not a singlestep exception, it's not ours */
3166 if (kvm_get_dr(&svm->vcpu, 6, &dr6))
3167 return NESTED_EXIT_DONE;
3168 if (!(dr6 & DR6_BS))
3169 return NESTED_EXIT_DONE;
3170
3171 /* if the guest is singlestepping, it should get the vmexit */
3172 if (svm->nmi_singlestep_guest_rflags & X86_EFLAGS_TF) {
3173 disable_nmi_singlestep(svm);
3174 return NESTED_EXIT_DONE;
3175 }
3176
3177 /* it's ours, the nested hypervisor must not see this one */
3178 return NESTED_EXIT_HOST;
3179 }
3180
3181 static int nested_svm_exit_special(struct vcpu_svm *svm)
3182 {
3183 u32 exit_code = svm->vmcb->control.exit_code;
3184
3185 switch (exit_code) {
3186 case SVM_EXIT_INTR:
3187 case SVM_EXIT_NMI:
3188 case SVM_EXIT_EXCP_BASE + MC_VECTOR:
3189 return NESTED_EXIT_HOST;
3190 case SVM_EXIT_NPF:
3191 /* For now we are always handling NPFs when using them */
3192 if (npt_enabled)
3193 return NESTED_EXIT_HOST;
3194 break;
3195 case SVM_EXIT_EXCP_BASE + PF_VECTOR:
3196 /* When we're shadowing, trap PFs, but not async PF */
3197 if (!npt_enabled && svm->vcpu.arch.apf.host_apf_reason == 0)
3198 return NESTED_EXIT_HOST;
3199 break;
3200 default:
3201 break;
3202 }
3203
3204 return NESTED_EXIT_CONTINUE;
3205 }
3206
3207 /*
3208 * If this function returns true, this #vmexit was already handled
3209 */
3210 static int nested_svm_intercept(struct vcpu_svm *svm)
3211 {
3212 u32 exit_code = svm->vmcb->control.exit_code;
3213 int vmexit = NESTED_EXIT_HOST;
3214
3215 switch (exit_code) {
3216 case SVM_EXIT_MSR:
3217 vmexit = nested_svm_exit_handled_msr(svm);
3218 break;
3219 case SVM_EXIT_IOIO:
3220 vmexit = nested_svm_intercept_ioio(svm);
3221 break;
3222 case SVM_EXIT_READ_CR0 ... SVM_EXIT_WRITE_CR8: {
3223 u32 bit = 1U << (exit_code - SVM_EXIT_READ_CR0);
3224 if (svm->nested.intercept_cr & bit)
3225 vmexit = NESTED_EXIT_DONE;
3226 break;
3227 }
3228 case SVM_EXIT_READ_DR0 ... SVM_EXIT_WRITE_DR7: {
3229 u32 bit = 1U << (exit_code - SVM_EXIT_READ_DR0);
3230 if (svm->nested.intercept_dr & bit)
3231 vmexit = NESTED_EXIT_DONE;
3232 break;
3233 }
3234 case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 0x1f: {
3235 u32 excp_bits = 1 << (exit_code - SVM_EXIT_EXCP_BASE);
3236 if (svm->nested.intercept_exceptions & excp_bits) {
3237 if (exit_code == SVM_EXIT_EXCP_BASE + DB_VECTOR)
3238 vmexit = nested_svm_intercept_db(svm);
3239 else
3240 vmexit = NESTED_EXIT_DONE;
3241 }
3242 /* async page fault always cause vmexit */
3243 else if ((exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR) &&
3244 svm->vcpu.arch.exception.nested_apf != 0)
3245 vmexit = NESTED_EXIT_DONE;
3246 break;
3247 }
3248 case SVM_EXIT_ERR: {
3249 vmexit = NESTED_EXIT_DONE;
3250 break;
3251 }
3252 default: {
3253 u64 exit_bits = 1ULL << (exit_code - SVM_EXIT_INTR);
3254 if (svm->nested.intercept & exit_bits)
3255 vmexit = NESTED_EXIT_DONE;
3256 }
3257 }
3258
3259 return vmexit;
3260 }
3261
3262 static int nested_svm_exit_handled(struct vcpu_svm *svm)
3263 {
3264 int vmexit;
3265
3266 vmexit = nested_svm_intercept(svm);
3267
3268 if (vmexit == NESTED_EXIT_DONE)
3269 nested_svm_vmexit(svm);
3270
3271 return vmexit;
3272 }
3273
3274 static inline void copy_vmcb_control_area(struct vmcb *dst_vmcb, struct vmcb *from_vmcb)
3275 {
3276 struct vmcb_control_area *dst = &dst_vmcb->control;
3277 struct vmcb_control_area *from = &from_vmcb->control;
3278
3279 dst->intercept_cr = from->intercept_cr;
3280 dst->intercept_dr = from->intercept_dr;
3281 dst->intercept_exceptions = from->intercept_exceptions;
3282 dst->intercept = from->intercept;
3283 dst->iopm_base_pa = from->iopm_base_pa;
3284 dst->msrpm_base_pa = from->msrpm_base_pa;
3285 dst->tsc_offset = from->tsc_offset;
3286 dst->asid = from->asid;
3287 dst->tlb_ctl = from->tlb_ctl;
3288 dst->int_ctl = from->int_ctl;
3289 dst->int_vector = from->int_vector;
3290 dst->int_state = from->int_state;
3291 dst->exit_code = from->exit_code;
3292 dst->exit_code_hi = from->exit_code_hi;
3293 dst->exit_info_1 = from->exit_info_1;
3294 dst->exit_info_2 = from->exit_info_2;
3295 dst->exit_int_info = from->exit_int_info;
3296 dst->exit_int_info_err = from->exit_int_info_err;
3297 dst->nested_ctl = from->nested_ctl;
3298 dst->event_inj = from->event_inj;
3299 dst->event_inj_err = from->event_inj_err;
3300 dst->nested_cr3 = from->nested_cr3;
3301 dst->virt_ext = from->virt_ext;
3302 dst->pause_filter_count = from->pause_filter_count;
3303 dst->pause_filter_thresh = from->pause_filter_thresh;
3304 }
3305
3306 static int nested_svm_vmexit(struct vcpu_svm *svm)
3307 {
3308 int rc;
3309 struct vmcb *nested_vmcb;
3310 struct vmcb *hsave = svm->nested.hsave;
3311 struct vmcb *vmcb = svm->vmcb;
3312 struct kvm_host_map map;
3313
3314 trace_kvm_nested_vmexit_inject(vmcb->control.exit_code,
3315 vmcb->control.exit_info_1,
3316 vmcb->control.exit_info_2,
3317 vmcb->control.exit_int_info,
3318 vmcb->control.exit_int_info_err,
3319 KVM_ISA_SVM);
3320
3321 rc = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->nested.vmcb), &map);
3322 if (rc) {
3323 if (rc == -EINVAL)
3324 kvm_inject_gp(&svm->vcpu, 0);
3325 return 1;
3326 }
3327
3328 nested_vmcb = map.hva;
3329
3330 /* Exit Guest-Mode */
3331 leave_guest_mode(&svm->vcpu);
3332 svm->nested.vmcb = 0;
3333
3334 /* Give the current vmcb to the guest */
3335 disable_gif(svm);
3336
3337 nested_vmcb->save.es = vmcb->save.es;
3338 nested_vmcb->save.cs = vmcb->save.cs;
3339 nested_vmcb->save.ss = vmcb->save.ss;
3340 nested_vmcb->save.ds = vmcb->save.ds;
3341 nested_vmcb->save.gdtr = vmcb->save.gdtr;
3342 nested_vmcb->save.idtr = vmcb->save.idtr;
3343 nested_vmcb->save.efer = svm->vcpu.arch.efer;
3344 nested_vmcb->save.cr0 = kvm_read_cr0(&svm->vcpu);
3345 nested_vmcb->save.cr3 = kvm_read_cr3(&svm->vcpu);
3346 nested_vmcb->save.cr2 = vmcb->save.cr2;
3347 nested_vmcb->save.cr4 = svm->vcpu.arch.cr4;
3348 nested_vmcb->save.rflags = kvm_get_rflags(&svm->vcpu);
3349 nested_vmcb->save.rip = vmcb->save.rip;
3350 nested_vmcb->save.rsp = vmcb->save.rsp;
3351 nested_vmcb->save.rax = vmcb->save.rax;
3352 nested_vmcb->save.dr7 = vmcb->save.dr7;
3353 nested_vmcb->save.dr6 = vmcb->save.dr6;
3354 nested_vmcb->save.cpl = vmcb->save.cpl;
3355
3356 nested_vmcb->control.int_ctl = vmcb->control.int_ctl;
3357 nested_vmcb->control.int_vector = vmcb->control.int_vector;
3358 nested_vmcb->control.int_state = vmcb->control.int_state;
3359 nested_vmcb->control.exit_code = vmcb->control.exit_code;
3360 nested_vmcb->control.exit_code_hi = vmcb->control.exit_code_hi;
3361 nested_vmcb->control.exit_info_1 = vmcb->control.exit_info_1;
3362 nested_vmcb->control.exit_info_2 = vmcb->control.exit_info_2;
3363 nested_vmcb->control.exit_int_info = vmcb->control.exit_int_info;
3364 nested_vmcb->control.exit_int_info_err = vmcb->control.exit_int_info_err;
3365
3366 if (svm->nrips_enabled)
3367 nested_vmcb->control.next_rip = vmcb->control.next_rip;
3368
3369 /*
3370 * If we emulate a VMRUN/#VMEXIT in the same host #vmexit cycle we have
3371 * to make sure that we do not lose injected events. So check event_inj
3372 * here and copy it to exit_int_info if it is valid.
3373 * Exit_int_info and event_inj can't be both valid because the case
3374 * below only happens on a VMRUN instruction intercept which has
3375 * no valid exit_int_info set.
3376 */
3377 if (vmcb->control.event_inj & SVM_EVTINJ_VALID) {
3378 struct vmcb_control_area *nc = &nested_vmcb->control;
3379
3380 nc->exit_int_info = vmcb->control.event_inj;
3381 nc->exit_int_info_err = vmcb->control.event_inj_err;
3382 }
3383
3384 nested_vmcb->control.tlb_ctl = 0;
3385 nested_vmcb->control.event_inj = 0;
3386 nested_vmcb->control.event_inj_err = 0;
3387
3388 nested_vmcb->control.pause_filter_count =
3389 svm->vmcb->control.pause_filter_count;
3390 nested_vmcb->control.pause_filter_thresh =
3391 svm->vmcb->control.pause_filter_thresh;
3392
3393 /* We always set V_INTR_MASKING and remember the old value in hflags */
3394 if (!(svm->vcpu.arch.hflags & HF_VINTR_MASK))
3395 nested_vmcb->control.int_ctl &= ~V_INTR_MASKING_MASK;
3396
3397 /* Restore the original control entries */
3398 copy_vmcb_control_area(vmcb, hsave);
3399
3400 svm->vcpu.arch.tsc_offset = svm->vmcb->control.tsc_offset;
3401 kvm_clear_exception_queue(&svm->vcpu);
3402 kvm_clear_interrupt_queue(&svm->vcpu);
3403
3404 svm->nested.nested_cr3 = 0;
3405
3406 /* Restore selected save entries */
3407 svm->vmcb->save.es = hsave->save.es;
3408 svm->vmcb->save.cs = hsave->save.cs;
3409 svm->vmcb->save.ss = hsave->save.ss;
3410 svm->vmcb->save.ds = hsave->save.ds;
3411 svm->vmcb->save.gdtr = hsave->save.gdtr;
3412 svm->vmcb->save.idtr = hsave->save.idtr;
3413 kvm_set_rflags(&svm->vcpu, hsave->save.rflags);
3414 svm_set_efer(&svm->vcpu, hsave->save.efer);
3415 svm_set_cr0(&svm->vcpu, hsave->save.cr0 | X86_CR0_PE);
3416 svm_set_cr4(&svm->vcpu, hsave->save.cr4);
3417 if (npt_enabled) {
3418 svm->vmcb->save.cr3 = hsave->save.cr3;
3419 svm->vcpu.arch.cr3 = hsave->save.cr3;
3420 } else {
3421 (void)kvm_set_cr3(&svm->vcpu, hsave->save.cr3);
3422 }
3423 kvm_rax_write(&svm->vcpu, hsave->save.rax);
3424 kvm_rsp_write(&svm->vcpu, hsave->save.rsp);
3425 kvm_rip_write(&svm->vcpu, hsave->save.rip);
3426 svm->vmcb->save.dr7 = 0;
3427 svm->vmcb->save.cpl = 0;
3428 svm->vmcb->control.exit_int_info = 0;
3429
3430 mark_all_dirty(svm->vmcb);
3431
3432 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3433
3434 nested_svm_uninit_mmu_context(&svm->vcpu);
3435 kvm_mmu_reset_context(&svm->vcpu);
3436 kvm_mmu_load(&svm->vcpu);
3437
3438 /*
3439 * Drop what we picked up for L2 via svm_complete_interrupts() so it
3440 * doesn't end up in L1.
3441 */
3442 svm->vcpu.arch.nmi_injected = false;
3443 kvm_clear_exception_queue(&svm->vcpu);
3444 kvm_clear_interrupt_queue(&svm->vcpu);
3445
3446 return 0;
3447 }
3448
3449 static bool nested_svm_vmrun_msrpm(struct vcpu_svm *svm)
3450 {
3451 /*
3452 * This function merges the msr permission bitmaps of kvm and the
3453 * nested vmcb. It is optimized in that it only merges the parts where
3454 * the kvm msr permission bitmap may contain zero bits
3455 */
3456 int i;
3457
3458 if (!(svm->nested.intercept & (1ULL << INTERCEPT_MSR_PROT)))
3459 return true;
3460
3461 for (i = 0; i < MSRPM_OFFSETS; i++) {
3462 u32 value, p;
3463 u64 offset;
3464
3465 if (msrpm_offsets[i] == 0xffffffff)
3466 break;
3467
3468 p = msrpm_offsets[i];
3469 offset = svm->nested.vmcb_msrpm + (p * 4);
3470
3471 if (kvm_vcpu_read_guest(&svm->vcpu, offset, &value, 4))
3472 return false;
3473
3474 svm->nested.msrpm[p] = svm->msrpm[p] | value;
3475 }
3476
3477 svm->vmcb->control.msrpm_base_pa = __sme_set(__pa(svm->nested.msrpm));
3478
3479 return true;
3480 }
3481
3482 static bool nested_vmcb_checks(struct vmcb *vmcb)
3483 {
3484 if ((vmcb->control.intercept & (1ULL << INTERCEPT_VMRUN)) == 0)
3485 return false;
3486
3487 if (vmcb->control.asid == 0)
3488 return false;
3489
3490 if ((vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) &&
3491 !npt_enabled)
3492 return false;
3493
3494 return true;
3495 }
3496
3497 static void enter_svm_guest_mode(struct vcpu_svm *svm, u64 vmcb_gpa,
3498 struct vmcb *nested_vmcb, struct kvm_host_map *map)
3499 {
3500 if (kvm_get_rflags(&svm->vcpu) & X86_EFLAGS_IF)
3501 svm->vcpu.arch.hflags |= HF_HIF_MASK;
3502 else
3503 svm->vcpu.arch.hflags &= ~HF_HIF_MASK;
3504
3505 if (nested_vmcb->control.nested_ctl & SVM_NESTED_CTL_NP_ENABLE) {
3506 svm->nested.nested_cr3 = nested_vmcb->control.nested_cr3;
3507 nested_svm_init_mmu_context(&svm->vcpu);
3508 }
3509
3510 /* Load the nested guest state */
3511 svm->vmcb->save.es = nested_vmcb->save.es;
3512 svm->vmcb->save.cs = nested_vmcb->save.cs;
3513 svm->vmcb->save.ss = nested_vmcb->save.ss;
3514 svm->vmcb->save.ds = nested_vmcb->save.ds;
3515 svm->vmcb->save.gdtr = nested_vmcb->save.gdtr;
3516 svm->vmcb->save.idtr = nested_vmcb->save.idtr;
3517 kvm_set_rflags(&svm->vcpu, nested_vmcb->save.rflags);
3518 svm_set_efer(&svm->vcpu, nested_vmcb->save.efer);
3519 svm_set_cr0(&svm->vcpu, nested_vmcb->save.cr0);
3520 svm_set_cr4(&svm->vcpu, nested_vmcb->save.cr4);
3521 if (npt_enabled) {
3522 svm->vmcb->save.cr3 = nested_vmcb->save.cr3;
3523 svm->vcpu.arch.cr3 = nested_vmcb->save.cr3;
3524 } else
3525 (void)kvm_set_cr3(&svm->vcpu, nested_vmcb->save.cr3);
3526
3527 /* Guest paging mode is active - reset mmu */
3528 kvm_mmu_reset_context(&svm->vcpu);
3529
3530 svm->vmcb->save.cr2 = svm->vcpu.arch.cr2 = nested_vmcb->save.cr2;
3531 kvm_rax_write(&svm->vcpu, nested_vmcb->save.rax);
3532 kvm_rsp_write(&svm->vcpu, nested_vmcb->save.rsp);
3533 kvm_rip_write(&svm->vcpu, nested_vmcb->save.rip);
3534
3535 /* In case we don't even reach vcpu_run, the fields are not updated */
3536 svm->vmcb->save.rax = nested_vmcb->save.rax;
3537 svm->vmcb->save.rsp = nested_vmcb->save.rsp;
3538 svm->vmcb->save.rip = nested_vmcb->save.rip;
3539 svm->vmcb->save.dr7 = nested_vmcb->save.dr7;
3540 svm->vmcb->save.dr6 = nested_vmcb->save.dr6;
3541 svm->vmcb->save.cpl = nested_vmcb->save.cpl;
3542
3543 svm->nested.vmcb_msrpm = nested_vmcb->control.msrpm_base_pa & ~0x0fffULL;
3544 svm->nested.vmcb_iopm = nested_vmcb->control.iopm_base_pa & ~0x0fffULL;
3545
3546 /* cache intercepts */
3547 svm->nested.intercept_cr = nested_vmcb->control.intercept_cr;
3548 svm->nested.intercept_dr = nested_vmcb->control.intercept_dr;
3549 svm->nested.intercept_exceptions = nested_vmcb->control.intercept_exceptions;
3550 svm->nested.intercept = nested_vmcb->control.intercept;
3551
3552 svm_flush_tlb(&svm->vcpu, true);
3553 svm->vmcb->control.int_ctl = nested_vmcb->control.int_ctl | V_INTR_MASKING_MASK;
3554 if (nested_vmcb->control.int_ctl & V_INTR_MASKING_MASK)
3555 svm->vcpu.arch.hflags |= HF_VINTR_MASK;
3556 else
3557 svm->vcpu.arch.hflags &= ~HF_VINTR_MASK;
3558
3559 if (svm->vcpu.arch.hflags & HF_VINTR_MASK) {
3560 /* We only want the cr8 intercept bits of the guest */
3561 clr_cr_intercept(svm, INTERCEPT_CR8_READ);
3562 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
3563 }
3564
3565 /* We don't want to see VMMCALLs from a nested guest */
3566 clr_intercept(svm, INTERCEPT_VMMCALL);
3567
3568 svm->vcpu.arch.tsc_offset += nested_vmcb->control.tsc_offset;
3569 svm->vmcb->control.tsc_offset = svm->vcpu.arch.tsc_offset;
3570
3571 svm->vmcb->control.virt_ext = nested_vmcb->control.virt_ext;
3572 svm->vmcb->control.int_vector = nested_vmcb->control.int_vector;
3573 svm->vmcb->control.int_state = nested_vmcb->control.int_state;
3574 svm->vmcb->control.event_inj = nested_vmcb->control.event_inj;
3575 svm->vmcb->control.event_inj_err = nested_vmcb->control.event_inj_err;
3576
3577 svm->vmcb->control.pause_filter_count =
3578 nested_vmcb->control.pause_filter_count;
3579 svm->vmcb->control.pause_filter_thresh =
3580 nested_vmcb->control.pause_filter_thresh;
3581
3582 kvm_vcpu_unmap(&svm->vcpu, map, true);
3583
3584 /* Enter Guest-Mode */
3585 enter_guest_mode(&svm->vcpu);
3586
3587 /*
3588 * Merge guest and host intercepts - must be called with vcpu in
3589 * guest-mode to take affect here
3590 */
3591 recalc_intercepts(svm);
3592
3593 svm->nested.vmcb = vmcb_gpa;
3594
3595 enable_gif(svm);
3596
3597 mark_all_dirty(svm->vmcb);
3598 }
3599
3600 static int nested_svm_vmrun(struct vcpu_svm *svm)
3601 {
3602 int ret;
3603 struct vmcb *nested_vmcb;
3604 struct vmcb *hsave = svm->nested.hsave;
3605 struct vmcb *vmcb = svm->vmcb;
3606 struct kvm_host_map map;
3607 u64 vmcb_gpa;
3608
3609 vmcb_gpa = svm->vmcb->save.rax;
3610
3611 ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb_gpa), &map);
3612 if (ret == -EINVAL) {
3613 kvm_inject_gp(&svm->vcpu, 0);
3614 return 1;
3615 } else if (ret) {
3616 return kvm_skip_emulated_instruction(&svm->vcpu);
3617 }
3618
3619 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3620
3621 nested_vmcb = map.hva;
3622
3623 if (!nested_vmcb_checks(nested_vmcb)) {
3624 nested_vmcb->control.exit_code = SVM_EXIT_ERR;
3625 nested_vmcb->control.exit_code_hi = 0;
3626 nested_vmcb->control.exit_info_1 = 0;
3627 nested_vmcb->control.exit_info_2 = 0;
3628
3629 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3630
3631 return ret;
3632 }
3633
3634 trace_kvm_nested_vmrun(svm->vmcb->save.rip, vmcb_gpa,
3635 nested_vmcb->save.rip,
3636 nested_vmcb->control.int_ctl,
3637 nested_vmcb->control.event_inj,
3638 nested_vmcb->control.nested_ctl);
3639
3640 trace_kvm_nested_intercepts(nested_vmcb->control.intercept_cr & 0xffff,
3641 nested_vmcb->control.intercept_cr >> 16,
3642 nested_vmcb->control.intercept_exceptions,
3643 nested_vmcb->control.intercept);
3644
3645 /* Clear internal status */
3646 kvm_clear_exception_queue(&svm->vcpu);
3647 kvm_clear_interrupt_queue(&svm->vcpu);
3648
3649 /*
3650 * Save the old vmcb, so we don't need to pick what we save, but can
3651 * restore everything when a VMEXIT occurs
3652 */
3653 hsave->save.es = vmcb->save.es;
3654 hsave->save.cs = vmcb->save.cs;
3655 hsave->save.ss = vmcb->save.ss;
3656 hsave->save.ds = vmcb->save.ds;
3657 hsave->save.gdtr = vmcb->save.gdtr;
3658 hsave->save.idtr = vmcb->save.idtr;
3659 hsave->save.efer = svm->vcpu.arch.efer;
3660 hsave->save.cr0 = kvm_read_cr0(&svm->vcpu);
3661 hsave->save.cr4 = svm->vcpu.arch.cr4;
3662 hsave->save.rflags = kvm_get_rflags(&svm->vcpu);
3663 hsave->save.rip = kvm_rip_read(&svm->vcpu);
3664 hsave->save.rsp = vmcb->save.rsp;
3665 hsave->save.rax = vmcb->save.rax;
3666 if (npt_enabled)
3667 hsave->save.cr3 = vmcb->save.cr3;
3668 else
3669 hsave->save.cr3 = kvm_read_cr3(&svm->vcpu);
3670
3671 copy_vmcb_control_area(hsave, vmcb);
3672
3673 enter_svm_guest_mode(svm, vmcb_gpa, nested_vmcb, &map);
3674
3675 if (!nested_svm_vmrun_msrpm(svm)) {
3676 svm->vmcb->control.exit_code = SVM_EXIT_ERR;
3677 svm->vmcb->control.exit_code_hi = 0;
3678 svm->vmcb->control.exit_info_1 = 0;
3679 svm->vmcb->control.exit_info_2 = 0;
3680
3681 nested_svm_vmexit(svm);
3682 }
3683
3684 return ret;
3685 }
3686
3687 static void nested_svm_vmloadsave(struct vmcb *from_vmcb, struct vmcb *to_vmcb)
3688 {
3689 to_vmcb->save.fs = from_vmcb->save.fs;
3690 to_vmcb->save.gs = from_vmcb->save.gs;
3691 to_vmcb->save.tr = from_vmcb->save.tr;
3692 to_vmcb->save.ldtr = from_vmcb->save.ldtr;
3693 to_vmcb->save.kernel_gs_base = from_vmcb->save.kernel_gs_base;
3694 to_vmcb->save.star = from_vmcb->save.star;
3695 to_vmcb->save.lstar = from_vmcb->save.lstar;
3696 to_vmcb->save.cstar = from_vmcb->save.cstar;
3697 to_vmcb->save.sfmask = from_vmcb->save.sfmask;
3698 to_vmcb->save.sysenter_cs = from_vmcb->save.sysenter_cs;
3699 to_vmcb->save.sysenter_esp = from_vmcb->save.sysenter_esp;
3700 to_vmcb->save.sysenter_eip = from_vmcb->save.sysenter_eip;
3701 }
3702
3703 static int vmload_interception(struct vcpu_svm *svm)
3704 {
3705 struct vmcb *nested_vmcb;
3706 struct kvm_host_map map;
3707 int ret;
3708
3709 if (nested_svm_check_permissions(svm))
3710 return 1;
3711
3712 ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
3713 if (ret) {
3714 if (ret == -EINVAL)
3715 kvm_inject_gp(&svm->vcpu, 0);
3716 return 1;
3717 }
3718
3719 nested_vmcb = map.hva;
3720
3721 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3722
3723 nested_svm_vmloadsave(nested_vmcb, svm->vmcb);
3724 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3725
3726 return ret;
3727 }
3728
3729 static int vmsave_interception(struct vcpu_svm *svm)
3730 {
3731 struct vmcb *nested_vmcb;
3732 struct kvm_host_map map;
3733 int ret;
3734
3735 if (nested_svm_check_permissions(svm))
3736 return 1;
3737
3738 ret = kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(svm->vmcb->save.rax), &map);
3739 if (ret) {
3740 if (ret == -EINVAL)
3741 kvm_inject_gp(&svm->vcpu, 0);
3742 return 1;
3743 }
3744
3745 nested_vmcb = map.hva;
3746
3747 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3748
3749 nested_svm_vmloadsave(svm->vmcb, nested_vmcb);
3750 kvm_vcpu_unmap(&svm->vcpu, &map, true);
3751
3752 return ret;
3753 }
3754
3755 static int vmrun_interception(struct vcpu_svm *svm)
3756 {
3757 if (nested_svm_check_permissions(svm))
3758 return 1;
3759
3760 return nested_svm_vmrun(svm);
3761 }
3762
3763 static int stgi_interception(struct vcpu_svm *svm)
3764 {
3765 int ret;
3766
3767 if (nested_svm_check_permissions(svm))
3768 return 1;
3769
3770 /*
3771 * If VGIF is enabled, the STGI intercept is only added to
3772 * detect the opening of the SMI/NMI window; remove it now.
3773 */
3774 if (vgif_enabled(svm))
3775 clr_intercept(svm, INTERCEPT_STGI);
3776
3777 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3778 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3779
3780 enable_gif(svm);
3781
3782 return ret;
3783 }
3784
3785 static int clgi_interception(struct vcpu_svm *svm)
3786 {
3787 int ret;
3788
3789 if (nested_svm_check_permissions(svm))
3790 return 1;
3791
3792 ret = kvm_skip_emulated_instruction(&svm->vcpu);
3793
3794 disable_gif(svm);
3795
3796 /* After a CLGI no interrupts should come */
3797 if (!kvm_vcpu_apicv_active(&svm->vcpu)) {
3798 svm_clear_vintr(svm);
3799 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
3800 mark_dirty(svm->vmcb, VMCB_INTR);
3801 }
3802
3803 return ret;
3804 }
3805
3806 static int invlpga_interception(struct vcpu_svm *svm)
3807 {
3808 struct kvm_vcpu *vcpu = &svm->vcpu;
3809
3810 trace_kvm_invlpga(svm->vmcb->save.rip, kvm_rcx_read(&svm->vcpu),
3811 kvm_rax_read(&svm->vcpu));
3812
3813 /* Let's treat INVLPGA the same as INVLPG (can be optimized!) */
3814 kvm_mmu_invlpg(vcpu, kvm_rax_read(&svm->vcpu));
3815
3816 return kvm_skip_emulated_instruction(&svm->vcpu);
3817 }
3818
3819 static int skinit_interception(struct vcpu_svm *svm)
3820 {
3821 trace_kvm_skinit(svm->vmcb->save.rip, kvm_rax_read(&svm->vcpu));
3822
3823 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3824 return 1;
3825 }
3826
3827 static int wbinvd_interception(struct vcpu_svm *svm)
3828 {
3829 return kvm_emulate_wbinvd(&svm->vcpu);
3830 }
3831
3832 static int xsetbv_interception(struct vcpu_svm *svm)
3833 {
3834 u64 new_bv = kvm_read_edx_eax(&svm->vcpu);
3835 u32 index = kvm_rcx_read(&svm->vcpu);
3836
3837 if (kvm_set_xcr(&svm->vcpu, index, new_bv) == 0) {
3838 return kvm_skip_emulated_instruction(&svm->vcpu);
3839 }
3840
3841 return 1;
3842 }
3843
3844 static int rdpru_interception(struct vcpu_svm *svm)
3845 {
3846 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
3847 return 1;
3848 }
3849
3850 static int task_switch_interception(struct vcpu_svm *svm)
3851 {
3852 u16 tss_selector;
3853 int reason;
3854 int int_type = svm->vmcb->control.exit_int_info &
3855 SVM_EXITINTINFO_TYPE_MASK;
3856 int int_vec = svm->vmcb->control.exit_int_info & SVM_EVTINJ_VEC_MASK;
3857 uint32_t type =
3858 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_TYPE_MASK;
3859 uint32_t idt_v =
3860 svm->vmcb->control.exit_int_info & SVM_EXITINTINFO_VALID;
3861 bool has_error_code = false;
3862 u32 error_code = 0;
3863
3864 tss_selector = (u16)svm->vmcb->control.exit_info_1;
3865
3866 if (svm->vmcb->control.exit_info_2 &
3867 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_IRET))
3868 reason = TASK_SWITCH_IRET;
3869 else if (svm->vmcb->control.exit_info_2 &
3870 (1ULL << SVM_EXITINFOSHIFT_TS_REASON_JMP))
3871 reason = TASK_SWITCH_JMP;
3872 else if (idt_v)
3873 reason = TASK_SWITCH_GATE;
3874 else
3875 reason = TASK_SWITCH_CALL;
3876
3877 if (reason == TASK_SWITCH_GATE) {
3878 switch (type) {
3879 case SVM_EXITINTINFO_TYPE_NMI:
3880 svm->vcpu.arch.nmi_injected = false;
3881 break;
3882 case SVM_EXITINTINFO_TYPE_EXEPT:
3883 if (svm->vmcb->control.exit_info_2 &
3884 (1ULL << SVM_EXITINFOSHIFT_TS_HAS_ERROR_CODE)) {
3885 has_error_code = true;
3886 error_code =
3887 (u32)svm->vmcb->control.exit_info_2;
3888 }
3889 kvm_clear_exception_queue(&svm->vcpu);
3890 break;
3891 case SVM_EXITINTINFO_TYPE_INTR:
3892 kvm_clear_interrupt_queue(&svm->vcpu);
3893 break;
3894 default:
3895 break;
3896 }
3897 }
3898
3899 if (reason != TASK_SWITCH_GATE ||
3900 int_type == SVM_EXITINTINFO_TYPE_SOFT ||
3901 (int_type == SVM_EXITINTINFO_TYPE_EXEPT &&
3902 (int_vec == OF_VECTOR || int_vec == BP_VECTOR))) {
3903 if (!skip_emulated_instruction(&svm->vcpu))
3904 return 0;
3905 }
3906
3907 if (int_type != SVM_EXITINTINFO_TYPE_SOFT)
3908 int_vec = -1;
3909
3910 return kvm_task_switch(&svm->vcpu, tss_selector, int_vec, reason,
3911 has_error_code, error_code);
3912 }
3913
3914 static int cpuid_interception(struct vcpu_svm *svm)
3915 {
3916 return kvm_emulate_cpuid(&svm->vcpu);
3917 }
3918
3919 static int iret_interception(struct vcpu_svm *svm)
3920 {
3921 ++svm->vcpu.stat.nmi_window_exits;
3922 clr_intercept(svm, INTERCEPT_IRET);
3923 svm->vcpu.arch.hflags |= HF_IRET_MASK;
3924 svm->nmi_iret_rip = kvm_rip_read(&svm->vcpu);
3925 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
3926 return 1;
3927 }
3928
3929 static int invlpg_interception(struct vcpu_svm *svm)
3930 {
3931 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3932 return kvm_emulate_instruction(&svm->vcpu, 0);
3933
3934 kvm_mmu_invlpg(&svm->vcpu, svm->vmcb->control.exit_info_1);
3935 return kvm_skip_emulated_instruction(&svm->vcpu);
3936 }
3937
3938 static int emulate_on_interception(struct vcpu_svm *svm)
3939 {
3940 return kvm_emulate_instruction(&svm->vcpu, 0);
3941 }
3942
3943 static int rsm_interception(struct vcpu_svm *svm)
3944 {
3945 return kvm_emulate_instruction_from_buffer(&svm->vcpu, rsm_ins_bytes, 2);
3946 }
3947
3948 static int rdpmc_interception(struct vcpu_svm *svm)
3949 {
3950 int err;
3951
3952 if (!nrips)
3953 return emulate_on_interception(svm);
3954
3955 err = kvm_rdpmc(&svm->vcpu);
3956 return kvm_complete_insn_gp(&svm->vcpu, err);
3957 }
3958
3959 static bool check_selective_cr0_intercepted(struct vcpu_svm *svm,
3960 unsigned long val)
3961 {
3962 unsigned long cr0 = svm->vcpu.arch.cr0;
3963 bool ret = false;
3964 u64 intercept;
3965
3966 intercept = svm->nested.intercept;
3967
3968 if (!is_guest_mode(&svm->vcpu) ||
3969 (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0))))
3970 return false;
3971
3972 cr0 &= ~SVM_CR0_SELECTIVE_MASK;
3973 val &= ~SVM_CR0_SELECTIVE_MASK;
3974
3975 if (cr0 ^ val) {
3976 svm->vmcb->control.exit_code = SVM_EXIT_CR0_SEL_WRITE;
3977 ret = (nested_svm_exit_handled(svm) == NESTED_EXIT_DONE);
3978 }
3979
3980 return ret;
3981 }
3982
3983 #define CR_VALID (1ULL << 63)
3984
3985 static int cr_interception(struct vcpu_svm *svm)
3986 {
3987 int reg, cr;
3988 unsigned long val;
3989 int err;
3990
3991 if (!static_cpu_has(X86_FEATURE_DECODEASSISTS))
3992 return emulate_on_interception(svm);
3993
3994 if (unlikely((svm->vmcb->control.exit_info_1 & CR_VALID) == 0))
3995 return emulate_on_interception(svm);
3996
3997 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
3998 if (svm->vmcb->control.exit_code == SVM_EXIT_CR0_SEL_WRITE)
3999 cr = SVM_EXIT_WRITE_CR0 - SVM_EXIT_READ_CR0;
4000 else
4001 cr = svm->vmcb->control.exit_code - SVM_EXIT_READ_CR0;
4002
4003 err = 0;
4004 if (cr >= 16) { /* mov to cr */
4005 cr -= 16;
4006 val = kvm_register_read(&svm->vcpu, reg);
4007 switch (cr) {
4008 case 0:
4009 if (!check_selective_cr0_intercepted(svm, val))
4010 err = kvm_set_cr0(&svm->vcpu, val);
4011 else
4012 return 1;
4013
4014 break;
4015 case 3:
4016 err = kvm_set_cr3(&svm->vcpu, val);
4017 break;
4018 case 4:
4019 err = kvm_set_cr4(&svm->vcpu, val);
4020 break;
4021 case 8:
4022 err = kvm_set_cr8(&svm->vcpu, val);
4023 break;
4024 default:
4025 WARN(1, "unhandled write to CR%d", cr);
4026 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4027 return 1;
4028 }
4029 } else { /* mov from cr */
4030 switch (cr) {
4031 case 0:
4032 val = kvm_read_cr0(&svm->vcpu);
4033 break;
4034 case 2:
4035 val = svm->vcpu.arch.cr2;
4036 break;
4037 case 3:
4038 val = kvm_read_cr3(&svm->vcpu);
4039 break;
4040 case 4:
4041 val = kvm_read_cr4(&svm->vcpu);
4042 break;
4043 case 8:
4044 val = kvm_get_cr8(&svm->vcpu);
4045 break;
4046 default:
4047 WARN(1, "unhandled read from CR%d", cr);
4048 kvm_queue_exception(&svm->vcpu, UD_VECTOR);
4049 return 1;
4050 }
4051 kvm_register_write(&svm->vcpu, reg, val);
4052 }
4053 return kvm_complete_insn_gp(&svm->vcpu, err);
4054 }
4055
4056 static int dr_interception(struct vcpu_svm *svm)
4057 {
4058 int reg, dr;
4059 unsigned long val;
4060
4061 if (svm->vcpu.guest_debug == 0) {
4062 /*
4063 * No more DR vmexits; force a reload of the debug registers
4064 * and reenter on this instruction. The next vmexit will
4065 * retrieve the full state of the debug registers.
4066 */
4067 clr_dr_intercepts(svm);
4068 svm->vcpu.arch.switch_db_regs |= KVM_DEBUGREG_WONT_EXIT;
4069 return 1;
4070 }
4071
4072 if (!boot_cpu_has(X86_FEATURE_DECODEASSISTS))
4073 return emulate_on_interception(svm);
4074
4075 reg = svm->vmcb->control.exit_info_1 & SVM_EXITINFO_REG_MASK;
4076 dr = svm->vmcb->control.exit_code - SVM_EXIT_READ_DR0;
4077
4078 if (dr >= 16) { /* mov to DRn */
4079 if (!kvm_require_dr(&svm->vcpu, dr - 16))
4080 return 1;
4081 val = kvm_register_read(&svm->vcpu, reg);
4082 kvm_set_dr(&svm->vcpu, dr - 16, val);
4083 } else {
4084 if (!kvm_require_dr(&svm->vcpu, dr))
4085 return 1;
4086 kvm_get_dr(&svm->vcpu, dr, &val);
4087 kvm_register_write(&svm->vcpu, reg, val);
4088 }
4089
4090 return kvm_skip_emulated_instruction(&svm->vcpu);
4091 }
4092
4093 static int cr8_write_interception(struct vcpu_svm *svm)
4094 {
4095 struct kvm_run *kvm_run = svm->vcpu.run;
4096 int r;
4097
4098 u8 cr8_prev = kvm_get_cr8(&svm->vcpu);
4099 /* instruction emulation calls kvm_set_cr8() */
4100 r = cr_interception(svm);
4101 if (lapic_in_kernel(&svm->vcpu))
4102 return r;
4103 if (cr8_prev <= kvm_get_cr8(&svm->vcpu))
4104 return r;
4105 kvm_run->exit_reason = KVM_EXIT_SET_TPR;
4106 return 0;
4107 }
4108
4109 static int svm_get_msr_feature(struct kvm_msr_entry *msr)
4110 {
4111 msr->data = 0;
4112
4113 switch (msr->index) {
4114 case MSR_F10H_DECFG:
4115 if (boot_cpu_has(X86_FEATURE_LFENCE_RDTSC))
4116 msr->data |= MSR_F10H_DECFG_LFENCE_SERIALIZE;
4117 break;
4118 default:
4119 return 1;
4120 }
4121
4122 return 0;
4123 }
4124
4125 static int svm_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
4126 {
4127 struct vcpu_svm *svm = to_svm(vcpu);
4128
4129 switch (msr_info->index) {
4130 case MSR_STAR:
4131 msr_info->data = svm->vmcb->save.star;
4132 break;
4133 #ifdef CONFIG_X86_64
4134 case MSR_LSTAR:
4135 msr_info->data = svm->vmcb->save.lstar;
4136 break;
4137 case MSR_CSTAR:
4138 msr_info->data = svm->vmcb->save.cstar;
4139 break;
4140 case MSR_KERNEL_GS_BASE:
4141 msr_info->data = svm->vmcb->save.kernel_gs_base;
4142 break;
4143 case MSR_SYSCALL_MASK:
4144 msr_info->data = svm->vmcb->save.sfmask;
4145 break;
4146 #endif
4147 case MSR_IA32_SYSENTER_CS:
4148 msr_info->data = svm->vmcb->save.sysenter_cs;
4149 break;
4150 case MSR_IA32_SYSENTER_EIP:
4151 msr_info->data = svm->sysenter_eip;
4152 break;
4153 case MSR_IA32_SYSENTER_ESP:
4154 msr_info->data = svm->sysenter_esp;
4155 break;
4156 case MSR_TSC_AUX:
4157 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4158 return 1;
4159 msr_info->data = svm->tsc_aux;
4160 break;
4161 /*
4162 * Nobody will change the following 5 values in the VMCB so we can
4163 * safely return them on rdmsr. They will always be 0 until LBRV is
4164 * implemented.
4165 */
4166 case MSR_IA32_DEBUGCTLMSR:
4167 msr_info->data = svm->vmcb->save.dbgctl;
4168 break;
4169 case MSR_IA32_LASTBRANCHFROMIP:
4170 msr_info->data = svm->vmcb->save.br_from;
4171 break;
4172 case MSR_IA32_LASTBRANCHTOIP:
4173 msr_info->data = svm->vmcb->save.br_to;
4174 break;
4175 case MSR_IA32_LASTINTFROMIP:
4176 msr_info->data = svm->vmcb->save.last_excp_from;
4177 break;
4178 case MSR_IA32_LASTINTTOIP:
4179 msr_info->data = svm->vmcb->save.last_excp_to;
4180 break;
4181 case MSR_VM_HSAVE_PA:
4182 msr_info->data = svm->nested.hsave_msr;
4183 break;
4184 case MSR_VM_CR:
4185 msr_info->data = svm->nested.vm_cr_msr;
4186 break;
4187 case MSR_IA32_SPEC_CTRL:
4188 if (!msr_info->host_initiated &&
4189 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4190 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4191 return 1;
4192
4193 msr_info->data = svm->spec_ctrl;
4194 break;
4195 case MSR_AMD64_VIRT_SPEC_CTRL:
4196 if (!msr_info->host_initiated &&
4197 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4198 return 1;
4199
4200 msr_info->data = svm->virt_spec_ctrl;
4201 break;
4202 case MSR_F15H_IC_CFG: {
4203
4204 int family, model;
4205
4206 family = guest_cpuid_family(vcpu);
4207 model = guest_cpuid_model(vcpu);
4208
4209 if (family < 0 || model < 0)
4210 return kvm_get_msr_common(vcpu, msr_info);
4211
4212 msr_info->data = 0;
4213
4214 if (family == 0x15 &&
4215 (model >= 0x2 && model < 0x20))
4216 msr_info->data = 0x1E;
4217 }
4218 break;
4219 case MSR_F10H_DECFG:
4220 msr_info->data = svm->msr_decfg;
4221 break;
4222 default:
4223 return kvm_get_msr_common(vcpu, msr_info);
4224 }
4225 return 0;
4226 }
4227
4228 static int rdmsr_interception(struct vcpu_svm *svm)
4229 {
4230 return kvm_emulate_rdmsr(&svm->vcpu);
4231 }
4232
4233 static int svm_set_vm_cr(struct kvm_vcpu *vcpu, u64 data)
4234 {
4235 struct vcpu_svm *svm = to_svm(vcpu);
4236 int svm_dis, chg_mask;
4237
4238 if (data & ~SVM_VM_CR_VALID_MASK)
4239 return 1;
4240
4241 chg_mask = SVM_VM_CR_VALID_MASK;
4242
4243 if (svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK)
4244 chg_mask &= ~(SVM_VM_CR_SVM_LOCK_MASK | SVM_VM_CR_SVM_DIS_MASK);
4245
4246 svm->nested.vm_cr_msr &= ~chg_mask;
4247 svm->nested.vm_cr_msr |= (data & chg_mask);
4248
4249 svm_dis = svm->nested.vm_cr_msr & SVM_VM_CR_SVM_DIS_MASK;
4250
4251 /* check for svm_disable while efer.svme is set */
4252 if (svm_dis && (vcpu->arch.efer & EFER_SVME))
4253 return 1;
4254
4255 return 0;
4256 }
4257
4258 static int svm_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr)
4259 {
4260 struct vcpu_svm *svm = to_svm(vcpu);
4261
4262 u32 ecx = msr->index;
4263 u64 data = msr->data;
4264 switch (ecx) {
4265 case MSR_IA32_CR_PAT:
4266 if (!kvm_mtrr_valid(vcpu, MSR_IA32_CR_PAT, data))
4267 return 1;
4268 vcpu->arch.pat = data;
4269 svm->vmcb->save.g_pat = data;
4270 mark_dirty(svm->vmcb, VMCB_NPT);
4271 break;
4272 case MSR_IA32_SPEC_CTRL:
4273 if (!msr->host_initiated &&
4274 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBRS) &&
4275 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_SSBD))
4276 return 1;
4277
4278 /* The STIBP bit doesn't fault even if it's not advertised */
4279 if (data & ~(SPEC_CTRL_IBRS | SPEC_CTRL_STIBP | SPEC_CTRL_SSBD))
4280 return 1;
4281
4282 svm->spec_ctrl = data;
4283
4284 if (!data)
4285 break;
4286
4287 /*
4288 * For non-nested:
4289 * When it's written (to non-zero) for the first time, pass
4290 * it through.
4291 *
4292 * For nested:
4293 * The handling of the MSR bitmap for L2 guests is done in
4294 * nested_svm_vmrun_msrpm.
4295 * We update the L1 MSR bit as well since it will end up
4296 * touching the MSR anyway now.
4297 */
4298 set_msr_interception(svm->msrpm, MSR_IA32_SPEC_CTRL, 1, 1);
4299 break;
4300 case MSR_IA32_PRED_CMD:
4301 if (!msr->host_initiated &&
4302 !guest_cpuid_has(vcpu, X86_FEATURE_AMD_IBPB))
4303 return 1;
4304
4305 if (data & ~PRED_CMD_IBPB)
4306 return 1;
4307
4308 if (!data)
4309 break;
4310
4311 wrmsrl(MSR_IA32_PRED_CMD, PRED_CMD_IBPB);
4312 if (is_guest_mode(vcpu))
4313 break;
4314 set_msr_interception(svm->msrpm, MSR_IA32_PRED_CMD, 0, 1);
4315 break;
4316 case MSR_AMD64_VIRT_SPEC_CTRL:
4317 if (!msr->host_initiated &&
4318 !guest_cpuid_has(vcpu, X86_FEATURE_VIRT_SSBD))
4319 return 1;
4320
4321 if (data & ~SPEC_CTRL_SSBD)
4322 return 1;
4323
4324 svm->virt_spec_ctrl = data;
4325 break;
4326 case MSR_STAR:
4327 svm->vmcb->save.star = data;
4328 break;
4329 #ifdef CONFIG_X86_64
4330 case MSR_LSTAR:
4331 svm->vmcb->save.lstar = data;
4332 break;
4333 case MSR_CSTAR:
4334 svm->vmcb->save.cstar = data;
4335 break;
4336 case MSR_KERNEL_GS_BASE:
4337 svm->vmcb->save.kernel_gs_base = data;
4338 break;
4339 case MSR_SYSCALL_MASK:
4340 svm->vmcb->save.sfmask = data;
4341 break;
4342 #endif
4343 case MSR_IA32_SYSENTER_CS:
4344 svm->vmcb->save.sysenter_cs = data;
4345 break;
4346 case MSR_IA32_SYSENTER_EIP:
4347 svm->sysenter_eip = data;
4348 svm->vmcb->save.sysenter_eip = data;
4349 break;
4350 case MSR_IA32_SYSENTER_ESP:
4351 svm->sysenter_esp = data;
4352 svm->vmcb->save.sysenter_esp = data;
4353 break;
4354 case MSR_TSC_AUX:
4355 if (!boot_cpu_has(X86_FEATURE_RDTSCP))
4356 return 1;
4357
4358 /*
4359 * This is rare, so we update the MSR here instead of using
4360 * direct_access_msrs. Doing that would require a rdmsr in
4361 * svm_vcpu_put.
4362 */
4363 svm->tsc_aux = data;
4364 wrmsrl(MSR_TSC_AUX, svm->tsc_aux);
4365 break;
4366 case MSR_IA32_DEBUGCTLMSR:
4367 if (!boot_cpu_has(X86_FEATURE_LBRV)) {
4368 vcpu_unimpl(vcpu, "%s: MSR_IA32_DEBUGCTL 0x%llx, nop\n",
4369 __func__, data);
4370 break;
4371 }
4372 if (data & DEBUGCTL_RESERVED_BITS)
4373 return 1;
4374
4375 svm->vmcb->save.dbgctl = data;
4376 mark_dirty(svm->vmcb, VMCB_LBR);
4377 if (data & (1ULL<<0))
4378 svm_enable_lbrv(svm);
4379 else
4380 svm_disable_lbrv(svm);
4381 break;
4382 case MSR_VM_HSAVE_PA:
4383 svm->nested.hsave_msr = data;
4384 break;
4385 case MSR_VM_CR:
4386 return svm_set_vm_cr(vcpu, data);
4387 case MSR_VM_IGNNE:
4388 vcpu_unimpl(vcpu, "unimplemented wrmsr: 0x%x data 0x%llx\n", ecx, data);
4389 break;
4390 case MSR_F10H_DECFG: {
4391 struct kvm_msr_entry msr_entry;
4392
4393 msr_entry.index = msr->index;
4394 if (svm_get_msr_feature(&msr_entry))
4395 return 1;
4396
4397 /* Check the supported bits */
4398 if (data & ~msr_entry.data)
4399 return 1;
4400
4401 /* Don't allow the guest to change a bit, #GP */
4402 if (!msr->host_initiated && (data ^ msr_entry.data))
4403 return 1;
4404
4405 svm->msr_decfg = data;
4406 break;
4407 }
4408 case MSR_IA32_APICBASE:
4409 if (kvm_vcpu_apicv_active(vcpu))
4410 avic_update_vapic_bar(to_svm(vcpu), data);
4411 /* Fall through */
4412 default:
4413 return kvm_set_msr_common(vcpu, msr);
4414 }
4415 return 0;
4416 }
4417
4418 static int wrmsr_interception(struct vcpu_svm *svm)
4419 {
4420 return kvm_emulate_wrmsr(&svm->vcpu);
4421 }
4422
4423 static int msr_interception(struct vcpu_svm *svm)
4424 {
4425 if (svm->vmcb->control.exit_info_1)
4426 return wrmsr_interception(svm);
4427 else
4428 return rdmsr_interception(svm);
4429 }
4430
4431 static int interrupt_window_interception(struct vcpu_svm *svm)
4432 {
4433 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
4434 svm_clear_vintr(svm);
4435 svm->vmcb->control.int_ctl &= ~V_IRQ_MASK;
4436 mark_dirty(svm->vmcb, VMCB_INTR);
4437 ++svm->vcpu.stat.irq_window_exits;
4438 return 1;
4439 }
4440
4441 static int pause_interception(struct vcpu_svm *svm)
4442 {
4443 struct kvm_vcpu *vcpu = &svm->vcpu;
4444 bool in_kernel = (svm_get_cpl(vcpu) == 0);
4445
4446 if (pause_filter_thresh)
4447 grow_ple_window(vcpu);
4448
4449 kvm_vcpu_on_spin(vcpu, in_kernel);
4450 return 1;
4451 }
4452
4453 static int nop_interception(struct vcpu_svm *svm)
4454 {
4455 return kvm_skip_emulated_instruction(&(svm->vcpu));
4456 }
4457
4458 static int monitor_interception(struct vcpu_svm *svm)
4459 {
4460 printk_once(KERN_WARNING "kvm: MONITOR instruction emulated as NOP!\n");
4461 return nop_interception(svm);
4462 }
4463
4464 static int mwait_interception(struct vcpu_svm *svm)
4465 {
4466 printk_once(KERN_WARNING "kvm: MWAIT instruction emulated as NOP!\n");
4467 return nop_interception(svm);
4468 }
4469
4470 enum avic_ipi_failure_cause {
4471 AVIC_IPI_FAILURE_INVALID_INT_TYPE,
4472 AVIC_IPI_FAILURE_TARGET_NOT_RUNNING,
4473 AVIC_IPI_FAILURE_INVALID_TARGET,
4474 AVIC_IPI_FAILURE_INVALID_BACKING_PAGE,
4475 };
4476
4477 static int avic_incomplete_ipi_interception(struct vcpu_svm *svm)
4478 {
4479 u32 icrh = svm->vmcb->control.exit_info_1 >> 32;
4480 u32 icrl = svm->vmcb->control.exit_info_1;
4481 u32 id = svm->vmcb->control.exit_info_2 >> 32;
4482 u32 index = svm->vmcb->control.exit_info_2 & 0xFF;
4483 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4484
4485 trace_kvm_avic_incomplete_ipi(svm->vcpu.vcpu_id, icrh, icrl, id, index);
4486
4487 switch (id) {
4488 case AVIC_IPI_FAILURE_INVALID_INT_TYPE:
4489 /*
4490 * AVIC hardware handles the generation of
4491 * IPIs when the specified Message Type is Fixed
4492 * (also known as fixed delivery mode) and
4493 * the Trigger Mode is edge-triggered. The hardware
4494 * also supports self and broadcast delivery modes
4495 * specified via the Destination Shorthand(DSH)
4496 * field of the ICRL. Logical and physical APIC ID
4497 * formats are supported. All other IPI types cause
4498 * a #VMEXIT, which needs to emulated.
4499 */
4500 kvm_lapic_reg_write(apic, APIC_ICR2, icrh);
4501 kvm_lapic_reg_write(apic, APIC_ICR, icrl);
4502 break;
4503 case AVIC_IPI_FAILURE_TARGET_NOT_RUNNING: {
4504 int i;
4505 struct kvm_vcpu *vcpu;
4506 struct kvm *kvm = svm->vcpu.kvm;
4507 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4508
4509 /*
4510 * At this point, we expect that the AVIC HW has already
4511 * set the appropriate IRR bits on the valid target
4512 * vcpus. So, we just need to kick the appropriate vcpu.
4513 */
4514 kvm_for_each_vcpu(i, vcpu, kvm) {
4515 bool m = kvm_apic_match_dest(vcpu, apic,
4516 icrl & KVM_APIC_SHORT_MASK,
4517 GET_APIC_DEST_FIELD(icrh),
4518 icrl & KVM_APIC_DEST_MASK);
4519
4520 if (m && !avic_vcpu_is_running(vcpu))
4521 kvm_vcpu_wake_up(vcpu);
4522 }
4523 break;
4524 }
4525 case AVIC_IPI_FAILURE_INVALID_TARGET:
4526 WARN_ONCE(1, "Invalid IPI target: index=%u, vcpu=%d, icr=%#0x:%#0x\n",
4527 index, svm->vcpu.vcpu_id, icrh, icrl);
4528 break;
4529 case AVIC_IPI_FAILURE_INVALID_BACKING_PAGE:
4530 WARN_ONCE(1, "Invalid backing page\n");
4531 break;
4532 default:
4533 pr_err("Unknown IPI interception\n");
4534 }
4535
4536 return 1;
4537 }
4538
4539 static u32 *avic_get_logical_id_entry(struct kvm_vcpu *vcpu, u32 ldr, bool flat)
4540 {
4541 struct kvm_svm *kvm_svm = to_kvm_svm(vcpu->kvm);
4542 int index;
4543 u32 *logical_apic_id_table;
4544 int dlid = GET_APIC_LOGICAL_ID(ldr);
4545
4546 if (!dlid)
4547 return NULL;
4548
4549 if (flat) { /* flat */
4550 index = ffs(dlid) - 1;
4551 if (index > 7)
4552 return NULL;
4553 } else { /* cluster */
4554 int cluster = (dlid & 0xf0) >> 4;
4555 int apic = ffs(dlid & 0x0f) - 1;
4556
4557 if ((apic < 0) || (apic > 7) ||
4558 (cluster >= 0xf))
4559 return NULL;
4560 index = (cluster << 2) + apic;
4561 }
4562
4563 logical_apic_id_table = (u32 *) page_address(kvm_svm->avic_logical_id_table_page);
4564
4565 return &logical_apic_id_table[index];
4566 }
4567
4568 static int avic_ldr_write(struct kvm_vcpu *vcpu, u8 g_physical_id, u32 ldr)
4569 {
4570 bool flat;
4571 u32 *entry, new_entry;
4572
4573 flat = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR) == APIC_DFR_FLAT;
4574 entry = avic_get_logical_id_entry(vcpu, ldr, flat);
4575 if (!entry)
4576 return -EINVAL;
4577
4578 new_entry = READ_ONCE(*entry);
4579 new_entry &= ~AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK;
4580 new_entry |= (g_physical_id & AVIC_LOGICAL_ID_ENTRY_GUEST_PHYSICAL_ID_MASK);
4581 new_entry |= AVIC_LOGICAL_ID_ENTRY_VALID_MASK;
4582 WRITE_ONCE(*entry, new_entry);
4583
4584 return 0;
4585 }
4586
4587 static void avic_invalidate_logical_id_entry(struct kvm_vcpu *vcpu)
4588 {
4589 struct vcpu_svm *svm = to_svm(vcpu);
4590 bool flat = svm->dfr_reg == APIC_DFR_FLAT;
4591 u32 *entry = avic_get_logical_id_entry(vcpu, svm->ldr_reg, flat);
4592
4593 if (entry)
4594 clear_bit(AVIC_LOGICAL_ID_ENTRY_VALID_BIT, (unsigned long *)entry);
4595 }
4596
4597 static int avic_handle_ldr_update(struct kvm_vcpu *vcpu)
4598 {
4599 int ret = 0;
4600 struct vcpu_svm *svm = to_svm(vcpu);
4601 u32 ldr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_LDR);
4602
4603 if (ldr == svm->ldr_reg)
4604 return 0;
4605
4606 avic_invalidate_logical_id_entry(vcpu);
4607
4608 if (ldr)
4609 ret = avic_ldr_write(vcpu, vcpu->vcpu_id, ldr);
4610
4611 if (!ret)
4612 svm->ldr_reg = ldr;
4613
4614 return ret;
4615 }
4616
4617 static int avic_handle_apic_id_update(struct kvm_vcpu *vcpu)
4618 {
4619 u64 *old, *new;
4620 struct vcpu_svm *svm = to_svm(vcpu);
4621 u32 apic_id_reg = kvm_lapic_get_reg(vcpu->arch.apic, APIC_ID);
4622 u32 id = (apic_id_reg >> 24) & 0xff;
4623
4624 if (vcpu->vcpu_id == id)
4625 return 0;
4626
4627 old = avic_get_physical_id_entry(vcpu, vcpu->vcpu_id);
4628 new = avic_get_physical_id_entry(vcpu, id);
4629 if (!new || !old)
4630 return 1;
4631
4632 /* We need to move physical_id_entry to new offset */
4633 *new = *old;
4634 *old = 0ULL;
4635 to_svm(vcpu)->avic_physical_id_cache = new;
4636
4637 /*
4638 * Also update the guest physical APIC ID in the logical
4639 * APIC ID table entry if already setup the LDR.
4640 */
4641 if (svm->ldr_reg)
4642 avic_handle_ldr_update(vcpu);
4643
4644 return 0;
4645 }
4646
4647 static void avic_handle_dfr_update(struct kvm_vcpu *vcpu)
4648 {
4649 struct vcpu_svm *svm = to_svm(vcpu);
4650 u32 dfr = kvm_lapic_get_reg(vcpu->arch.apic, APIC_DFR);
4651
4652 if (svm->dfr_reg == dfr)
4653 return;
4654
4655 avic_invalidate_logical_id_entry(vcpu);
4656 svm->dfr_reg = dfr;
4657 }
4658
4659 static int avic_unaccel_trap_write(struct vcpu_svm *svm)
4660 {
4661 struct kvm_lapic *apic = svm->vcpu.arch.apic;
4662 u32 offset = svm->vmcb->control.exit_info_1 &
4663 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4664
4665 switch (offset) {
4666 case APIC_ID:
4667 if (avic_handle_apic_id_update(&svm->vcpu))
4668 return 0;
4669 break;
4670 case APIC_LDR:
4671 if (avic_handle_ldr_update(&svm->vcpu))
4672 return 0;
4673 break;
4674 case APIC_DFR:
4675 avic_handle_dfr_update(&svm->vcpu);
4676 break;
4677 default:
4678 break;
4679 }
4680
4681 kvm_lapic_reg_write(apic, offset, kvm_lapic_get_reg(apic, offset));
4682
4683 return 1;
4684 }
4685
4686 static bool is_avic_unaccelerated_access_trap(u32 offset)
4687 {
4688 bool ret = false;
4689
4690 switch (offset) {
4691 case APIC_ID:
4692 case APIC_EOI:
4693 case APIC_RRR:
4694 case APIC_LDR:
4695 case APIC_DFR:
4696 case APIC_SPIV:
4697 case APIC_ESR:
4698 case APIC_ICR:
4699 case APIC_LVTT:
4700 case APIC_LVTTHMR:
4701 case APIC_LVTPC:
4702 case APIC_LVT0:
4703 case APIC_LVT1:
4704 case APIC_LVTERR:
4705 case APIC_TMICT:
4706 case APIC_TDCR:
4707 ret = true;
4708 break;
4709 default:
4710 break;
4711 }
4712 return ret;
4713 }
4714
4715 static int avic_unaccelerated_access_interception(struct vcpu_svm *svm)
4716 {
4717 int ret = 0;
4718 u32 offset = svm->vmcb->control.exit_info_1 &
4719 AVIC_UNACCEL_ACCESS_OFFSET_MASK;
4720 u32 vector = svm->vmcb->control.exit_info_2 &
4721 AVIC_UNACCEL_ACCESS_VECTOR_MASK;
4722 bool write = (svm->vmcb->control.exit_info_1 >> 32) &
4723 AVIC_UNACCEL_ACCESS_WRITE_MASK;
4724 bool trap = is_avic_unaccelerated_access_trap(offset);
4725
4726 trace_kvm_avic_unaccelerated_access(svm->vcpu.vcpu_id, offset,
4727 trap, write, vector);
4728 if (trap) {
4729 /* Handling Trap */
4730 WARN_ONCE(!write, "svm: Handling trap read.\n");
4731 ret = avic_unaccel_trap_write(svm);
4732 } else {
4733 /* Handling Fault */
4734 ret = kvm_emulate_instruction(&svm->vcpu, 0);
4735 }
4736
4737 return ret;
4738 }
4739
4740 static int (*const svm_exit_handlers[])(struct vcpu_svm *svm) = {
4741 [SVM_EXIT_READ_CR0] = cr_interception,
4742 [SVM_EXIT_READ_CR3] = cr_interception,
4743 [SVM_EXIT_READ_CR4] = cr_interception,
4744 [SVM_EXIT_READ_CR8] = cr_interception,
4745 [SVM_EXIT_CR0_SEL_WRITE] = cr_interception,
4746 [SVM_EXIT_WRITE_CR0] = cr_interception,
4747 [SVM_EXIT_WRITE_CR3] = cr_interception,
4748 [SVM_EXIT_WRITE_CR4] = cr_interception,
4749 [SVM_EXIT_WRITE_CR8] = cr8_write_interception,
4750 [SVM_EXIT_READ_DR0] = dr_interception,
4751 [SVM_EXIT_READ_DR1] = dr_interception,
4752 [SVM_EXIT_READ_DR2] = dr_interception,
4753 [SVM_EXIT_READ_DR3] = dr_interception,
4754 [SVM_EXIT_READ_DR4] = dr_interception,
4755 [SVM_EXIT_READ_DR5] = dr_interception,
4756 [SVM_EXIT_READ_DR6] = dr_interception,
4757 [SVM_EXIT_READ_DR7] = dr_interception,
4758 [SVM_EXIT_WRITE_DR0] = dr_interception,
4759 [SVM_EXIT_WRITE_DR1] = dr_interception,
4760 [SVM_EXIT_WRITE_DR2] = dr_interception,
4761 [SVM_EXIT_WRITE_DR3] = dr_interception,
4762 [SVM_EXIT_WRITE_DR4] = dr_interception,
4763 [SVM_EXIT_WRITE_DR5] = dr_interception,
4764 [SVM_EXIT_WRITE_DR6] = dr_interception,
4765 [SVM_EXIT_WRITE_DR7] = dr_interception,
4766 [SVM_EXIT_EXCP_BASE + DB_VECTOR] = db_interception,
4767 [SVM_EXIT_EXCP_BASE + BP_VECTOR] = bp_interception,
4768 [SVM_EXIT_EXCP_BASE + UD_VECTOR] = ud_interception,
4769 [SVM_EXIT_EXCP_BASE + PF_VECTOR] = pf_interception,
4770 [SVM_EXIT_EXCP_BASE + MC_VECTOR] = mc_interception,
4771 [SVM_EXIT_EXCP_BASE + AC_VECTOR] = ac_interception,
4772 [SVM_EXIT_EXCP_BASE + GP_VECTOR] = gp_interception,
4773 [SVM_EXIT_INTR] = intr_interception,
4774 [SVM_EXIT_NMI] = nmi_interception,
4775 [SVM_EXIT_SMI] = nop_on_interception,
4776 [SVM_EXIT_INIT] = nop_on_interception,
4777 [SVM_EXIT_VINTR] = interrupt_window_interception,
4778 [SVM_EXIT_RDPMC] = rdpmc_interception,
4779 [SVM_EXIT_CPUID] = cpuid_interception,
4780 [SVM_EXIT_IRET] = iret_interception,
4781 [SVM_EXIT_INVD] = emulate_on_interception,
4782 [SVM_EXIT_PAUSE] = pause_interception,
4783 [SVM_EXIT_HLT] = halt_interception,
4784 [SVM_EXIT_INVLPG] = invlpg_interception,
4785 [SVM_EXIT_INVLPGA] = invlpga_interception,
4786 [SVM_EXIT_IOIO] = io_interception,
4787 [SVM_EXIT_MSR] = msr_interception,
4788 [SVM_EXIT_TASK_SWITCH] = task_switch_interception,
4789 [SVM_EXIT_SHUTDOWN] = shutdown_interception,
4790 [SVM_EXIT_VMRUN] = vmrun_interception,
4791 [SVM_EXIT_VMMCALL] = vmmcall_interception,
4792 [SVM_EXIT_VMLOAD] = vmload_interception,
4793 [SVM_EXIT_VMSAVE] = vmsave_interception,
4794 [SVM_EXIT_STGI] = stgi_interception,
4795 [SVM_EXIT_CLGI] = clgi_interception,
4796 [SVM_EXIT_SKINIT] = skinit_interception,
4797 [SVM_EXIT_WBINVD] = wbinvd_interception,
4798 [SVM_EXIT_MONITOR] = monitor_interception,
4799 [SVM_EXIT_MWAIT] = mwait_interception,
4800 [SVM_EXIT_XSETBV] = xsetbv_interception,
4801 [SVM_EXIT_RDPRU] = rdpru_interception,
4802 [SVM_EXIT_NPF] = npf_interception,
4803 [SVM_EXIT_RSM] = rsm_interception,
4804 [SVM_EXIT_AVIC_INCOMPLETE_IPI] = avic_incomplete_ipi_interception,
4805 [SVM_EXIT_AVIC_UNACCELERATED_ACCESS] = avic_unaccelerated_access_interception,
4806 };
4807
4808 static void dump_vmcb(struct kvm_vcpu *vcpu)
4809 {
4810 struct vcpu_svm *svm = to_svm(vcpu);
4811 struct vmcb_control_area *control = &svm->vmcb->control;
4812 struct vmcb_save_area *save = &svm->vmcb->save;
4813
4814 if (!dump_invalid_vmcb) {
4815 pr_warn_ratelimited("set kvm_amd.dump_invalid_vmcb=1 to dump internal KVM state.\n");
4816 return;
4817 }
4818
4819 pr_err("VMCB Control Area:\n");
4820 pr_err("%-20s%04x\n", "cr_read:", control->intercept_cr & 0xffff);
4821 pr_err("%-20s%04x\n", "cr_write:", control->intercept_cr >> 16);
4822 pr_err("%-20s%04x\n", "dr_read:", control->intercept_dr & 0xffff);
4823 pr_err("%-20s%04x\n", "dr_write:", control->intercept_dr >> 16);
4824 pr_err("%-20s%08x\n", "exceptions:", control->intercept_exceptions);
4825 pr_err("%-20s%016llx\n", "intercepts:", control->intercept);
4826 pr_err("%-20s%d\n", "pause filter count:", control->pause_filter_count);
4827 pr_err("%-20s%d\n", "pause filter threshold:",
4828 control->pause_filter_thresh);
4829 pr_err("%-20s%016llx\n", "iopm_base_pa:", control->iopm_base_pa);
4830 pr_err("%-20s%016llx\n", "msrpm_base_pa:", control->msrpm_base_pa);
4831 pr_err("%-20s%016llx\n", "tsc_offset:", control->tsc_offset);
4832 pr_err("%-20s%d\n", "asid:", control->asid);
4833 pr_err("%-20s%d\n", "tlb_ctl:", control->tlb_ctl);
4834 pr_err("%-20s%08x\n", "int_ctl:", control->int_ctl);
4835 pr_err("%-20s%08x\n", "int_vector:", control->int_vector);
4836 pr_err("%-20s%08x\n", "int_state:", control->int_state);
4837 pr_err("%-20s%08x\n", "exit_code:", control->exit_code);
4838 pr_err("%-20s%016llx\n", "exit_info1:", control->exit_info_1);
4839 pr_err("%-20s%016llx\n", "exit_info2:", control->exit_info_2);
4840 pr_err("%-20s%08x\n", "exit_int_info:", control->exit_int_info);
4841 pr_err("%-20s%08x\n", "exit_int_info_err:", control->exit_int_info_err);
4842 pr_err("%-20s%lld\n", "nested_ctl:", control->nested_ctl);
4843 pr_err("%-20s%016llx\n", "nested_cr3:", control->nested_cr3);
4844 pr_err("%-20s%016llx\n", "avic_vapic_bar:", control->avic_vapic_bar);
4845 pr_err("%-20s%08x\n", "event_inj:", control->event_inj);
4846 pr_err("%-20s%08x\n", "event_inj_err:", control->event_inj_err);
4847 pr_err("%-20s%lld\n", "virt_ext:", control->virt_ext);
4848 pr_err("%-20s%016llx\n", "next_rip:", control->next_rip);
4849 pr_err("%-20s%016llx\n", "avic_backing_page:", control->avic_backing_page);
4850 pr_err("%-20s%016llx\n", "avic_logical_id:", control->avic_logical_id);
4851 pr_err("%-20s%016llx\n", "avic_physical_id:", control->avic_physical_id);
4852 pr_err("VMCB State Save Area:\n");
4853 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4854 "es:",
4855 save->es.selector, save->es.attrib,
4856 save->es.limit, save->es.base);
4857 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4858 "cs:",
4859 save->cs.selector, save->cs.attrib,
4860 save->cs.limit, save->cs.base);
4861 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4862 "ss:",
4863 save->ss.selector, save->ss.attrib,
4864 save->ss.limit, save->ss.base);
4865 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4866 "ds:",
4867 save->ds.selector, save->ds.attrib,
4868 save->ds.limit, save->ds.base);
4869 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4870 "fs:",
4871 save->fs.selector, save->fs.attrib,
4872 save->fs.limit, save->fs.base);
4873 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4874 "gs:",
4875 save->gs.selector, save->gs.attrib,
4876 save->gs.limit, save->gs.base);
4877 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4878 "gdtr:",
4879 save->gdtr.selector, save->gdtr.attrib,
4880 save->gdtr.limit, save->gdtr.base);
4881 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4882 "ldtr:",
4883 save->ldtr.selector, save->ldtr.attrib,
4884 save->ldtr.limit, save->ldtr.base);
4885 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4886 "idtr:",
4887 save->idtr.selector, save->idtr.attrib,
4888 save->idtr.limit, save->idtr.base);
4889 pr_err("%-5s s: %04x a: %04x l: %08x b: %016llx\n",
4890 "tr:",
4891 save->tr.selector, save->tr.attrib,
4892 save->tr.limit, save->tr.base);
4893 pr_err("cpl: %d efer: %016llx\n",
4894 save->cpl, save->efer);
4895 pr_err("%-15s %016llx %-13s %016llx\n",
4896 "cr0:", save->cr0, "cr2:", save->cr2);
4897 pr_err("%-15s %016llx %-13s %016llx\n",
4898 "cr3:", save->cr3, "cr4:", save->cr4);
4899 pr_err("%-15s %016llx %-13s %016llx\n",
4900 "dr6:", save->dr6, "dr7:", save->dr7);
4901 pr_err("%-15s %016llx %-13s %016llx\n",
4902 "rip:", save->rip, "rflags:", save->rflags);
4903 pr_err("%-15s %016llx %-13s %016llx\n",
4904 "rsp:", save->rsp, "rax:", save->rax);
4905 pr_err("%-15s %016llx %-13s %016llx\n",
4906 "star:", save->star, "lstar:", save->lstar);
4907 pr_err("%-15s %016llx %-13s %016llx\n",
4908 "cstar:", save->cstar, "sfmask:", save->sfmask);
4909 pr_err("%-15s %016llx %-13s %016llx\n",
4910 "kernel_gs_base:", save->kernel_gs_base,
4911 "sysenter_cs:", save->sysenter_cs);
4912 pr_err("%-15s %016llx %-13s %016llx\n",
4913 "sysenter_esp:", save->sysenter_esp,
4914 "sysenter_eip:", save->sysenter_eip);
4915 pr_err("%-15s %016llx %-13s %016llx\n",
4916 "gpat:", save->g_pat, "dbgctl:", save->dbgctl);
4917 pr_err("%-15s %016llx %-13s %016llx\n",
4918 "br_from:", save->br_from, "br_to:", save->br_to);
4919 pr_err("%-15s %016llx %-13s %016llx\n",
4920 "excp_from:", save->last_excp_from,
4921 "excp_to:", save->last_excp_to);
4922 }
4923
4924 static void svm_get_exit_info(struct kvm_vcpu *vcpu, u64 *info1, u64 *info2)
4925 {
4926 struct vmcb_control_area *control = &to_svm(vcpu)->vmcb->control;
4927
4928 *info1 = control->exit_info_1;
4929 *info2 = control->exit_info_2;
4930 }
4931
4932 static int handle_exit(struct kvm_vcpu *vcpu)
4933 {
4934 struct vcpu_svm *svm = to_svm(vcpu);
4935 struct kvm_run *kvm_run = vcpu->run;
4936 u32 exit_code = svm->vmcb->control.exit_code;
4937
4938 trace_kvm_exit(exit_code, vcpu, KVM_ISA_SVM);
4939
4940 if (!is_cr_intercept(svm, INTERCEPT_CR0_WRITE))
4941 vcpu->arch.cr0 = svm->vmcb->save.cr0;
4942 if (npt_enabled)
4943 vcpu->arch.cr3 = svm->vmcb->save.cr3;
4944
4945 if (unlikely(svm->nested.exit_required)) {
4946 nested_svm_vmexit(svm);
4947 svm->nested.exit_required = false;
4948
4949 return 1;
4950 }
4951
4952 if (is_guest_mode(vcpu)) {
4953 int vmexit;
4954
4955 trace_kvm_nested_vmexit(svm->vmcb->save.rip, exit_code,
4956 svm->vmcb->control.exit_info_1,
4957 svm->vmcb->control.exit_info_2,
4958 svm->vmcb->control.exit_int_info,
4959 svm->vmcb->control.exit_int_info_err,
4960 KVM_ISA_SVM);
4961
4962 vmexit = nested_svm_exit_special(svm);
4963
4964 if (vmexit == NESTED_EXIT_CONTINUE)
4965 vmexit = nested_svm_exit_handled(svm);
4966
4967 if (vmexit == NESTED_EXIT_DONE)
4968 return 1;
4969 }
4970
4971 svm_complete_interrupts(svm);
4972
4973 if (svm->vmcb->control.exit_code == SVM_EXIT_ERR) {
4974 kvm_run->exit_reason = KVM_EXIT_FAIL_ENTRY;
4975 kvm_run->fail_entry.hardware_entry_failure_reason
4976 = svm->vmcb->control.exit_code;
4977 dump_vmcb(vcpu);
4978 return 0;
4979 }
4980
4981 if (is_external_interrupt(svm->vmcb->control.exit_int_info) &&
4982 exit_code != SVM_EXIT_EXCP_BASE + PF_VECTOR &&
4983 exit_code != SVM_EXIT_NPF && exit_code != SVM_EXIT_TASK_SWITCH &&
4984 exit_code != SVM_EXIT_INTR && exit_code != SVM_EXIT_NMI)
4985 printk(KERN_ERR "%s: unexpected exit_int_info 0x%x "
4986 "exit_code 0x%x\n",
4987 __func__, svm->vmcb->control.exit_int_info,
4988 exit_code);
4989
4990 if (exit_code >= ARRAY_SIZE(svm_exit_handlers)
4991 || !svm_exit_handlers[exit_code]) {
4992 vcpu_unimpl(vcpu, "svm: unexpected exit reason 0x%x\n", exit_code);
4993 dump_vmcb(vcpu);
4994 vcpu->run->exit_reason = KVM_EXIT_INTERNAL_ERROR;
4995 vcpu->run->internal.suberror =
4996 KVM_INTERNAL_ERROR_UNEXPECTED_EXIT_REASON;
4997 vcpu->run->internal.ndata = 1;
4998 vcpu->run->internal.data[0] = exit_code;
4999 return 0;
5000 }
5001
5002 return svm_exit_handlers[exit_code](svm);
5003 }
5004
5005 static void reload_tss(struct kvm_vcpu *vcpu)
5006 {
5007 int cpu = raw_smp_processor_id();
5008
5009 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5010 sd->tss_desc->type = 9; /* available 32/64-bit TSS */
5011 load_TR_desc();
5012 }
5013
5014 static void pre_sev_run(struct vcpu_svm *svm, int cpu)
5015 {
5016 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5017 int asid = sev_get_asid(svm->vcpu.kvm);
5018
5019 /* Assign the asid allocated with this SEV guest */
5020 svm->vmcb->control.asid = asid;
5021
5022 /*
5023 * Flush guest TLB:
5024 *
5025 * 1) when different VMCB for the same ASID is to be run on the same host CPU.
5026 * 2) or this VMCB was executed on different host CPU in previous VMRUNs.
5027 */
5028 if (sd->sev_vmcbs[asid] == svm->vmcb &&
5029 svm->last_cpu == cpu)
5030 return;
5031
5032 svm->last_cpu = cpu;
5033 sd->sev_vmcbs[asid] = svm->vmcb;
5034 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5035 mark_dirty(svm->vmcb, VMCB_ASID);
5036 }
5037
5038 static void pre_svm_run(struct vcpu_svm *svm)
5039 {
5040 int cpu = raw_smp_processor_id();
5041
5042 struct svm_cpu_data *sd = per_cpu(svm_data, cpu);
5043
5044 if (sev_guest(svm->vcpu.kvm))
5045 return pre_sev_run(svm, cpu);
5046
5047 /* FIXME: handle wraparound of asid_generation */
5048 if (svm->asid_generation != sd->asid_generation)
5049 new_asid(svm, sd);
5050 }
5051
5052 static void svm_inject_nmi(struct kvm_vcpu *vcpu)
5053 {
5054 struct vcpu_svm *svm = to_svm(vcpu);
5055
5056 svm->vmcb->control.event_inj = SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_NMI;
5057 vcpu->arch.hflags |= HF_NMI_MASK;
5058 set_intercept(svm, INTERCEPT_IRET);
5059 ++vcpu->stat.nmi_injections;
5060 }
5061
5062 static inline void svm_inject_irq(struct vcpu_svm *svm, int irq)
5063 {
5064 struct vmcb_control_area *control;
5065
5066 /* The following fields are ignored when AVIC is enabled */
5067 control = &svm->vmcb->control;
5068 control->int_vector = irq;
5069 control->int_ctl &= ~V_INTR_PRIO_MASK;
5070 control->int_ctl |= V_IRQ_MASK |
5071 ((/*control->int_vector >> 4*/ 0xf) << V_INTR_PRIO_SHIFT);
5072 mark_dirty(svm->vmcb, VMCB_INTR);
5073 }
5074
5075 static void svm_set_irq(struct kvm_vcpu *vcpu)
5076 {
5077 struct vcpu_svm *svm = to_svm(vcpu);
5078
5079 BUG_ON(!(gif_set(svm)));
5080
5081 trace_kvm_inj_virq(vcpu->arch.interrupt.nr);
5082 ++vcpu->stat.irq_injections;
5083
5084 svm->vmcb->control.event_inj = vcpu->arch.interrupt.nr |
5085 SVM_EVTINJ_VALID | SVM_EVTINJ_TYPE_INTR;
5086 }
5087
5088 static inline bool svm_nested_virtualize_tpr(struct kvm_vcpu *vcpu)
5089 {
5090 return is_guest_mode(vcpu) && (vcpu->arch.hflags & HF_VINTR_MASK);
5091 }
5092
5093 static void update_cr8_intercept(struct kvm_vcpu *vcpu, int tpr, int irr)
5094 {
5095 struct vcpu_svm *svm = to_svm(vcpu);
5096
5097 if (svm_nested_virtualize_tpr(vcpu) ||
5098 kvm_vcpu_apicv_active(vcpu))
5099 return;
5100
5101 clr_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5102
5103 if (irr == -1)
5104 return;
5105
5106 if (tpr >= irr)
5107 set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
5108 }
5109
5110 static void svm_set_virtual_apic_mode(struct kvm_vcpu *vcpu)
5111 {
5112 return;
5113 }
5114
5115 static bool svm_get_enable_apicv(struct kvm *kvm)
5116 {
5117 return avic && irqchip_split(kvm);
5118 }
5119
5120 static void svm_hwapic_irr_update(struct kvm_vcpu *vcpu, int max_irr)
5121 {
5122 }
5123
5124 static void svm_hwapic_isr_update(struct kvm_vcpu *vcpu, int max_isr)
5125 {
5126 }
5127
5128 /* Note: Currently only used by Hyper-V. */
5129 static void svm_refresh_apicv_exec_ctrl(struct kvm_vcpu *vcpu)
5130 {
5131 struct vcpu_svm *svm = to_svm(vcpu);
5132 struct vmcb *vmcb = svm->vmcb;
5133
5134 if (kvm_vcpu_apicv_active(vcpu))
5135 vmcb->control.int_ctl |= AVIC_ENABLE_MASK;
5136 else
5137 vmcb->control.int_ctl &= ~AVIC_ENABLE_MASK;
5138 mark_dirty(vmcb, VMCB_AVIC);
5139 }
5140
5141 static void svm_load_eoi_exitmap(struct kvm_vcpu *vcpu, u64 *eoi_exit_bitmap)
5142 {
5143 return;
5144 }
5145
5146 static void svm_deliver_avic_intr(struct kvm_vcpu *vcpu, int vec)
5147 {
5148 kvm_lapic_set_irr(vec, vcpu->arch.apic);
5149 smp_mb__after_atomic();
5150
5151 if (avic_vcpu_is_running(vcpu)) {
5152 int cpuid = vcpu->cpu;
5153
5154 if (cpuid != get_cpu())
5155 wrmsrl(SVM_AVIC_DOORBELL, kvm_cpu_get_apicid(cpuid));
5156 put_cpu();
5157 } else
5158 kvm_vcpu_wake_up(vcpu);
5159 }
5160
5161 static bool svm_dy_apicv_has_pending_interrupt(struct kvm_vcpu *vcpu)
5162 {
5163 return false;
5164 }
5165
5166 static void svm_ir_list_del(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5167 {
5168 unsigned long flags;
5169 struct amd_svm_iommu_ir *cur;
5170
5171 spin_lock_irqsave(&svm->ir_list_lock, flags);
5172 list_for_each_entry(cur, &svm->ir_list, node) {
5173 if (cur->data != pi->ir_data)
5174 continue;
5175 list_del(&cur->node);
5176 kfree(cur);
5177 break;
5178 }
5179 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5180 }
5181
5182 static int svm_ir_list_add(struct vcpu_svm *svm, struct amd_iommu_pi_data *pi)
5183 {
5184 int ret = 0;
5185 unsigned long flags;
5186 struct amd_svm_iommu_ir *ir;
5187
5188 /**
5189 * In some cases, the existing irte is updaed and re-set,
5190 * so we need to check here if it's already been * added
5191 * to the ir_list.
5192 */
5193 if (pi->ir_data && (pi->prev_ga_tag != 0)) {
5194 struct kvm *kvm = svm->vcpu.kvm;
5195 u32 vcpu_id = AVIC_GATAG_TO_VCPUID(pi->prev_ga_tag);
5196 struct kvm_vcpu *prev_vcpu = kvm_get_vcpu_by_id(kvm, vcpu_id);
5197 struct vcpu_svm *prev_svm;
5198
5199 if (!prev_vcpu) {
5200 ret = -EINVAL;
5201 goto out;
5202 }
5203
5204 prev_svm = to_svm(prev_vcpu);
5205 svm_ir_list_del(prev_svm, pi);
5206 }
5207
5208 /**
5209 * Allocating new amd_iommu_pi_data, which will get
5210 * add to the per-vcpu ir_list.
5211 */
5212 ir = kzalloc(sizeof(struct amd_svm_iommu_ir), GFP_KERNEL_ACCOUNT);
5213 if (!ir) {
5214 ret = -ENOMEM;
5215 goto out;
5216 }
5217 ir->data = pi->ir_data;
5218
5219 spin_lock_irqsave(&svm->ir_list_lock, flags);
5220 list_add(&ir->node, &svm->ir_list);
5221 spin_unlock_irqrestore(&svm->ir_list_lock, flags);
5222 out:
5223 return ret;
5224 }
5225
5226 /**
5227 * Note:
5228 * The HW cannot support posting multicast/broadcast
5229 * interrupts to a vCPU. So, we still use legacy interrupt
5230 * remapping for these kind of interrupts.
5231 *
5232 * For lowest-priority interrupts, we only support
5233 * those with single CPU as the destination, e.g. user
5234 * configures the interrupts via /proc/irq or uses
5235 * irqbalance to make the interrupts single-CPU.
5236 */
5237 static int
5238 get_pi_vcpu_info(struct kvm *kvm, struct kvm_kernel_irq_routing_entry *e,
5239 struct vcpu_data *vcpu_info, struct vcpu_svm **svm)
5240 {
5241 struct kvm_lapic_irq irq;
5242 struct kvm_vcpu *vcpu = NULL;
5243
5244 kvm_set_msi_irq(kvm, e, &irq);
5245
5246 if (!kvm_intr_is_single_vcpu(kvm, &irq, &vcpu) ||
5247 !kvm_irq_is_postable(&irq)) {
5248 pr_debug("SVM: %s: use legacy intr remap mode for irq %u\n",
5249 __func__, irq.vector);
5250 return -1;
5251 }
5252
5253 pr_debug("SVM: %s: use GA mode for irq %u\n", __func__,
5254 irq.vector);
5255 *svm = to_svm(vcpu);
5256 vcpu_info->pi_desc_addr = __sme_set(page_to_phys((*svm)->avic_backing_page));
5257 vcpu_info->vector = irq.vector;
5258
5259 return 0;
5260 }
5261
5262 /*
5263 * svm_update_pi_irte - set IRTE for Posted-Interrupts
5264 *
5265 * @kvm: kvm
5266 * @host_irq: host irq of the interrupt
5267 * @guest_irq: gsi of the interrupt
5268 * @set: set or unset PI
5269 * returns 0 on success, < 0 on failure
5270 */
5271 static int svm_update_pi_irte(struct kvm *kvm, unsigned int host_irq,
5272 uint32_t guest_irq, bool set)
5273 {
5274 struct kvm_kernel_irq_routing_entry *e;
5275 struct kvm_irq_routing_table *irq_rt;
5276 int idx, ret = -EINVAL;
5277
5278 if (!kvm_arch_has_assigned_device(kvm) ||
5279 !irq_remapping_cap(IRQ_POSTING_CAP))
5280 return 0;
5281
5282 pr_debug("SVM: %s: host_irq=%#x, guest_irq=%#x, set=%#x\n",
5283 __func__, host_irq, guest_irq, set);
5284
5285 idx = srcu_read_lock(&kvm->irq_srcu);
5286 irq_rt = srcu_dereference(kvm->irq_routing, &kvm->irq_srcu);
5287 WARN_ON(guest_irq >= irq_rt->nr_rt_entries);
5288
5289 hlist_for_each_entry(e, &irq_rt->map[guest_irq], link) {
5290 struct vcpu_data vcpu_info;
5291 struct vcpu_svm *svm = NULL;
5292
5293 if (e->type != KVM_IRQ_ROUTING_MSI)
5294 continue;
5295
5296 /**
5297 * Here, we setup with legacy mode in the following cases:
5298 * 1. When cannot target interrupt to a specific vcpu.
5299 * 2. Unsetting posted interrupt.
5300 * 3. APIC virtialization is disabled for the vcpu.
5301 * 4. IRQ has incompatible delivery mode (SMI, INIT, etc)
5302 */
5303 if (!get_pi_vcpu_info(kvm, e, &vcpu_info, &svm) && set &&
5304 kvm_vcpu_apicv_active(&svm->vcpu)) {
5305 struct amd_iommu_pi_data pi;
5306
5307 /* Try to enable guest_mode in IRTE */
5308 pi.base = __sme_set(page_to_phys(svm->avic_backing_page) &
5309 AVIC_HPA_MASK);
5310 pi.ga_tag = AVIC_GATAG(to_kvm_svm(kvm)->avic_vm_id,
5311 svm->vcpu.vcpu_id);
5312 pi.is_guest_mode = true;
5313 pi.vcpu_data = &vcpu_info;
5314 ret = irq_set_vcpu_affinity(host_irq, &pi);
5315
5316 /**
5317 * Here, we successfully setting up vcpu affinity in
5318 * IOMMU guest mode. Now, we need to store the posted
5319 * interrupt information in a per-vcpu ir_list so that
5320 * we can reference to them directly when we update vcpu
5321 * scheduling information in IOMMU irte.
5322 */
5323 if (!ret && pi.is_guest_mode)
5324 svm_ir_list_add(svm, &pi);
5325 } else {
5326 /* Use legacy mode in IRTE */
5327 struct amd_iommu_pi_data pi;
5328
5329 /**
5330 * Here, pi is used to:
5331 * - Tell IOMMU to use legacy mode for this interrupt.
5332 * - Retrieve ga_tag of prior interrupt remapping data.
5333 */
5334 pi.is_guest_mode = false;
5335 ret = irq_set_vcpu_affinity(host_irq, &pi);
5336
5337 /**
5338 * Check if the posted interrupt was previously
5339 * setup with the guest_mode by checking if the ga_tag
5340 * was cached. If so, we need to clean up the per-vcpu
5341 * ir_list.
5342 */
5343 if (!ret && pi.prev_ga_tag) {
5344 int id = AVIC_GATAG_TO_VCPUID(pi.prev_ga_tag);
5345 struct kvm_vcpu *vcpu;
5346
5347 vcpu = kvm_get_vcpu_by_id(kvm, id);
5348 if (vcpu)
5349 svm_ir_list_del(to_svm(vcpu), &pi);
5350 }
5351 }
5352
5353 if (!ret && svm) {
5354 trace_kvm_pi_irte_update(host_irq, svm->vcpu.vcpu_id,
5355 e->gsi, vcpu_info.vector,
5356 vcpu_info.pi_desc_addr, set);
5357 }
5358
5359 if (ret < 0) {
5360 pr_err("%s: failed to update PI IRTE\n", __func__);
5361 goto out;
5362 }
5363 }
5364
5365 ret = 0;
5366 out:
5367 srcu_read_unlock(&kvm->irq_srcu, idx);
5368 return ret;
5369 }
5370
5371 static int svm_nmi_allowed(struct kvm_vcpu *vcpu)
5372 {
5373 struct vcpu_svm *svm = to_svm(vcpu);
5374 struct vmcb *vmcb = svm->vmcb;
5375 int ret;
5376 ret = !(vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK) &&
5377 !(svm->vcpu.arch.hflags & HF_NMI_MASK);
5378 ret = ret && gif_set(svm) && nested_svm_nmi(svm);
5379
5380 return ret;
5381 }
5382
5383 static bool svm_get_nmi_mask(struct kvm_vcpu *vcpu)
5384 {
5385 struct vcpu_svm *svm = to_svm(vcpu);
5386
5387 return !!(svm->vcpu.arch.hflags & HF_NMI_MASK);
5388 }
5389
5390 static void svm_set_nmi_mask(struct kvm_vcpu *vcpu, bool masked)
5391 {
5392 struct vcpu_svm *svm = to_svm(vcpu);
5393
5394 if (masked) {
5395 svm->vcpu.arch.hflags |= HF_NMI_MASK;
5396 set_intercept(svm, INTERCEPT_IRET);
5397 } else {
5398 svm->vcpu.arch.hflags &= ~HF_NMI_MASK;
5399 clr_intercept(svm, INTERCEPT_IRET);
5400 }
5401 }
5402
5403 static int svm_interrupt_allowed(struct kvm_vcpu *vcpu)
5404 {
5405 struct vcpu_svm *svm = to_svm(vcpu);
5406 struct vmcb *vmcb = svm->vmcb;
5407 int ret;
5408
5409 if (!gif_set(svm) ||
5410 (vmcb->control.int_state & SVM_INTERRUPT_SHADOW_MASK))
5411 return 0;
5412
5413 ret = !!(kvm_get_rflags(vcpu) & X86_EFLAGS_IF);
5414
5415 if (is_guest_mode(vcpu))
5416 return ret && !(svm->vcpu.arch.hflags & HF_VINTR_MASK);
5417
5418 return ret;
5419 }
5420
5421 static void enable_irq_window(struct kvm_vcpu *vcpu)
5422 {
5423 struct vcpu_svm *svm = to_svm(vcpu);
5424
5425 if (kvm_vcpu_apicv_active(vcpu))
5426 return;
5427
5428 /*
5429 * In case GIF=0 we can't rely on the CPU to tell us when GIF becomes
5430 * 1, because that's a separate STGI/VMRUN intercept. The next time we
5431 * get that intercept, this function will be called again though and
5432 * we'll get the vintr intercept. However, if the vGIF feature is
5433 * enabled, the STGI interception will not occur. Enable the irq
5434 * window under the assumption that the hardware will set the GIF.
5435 */
5436 if ((vgif_enabled(svm) || gif_set(svm)) && nested_svm_intr(svm)) {
5437 svm_set_vintr(svm);
5438 svm_inject_irq(svm, 0x0);
5439 }
5440 }
5441
5442 static void enable_nmi_window(struct kvm_vcpu *vcpu)
5443 {
5444 struct vcpu_svm *svm = to_svm(vcpu);
5445
5446 if ((svm->vcpu.arch.hflags & (HF_NMI_MASK | HF_IRET_MASK))
5447 == HF_NMI_MASK)
5448 return; /* IRET will cause a vm exit */
5449
5450 if (!gif_set(svm)) {
5451 if (vgif_enabled(svm))
5452 set_intercept(svm, INTERCEPT_STGI);
5453 return; /* STGI will cause a vm exit */
5454 }
5455
5456 if (svm->nested.exit_required)
5457 return; /* we're not going to run the guest yet */
5458
5459 /*
5460 * Something prevents NMI from been injected. Single step over possible
5461 * problem (IRET or exception injection or interrupt shadow)
5462 */
5463 svm->nmi_singlestep_guest_rflags = svm_get_rflags(vcpu);
5464 svm->nmi_singlestep = true;
5465 svm->vmcb->save.rflags |= (X86_EFLAGS_TF | X86_EFLAGS_RF);
5466 }
5467
5468 static int svm_set_tss_addr(struct kvm *kvm, unsigned int addr)
5469 {
5470 return 0;
5471 }
5472
5473 static int svm_set_identity_map_addr(struct kvm *kvm, u64 ident_addr)
5474 {
5475 return 0;
5476 }
5477
5478 static void svm_flush_tlb(struct kvm_vcpu *vcpu, bool invalidate_gpa)
5479 {
5480 struct vcpu_svm *svm = to_svm(vcpu);
5481
5482 if (static_cpu_has(X86_FEATURE_FLUSHBYASID))
5483 svm->vmcb->control.tlb_ctl = TLB_CONTROL_FLUSH_ASID;
5484 else
5485 svm->asid_generation--;
5486 }
5487
5488 static void svm_flush_tlb_gva(struct kvm_vcpu *vcpu, gva_t gva)
5489 {
5490 struct vcpu_svm *svm = to_svm(vcpu);
5491
5492 invlpga(gva, svm->vmcb->control.asid);
5493 }
5494
5495 static void svm_prepare_guest_switch(struct kvm_vcpu *vcpu)
5496 {
5497 }
5498
5499 static inline void sync_cr8_to_lapic(struct kvm_vcpu *vcpu)
5500 {
5501 struct vcpu_svm *svm = to_svm(vcpu);
5502
5503 if (svm_nested_virtualize_tpr(vcpu))
5504 return;
5505
5506 if (!is_cr_intercept(svm, INTERCEPT_CR8_WRITE)) {
5507 int cr8 = svm->vmcb->control.int_ctl & V_TPR_MASK;
5508 kvm_set_cr8(vcpu, cr8);
5509 }
5510 }
5511
5512 static inline void sync_lapic_to_cr8(struct kvm_vcpu *vcpu)
5513 {
5514 struct vcpu_svm *svm = to_svm(vcpu);
5515 u64 cr8;
5516
5517 if (svm_nested_virtualize_tpr(vcpu) ||
5518 kvm_vcpu_apicv_active(vcpu))
5519 return;
5520
5521 cr8 = kvm_get_cr8(vcpu);
5522 svm->vmcb->control.int_ctl &= ~V_TPR_MASK;
5523 svm->vmcb->control.int_ctl |= cr8 & V_TPR_MASK;
5524 }
5525
5526 static void svm_complete_interrupts(struct vcpu_svm *svm)
5527 {
5528 u8 vector;
5529 int type;
5530 u32 exitintinfo = svm->vmcb->control.exit_int_info;
5531 unsigned int3_injected = svm->int3_injected;
5532
5533 svm->int3_injected = 0;
5534
5535 /*
5536 * If we've made progress since setting HF_IRET_MASK, we've
5537 * executed an IRET and can allow NMI injection.
5538 */
5539 if ((svm->vcpu.arch.hflags & HF_IRET_MASK)
5540 && kvm_rip_read(&svm->vcpu) != svm->nmi_iret_rip) {
5541 svm->vcpu.arch.hflags &= ~(HF_NMI_MASK | HF_IRET_MASK);
5542 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5543 }
5544
5545 svm->vcpu.arch.nmi_injected = false;
5546 kvm_clear_exception_queue(&svm->vcpu);
5547 kvm_clear_interrupt_queue(&svm->vcpu);
5548
5549 if (!(exitintinfo & SVM_EXITINTINFO_VALID))
5550 return;
5551
5552 kvm_make_request(KVM_REQ_EVENT, &svm->vcpu);
5553
5554 vector = exitintinfo & SVM_EXITINTINFO_VEC_MASK;
5555 type = exitintinfo & SVM_EXITINTINFO_TYPE_MASK;
5556
5557 switch (type) {
5558 case SVM_EXITINTINFO_TYPE_NMI:
5559 svm->vcpu.arch.nmi_injected = true;
5560 break;
5561 case SVM_EXITINTINFO_TYPE_EXEPT:
5562 /*
5563 * In case of software exceptions, do not reinject the vector,
5564 * but re-execute the instruction instead. Rewind RIP first
5565 * if we emulated INT3 before.
5566 */
5567 if (kvm_exception_is_soft(vector)) {
5568 if (vector == BP_VECTOR && int3_injected &&
5569 kvm_is_linear_rip(&svm->vcpu, svm->int3_rip))
5570 kvm_rip_write(&svm->vcpu,
5571 kvm_rip_read(&svm->vcpu) -
5572 int3_injected);
5573 break;
5574 }
5575 if (exitintinfo & SVM_EXITINTINFO_VALID_ERR) {
5576 u32 err = svm->vmcb->control.exit_int_info_err;
5577 kvm_requeue_exception_e(&svm->vcpu, vector, err);
5578
5579 } else
5580 kvm_requeue_exception(&svm->vcpu, vector);
5581 break;
5582 case SVM_EXITINTINFO_TYPE_INTR:
5583 kvm_queue_interrupt(&svm->vcpu, vector, false);
5584 break;
5585 default:
5586 break;
5587 }
5588 }
5589
5590 static void svm_cancel_injection(struct kvm_vcpu *vcpu)
5591 {
5592 struct vcpu_svm *svm = to_svm(vcpu);
5593 struct vmcb_control_area *control = &svm->vmcb->control;
5594
5595 control->exit_int_info = control->event_inj;
5596 control->exit_int_info_err = control->event_inj_err;
5597 control->event_inj = 0;
5598 svm_complete_interrupts(svm);
5599 }
5600
5601 static void svm_vcpu_run(struct kvm_vcpu *vcpu)
5602 {
5603 struct vcpu_svm *svm = to_svm(vcpu);
5604
5605 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
5606 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
5607 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
5608
5609 /*
5610 * A vmexit emulation is required before the vcpu can be executed
5611 * again.
5612 */
5613 if (unlikely(svm->nested.exit_required))
5614 return;
5615
5616 /*
5617 * Disable singlestep if we're injecting an interrupt/exception.
5618 * We don't want our modified rflags to be pushed on the stack where
5619 * we might not be able to easily reset them if we disabled NMI
5620 * singlestep later.
5621 */
5622 if (svm->nmi_singlestep && svm->vmcb->control.event_inj) {
5623 /*
5624 * Event injection happens before external interrupts cause a
5625 * vmexit and interrupts are disabled here, so smp_send_reschedule
5626 * is enough to force an immediate vmexit.
5627 */
5628 disable_nmi_singlestep(svm);
5629 smp_send_reschedule(vcpu->cpu);
5630 }
5631
5632 pre_svm_run(svm);
5633
5634 sync_lapic_to_cr8(vcpu);
5635
5636 svm->vmcb->save.cr2 = vcpu->arch.cr2;
5637
5638 clgi();
5639 kvm_load_guest_xcr0(vcpu);
5640
5641 if (lapic_in_kernel(vcpu) &&
5642 vcpu->arch.apic->lapic_timer.timer_advance_ns)
5643 kvm_wait_lapic_expire(vcpu);
5644
5645 /*
5646 * If this vCPU has touched SPEC_CTRL, restore the guest's value if
5647 * it's non-zero. Since vmentry is serialising on affected CPUs, there
5648 * is no need to worry about the conditional branch over the wrmsr
5649 * being speculatively taken.
5650 */
5651 x86_spec_ctrl_set_guest(svm->spec_ctrl, svm->virt_spec_ctrl);
5652
5653 local_irq_enable();
5654
5655 asm volatile (
5656 "push %%" _ASM_BP "; \n\t"
5657 "mov %c[rbx](%[svm]), %%" _ASM_BX " \n\t"
5658 "mov %c[rcx](%[svm]), %%" _ASM_CX " \n\t"
5659 "mov %c[rdx](%[svm]), %%" _ASM_DX " \n\t"
5660 "mov %c[rsi](%[svm]), %%" _ASM_SI " \n\t"
5661 "mov %c[rdi](%[svm]), %%" _ASM_DI " \n\t"
5662 "mov %c[rbp](%[svm]), %%" _ASM_BP " \n\t"
5663 #ifdef CONFIG_X86_64
5664 "mov %c[r8](%[svm]), %%r8 \n\t"
5665 "mov %c[r9](%[svm]), %%r9 \n\t"
5666 "mov %c[r10](%[svm]), %%r10 \n\t"
5667 "mov %c[r11](%[svm]), %%r11 \n\t"
5668 "mov %c[r12](%[svm]), %%r12 \n\t"
5669 "mov %c[r13](%[svm]), %%r13 \n\t"
5670 "mov %c[r14](%[svm]), %%r14 \n\t"
5671 "mov %c[r15](%[svm]), %%r15 \n\t"
5672 #endif
5673
5674 /* Enter guest mode */
5675 "push %%" _ASM_AX " \n\t"
5676 "mov %c[vmcb](%[svm]), %%" _ASM_AX " \n\t"
5677 __ex("vmload %%" _ASM_AX) "\n\t"
5678 __ex("vmrun %%" _ASM_AX) "\n\t"
5679 __ex("vmsave %%" _ASM_AX) "\n\t"
5680 "pop %%" _ASM_AX " \n\t"
5681
5682 /* Save guest registers, load host registers */
5683 "mov %%" _ASM_BX ", %c[rbx](%[svm]) \n\t"
5684 "mov %%" _ASM_CX ", %c[rcx](%[svm]) \n\t"
5685 "mov %%" _ASM_DX ", %c[rdx](%[svm]) \n\t"
5686 "mov %%" _ASM_SI ", %c[rsi](%[svm]) \n\t"
5687 "mov %%" _ASM_DI ", %c[rdi](%[svm]) \n\t"
5688 "mov %%" _ASM_BP ", %c[rbp](%[svm]) \n\t"
5689 #ifdef CONFIG_X86_64
5690 "mov %%r8, %c[r8](%[svm]) \n\t"
5691 "mov %%r9, %c[r9](%[svm]) \n\t"
5692 "mov %%r10, %c[r10](%[svm]) \n\t"
5693 "mov %%r11, %c[r11](%[svm]) \n\t"
5694 "mov %%r12, %c[r12](%[svm]) \n\t"
5695 "mov %%r13, %c[r13](%[svm]) \n\t"
5696 "mov %%r14, %c[r14](%[svm]) \n\t"
5697 "mov %%r15, %c[r15](%[svm]) \n\t"
5698 /*
5699 * Clear host registers marked as clobbered to prevent
5700 * speculative use.
5701 */
5702 "xor %%r8d, %%r8d \n\t"
5703 "xor %%r9d, %%r9d \n\t"
5704 "xor %%r10d, %%r10d \n\t"
5705 "xor %%r11d, %%r11d \n\t"
5706 "xor %%r12d, %%r12d \n\t"
5707 "xor %%r13d, %%r13d \n\t"
5708 "xor %%r14d, %%r14d \n\t"
5709 "xor %%r15d, %%r15d \n\t"
5710 #endif
5711 "xor %%ebx, %%ebx \n\t"
5712 "xor %%ecx, %%ecx \n\t"
5713 "xor %%edx, %%edx \n\t"
5714 "xor %%esi, %%esi \n\t"
5715 "xor %%edi, %%edi \n\t"
5716 "pop %%" _ASM_BP
5717 :
5718 : [svm]"a"(svm),
5719 [vmcb]"i"(offsetof(struct vcpu_svm, vmcb_pa)),
5720 [rbx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBX])),
5721 [rcx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RCX])),
5722 [rdx]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDX])),
5723 [rsi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RSI])),
5724 [rdi]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RDI])),
5725 [rbp]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_RBP]))
5726 #ifdef CONFIG_X86_64
5727 , [r8]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R8])),
5728 [r9]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R9])),
5729 [r10]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R10])),
5730 [r11]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R11])),
5731 [r12]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R12])),
5732 [r13]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R13])),
5733 [r14]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R14])),
5734 [r15]"i"(offsetof(struct vcpu_svm, vcpu.arch.regs[VCPU_REGS_R15]))
5735 #endif
5736 : "cc", "memory"
5737 #ifdef CONFIG_X86_64
5738 , "rbx", "rcx", "rdx", "rsi", "rdi"
5739 , "r8", "r9", "r10", "r11" , "r12", "r13", "r14", "r15"
5740 #else
5741 , "ebx", "ecx", "edx", "esi", "edi"
5742 #endif
5743 );
5744
5745 /* Eliminate branch target predictions from guest mode */
5746 vmexit_fill_RSB();
5747
5748 #ifdef CONFIG_X86_64
5749 wrmsrl(MSR_GS_BASE, svm->host.gs_base);
5750 #else
5751 loadsegment(fs, svm->host.fs);
5752 #ifndef CONFIG_X86_32_LAZY_GS
5753 loadsegment(gs, svm->host.gs);
5754 #endif
5755 #endif
5756
5757 /*
5758 * We do not use IBRS in the kernel. If this vCPU has used the
5759 * SPEC_CTRL MSR it may have left it on; save the value and
5760 * turn it off. This is much more efficient than blindly adding
5761 * it to the atomic save/restore list. Especially as the former
5762 * (Saving guest MSRs on vmexit) doesn't even exist in KVM.
5763 *
5764 * For non-nested case:
5765 * If the L01 MSR bitmap does not intercept the MSR, then we need to
5766 * save it.
5767 *
5768 * For nested case:
5769 * If the L02 MSR bitmap does not intercept the MSR, then we need to
5770 * save it.
5771 */
5772 if (unlikely(!msr_write_intercepted(vcpu, MSR_IA32_SPEC_CTRL)))
5773 svm->spec_ctrl = native_read_msr(MSR_IA32_SPEC_CTRL);
5774
5775 reload_tss(vcpu);
5776
5777 local_irq_disable();
5778
5779 x86_spec_ctrl_restore_host(svm->spec_ctrl, svm->virt_spec_ctrl);
5780
5781 vcpu->arch.cr2 = svm->vmcb->save.cr2;
5782 vcpu->arch.regs[VCPU_REGS_RAX] = svm->vmcb->save.rax;
5783 vcpu->arch.regs[VCPU_REGS_RSP] = svm->vmcb->save.rsp;
5784 vcpu->arch.regs[VCPU_REGS_RIP] = svm->vmcb->save.rip;
5785
5786 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5787 kvm_before_interrupt(&svm->vcpu);
5788
5789 kvm_put_guest_xcr0(vcpu);
5790 stgi();
5791
5792 /* Any pending NMI will happen here */
5793
5794 if (unlikely(svm->vmcb->control.exit_code == SVM_EXIT_NMI))
5795 kvm_after_interrupt(&svm->vcpu);
5796
5797 sync_cr8_to_lapic(vcpu);
5798
5799 svm->next_rip = 0;
5800
5801 svm->vmcb->control.tlb_ctl = TLB_CONTROL_DO_NOTHING;
5802
5803 /* if exit due to PF check for async PF */
5804 if (svm->vmcb->control.exit_code == SVM_EXIT_EXCP_BASE + PF_VECTOR)
5805 svm->vcpu.arch.apf.host_apf_reason = kvm_read_and_reset_pf_reason();
5806
5807 if (npt_enabled) {
5808 vcpu->arch.regs_avail &= ~(1 << VCPU_EXREG_PDPTR);
5809 vcpu->arch.regs_dirty &= ~(1 << VCPU_EXREG_PDPTR);
5810 }
5811
5812 /*
5813 * We need to handle MC intercepts here before the vcpu has a chance to
5814 * change the physical cpu
5815 */
5816 if (unlikely(svm->vmcb->control.exit_code ==
5817 SVM_EXIT_EXCP_BASE + MC_VECTOR))
5818 svm_handle_mce(svm);
5819
5820 mark_all_clean(svm->vmcb);
5821 }
5822 STACK_FRAME_NON_STANDARD(svm_vcpu_run);
5823
5824 static void svm_set_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5825 {
5826 struct vcpu_svm *svm = to_svm(vcpu);
5827
5828 svm->vmcb->save.cr3 = __sme_set(root);
5829 mark_dirty(svm->vmcb, VMCB_CR);
5830 }
5831
5832 static void set_tdp_cr3(struct kvm_vcpu *vcpu, unsigned long root)
5833 {
5834 struct vcpu_svm *svm = to_svm(vcpu);
5835
5836 svm->vmcb->control.nested_cr3 = __sme_set(root);
5837 mark_dirty(svm->vmcb, VMCB_NPT);
5838
5839 /* Also sync guest cr3 here in case we live migrate */
5840 svm->vmcb->save.cr3 = kvm_read_cr3(vcpu);
5841 mark_dirty(svm->vmcb, VMCB_CR);
5842 }
5843
5844 static int is_disabled(void)
5845 {
5846 u64 vm_cr;
5847
5848 rdmsrl(MSR_VM_CR, vm_cr);
5849 if (vm_cr & (1 << SVM_VM_CR_SVM_DISABLE))
5850 return 1;
5851
5852 return 0;
5853 }
5854
5855 static void
5856 svm_patch_hypercall(struct kvm_vcpu *vcpu, unsigned char *hypercall)
5857 {
5858 /*
5859 * Patch in the VMMCALL instruction:
5860 */
5861 hypercall[0] = 0x0f;
5862 hypercall[1] = 0x01;
5863 hypercall[2] = 0xd9;
5864 }
5865
5866 static int __init svm_check_processor_compat(void)
5867 {
5868 return 0;
5869 }
5870
5871 static bool svm_cpu_has_accelerated_tpr(void)
5872 {
5873 return false;
5874 }
5875
5876 static bool svm_has_emulated_msr(int index)
5877 {
5878 switch (index) {
5879 case MSR_IA32_MCG_EXT_CTL:
5880 case MSR_IA32_VMX_BASIC ... MSR_IA32_VMX_VMFUNC:
5881 return false;
5882 default:
5883 break;
5884 }
5885
5886 return true;
5887 }
5888
5889 static u64 svm_get_mt_mask(struct kvm_vcpu *vcpu, gfn_t gfn, bool is_mmio)
5890 {
5891 return 0;
5892 }
5893
5894 static void svm_cpuid_update(struct kvm_vcpu *vcpu)
5895 {
5896 struct vcpu_svm *svm = to_svm(vcpu);
5897
5898 /* Update nrips enabled cache */
5899 svm->nrips_enabled = !!guest_cpuid_has(&svm->vcpu, X86_FEATURE_NRIPS);
5900
5901 if (!kvm_vcpu_apicv_active(vcpu))
5902 return;
5903
5904 guest_cpuid_clear(vcpu, X86_FEATURE_X2APIC);
5905 }
5906
5907 #define F(x) bit(X86_FEATURE_##x)
5908
5909 static void svm_set_supported_cpuid(u32 func, struct kvm_cpuid_entry2 *entry)
5910 {
5911 switch (func) {
5912 case 0x1:
5913 if (avic)
5914 entry->ecx &= ~bit(X86_FEATURE_X2APIC);
5915 break;
5916 case 0x80000001:
5917 if (nested)
5918 entry->ecx |= (1 << 2); /* Set SVM bit */
5919 break;
5920 case 0x80000008:
5921 if (boot_cpu_has(X86_FEATURE_LS_CFG_SSBD) ||
5922 boot_cpu_has(X86_FEATURE_AMD_SSBD))
5923 entry->ebx |= F(VIRT_SSBD);
5924 break;
5925 case 0x8000000A:
5926 entry->eax = 1; /* SVM revision 1 */
5927 entry->ebx = 8; /* Lets support 8 ASIDs in case we add proper
5928 ASID emulation to nested SVM */
5929 entry->ecx = 0; /* Reserved */
5930 entry->edx = 0; /* Per default do not support any
5931 additional features */
5932
5933 /* Support next_rip if host supports it */
5934 if (boot_cpu_has(X86_FEATURE_NRIPS))
5935 entry->edx |= F(NRIPS);
5936
5937 /* Support NPT for the guest if enabled */
5938 if (npt_enabled)
5939 entry->edx |= F(NPT);
5940
5941 break;
5942 case 0x8000001F:
5943 /* Support memory encryption cpuid if host supports it */
5944 if (boot_cpu_has(X86_FEATURE_SEV))
5945 cpuid(0x8000001f, &entry->eax, &entry->ebx,
5946 &entry->ecx, &entry->edx);
5947
5948 }
5949 }
5950
5951 static int svm_get_lpage_level(void)
5952 {
5953 return PT_PDPE_LEVEL;
5954 }
5955
5956 static bool svm_rdtscp_supported(void)
5957 {
5958 return boot_cpu_has(X86_FEATURE_RDTSCP);
5959 }
5960
5961 static bool svm_invpcid_supported(void)
5962 {
5963 return false;
5964 }
5965
5966 static bool svm_mpx_supported(void)
5967 {
5968 return false;
5969 }
5970
5971 static bool svm_xsaves_supported(void)
5972 {
5973 return false;
5974 }
5975
5976 static bool svm_umip_emulated(void)
5977 {
5978 return false;
5979 }
5980
5981 static bool svm_pt_supported(void)
5982 {
5983 return false;
5984 }
5985
5986 static bool svm_has_wbinvd_exit(void)
5987 {
5988 return true;
5989 }
5990
5991 #define PRE_EX(exit) { .exit_code = (exit), \
5992 .stage = X86_ICPT_PRE_EXCEPT, }
5993 #define POST_EX(exit) { .exit_code = (exit), \
5994 .stage = X86_ICPT_POST_EXCEPT, }
5995 #define POST_MEM(exit) { .exit_code = (exit), \
5996 .stage = X86_ICPT_POST_MEMACCESS, }
5997
5998 static const struct __x86_intercept {
5999 u32 exit_code;
6000 enum x86_intercept_stage stage;
6001 } x86_intercept_map[] = {
6002 [x86_intercept_cr_read] = POST_EX(SVM_EXIT_READ_CR0),
6003 [x86_intercept_cr_write] = POST_EX(SVM_EXIT_WRITE_CR0),
6004 [x86_intercept_clts] = POST_EX(SVM_EXIT_WRITE_CR0),
6005 [x86_intercept_lmsw] = POST_EX(SVM_EXIT_WRITE_CR0),
6006 [x86_intercept_smsw] = POST_EX(SVM_EXIT_READ_CR0),
6007 [x86_intercept_dr_read] = POST_EX(SVM_EXIT_READ_DR0),
6008 [x86_intercept_dr_write] = POST_EX(SVM_EXIT_WRITE_DR0),
6009 [x86_intercept_sldt] = POST_EX(SVM_EXIT_LDTR_READ),
6010 [x86_intercept_str] = POST_EX(SVM_EXIT_TR_READ),
6011 [x86_intercept_lldt] = POST_EX(SVM_EXIT_LDTR_WRITE),
6012 [x86_intercept_ltr] = POST_EX(SVM_EXIT_TR_WRITE),
6013 [x86_intercept_sgdt] = POST_EX(SVM_EXIT_GDTR_READ),
6014 [x86_intercept_sidt] = POST_EX(SVM_EXIT_IDTR_READ),
6015 [x86_intercept_lgdt] = POST_EX(SVM_EXIT_GDTR_WRITE),
6016 [x86_intercept_lidt] = POST_EX(SVM_EXIT_IDTR_WRITE),
6017 [x86_intercept_vmrun] = POST_EX(SVM_EXIT_VMRUN),
6018 [x86_intercept_vmmcall] = POST_EX(SVM_EXIT_VMMCALL),
6019 [x86_intercept_vmload] = POST_EX(SVM_EXIT_VMLOAD),
6020 [x86_intercept_vmsave] = POST_EX(SVM_EXIT_VMSAVE),
6021 [x86_intercept_stgi] = POST_EX(SVM_EXIT_STGI),
6022 [x86_intercept_clgi] = POST_EX(SVM_EXIT_CLGI),
6023 [x86_intercept_skinit] = POST_EX(SVM_EXIT_SKINIT),
6024 [x86_intercept_invlpga] = POST_EX(SVM_EXIT_INVLPGA),
6025 [x86_intercept_rdtscp] = POST_EX(SVM_EXIT_RDTSCP),
6026 [x86_intercept_monitor] = POST_MEM(SVM_EXIT_MONITOR),
6027 [x86_intercept_mwait] = POST_EX(SVM_EXIT_MWAIT),
6028 [x86_intercept_invlpg] = POST_EX(SVM_EXIT_INVLPG),
6029 [x86_intercept_invd] = POST_EX(SVM_EXIT_INVD),
6030 [x86_intercept_wbinvd] = POST_EX(SVM_EXIT_WBINVD),
6031 [x86_intercept_wrmsr] = POST_EX(SVM_EXIT_MSR),
6032 [x86_intercept_rdtsc] = POST_EX(SVM_EXIT_RDTSC),
6033 [x86_intercept_rdmsr] = POST_EX(SVM_EXIT_MSR),
6034 [x86_intercept_rdpmc] = POST_EX(SVM_EXIT_RDPMC),
6035 [x86_intercept_cpuid] = PRE_EX(SVM_EXIT_CPUID),
6036 [x86_intercept_rsm] = PRE_EX(SVM_EXIT_RSM),
6037 [x86_intercept_pause] = PRE_EX(SVM_EXIT_PAUSE),
6038 [x86_intercept_pushf] = PRE_EX(SVM_EXIT_PUSHF),
6039 [x86_intercept_popf] = PRE_EX(SVM_EXIT_POPF),
6040 [x86_intercept_intn] = PRE_EX(SVM_EXIT_SWINT),
6041 [x86_intercept_iret] = PRE_EX(SVM_EXIT_IRET),
6042 [x86_intercept_icebp] = PRE_EX(SVM_EXIT_ICEBP),
6043 [x86_intercept_hlt] = POST_EX(SVM_EXIT_HLT),
6044 [x86_intercept_in] = POST_EX(SVM_EXIT_IOIO),
6045 [x86_intercept_ins] = POST_EX(SVM_EXIT_IOIO),
6046 [x86_intercept_out] = POST_EX(SVM_EXIT_IOIO),
6047 [x86_intercept_outs] = POST_EX(SVM_EXIT_IOIO),
6048 [x86_intercept_xsetbv] = PRE_EX(SVM_EXIT_XSETBV),
6049 };
6050
6051 #undef PRE_EX
6052 #undef POST_EX
6053 #undef POST_MEM
6054
6055 static int svm_check_intercept(struct kvm_vcpu *vcpu,
6056 struct x86_instruction_info *info,
6057 enum x86_intercept_stage stage)
6058 {
6059 struct vcpu_svm *svm = to_svm(vcpu);
6060 int vmexit, ret = X86EMUL_CONTINUE;
6061 struct __x86_intercept icpt_info;
6062 struct vmcb *vmcb = svm->vmcb;
6063
6064 if (info->intercept >= ARRAY_SIZE(x86_intercept_map))
6065 goto out;
6066
6067 icpt_info = x86_intercept_map[info->intercept];
6068
6069 if (stage != icpt_info.stage)
6070 goto out;
6071
6072 switch (icpt_info.exit_code) {
6073 case SVM_EXIT_READ_CR0:
6074 if (info->intercept == x86_intercept_cr_read)
6075 icpt_info.exit_code += info->modrm_reg;
6076 break;
6077 case SVM_EXIT_WRITE_CR0: {
6078 unsigned long cr0, val;
6079 u64 intercept;
6080
6081 if (info->intercept == x86_intercept_cr_write)
6082 icpt_info.exit_code += info->modrm_reg;
6083
6084 if (icpt_info.exit_code != SVM_EXIT_WRITE_CR0 ||
6085 info->intercept == x86_intercept_clts)
6086 break;
6087
6088 intercept = svm->nested.intercept;
6089
6090 if (!(intercept & (1ULL << INTERCEPT_SELECTIVE_CR0)))
6091 break;
6092
6093 cr0 = vcpu->arch.cr0 & ~SVM_CR0_SELECTIVE_MASK;
6094 val = info->src_val & ~SVM_CR0_SELECTIVE_MASK;
6095
6096 if (info->intercept == x86_intercept_lmsw) {
6097 cr0 &= 0xfUL;
6098 val &= 0xfUL;
6099 /* lmsw can't clear PE - catch this here */
6100 if (cr0 & X86_CR0_PE)
6101 val |= X86_CR0_PE;
6102 }
6103
6104 if (cr0 ^ val)
6105 icpt_info.exit_code = SVM_EXIT_CR0_SEL_WRITE;
6106
6107 break;
6108 }
6109 case SVM_EXIT_READ_DR0:
6110 case SVM_EXIT_WRITE_DR0:
6111 icpt_info.exit_code += info->modrm_reg;
6112 break;
6113 case SVM_EXIT_MSR:
6114 if (info->intercept == x86_intercept_wrmsr)
6115 vmcb->control.exit_info_1 = 1;
6116 else
6117 vmcb->control.exit_info_1 = 0;
6118 break;
6119 case SVM_EXIT_PAUSE:
6120 /*
6121 * We get this for NOP only, but pause
6122 * is rep not, check this here
6123 */
6124 if (info->rep_prefix != REPE_PREFIX)
6125 goto out;
6126 break;
6127 case SVM_EXIT_IOIO: {
6128 u64 exit_info;
6129 u32 bytes;
6130
6131 if (info->intercept == x86_intercept_in ||
6132 info->intercept == x86_intercept_ins) {
6133 exit_info = ((info->src_val & 0xffff) << 16) |
6134 SVM_IOIO_TYPE_MASK;
6135 bytes = info->dst_bytes;
6136 } else {
6137 exit_info = (info->dst_val & 0xffff) << 16;
6138 bytes = info->src_bytes;
6139 }
6140
6141 if (info->intercept == x86_intercept_outs ||
6142 info->intercept == x86_intercept_ins)
6143 exit_info |= SVM_IOIO_STR_MASK;
6144
6145 if (info->rep_prefix)
6146 exit_info |= SVM_IOIO_REP_MASK;
6147
6148 bytes = min(bytes, 4u);
6149
6150 exit_info |= bytes << SVM_IOIO_SIZE_SHIFT;
6151
6152 exit_info |= (u32)info->ad_bytes << (SVM_IOIO_ASIZE_SHIFT - 1);
6153
6154 vmcb->control.exit_info_1 = exit_info;
6155 vmcb->control.exit_info_2 = info->next_rip;
6156
6157 break;
6158 }
6159 default:
6160 break;
6161 }
6162
6163 /* TODO: Advertise NRIPS to guest hypervisor unconditionally */
6164 if (static_cpu_has(X86_FEATURE_NRIPS))
6165 vmcb->control.next_rip = info->next_rip;
6166 vmcb->control.exit_code = icpt_info.exit_code;
6167 vmexit = nested_svm_exit_handled(svm);
6168
6169 ret = (vmexit == NESTED_EXIT_DONE) ? X86EMUL_INTERCEPTED
6170 : X86EMUL_CONTINUE;
6171
6172 out:
6173 return ret;
6174 }
6175
6176 static void svm_handle_exit_irqoff(struct kvm_vcpu *vcpu)
6177 {
6178
6179 }
6180
6181 static void svm_sched_in(struct kvm_vcpu *vcpu, int cpu)
6182 {
6183 if (pause_filter_thresh)
6184 shrink_ple_window(vcpu);
6185 }
6186
6187 static inline void avic_post_state_restore(struct kvm_vcpu *vcpu)
6188 {
6189 if (avic_handle_apic_id_update(vcpu) != 0)
6190 return;
6191 avic_handle_dfr_update(vcpu);
6192 avic_handle_ldr_update(vcpu);
6193 }
6194
6195 static void svm_setup_mce(struct kvm_vcpu *vcpu)
6196 {
6197 /* [63:9] are reserved. */
6198 vcpu->arch.mcg_cap &= 0x1ff;
6199 }
6200
6201 static int svm_smi_allowed(struct kvm_vcpu *vcpu)
6202 {
6203 struct vcpu_svm *svm = to_svm(vcpu);
6204
6205 /* Per APM Vol.2 15.22.2 "Response to SMI" */
6206 if (!gif_set(svm))
6207 return 0;
6208
6209 if (is_guest_mode(&svm->vcpu) &&
6210 svm->nested.intercept & (1ULL << INTERCEPT_SMI)) {
6211 /* TODO: Might need to set exit_info_1 and exit_info_2 here */
6212 svm->vmcb->control.exit_code = SVM_EXIT_SMI;
6213 svm->nested.exit_required = true;
6214 return 0;
6215 }
6216
6217 return 1;
6218 }
6219
6220 static int svm_pre_enter_smm(struct kvm_vcpu *vcpu, char *smstate)
6221 {
6222 struct vcpu_svm *svm = to_svm(vcpu);
6223 int ret;
6224
6225 if (is_guest_mode(vcpu)) {
6226 /* FED8h - SVM Guest */
6227 put_smstate(u64, smstate, 0x7ed8, 1);
6228 /* FEE0h - SVM Guest VMCB Physical Address */
6229 put_smstate(u64, smstate, 0x7ee0, svm->nested.vmcb);
6230
6231 svm->vmcb->save.rax = vcpu->arch.regs[VCPU_REGS_RAX];
6232 svm->vmcb->save.rsp = vcpu->arch.regs[VCPU_REGS_RSP];
6233 svm->vmcb->save.rip = vcpu->arch.regs[VCPU_REGS_RIP];
6234
6235 ret = nested_svm_vmexit(svm);
6236 if (ret)
6237 return ret;
6238 }
6239 return 0;
6240 }
6241
6242 static int svm_pre_leave_smm(struct kvm_vcpu *vcpu, const char *smstate)
6243 {
6244 struct vcpu_svm *svm = to_svm(vcpu);
6245 struct vmcb *nested_vmcb;
6246 struct kvm_host_map map;
6247 u64 guest;
6248 u64 vmcb;
6249
6250 guest = GET_SMSTATE(u64, smstate, 0x7ed8);
6251 vmcb = GET_SMSTATE(u64, smstate, 0x7ee0);
6252
6253 if (guest) {
6254 if (kvm_vcpu_map(&svm->vcpu, gpa_to_gfn(vmcb), &map) == -EINVAL)
6255 return 1;
6256 nested_vmcb = map.hva;
6257 enter_svm_guest_mode(svm, vmcb, nested_vmcb, &map);
6258 }
6259 return 0;
6260 }
6261
6262 static int enable_smi_window(struct kvm_vcpu *vcpu)
6263 {
6264 struct vcpu_svm *svm = to_svm(vcpu);
6265
6266 if (!gif_set(svm)) {
6267 if (vgif_enabled(svm))
6268 set_intercept(svm, INTERCEPT_STGI);
6269 /* STGI will cause a vm exit */
6270 return 1;
6271 }
6272 return 0;
6273 }
6274
6275 static int sev_flush_asids(void)
6276 {
6277 int ret, error;
6278
6279 /*
6280 * DEACTIVATE will clear the WBINVD indicator causing DF_FLUSH to fail,
6281 * so it must be guarded.
6282 */
6283 down_write(&sev_deactivate_lock);
6284
6285 wbinvd_on_all_cpus();
6286 ret = sev_guest_df_flush(&error);
6287
6288 up_write(&sev_deactivate_lock);
6289
6290 if (ret)
6291 pr_err("SEV: DF_FLUSH failed, ret=%d, error=%#x\n", ret, error);
6292
6293 return ret;
6294 }
6295
6296 /* Must be called with the sev_bitmap_lock held */
6297 static bool __sev_recycle_asids(void)
6298 {
6299 int pos;
6300
6301 /* Check if there are any ASIDs to reclaim before performing a flush */
6302 pos = find_next_bit(sev_reclaim_asid_bitmap,
6303 max_sev_asid, min_sev_asid - 1);
6304 if (pos >= max_sev_asid)
6305 return false;
6306
6307 if (sev_flush_asids())
6308 return false;
6309
6310 bitmap_xor(sev_asid_bitmap, sev_asid_bitmap, sev_reclaim_asid_bitmap,
6311 max_sev_asid);
6312 bitmap_zero(sev_reclaim_asid_bitmap, max_sev_asid);
6313
6314 return true;
6315 }
6316
6317 static int sev_asid_new(void)
6318 {
6319 bool retry = true;
6320 int pos;
6321
6322 mutex_lock(&sev_bitmap_lock);
6323
6324 /*
6325 * SEV-enabled guest must use asid from min_sev_asid to max_sev_asid.
6326 */
6327 again:
6328 pos = find_next_zero_bit(sev_asid_bitmap, max_sev_asid, min_sev_asid - 1);
6329 if (pos >= max_sev_asid) {
6330 if (retry && __sev_recycle_asids()) {
6331 retry = false;
6332 goto again;
6333 }
6334 mutex_unlock(&sev_bitmap_lock);
6335 return -EBUSY;
6336 }
6337
6338 __set_bit(pos, sev_asid_bitmap);
6339
6340 mutex_unlock(&sev_bitmap_lock);
6341
6342 return pos + 1;
6343 }
6344
6345 static int sev_guest_init(struct kvm *kvm, struct kvm_sev_cmd *argp)
6346 {
6347 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6348 int asid, ret;
6349
6350 ret = -EBUSY;
6351 if (unlikely(sev->active))
6352 return ret;
6353
6354 asid = sev_asid_new();
6355 if (asid < 0)
6356 return ret;
6357
6358 ret = sev_platform_init(&argp->error);
6359 if (ret)
6360 goto e_free;
6361
6362 sev->active = true;
6363 sev->asid = asid;
6364 INIT_LIST_HEAD(&sev->regions_list);
6365
6366 return 0;
6367
6368 e_free:
6369 sev_asid_free(asid);
6370 return ret;
6371 }
6372
6373 static int sev_bind_asid(struct kvm *kvm, unsigned int handle, int *error)
6374 {
6375 struct sev_data_activate *data;
6376 int asid = sev_get_asid(kvm);
6377 int ret;
6378
6379 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6380 if (!data)
6381 return -ENOMEM;
6382
6383 /* activate ASID on the given handle */
6384 data->handle = handle;
6385 data->asid = asid;
6386 ret = sev_guest_activate(data, error);
6387 kfree(data);
6388
6389 return ret;
6390 }
6391
6392 static int __sev_issue_cmd(int fd, int id, void *data, int *error)
6393 {
6394 struct fd f;
6395 int ret;
6396
6397 f = fdget(fd);
6398 if (!f.file)
6399 return -EBADF;
6400
6401 ret = sev_issue_cmd_external_user(f.file, id, data, error);
6402
6403 fdput(f);
6404 return ret;
6405 }
6406
6407 static int sev_issue_cmd(struct kvm *kvm, int id, void *data, int *error)
6408 {
6409 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6410
6411 return __sev_issue_cmd(sev->fd, id, data, error);
6412 }
6413
6414 static int sev_launch_start(struct kvm *kvm, struct kvm_sev_cmd *argp)
6415 {
6416 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6417 struct sev_data_launch_start *start;
6418 struct kvm_sev_launch_start params;
6419 void *dh_blob, *session_blob;
6420 int *error = &argp->error;
6421 int ret;
6422
6423 if (!sev_guest(kvm))
6424 return -ENOTTY;
6425
6426 if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6427 return -EFAULT;
6428
6429 start = kzalloc(sizeof(*start), GFP_KERNEL_ACCOUNT);
6430 if (!start)
6431 return -ENOMEM;
6432
6433 dh_blob = NULL;
6434 if (params.dh_uaddr) {
6435 dh_blob = psp_copy_user_blob(params.dh_uaddr, params.dh_len);
6436 if (IS_ERR(dh_blob)) {
6437 ret = PTR_ERR(dh_blob);
6438 goto e_free;
6439 }
6440
6441 start->dh_cert_address = __sme_set(__pa(dh_blob));
6442 start->dh_cert_len = params.dh_len;
6443 }
6444
6445 session_blob = NULL;
6446 if (params.session_uaddr) {
6447 session_blob = psp_copy_user_blob(params.session_uaddr, params.session_len);
6448 if (IS_ERR(session_blob)) {
6449 ret = PTR_ERR(session_blob);
6450 goto e_free_dh;
6451 }
6452
6453 start->session_address = __sme_set(__pa(session_blob));
6454 start->session_len = params.session_len;
6455 }
6456
6457 start->handle = params.handle;
6458 start->policy = params.policy;
6459
6460 /* create memory encryption context */
6461 ret = __sev_issue_cmd(argp->sev_fd, SEV_CMD_LAUNCH_START, start, error);
6462 if (ret)
6463 goto e_free_session;
6464
6465 /* Bind ASID to this guest */
6466 ret = sev_bind_asid(kvm, start->handle, error);
6467 if (ret)
6468 goto e_free_session;
6469
6470 /* return handle to userspace */
6471 params.handle = start->handle;
6472 if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params))) {
6473 sev_unbind_asid(kvm, start->handle);
6474 ret = -EFAULT;
6475 goto e_free_session;
6476 }
6477
6478 sev->handle = start->handle;
6479 sev->fd = argp->sev_fd;
6480
6481 e_free_session:
6482 kfree(session_blob);
6483 e_free_dh:
6484 kfree(dh_blob);
6485 e_free:
6486 kfree(start);
6487 return ret;
6488 }
6489
6490 static unsigned long get_num_contig_pages(unsigned long idx,
6491 struct page **inpages, unsigned long npages)
6492 {
6493 unsigned long paddr, next_paddr;
6494 unsigned long i = idx + 1, pages = 1;
6495
6496 /* find the number of contiguous pages starting from idx */
6497 paddr = __sme_page_pa(inpages[idx]);
6498 while (i < npages) {
6499 next_paddr = __sme_page_pa(inpages[i++]);
6500 if ((paddr + PAGE_SIZE) == next_paddr) {
6501 pages++;
6502 paddr = next_paddr;
6503 continue;
6504 }
6505 break;
6506 }
6507
6508 return pages;
6509 }
6510
6511 static int sev_launch_update_data(struct kvm *kvm, struct kvm_sev_cmd *argp)
6512 {
6513 unsigned long vaddr, vaddr_end, next_vaddr, npages, pages, size, i;
6514 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6515 struct kvm_sev_launch_update_data params;
6516 struct sev_data_launch_update_data *data;
6517 struct page **inpages;
6518 int ret;
6519
6520 if (!sev_guest(kvm))
6521 return -ENOTTY;
6522
6523 if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6524 return -EFAULT;
6525
6526 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6527 if (!data)
6528 return -ENOMEM;
6529
6530 vaddr = params.uaddr;
6531 size = params.len;
6532 vaddr_end = vaddr + size;
6533
6534 /* Lock the user memory. */
6535 inpages = sev_pin_memory(kvm, vaddr, size, &npages, 1);
6536 if (!inpages) {
6537 ret = -ENOMEM;
6538 goto e_free;
6539 }
6540
6541 /*
6542 * The LAUNCH_UPDATE command will perform in-place encryption of the
6543 * memory content (i.e it will write the same memory region with C=1).
6544 * It's possible that the cache may contain the data with C=0, i.e.,
6545 * unencrypted so invalidate it first.
6546 */
6547 sev_clflush_pages(inpages, npages);
6548
6549 for (i = 0; vaddr < vaddr_end; vaddr = next_vaddr, i += pages) {
6550 int offset, len;
6551
6552 /*
6553 * If the user buffer is not page-aligned, calculate the offset
6554 * within the page.
6555 */
6556 offset = vaddr & (PAGE_SIZE - 1);
6557
6558 /* Calculate the number of pages that can be encrypted in one go. */
6559 pages = get_num_contig_pages(i, inpages, npages);
6560
6561 len = min_t(size_t, ((pages * PAGE_SIZE) - offset), size);
6562
6563 data->handle = sev->handle;
6564 data->len = len;
6565 data->address = __sme_page_pa(inpages[i]) + offset;
6566 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_DATA, data, &argp->error);
6567 if (ret)
6568 goto e_unpin;
6569
6570 size -= len;
6571 next_vaddr = vaddr + len;
6572 }
6573
6574 e_unpin:
6575 /* content of memory is updated, mark pages dirty */
6576 for (i = 0; i < npages; i++) {
6577 set_page_dirty_lock(inpages[i]);
6578 mark_page_accessed(inpages[i]);
6579 }
6580 /* unlock the user pages */
6581 sev_unpin_memory(kvm, inpages, npages);
6582 e_free:
6583 kfree(data);
6584 return ret;
6585 }
6586
6587 static int sev_launch_measure(struct kvm *kvm, struct kvm_sev_cmd *argp)
6588 {
6589 void __user *measure = (void __user *)(uintptr_t)argp->data;
6590 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6591 struct sev_data_launch_measure *data;
6592 struct kvm_sev_launch_measure params;
6593 void __user *p = NULL;
6594 void *blob = NULL;
6595 int ret;
6596
6597 if (!sev_guest(kvm))
6598 return -ENOTTY;
6599
6600 if (copy_from_user(&params, measure, sizeof(params)))
6601 return -EFAULT;
6602
6603 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6604 if (!data)
6605 return -ENOMEM;
6606
6607 /* User wants to query the blob length */
6608 if (!params.len)
6609 goto cmd;
6610
6611 p = (void __user *)(uintptr_t)params.uaddr;
6612 if (p) {
6613 if (params.len > SEV_FW_BLOB_MAX_SIZE) {
6614 ret = -EINVAL;
6615 goto e_free;
6616 }
6617
6618 ret = -ENOMEM;
6619 blob = kmalloc(params.len, GFP_KERNEL);
6620 if (!blob)
6621 goto e_free;
6622
6623 data->address = __psp_pa(blob);
6624 data->len = params.len;
6625 }
6626
6627 cmd:
6628 data->handle = sev->handle;
6629 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_MEASURE, data, &argp->error);
6630
6631 /*
6632 * If we query the session length, FW responded with expected data.
6633 */
6634 if (!params.len)
6635 goto done;
6636
6637 if (ret)
6638 goto e_free_blob;
6639
6640 if (blob) {
6641 if (copy_to_user(p, blob, params.len))
6642 ret = -EFAULT;
6643 }
6644
6645 done:
6646 params.len = data->len;
6647 if (copy_to_user(measure, &params, sizeof(params)))
6648 ret = -EFAULT;
6649 e_free_blob:
6650 kfree(blob);
6651 e_free:
6652 kfree(data);
6653 return ret;
6654 }
6655
6656 static int sev_launch_finish(struct kvm *kvm, struct kvm_sev_cmd *argp)
6657 {
6658 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6659 struct sev_data_launch_finish *data;
6660 int ret;
6661
6662 if (!sev_guest(kvm))
6663 return -ENOTTY;
6664
6665 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6666 if (!data)
6667 return -ENOMEM;
6668
6669 data->handle = sev->handle;
6670 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_FINISH, data, &argp->error);
6671
6672 kfree(data);
6673 return ret;
6674 }
6675
6676 static int sev_guest_status(struct kvm *kvm, struct kvm_sev_cmd *argp)
6677 {
6678 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6679 struct kvm_sev_guest_status params;
6680 struct sev_data_guest_status *data;
6681 int ret;
6682
6683 if (!sev_guest(kvm))
6684 return -ENOTTY;
6685
6686 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6687 if (!data)
6688 return -ENOMEM;
6689
6690 data->handle = sev->handle;
6691 ret = sev_issue_cmd(kvm, SEV_CMD_GUEST_STATUS, data, &argp->error);
6692 if (ret)
6693 goto e_free;
6694
6695 params.policy = data->policy;
6696 params.state = data->state;
6697 params.handle = data->handle;
6698
6699 if (copy_to_user((void __user *)(uintptr_t)argp->data, &params, sizeof(params)))
6700 ret = -EFAULT;
6701 e_free:
6702 kfree(data);
6703 return ret;
6704 }
6705
6706 static int __sev_issue_dbg_cmd(struct kvm *kvm, unsigned long src,
6707 unsigned long dst, int size,
6708 int *error, bool enc)
6709 {
6710 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6711 struct sev_data_dbg *data;
6712 int ret;
6713
6714 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6715 if (!data)
6716 return -ENOMEM;
6717
6718 data->handle = sev->handle;
6719 data->dst_addr = dst;
6720 data->src_addr = src;
6721 data->len = size;
6722
6723 ret = sev_issue_cmd(kvm,
6724 enc ? SEV_CMD_DBG_ENCRYPT : SEV_CMD_DBG_DECRYPT,
6725 data, error);
6726 kfree(data);
6727 return ret;
6728 }
6729
6730 static int __sev_dbg_decrypt(struct kvm *kvm, unsigned long src_paddr,
6731 unsigned long dst_paddr, int sz, int *err)
6732 {
6733 int offset;
6734
6735 /*
6736 * Its safe to read more than we are asked, caller should ensure that
6737 * destination has enough space.
6738 */
6739 src_paddr = round_down(src_paddr, 16);
6740 offset = src_paddr & 15;
6741 sz = round_up(sz + offset, 16);
6742
6743 return __sev_issue_dbg_cmd(kvm, src_paddr, dst_paddr, sz, err, false);
6744 }
6745
6746 static int __sev_dbg_decrypt_user(struct kvm *kvm, unsigned long paddr,
6747 unsigned long __user dst_uaddr,
6748 unsigned long dst_paddr,
6749 int size, int *err)
6750 {
6751 struct page *tpage = NULL;
6752 int ret, offset;
6753
6754 /* if inputs are not 16-byte then use intermediate buffer */
6755 if (!IS_ALIGNED(dst_paddr, 16) ||
6756 !IS_ALIGNED(paddr, 16) ||
6757 !IS_ALIGNED(size, 16)) {
6758 tpage = (void *)alloc_page(GFP_KERNEL);
6759 if (!tpage)
6760 return -ENOMEM;
6761
6762 dst_paddr = __sme_page_pa(tpage);
6763 }
6764
6765 ret = __sev_dbg_decrypt(kvm, paddr, dst_paddr, size, err);
6766 if (ret)
6767 goto e_free;
6768
6769 if (tpage) {
6770 offset = paddr & 15;
6771 if (copy_to_user((void __user *)(uintptr_t)dst_uaddr,
6772 page_address(tpage) + offset, size))
6773 ret = -EFAULT;
6774 }
6775
6776 e_free:
6777 if (tpage)
6778 __free_page(tpage);
6779
6780 return ret;
6781 }
6782
6783 static int __sev_dbg_encrypt_user(struct kvm *kvm, unsigned long paddr,
6784 unsigned long __user vaddr,
6785 unsigned long dst_paddr,
6786 unsigned long __user dst_vaddr,
6787 int size, int *error)
6788 {
6789 struct page *src_tpage = NULL;
6790 struct page *dst_tpage = NULL;
6791 int ret, len = size;
6792
6793 /* If source buffer is not aligned then use an intermediate buffer */
6794 if (!IS_ALIGNED(vaddr, 16)) {
6795 src_tpage = alloc_page(GFP_KERNEL);
6796 if (!src_tpage)
6797 return -ENOMEM;
6798
6799 if (copy_from_user(page_address(src_tpage),
6800 (void __user *)(uintptr_t)vaddr, size)) {
6801 __free_page(src_tpage);
6802 return -EFAULT;
6803 }
6804
6805 paddr = __sme_page_pa(src_tpage);
6806 }
6807
6808 /*
6809 * If destination buffer or length is not aligned then do read-modify-write:
6810 * - decrypt destination in an intermediate buffer
6811 * - copy the source buffer in an intermediate buffer
6812 * - use the intermediate buffer as source buffer
6813 */
6814 if (!IS_ALIGNED(dst_vaddr, 16) || !IS_ALIGNED(size, 16)) {
6815 int dst_offset;
6816
6817 dst_tpage = alloc_page(GFP_KERNEL);
6818 if (!dst_tpage) {
6819 ret = -ENOMEM;
6820 goto e_free;
6821 }
6822
6823 ret = __sev_dbg_decrypt(kvm, dst_paddr,
6824 __sme_page_pa(dst_tpage), size, error);
6825 if (ret)
6826 goto e_free;
6827
6828 /*
6829 * If source is kernel buffer then use memcpy() otherwise
6830 * copy_from_user().
6831 */
6832 dst_offset = dst_paddr & 15;
6833
6834 if (src_tpage)
6835 memcpy(page_address(dst_tpage) + dst_offset,
6836 page_address(src_tpage), size);
6837 else {
6838 if (copy_from_user(page_address(dst_tpage) + dst_offset,
6839 (void __user *)(uintptr_t)vaddr, size)) {
6840 ret = -EFAULT;
6841 goto e_free;
6842 }
6843 }
6844
6845 paddr = __sme_page_pa(dst_tpage);
6846 dst_paddr = round_down(dst_paddr, 16);
6847 len = round_up(size, 16);
6848 }
6849
6850 ret = __sev_issue_dbg_cmd(kvm, paddr, dst_paddr, len, error, true);
6851
6852 e_free:
6853 if (src_tpage)
6854 __free_page(src_tpage);
6855 if (dst_tpage)
6856 __free_page(dst_tpage);
6857 return ret;
6858 }
6859
6860 static int sev_dbg_crypt(struct kvm *kvm, struct kvm_sev_cmd *argp, bool dec)
6861 {
6862 unsigned long vaddr, vaddr_end, next_vaddr;
6863 unsigned long dst_vaddr;
6864 struct page **src_p, **dst_p;
6865 struct kvm_sev_dbg debug;
6866 unsigned long n;
6867 unsigned int size;
6868 int ret;
6869
6870 if (!sev_guest(kvm))
6871 return -ENOTTY;
6872
6873 if (copy_from_user(&debug, (void __user *)(uintptr_t)argp->data, sizeof(debug)))
6874 return -EFAULT;
6875
6876 if (!debug.len || debug.src_uaddr + debug.len < debug.src_uaddr)
6877 return -EINVAL;
6878 if (!debug.dst_uaddr)
6879 return -EINVAL;
6880
6881 vaddr = debug.src_uaddr;
6882 size = debug.len;
6883 vaddr_end = vaddr + size;
6884 dst_vaddr = debug.dst_uaddr;
6885
6886 for (; vaddr < vaddr_end; vaddr = next_vaddr) {
6887 int len, s_off, d_off;
6888
6889 /* lock userspace source and destination page */
6890 src_p = sev_pin_memory(kvm, vaddr & PAGE_MASK, PAGE_SIZE, &n, 0);
6891 if (!src_p)
6892 return -EFAULT;
6893
6894 dst_p = sev_pin_memory(kvm, dst_vaddr & PAGE_MASK, PAGE_SIZE, &n, 1);
6895 if (!dst_p) {
6896 sev_unpin_memory(kvm, src_p, n);
6897 return -EFAULT;
6898 }
6899
6900 /*
6901 * The DBG_{DE,EN}CRYPT commands will perform {dec,en}cryption of the
6902 * memory content (i.e it will write the same memory region with C=1).
6903 * It's possible that the cache may contain the data with C=0, i.e.,
6904 * unencrypted so invalidate it first.
6905 */
6906 sev_clflush_pages(src_p, 1);
6907 sev_clflush_pages(dst_p, 1);
6908
6909 /*
6910 * Since user buffer may not be page aligned, calculate the
6911 * offset within the page.
6912 */
6913 s_off = vaddr & ~PAGE_MASK;
6914 d_off = dst_vaddr & ~PAGE_MASK;
6915 len = min_t(size_t, (PAGE_SIZE - s_off), size);
6916
6917 if (dec)
6918 ret = __sev_dbg_decrypt_user(kvm,
6919 __sme_page_pa(src_p[0]) + s_off,
6920 dst_vaddr,
6921 __sme_page_pa(dst_p[0]) + d_off,
6922 len, &argp->error);
6923 else
6924 ret = __sev_dbg_encrypt_user(kvm,
6925 __sme_page_pa(src_p[0]) + s_off,
6926 vaddr,
6927 __sme_page_pa(dst_p[0]) + d_off,
6928 dst_vaddr,
6929 len, &argp->error);
6930
6931 sev_unpin_memory(kvm, src_p, n);
6932 sev_unpin_memory(kvm, dst_p, n);
6933
6934 if (ret)
6935 goto err;
6936
6937 next_vaddr = vaddr + len;
6938 dst_vaddr = dst_vaddr + len;
6939 size -= len;
6940 }
6941 err:
6942 return ret;
6943 }
6944
6945 static int sev_launch_secret(struct kvm *kvm, struct kvm_sev_cmd *argp)
6946 {
6947 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
6948 struct sev_data_launch_secret *data;
6949 struct kvm_sev_launch_secret params;
6950 struct page **pages;
6951 void *blob, *hdr;
6952 unsigned long n;
6953 int ret, offset;
6954
6955 if (!sev_guest(kvm))
6956 return -ENOTTY;
6957
6958 if (copy_from_user(&params, (void __user *)(uintptr_t)argp->data, sizeof(params)))
6959 return -EFAULT;
6960
6961 pages = sev_pin_memory(kvm, params.guest_uaddr, params.guest_len, &n, 1);
6962 if (!pages)
6963 return -ENOMEM;
6964
6965 /*
6966 * The secret must be copied into contiguous memory region, lets verify
6967 * that userspace memory pages are contiguous before we issue command.
6968 */
6969 if (get_num_contig_pages(0, pages, n) != n) {
6970 ret = -EINVAL;
6971 goto e_unpin_memory;
6972 }
6973
6974 ret = -ENOMEM;
6975 data = kzalloc(sizeof(*data), GFP_KERNEL_ACCOUNT);
6976 if (!data)
6977 goto e_unpin_memory;
6978
6979 offset = params.guest_uaddr & (PAGE_SIZE - 1);
6980 data->guest_address = __sme_page_pa(pages[0]) + offset;
6981 data->guest_len = params.guest_len;
6982
6983 blob = psp_copy_user_blob(params.trans_uaddr, params.trans_len);
6984 if (IS_ERR(blob)) {
6985 ret = PTR_ERR(blob);
6986 goto e_free;
6987 }
6988
6989 data->trans_address = __psp_pa(blob);
6990 data->trans_len = params.trans_len;
6991
6992 hdr = psp_copy_user_blob(params.hdr_uaddr, params.hdr_len);
6993 if (IS_ERR(hdr)) {
6994 ret = PTR_ERR(hdr);
6995 goto e_free_blob;
6996 }
6997 data->hdr_address = __psp_pa(hdr);
6998 data->hdr_len = params.hdr_len;
6999
7000 data->handle = sev->handle;
7001 ret = sev_issue_cmd(kvm, SEV_CMD_LAUNCH_UPDATE_SECRET, data, &argp->error);
7002
7003 kfree(hdr);
7004
7005 e_free_blob:
7006 kfree(blob);
7007 e_free:
7008 kfree(data);
7009 e_unpin_memory:
7010 sev_unpin_memory(kvm, pages, n);
7011 return ret;
7012 }
7013
7014 static int svm_mem_enc_op(struct kvm *kvm, void __user *argp)
7015 {
7016 struct kvm_sev_cmd sev_cmd;
7017 int r;
7018
7019 if (!svm_sev_enabled())
7020 return -ENOTTY;
7021
7022 if (copy_from_user(&sev_cmd, argp, sizeof(struct kvm_sev_cmd)))
7023 return -EFAULT;
7024
7025 mutex_lock(&kvm->lock);
7026
7027 switch (sev_cmd.id) {
7028 case KVM_SEV_INIT:
7029 r = sev_guest_init(kvm, &sev_cmd);
7030 break;
7031 case KVM_SEV_LAUNCH_START:
7032 r = sev_launch_start(kvm, &sev_cmd);
7033 break;
7034 case KVM_SEV_LAUNCH_UPDATE_DATA:
7035 r = sev_launch_update_data(kvm, &sev_cmd);
7036 break;
7037 case KVM_SEV_LAUNCH_MEASURE:
7038 r = sev_launch_measure(kvm, &sev_cmd);
7039 break;
7040 case KVM_SEV_LAUNCH_FINISH:
7041 r = sev_launch_finish(kvm, &sev_cmd);
7042 break;
7043 case KVM_SEV_GUEST_STATUS:
7044 r = sev_guest_status(kvm, &sev_cmd);
7045 break;
7046 case KVM_SEV_DBG_DECRYPT:
7047 r = sev_dbg_crypt(kvm, &sev_cmd, true);
7048 break;
7049 case KVM_SEV_DBG_ENCRYPT:
7050 r = sev_dbg_crypt(kvm, &sev_cmd, false);
7051 break;
7052 case KVM_SEV_LAUNCH_SECRET:
7053 r = sev_launch_secret(kvm, &sev_cmd);
7054 break;
7055 default:
7056 r = -EINVAL;
7057 goto out;
7058 }
7059
7060 if (copy_to_user(argp, &sev_cmd, sizeof(struct kvm_sev_cmd)))
7061 r = -EFAULT;
7062
7063 out:
7064 mutex_unlock(&kvm->lock);
7065 return r;
7066 }
7067
7068 static int svm_register_enc_region(struct kvm *kvm,
7069 struct kvm_enc_region *range)
7070 {
7071 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7072 struct enc_region *region;
7073 int ret = 0;
7074
7075 if (!sev_guest(kvm))
7076 return -ENOTTY;
7077
7078 if (range->addr > ULONG_MAX || range->size > ULONG_MAX)
7079 return -EINVAL;
7080
7081 region = kzalloc(sizeof(*region), GFP_KERNEL_ACCOUNT);
7082 if (!region)
7083 return -ENOMEM;
7084
7085 region->pages = sev_pin_memory(kvm, range->addr, range->size, &region->npages, 1);
7086 if (!region->pages) {
7087 ret = -ENOMEM;
7088 goto e_free;
7089 }
7090
7091 /*
7092 * The guest may change the memory encryption attribute from C=0 -> C=1
7093 * or vice versa for this memory range. Lets make sure caches are
7094 * flushed to ensure that guest data gets written into memory with
7095 * correct C-bit.
7096 */
7097 sev_clflush_pages(region->pages, region->npages);
7098
7099 region->uaddr = range->addr;
7100 region->size = range->size;
7101
7102 mutex_lock(&kvm->lock);
7103 list_add_tail(&region->list, &sev->regions_list);
7104 mutex_unlock(&kvm->lock);
7105
7106 return ret;
7107
7108 e_free:
7109 kfree(region);
7110 return ret;
7111 }
7112
7113 static struct enc_region *
7114 find_enc_region(struct kvm *kvm, struct kvm_enc_region *range)
7115 {
7116 struct kvm_sev_info *sev = &to_kvm_svm(kvm)->sev_info;
7117 struct list_head *head = &sev->regions_list;
7118 struct enc_region *i;
7119
7120 list_for_each_entry(i, head, list) {
7121 if (i->uaddr == range->addr &&
7122 i->size == range->size)
7123 return i;
7124 }
7125
7126 return NULL;
7127 }
7128
7129
7130 static int svm_unregister_enc_region(struct kvm *kvm,
7131 struct kvm_enc_region *range)
7132 {
7133 struct enc_region *region;
7134 int ret;
7135
7136 mutex_lock(&kvm->lock);
7137
7138 if (!sev_guest(kvm)) {
7139 ret = -ENOTTY;
7140 goto failed;
7141 }
7142
7143 region = find_enc_region(kvm, range);
7144 if (!region) {
7145 ret = -EINVAL;
7146 goto failed;
7147 }
7148
7149 __unregister_enc_region_locked(kvm, region);
7150
7151 mutex_unlock(&kvm->lock);
7152 return 0;
7153
7154 failed:
7155 mutex_unlock(&kvm->lock);
7156 return ret;
7157 }
7158
7159 static bool svm_need_emulation_on_page_fault(struct kvm_vcpu *vcpu)
7160 {
7161 unsigned long cr4 = kvm_read_cr4(vcpu);
7162 bool smep = cr4 & X86_CR4_SMEP;
7163 bool smap = cr4 & X86_CR4_SMAP;
7164 bool is_user = svm_get_cpl(vcpu) == 3;
7165
7166 /*
7167 * Detect and workaround Errata 1096 Fam_17h_00_0Fh.
7168 *
7169 * Errata:
7170 * When CPU raise #NPF on guest data access and vCPU CR4.SMAP=1, it is
7171 * possible that CPU microcode implementing DecodeAssist will fail
7172 * to read bytes of instruction which caused #NPF. In this case,
7173 * GuestIntrBytes field of the VMCB on a VMEXIT will incorrectly
7174 * return 0 instead of the correct guest instruction bytes.
7175 *
7176 * This happens because CPU microcode reading instruction bytes
7177 * uses a special opcode which attempts to read data using CPL=0
7178 * priviledges. The microcode reads CS:RIP and if it hits a SMAP
7179 * fault, it gives up and returns no instruction bytes.
7180 *
7181 * Detection:
7182 * We reach here in case CPU supports DecodeAssist, raised #NPF and
7183 * returned 0 in GuestIntrBytes field of the VMCB.
7184 * First, errata can only be triggered in case vCPU CR4.SMAP=1.
7185 * Second, if vCPU CR4.SMEP=1, errata could only be triggered
7186 * in case vCPU CPL==3 (Because otherwise guest would have triggered
7187 * a SMEP fault instead of #NPF).
7188 * Otherwise, vCPU CR4.SMEP=0, errata could be triggered by any vCPU CPL.
7189 * As most guests enable SMAP if they have also enabled SMEP, use above
7190 * logic in order to attempt minimize false-positive of detecting errata
7191 * while still preserving all cases semantic correctness.
7192 *
7193 * Workaround:
7194 * To determine what instruction the guest was executing, the hypervisor
7195 * will have to decode the instruction at the instruction pointer.
7196 *
7197 * In non SEV guest, hypervisor will be able to read the guest
7198 * memory to decode the instruction pointer when insn_len is zero
7199 * so we return true to indicate that decoding is possible.
7200 *
7201 * But in the SEV guest, the guest memory is encrypted with the
7202 * guest specific key and hypervisor will not be able to decode the
7203 * instruction pointer so we will not able to workaround it. Lets
7204 * print the error and request to kill the guest.
7205 */
7206 if (smap && (!smep || is_user)) {
7207 if (!sev_guest(vcpu->kvm))
7208 return true;
7209
7210 pr_err_ratelimited("KVM: SEV Guest triggered AMD Erratum 1096\n");
7211 kvm_make_request(KVM_REQ_TRIPLE_FAULT, vcpu);
7212 }
7213
7214 return false;
7215 }
7216
7217 static bool svm_apic_init_signal_blocked(struct kvm_vcpu *vcpu)
7218 {
7219 struct vcpu_svm *svm = to_svm(vcpu);
7220
7221 /*
7222 * TODO: Last condition latch INIT signals on vCPU when
7223 * vCPU is in guest-mode and vmcb12 defines intercept on INIT.
7224 * To properly emulate the INIT intercept, SVM should implement
7225 * kvm_x86_ops->check_nested_events() and call nested_svm_vmexit()
7226 * there if an INIT signal is pending.
7227 */
7228 return !gif_set(svm) ||
7229 (svm->vmcb->control.intercept & (1ULL << INTERCEPT_INIT));
7230 }
7231
7232 static struct kvm_x86_ops svm_x86_ops __ro_after_init = {
7233 .cpu_has_kvm_support = has_svm,
7234 .disabled_by_bios = is_disabled,
7235 .hardware_setup = svm_hardware_setup,
7236 .hardware_unsetup = svm_hardware_unsetup,
7237 .check_processor_compatibility = svm_check_processor_compat,
7238 .hardware_enable = svm_hardware_enable,
7239 .hardware_disable = svm_hardware_disable,
7240 .cpu_has_accelerated_tpr = svm_cpu_has_accelerated_tpr,
7241 .has_emulated_msr = svm_has_emulated_msr,
7242
7243 .vcpu_create = svm_create_vcpu,
7244 .vcpu_free = svm_free_vcpu,
7245 .vcpu_reset = svm_vcpu_reset,
7246
7247 .vm_alloc = svm_vm_alloc,
7248 .vm_free = svm_vm_free,
7249 .vm_init = avic_vm_init,
7250 .vm_destroy = svm_vm_destroy,
7251
7252 .prepare_guest_switch = svm_prepare_guest_switch,
7253 .vcpu_load = svm_vcpu_load,
7254 .vcpu_put = svm_vcpu_put,
7255 .vcpu_blocking = svm_vcpu_blocking,
7256 .vcpu_unblocking = svm_vcpu_unblocking,
7257
7258 .update_bp_intercept = update_bp_intercept,
7259 .get_msr_feature = svm_get_msr_feature,
7260 .get_msr = svm_get_msr,
7261 .set_msr = svm_set_msr,
7262 .get_segment_base = svm_get_segment_base,
7263 .get_segment = svm_get_segment,
7264 .set_segment = svm_set_segment,
7265 .get_cpl = svm_get_cpl,
7266 .get_cs_db_l_bits = kvm_get_cs_db_l_bits,
7267 .decache_cr0_guest_bits = svm_decache_cr0_guest_bits,
7268 .decache_cr4_guest_bits = svm_decache_cr4_guest_bits,
7269 .set_cr0 = svm_set_cr0,
7270 .set_cr3 = svm_set_cr3,
7271 .set_cr4 = svm_set_cr4,
7272 .set_efer = svm_set_efer,
7273 .get_idt = svm_get_idt,
7274 .set_idt = svm_set_idt,
7275 .get_gdt = svm_get_gdt,
7276 .set_gdt = svm_set_gdt,
7277 .get_dr6 = svm_get_dr6,
7278 .set_dr6 = svm_set_dr6,
7279 .set_dr7 = svm_set_dr7,
7280 .sync_dirty_debug_regs = svm_sync_dirty_debug_regs,
7281 .cache_reg = svm_cache_reg,
7282 .get_rflags = svm_get_rflags,
7283 .set_rflags = svm_set_rflags,
7284
7285 .tlb_flush = svm_flush_tlb,
7286 .tlb_flush_gva = svm_flush_tlb_gva,
7287
7288 .run = svm_vcpu_run,
7289 .handle_exit = handle_exit,
7290 .skip_emulated_instruction = skip_emulated_instruction,
7291 .set_interrupt_shadow = svm_set_interrupt_shadow,
7292 .get_interrupt_shadow = svm_get_interrupt_shadow,
7293 .patch_hypercall = svm_patch_hypercall,
7294 .set_irq = svm_set_irq,
7295 .set_nmi = svm_inject_nmi,
7296 .queue_exception = svm_queue_exception,
7297 .cancel_injection = svm_cancel_injection,
7298 .interrupt_allowed = svm_interrupt_allowed,
7299 .nmi_allowed = svm_nmi_allowed,
7300 .get_nmi_mask = svm_get_nmi_mask,
7301 .set_nmi_mask = svm_set_nmi_mask,
7302 .enable_nmi_window = enable_nmi_window,
7303 .enable_irq_window = enable_irq_window,
7304 .update_cr8_intercept = update_cr8_intercept,
7305 .set_virtual_apic_mode = svm_set_virtual_apic_mode,
7306 .get_enable_apicv = svm_get_enable_apicv,
7307 .refresh_apicv_exec_ctrl = svm_refresh_apicv_exec_ctrl,
7308 .load_eoi_exitmap = svm_load_eoi_exitmap,
7309 .hwapic_irr_update = svm_hwapic_irr_update,
7310 .hwapic_isr_update = svm_hwapic_isr_update,
7311 .sync_pir_to_irr = kvm_lapic_find_highest_irr,
7312 .apicv_post_state_restore = avic_post_state_restore,
7313
7314 .set_tss_addr = svm_set_tss_addr,
7315 .set_identity_map_addr = svm_set_identity_map_addr,
7316 .get_tdp_level = get_npt_level,
7317 .get_mt_mask = svm_get_mt_mask,
7318
7319 .get_exit_info = svm_get_exit_info,
7320
7321 .get_lpage_level = svm_get_lpage_level,
7322
7323 .cpuid_update = svm_cpuid_update,
7324
7325 .rdtscp_supported = svm_rdtscp_supported,
7326 .invpcid_supported = svm_invpcid_supported,
7327 .mpx_supported = svm_mpx_supported,
7328 .xsaves_supported = svm_xsaves_supported,
7329 .umip_emulated = svm_umip_emulated,
7330 .pt_supported = svm_pt_supported,
7331
7332 .set_supported_cpuid = svm_set_supported_cpuid,
7333
7334 .has_wbinvd_exit = svm_has_wbinvd_exit,
7335
7336 .read_l1_tsc_offset = svm_read_l1_tsc_offset,
7337 .write_l1_tsc_offset = svm_write_l1_tsc_offset,
7338
7339 .set_tdp_cr3 = set_tdp_cr3,
7340
7341 .check_intercept = svm_check_intercept,
7342 .handle_exit_irqoff = svm_handle_exit_irqoff,
7343
7344 .request_immediate_exit = __kvm_request_immediate_exit,
7345
7346 .sched_in = svm_sched_in,
7347
7348 .pmu_ops = &amd_pmu_ops,
7349 .deliver_posted_interrupt = svm_deliver_avic_intr,
7350 .dy_apicv_has_pending_interrupt = svm_dy_apicv_has_pending_interrupt,
7351 .update_pi_irte = svm_update_pi_irte,
7352 .setup_mce = svm_setup_mce,
7353
7354 .smi_allowed = svm_smi_allowed,
7355 .pre_enter_smm = svm_pre_enter_smm,
7356 .pre_leave_smm = svm_pre_leave_smm,
7357 .enable_smi_window = enable_smi_window,
7358
7359 .mem_enc_op = svm_mem_enc_op,
7360 .mem_enc_reg_region = svm_register_enc_region,
7361 .mem_enc_unreg_region = svm_unregister_enc_region,
7362
7363 .nested_enable_evmcs = NULL,
7364 .nested_get_evmcs_version = NULL,
7365
7366 .need_emulation_on_page_fault = svm_need_emulation_on_page_fault,
7367
7368 .apic_init_signal_blocked = svm_apic_init_signal_blocked,
7369 };
7370
7371 static int __init svm_init(void)
7372 {
7373 return kvm_init(&svm_x86_ops, sizeof(struct vcpu_svm),
7374 __alignof__(struct vcpu_svm), THIS_MODULE);
7375 }
7376
7377 static void __exit svm_exit(void)
7378 {
7379 kvm_exit();
7380 }
7381
7382 module_init(svm_init)
7383 module_exit(svm_exit)