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